Compare commits
No commits in common. "master" and "zustand-indexeddb" have entirely different histories.
master
...
zustand-in
11 changed files with 231 additions and 315 deletions
236
README.md
236
README.md
|
|
@ -1,25 +1,63 @@
|
||||||
# zulip
|
# Lit + Zustand Architecture
|
||||||
|
|
||||||
A modern, no-build web application using Lit web components with Zustand state management.
|
A simple (but modern & scalable) no-build web application architecture using Lit web components with Zustand state management and IndexedDB persistence.
|
||||||
|
|
||||||
|
## For TSX/React Developers
|
||||||
|
|
||||||
|
If you're coming from React/TSX, here's how this architecture maps to familiar concepts:
|
||||||
|
|
||||||
|
| React/TSX Pattern | This Architecture |
|
||||||
|
|-------------------|-------------------|
|
||||||
|
| `useState` / `useReducer` | Zustand vanilla store |
|
||||||
|
| `useEffect` + state subscription | `StoreController` (ReactiveController) |
|
||||||
|
| Context API | Global Zustand store |
|
||||||
|
| `localStorage` / `sessionStorage` | IndexedDB via persist middleware |
|
||||||
|
| JSX | Lit's `html` tagged template literals |
|
||||||
|
| CSS-in-JS / CSS Modules | Lit's `css` tagged template literals |
|
||||||
|
| React Router | Simple route state in store |
|
||||||
|
| Build step (Vite/Webpack) | Import maps (no build!) |
|
||||||
|
|
||||||
|
### Key Differences
|
||||||
|
|
||||||
|
1. **No Virtual DOM**: Lit uses native Web Components with efficient DOM updates
|
||||||
|
2. **No Build Step**: Import maps let you use npm packages directly from CDN
|
||||||
|
3. **Reactive Controllers**: Replace hooks - attach to component lifecycle
|
||||||
|
4. **Tagged Templates**: Instead of JSX, use `html\`<div>...</div>\``
|
||||||
|
|
||||||
## Architecture Overview
|
## Architecture Overview
|
||||||
|
|
||||||
* **Lit-based web components** - Standards-based, framework-agnostic UI
|
* **Lit-based web components** - Standards-based, framework-agnostic UI
|
||||||
* **No-build tooling** - Import maps only, no bundler required
|
* **No-build tooling** - Import maps only, no bundler required
|
||||||
* **Zustand state management** - Lightweight, vanilla JS store
|
* **Zustand state management** - Lightweight, vanilla JS store
|
||||||
* **StoreController** - Reactive controller that bridges Zustand and Lit
|
* **IndexedDB persistence** - Automatic state persistence with idb-keyval
|
||||||
|
|
||||||
## Project Structure
|
|
||||||
|
## Layout
|
||||||
|
|
||||||
```
|
```
|
||||||
components/ -> standard lit components, including top-level "app-root"
|
src/
|
||||||
controllers/ -> lit reactive controllers (such as Zustand<->Lit bridge)
|
store/
|
||||||
store/ -> defines specific accessor sets
|
index.js ← zustand store definition
|
||||||
index.html -> entry point with inline importmap and app-root
|
middleware/
|
||||||
README.md
|
persistence.js ← idb-keyval persist adapter
|
||||||
|
sync.js ← optional cross-tab broadcast
|
||||||
|
components/
|
||||||
|
app-root.js
|
||||||
|
feature-a/
|
||||||
|
feature-a.js ← Lit component
|
||||||
|
feature-a.css ← adopted stylesheet or constructable
|
||||||
|
controllers/
|
||||||
|
fetch.js ← ReactiveController for API calls
|
||||||
|
3d.js ← optional Three/WebGPU controller
|
||||||
|
lib/
|
||||||
|
idb.js ← thin idb-keyval wrapper/schema
|
||||||
|
index.html
|
||||||
|
importmap.json ← extracted importmap (referenced via <script src>)
|
||||||
```
|
```
|
||||||
|
|
||||||
## Data Flow Diagram
|
## Data Flow Diagrams
|
||||||
|
|
||||||
|
### Component-to-Store Pattern
|
||||||
|
|
||||||
```mermaid
|
```mermaid
|
||||||
sequenceDiagram
|
sequenceDiagram
|
||||||
|
|
@ -27,86 +65,116 @@ sequenceDiagram
|
||||||
participant LitComponent
|
participant LitComponent
|
||||||
participant StoreController
|
participant StoreController
|
||||||
participant ZustandStore
|
participant ZustandStore
|
||||||
|
participant IndexedDB
|
||||||
|
|
||||||
User->>LitComponent: Click button
|
User->>LitComponent: Click button
|
||||||
LitComponent->>ZustandStore: Call action (e.g., addItem)
|
LitComponent->>ZustandStore: Call action (e.g., addItem)
|
||||||
ZustandStore->>ZustandStore: Update state
|
ZustandStore->>ZustandStore: Update state
|
||||||
|
ZustandStore->>IndexedDB: Persist (via middleware)
|
||||||
ZustandStore->>StoreController: Notify subscribers
|
ZustandStore->>StoreController: Notify subscribers
|
||||||
StoreController->>LitComponent: requestUpdate()
|
StoreController->>LitComponent: requestUpdate()
|
||||||
LitComponent->>LitComponent: Re-render
|
LitComponent->>LitComponent: Re-render
|
||||||
LitComponent->>User: Show updated UI
|
LitComponent->>User: Show updated UI
|
||||||
```
|
```
|
||||||
|
|
||||||
## Example
|
### Store Subscription Pattern
|
||||||
|
|
||||||
### 1. Define Store (Zustand Vanilla)
|
```mermaid
|
||||||
|
graph TD
|
||||||
|
A[Zustand Store] -->|subscribe| B[StoreController]
|
||||||
|
B -->|selector function| C[Extract specific state]
|
||||||
|
C -->|value changed?| D{Compare}
|
||||||
|
D -->|Yes| E[host.requestUpdate]
|
||||||
|
D -->|No| F[Skip update]
|
||||||
|
E --> G[Lit re-renders component]
|
||||||
|
|
||||||
|
style A fill:#f9f,stroke:#333,stroke-width:2px
|
||||||
|
style B fill:#bbf,stroke:#333,stroke-width:2px
|
||||||
|
style G fill:#bfb,stroke:#333,stroke-width:2px
|
||||||
|
```
|
||||||
|
|
||||||
|
### Complete Mental Model
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────┐
|
||||||
|
│ User Interaction │
|
||||||
|
└──────────────┬──────────────────────────┘
|
||||||
|
│ (events)
|
||||||
|
▼
|
||||||
|
┌─────────────────────────────────────────┐
|
||||||
|
│ Lit Web Components │
|
||||||
|
│ - html`` templates (like JSX) │
|
||||||
|
│ - css`` styles (scoped) │
|
||||||
|
│ - Event handlers │
|
||||||
|
└──────────────┬──────────────────────────┘
|
||||||
|
│ (actions)
|
||||||
|
▼
|
||||||
|
┌─────────────────────────────────────────┐
|
||||||
|
│ StoreController (glue layer) │
|
||||||
|
│ - ReactiveController interface │
|
||||||
|
│ - Subscribes to store │
|
||||||
|
│ - Triggers requestUpdate() │
|
||||||
|
└──────────────┬──────────────────────────┘
|
||||||
|
│ (selector)
|
||||||
|
▼
|
||||||
|
┌─────────────────────────────────────────┐
|
||||||
|
│ Zustand Vanilla Store │
|
||||||
|
│ - Global state (like Context) │
|
||||||
|
│ - Actions (like reducers) │
|
||||||
|
│ - Subscriptions │
|
||||||
|
└──────────────┬──────────────────────────┘
|
||||||
|
│ (persist middleware)
|
||||||
|
▼
|
||||||
|
┌─────────────────────────────────────────┐
|
||||||
|
│ IndexedDB (via idb-keyval) │
|
||||||
|
│ - Automatic persistence │
|
||||||
|
│ - Async storage │
|
||||||
|
└─────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
## Quick Start Example
|
||||||
|
|
||||||
|
### 1. Define Store (like Redux/Zustand)
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
// store/index.js
|
// store/index.js
|
||||||
import { createStore } from 'zustand/vanilla'
|
import { createStore } from 'zustand/vanilla'
|
||||||
|
import { persist } from 'zustand/middleware'
|
||||||
|
|
||||||
export const store = createStore((set, get) => ({
|
export const store = createStore(
|
||||||
count: 0,
|
persist(
|
||||||
increment: () => set(s => ({ count: s.count + 1 })),
|
(set) => ({
|
||||||
decrement: () => set(s => ({ count: s.count - 1 })),
|
count: 0,
|
||||||
}))
|
increment: () => set(s => ({ count: s.count + 1 })),
|
||||||
|
}),
|
||||||
|
{ name: 'my-store' }
|
||||||
|
)
|
||||||
|
)
|
||||||
```
|
```
|
||||||
|
|
||||||
### 2. Create StoreController (Bridge)
|
### 2. Create Component (like React component)
|
||||||
|
|
||||||
```javascript
|
|
||||||
// controllers/store.js
|
|
||||||
export class StoreController {
|
|
||||||
constructor(host, store, selector) {
|
|
||||||
this.host = host
|
|
||||||
this.store = store
|
|
||||||
this.selector = selector
|
|
||||||
host.addController(this)
|
|
||||||
}
|
|
||||||
|
|
||||||
hostConnected() {
|
|
||||||
this._unsub = this.store.subscribe((state) => {
|
|
||||||
const next = this.selector(state)
|
|
||||||
if (next !== this.value) {
|
|
||||||
this.value = next
|
|
||||||
this.host.requestUpdate()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
this.value = this.selector(this.store.getState())
|
|
||||||
}
|
|
||||||
|
|
||||||
hostDisconnected() {
|
|
||||||
this._unsub?.()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### 3. Create Component (Lit + StoreController)
|
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
// components/counter.js
|
// components/counter.js
|
||||||
import { LitElement, html, css } from 'lit'
|
import { LitElement, html, css } from 'lit'
|
||||||
|
import { StoreController } from '../controllers/store.js'
|
||||||
|
import { store } from '../store/index.js'
|
||||||
|
|
||||||
class Counter extends LitElement {
|
class Counter extends LitElement {
|
||||||
static properties = {
|
// Subscribe to store (like useSelector)
|
||||||
count: { type: Number, state: true }
|
#count = new StoreController(this, store, s => s.count)
|
||||||
}
|
|
||||||
|
|
||||||
constructor() {
|
|
||||||
super()
|
|
||||||
this.count = 0
|
|
||||||
}
|
|
||||||
|
|
||||||
static styles = css`
|
static styles = css`
|
||||||
button { padding: 1rem; font-size: 1.2rem; margin: 0.5rem; }
|
button { padding: 1rem; font-size: 1.2rem; }
|
||||||
`
|
`
|
||||||
|
|
||||||
render() {
|
render() {
|
||||||
return html`
|
return html`
|
||||||
<div>
|
<div>
|
||||||
<p>Count: ${this.#count.value}</p>
|
<p>Count: ${this.#count.value}</p>
|
||||||
<button @click=${() => store.getState().decrement()}>-</button>
|
<button @click=${() => store.getState().increment()}>
|
||||||
<button @click=${() => store.getState().increment()}>+</button>
|
Increment
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
`
|
`
|
||||||
}
|
}
|
||||||
|
|
@ -115,32 +183,40 @@ class Counter extends LitElement {
|
||||||
customElements.define('my-counter', Counter)
|
customElements.define('my-counter', Counter)
|
||||||
```
|
```
|
||||||
|
|
||||||
### 4. Instantiate in parent (such as app-root)
|
### 3. Use in HTML (no build step!)
|
||||||
|
|
||||||
```js
|
```html
|
||||||
import counter from "./counter.js":
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
class AppRoot extends LitElement {
|
<head>
|
||||||
render() {
|
<script type="importmap">
|
||||||
return html`
|
{
|
||||||
<counter></counter>
|
"imports": {
|
||||||
`;
|
"lit": "https://esm.sh/lit@3",
|
||||||
|
"zustand/vanilla": "https://esm.sh/zustand@5/vanilla",
|
||||||
|
"zustand/middleware": "https://esm.sh/zustand@5/middleware"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
</script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<script type="module" src="components/counter.js"></script>
|
||||||
|
<my-counter></my-counter>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
```
|
```
|
||||||
|
|
||||||
## Benefits Over TSX
|
## Benefits Over React/TSX
|
||||||
|
|
||||||
1. **No build step** - Edit and refresh, instant feedback
|
✅ **No build step** - Edit and refresh, instant feedback
|
||||||
|
✅ **Smaller bundle** - No framework runtime, just standards
|
||||||
|
✅ **Better encapsulation** - Shadow DOM, scoped styles
|
||||||
|
✅ **Framework agnostic** - Works anywhere, even in React apps
|
||||||
|
✅ **Future-proof** - Built on web standards
|
||||||
|
|
||||||
1. **Smaller bundle** - No framework runtime, just standards
|
## See Also
|
||||||
|
|
||||||
1. **Better encapsulation** - Shadow DOM, scoped styles
|
- [tasks.md](./tasks.md) - Current issues and improvements
|
||||||
|
- [Lit Documentation](https://lit.dev)
|
||||||
1. **Framework agnostic** - Works anywhere, even in React apps
|
- [Zustand Documentation](https://zustand.docs.pmnd.rs)
|
||||||
|
- [Web Components](https://developer.mozilla.org/en-US/docs/Web/Web_Components)
|
||||||
1. **Future-proof** - Built on web standards
|
|
||||||
|
|
||||||
1. **Familiar patterns** - Zustand works like Redux/Context
|
|
||||||
|
|
||||||
1. **Type-safe** - Can add JSDoc or TypeScript without build step
|
|
||||||
|
|
|
||||||
66
TASKS.md
66
TASKS.md
|
|
@ -1,66 +0,0 @@
|
||||||
# Tasks & Issues
|
|
||||||
|
|
||||||
## 1. Critical Issues
|
|
||||||
|
|
||||||
- [x] **1.1 Fix missing `del` import in store/index.js** ✅ COMPLETE
|
|
||||||
- Line 3 now imports `get, set, del` from idb-keyval
|
|
||||||
- Used in removeItem function on line 13
|
|
||||||
- No more ReferenceError
|
|
||||||
|
|
||||||
- [x] **1.2 Fix hydration flag initialization** ✅ COMPLETE
|
|
||||||
- Implemented Option A: Initialize `_hydrated: true` by default
|
|
||||||
- Removed problematic `onRehydrateStorage` callback
|
|
||||||
- App now loads immediately without hanging on "loading..."
|
|
||||||
- Persistence happens in background automatically
|
|
||||||
|
|
||||||
- [x] **1.3 Consolidate duplicate storage implementation** ✅ COMPLETE
|
|
||||||
- Single storage implementation in `store/index.js`
|
|
||||||
- Uses idb-keyval directly with createJSONStorage
|
|
||||||
- Clean, simple approach without extra middleware files
|
|
||||||
|
|
||||||
## 2. Architectural Improvements
|
|
||||||
|
|
||||||
- [x] **2.1 Add error handling** ✅ COMPLETE
|
|
||||||
- Added try/catch blocks around all IndexedDB operations (getItem, setItem, removeItem)
|
|
||||||
- Implemented fallback: returns null on getItem error, silently fails on setItem/removeItem
|
|
||||||
- Added error state to store with auto-clear after 3 seconds
|
|
||||||
- Added validation in addItem and removeItem actions
|
|
||||||
- Created error-toast component with slide-in animation
|
|
||||||
- Toast shows error messages and allows manual dismissal
|
|
||||||
|
|
||||||
- [x] **2.2 Add partialize option to persist middleware** ✅ COMPLETE
|
|
||||||
- Added partialize to exclude `_hydrated` flag from persistence
|
|
||||||
- Only persists: user, items, and route
|
|
||||||
- Prevents unnecessary data in IndexedDB
|
|
||||||
|
|
||||||
- [ ] **2.3 Add basic CSS reset to index.html**
|
|
||||||
- No base styles, margins, or font settings currently
|
|
||||||
- Consider adding minimal reset or normalize.css
|
|
||||||
|
|
||||||
- [ ] **2.4 Add loading states for async operations**
|
|
||||||
- No loading indicators for add/remove item operations
|
|
||||||
- Consider adding optimistic updates
|
|
||||||
|
|
||||||
## 3. Nice to Have
|
|
||||||
|
|
||||||
- [ ] **3.1 Add TypeScript types** (optional)
|
|
||||||
- JSDoc comments for better IDE support
|
|
||||||
- Or migrate to .ts files with no-build setup
|
|
||||||
|
|
||||||
- [ ] **3.2 Add cross-tab synchronization**
|
|
||||||
- README mentions optional `sync.js` middleware
|
|
||||||
- Implement BroadcastChannel for cross-tab state sync
|
|
||||||
|
|
||||||
- [ ] **3.3 Add route history management**
|
|
||||||
- Integrate with browser history API
|
|
||||||
- Support back/forward navigation
|
|
||||||
|
|
||||||
- [ ] **3.4 Add unit tests**
|
|
||||||
- Test store actions and selectors
|
|
||||||
- Test component rendering
|
|
||||||
- Test persistence layer
|
|
||||||
|
|
||||||
- [ ] **3.5 Add Storybook support**
|
|
||||||
- Introduces parallel build (vite internally) but core app remains no-build
|
|
||||||
- Storybook includes raw/native web component support
|
|
||||||
- Ensure individual components and layouts are properly organized, documented, demonstrated, and tested
|
|
||||||
|
|
@ -1,10 +1,9 @@
|
||||||
import { LitElement, html, css } from "lit";
|
import { LitElement, html, css } from "lit";
|
||||||
import { store} from "../store/index.js";
|
import { store} from "../store/index.js";
|
||||||
import { StoreController } from "../controllers/store-controller.js";
|
import { StoreController } from "../controllers/store.js";
|
||||||
import "./nav-bar.js";
|
import "./nav-bar.js";
|
||||||
import "./page-home.js";
|
import "./page-home.js";
|
||||||
import "./page-items.js";
|
import "./page-items.js";
|
||||||
import "./error-toast.js";
|
|
||||||
|
|
||||||
class AppRoot extends LitElement {
|
class AppRoot extends LitElement {
|
||||||
#hydrated = new StoreController(this, store, s => s._hydrated);
|
#hydrated = new StoreController(this, store, s => s._hydrated);
|
||||||
|
|
@ -32,7 +31,6 @@ class AppRoot extends LitElement {
|
||||||
return html`
|
return html`
|
||||||
<nav-bar .user=${this.#user.value}></nav-bar>
|
<nav-bar .user=${this.#user.value}></nav-bar>
|
||||||
<main>${this.#renderRoute()}</main>
|
<main>${this.#renderRoute()}</main>
|
||||||
<error-toast></error-toast>
|
|
||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,79 +0,0 @@
|
||||||
// components/error-toast.js
|
|
||||||
import { LitElement, html, css } from 'lit'
|
|
||||||
import { store } from '../store/index.js'
|
|
||||||
import { StoreController } from '../controllers/store-controller.js'
|
|
||||||
|
|
||||||
class ErrorToast extends LitElement {
|
|
||||||
#error = new StoreController(this, store, s => s.error)
|
|
||||||
|
|
||||||
static styles = css`
|
|
||||||
:host {
|
|
||||||
position: fixed;
|
|
||||||
top: 1rem;
|
|
||||||
right: 1rem;
|
|
||||||
z-index: 1000;
|
|
||||||
}
|
|
||||||
|
|
||||||
.toast {
|
|
||||||
background: #ef4444;
|
|
||||||
color: white;
|
|
||||||
padding: 1rem 1.5rem;
|
|
||||||
border-radius: 8px;
|
|
||||||
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 1rem;
|
|
||||||
min-width: 300px;
|
|
||||||
animation: slideIn 0.3s ease-out;
|
|
||||||
}
|
|
||||||
|
|
||||||
@keyframes slideIn {
|
|
||||||
from {
|
|
||||||
transform: translateX(400px);
|
|
||||||
opacity: 0;
|
|
||||||
}
|
|
||||||
to {
|
|
||||||
transform: translateX(0);
|
|
||||||
opacity: 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.message {
|
|
||||||
flex: 1;
|
|
||||||
font-size: 0.9rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.close {
|
|
||||||
background: none;
|
|
||||||
border: none;
|
|
||||||
color: white;
|
|
||||||
cursor: pointer;
|
|
||||||
font-size: 1.2rem;
|
|
||||||
padding: 0;
|
|
||||||
opacity: 0.8;
|
|
||||||
}
|
|
||||||
|
|
||||||
.close:hover {
|
|
||||||
opacity: 1;
|
|
||||||
}
|
|
||||||
`
|
|
||||||
|
|
||||||
render() {
|
|
||||||
if (!this.#error.value) {
|
|
||||||
return html``
|
|
||||||
}
|
|
||||||
|
|
||||||
return html`
|
|
||||||
<div class="toast">
|
|
||||||
<span class="message">${this.#error.value}</span>
|
|
||||||
<button
|
|
||||||
class="close"
|
|
||||||
@click=${() => store.getState().clearError()}
|
|
||||||
aria-label="Close"
|
|
||||||
>×</button>
|
|
||||||
</div>
|
|
||||||
`
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
customElements.define('error-toast', ErrorToast)
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
// components/nav-bar.js
|
// components/nav-bar.js
|
||||||
import { LitElement, html, css } from 'lit'
|
import { LitElement, html, css } from 'lit'
|
||||||
import { store } from '../store/index.js'
|
import { store } from '../store/index.js'
|
||||||
import { StoreController } from "../controllers/store-controller.js";
|
import { StoreController } from '../controllers/store.js'
|
||||||
|
|
||||||
class NavBar extends LitElement {
|
class NavBar extends LitElement {
|
||||||
#route = new StoreController(this, store, s => s.route)
|
#route = new StoreController(this, store, s => s.route)
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
// components/page-home.js
|
// components/page-home.js
|
||||||
import { LitElement, html, css } from 'lit'
|
import { LitElement, html, css } from 'lit'
|
||||||
import { store } from '../store/index.js'
|
import { store } from '../store/index.js'
|
||||||
import { StoreController } from "../controllers/store-controller.js";
|
import { StoreController } from '../controllers/store.js'
|
||||||
|
|
||||||
class PageHome extends LitElement {
|
class PageHome extends LitElement {
|
||||||
#user = new StoreController(this, store, s => s.user)
|
#user = new StoreController(this, store, s => s.user)
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
// components/page-items.js
|
// components/page-items.js
|
||||||
import { LitElement, html, css } from 'lit'
|
import { LitElement, html, css } from 'lit'
|
||||||
import { store } from '../store/index.js'
|
import { store } from '../store/index.js'
|
||||||
import { StoreController } from "../controllers/store-controller.js";
|
import { StoreController } from '../controllers/store.js'
|
||||||
|
|
||||||
class PageItems extends LitElement {
|
class PageItems extends LitElement {
|
||||||
#items = new StoreController(this, store, s => s.items)
|
#items = new StoreController(this, store, s => s.items)
|
||||||
|
|
|
||||||
|
|
@ -1,86 +1,13 @@
|
||||||
import { createStore } from 'zustand/vanilla'
|
import { createStore } from 'zustand/vanilla'
|
||||||
import { persist, createJSONStorage } from 'zustand/middleware'
|
|
||||||
import { get, set, del } from 'idb-keyval'
|
|
||||||
|
|
||||||
// Create IndexedDB storage adapter with error handling
|
export const store = createStore((set, get) => ({
|
||||||
const storage = createJSONStorage(() => ({
|
user: null,
|
||||||
getItem: async (name) => {
|
items: [],
|
||||||
try {
|
route: 'home',
|
||||||
const value = await get(name)
|
|
||||||
return value ?? null
|
// Actions
|
||||||
} catch (error) {
|
setUser: (user) => set({ user }),
|
||||||
console.error('IndexedDB getItem error:', error)
|
addItem: (item) => set(s => ({ items: [...s.items, item] })),
|
||||||
return null // Fallback to null if IndexedDB fails
|
removeItem: (id) => set(s => ({ items: s.items.filter(i => i.id !== id) })),
|
||||||
}
|
navigate: (route) => set({ route }),
|
||||||
},
|
|
||||||
setItem: async (name, value) => {
|
|
||||||
try {
|
|
||||||
await set(name, value)
|
|
||||||
} catch (error) {
|
|
||||||
console.error('IndexedDB setItem error:', error)
|
|
||||||
// Silently fail - app continues to work without persistence
|
|
||||||
}
|
|
||||||
},
|
|
||||||
removeItem: async (name) => {
|
|
||||||
try {
|
|
||||||
await del(name)
|
|
||||||
} catch (error) {
|
|
||||||
console.error('IndexedDB removeItem error:', error)
|
|
||||||
// Silently fail
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}))
|
}))
|
||||||
|
|
||||||
export const store = createStore(
|
|
||||||
persist(
|
|
||||||
(set, get) => ({
|
|
||||||
_hydrated: true, // Start as true - persistence happens in background
|
|
||||||
user: null,
|
|
||||||
items: [],
|
|
||||||
route: 'home',
|
|
||||||
error: null, // For error notifications
|
|
||||||
|
|
||||||
// Actions
|
|
||||||
setUser: (user) => set({ user }),
|
|
||||||
|
|
||||||
addItem: (item) => {
|
|
||||||
try {
|
|
||||||
if (!item || !item.name || !item.name.trim()) {
|
|
||||||
throw new Error('Item name is required')
|
|
||||||
}
|
|
||||||
set(s => ({ items: [...s.items, item], error: null }))
|
|
||||||
} catch (error) {
|
|
||||||
console.error('addItem error:', error)
|
|
||||||
set({ error: error.message })
|
|
||||||
setTimeout(() => set({ error: null }), 3000) // Clear after 3s
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
removeItem: (id) => {
|
|
||||||
try {
|
|
||||||
if (!id) {
|
|
||||||
throw new Error('Item ID is required')
|
|
||||||
}
|
|
||||||
set(s => ({ items: s.items.filter(i => i.id !== id), error: null }))
|
|
||||||
} catch (error) {
|
|
||||||
console.error('removeItem error:', error)
|
|
||||||
set({ error: error.message })
|
|
||||||
setTimeout(() => set({ error: null }), 3000)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
navigate: (route) => set({ route }),
|
|
||||||
|
|
||||||
clearError: () => set({ error: null }),
|
|
||||||
}),
|
|
||||||
{
|
|
||||||
name: 'app-store',
|
|
||||||
storage,
|
|
||||||
partialize: (state) => ({
|
|
||||||
user: state.user,
|
|
||||||
items: state.items,
|
|
||||||
route: state.route,
|
|
||||||
}),
|
|
||||||
}
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
// store/middleware/persistence.js
|
// store/middleware/persistence.js
|
||||||
import { db } from './idb.js'
|
import { db } from '../idb.js'
|
||||||
|
|
||||||
export const makeIdbStorage = (storeName) =>
|
export const makeIdbStorage = (storeName) =>
|
||||||
createJSONStorage(() => ({
|
createJSONStorage(() => ({
|
||||||
60
tasks.md
Normal file
60
tasks.md
Normal file
|
|
@ -0,0 +1,60 @@
|
||||||
|
# Tasks & Issues
|
||||||
|
|
||||||
|
## 1. Critical Issues
|
||||||
|
|
||||||
|
- [ ] **1.1 Fix missing `del` import in store/index.js**
|
||||||
|
- Line 3 imports `get, set` from idb-keyval but `del` is used on line 13
|
||||||
|
- Add `del` to the import statement
|
||||||
|
- This will cause a ReferenceError when removeItem is called
|
||||||
|
|
||||||
|
- [ ] **1.2 Fix hydration flag initialization**
|
||||||
|
- The `onRehydrateStorage` callback uses `store.setState()` before `store` is fully initialized
|
||||||
|
- Creates a circular reference issue preventing app from loading
|
||||||
|
- **Options:**
|
||||||
|
- A) Initialize `_hydrated: true` by default (simplest)
|
||||||
|
- B) Use Zustand's persist middleware built-in hydration detection
|
||||||
|
- C) Move hydration callback outside store creation
|
||||||
|
|
||||||
|
- [ ] **1.3 Consolidate duplicate storage implementation**
|
||||||
|
- Storage is defined in both `store/index.js` AND `store/middleware/persistence.js`
|
||||||
|
- The middleware file exports `idbStorage` but it's not being used
|
||||||
|
- **Decision needed:** Use one or the other, not both
|
||||||
|
|
||||||
|
## 2. Architectural Improvements
|
||||||
|
|
||||||
|
- [ ] **2.1 Add error handling**
|
||||||
|
- Add try/catch blocks around IndexedDB operations
|
||||||
|
- Implement fallback if IndexedDB fails or is unavailable
|
||||||
|
- Add user feedback for errors (toast notifications?)
|
||||||
|
|
||||||
|
- [ ] **2.2 Add partialize option to persist middleware**
|
||||||
|
- Currently saves ALL state including `_hydrated` flag and `route`
|
||||||
|
- Should use `partialize: (state) => ({ user: state.user, items: state.items })`
|
||||||
|
- Prevents unnecessary data in IndexedDB
|
||||||
|
|
||||||
|
- [ ] **2.3 Add basic CSS reset to index.html**
|
||||||
|
- No base styles, margins, or font settings currently
|
||||||
|
- Consider adding minimal reset or normalize.css
|
||||||
|
|
||||||
|
- [ ] **2.4 Add loading states for async operations**
|
||||||
|
- No loading indicators for add/remove item operations
|
||||||
|
- Consider adding optimistic updates
|
||||||
|
|
||||||
|
## 3. Nice to Have
|
||||||
|
|
||||||
|
- [ ] **3.1 Add TypeScript types** (optional)
|
||||||
|
- JSDoc comments for better IDE support
|
||||||
|
- Or migrate to .ts files with no-build setup
|
||||||
|
|
||||||
|
- [ ] **3.2 Add cross-tab synchronization**
|
||||||
|
- README mentions optional `sync.js` middleware
|
||||||
|
- Implement BroadcastChannel for cross-tab state sync
|
||||||
|
|
||||||
|
- [ ] **3.3 Add route history management**
|
||||||
|
- Integrate with browser history API
|
||||||
|
- Support back/forward navigation
|
||||||
|
|
||||||
|
- [ ] **3.4 Add unit tests**
|
||||||
|
- Test store actions and selectors
|
||||||
|
- Test component rendering
|
||||||
|
- Test persistence layer
|
||||||
Loading…
Add table
Add a link
Reference in a new issue