cleanup
This commit is contained in:
parent
4e612cb224
commit
28d57323b6
6 changed files with 316 additions and 35 deletions
207
README.md
207
README.md
|
|
@ -1,10 +1,36 @@
|
|||
## Architecture
|
||||
# Lit + Zustand Architecture
|
||||
|
||||
* Lit-based web components
|
||||
A modern, no-build web application architecture using Lit web components with Zustand state management and IndexedDB persistence.
|
||||
|
||||
* No-build tooling (importmap only)
|
||||
## 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
|
||||
|
||||
* **Lit-based web components** - Standards-based, framework-agnostic UI
|
||||
* **No-build tooling** - Import maps only, no bundler required
|
||||
* **Zustand state management** - Lightweight, vanilla JS store
|
||||
* **IndexedDB persistence** - Automatic state persistence with idb-keyval
|
||||
|
||||
* Zustand-moderated state management with IndexedDB storage mechanism
|
||||
|
||||
## Layout
|
||||
|
||||
|
|
@ -29,15 +55,168 @@ index.html
|
|||
importmap.json ← extracted importmap (referenced via <script src>)
|
||||
```
|
||||
|
||||
## The Complete Mental Model
|
||||
## Data Flow Diagrams
|
||||
|
||||
### Component-to-Store Pattern
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant User
|
||||
participant LitComponent
|
||||
participant StoreController
|
||||
participant ZustandStore
|
||||
participant IndexedDB
|
||||
|
||||
User->>LitComponent: Click button
|
||||
LitComponent->>ZustandStore: Call action (e.g., addItem)
|
||||
ZustandStore->>ZustandStore: Update state
|
||||
ZustandStore->>IndexedDB: Persist (via middleware)
|
||||
ZustandStore->>StoreController: Notify subscribers
|
||||
StoreController->>LitComponent: requestUpdate()
|
||||
LitComponent->>LitComponent: Re-render
|
||||
LitComponent->>User: Show updated UI
|
||||
```
|
||||
IndexedDB
|
||||
↕ (idb-keyval adapter)
|
||||
Zustand persist middleware
|
||||
↕ (vanilla store)
|
||||
StoreController (ReactiveController)
|
||||
↕ (requestUpdate → selector)
|
||||
Lit Web Components
|
||||
↕ (events / store actions)
|
||||
User
|
||||
|
||||
### Store Subscription Pattern
|
||||
|
||||
```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
|
||||
// store/index.js
|
||||
import { createStore } from 'zustand/vanilla'
|
||||
import { persist } from 'zustand/middleware'
|
||||
|
||||
export const store = createStore(
|
||||
persist(
|
||||
(set) => ({
|
||||
count: 0,
|
||||
increment: () => set(s => ({ count: s.count + 1 })),
|
||||
}),
|
||||
{ name: 'my-store' }
|
||||
)
|
||||
)
|
||||
```
|
||||
|
||||
### 2. Create Component (like React component)
|
||||
|
||||
```javascript
|
||||
// components/counter.js
|
||||
import { LitElement, html, css } from 'lit'
|
||||
import { StoreController } from '../controllers/store.js'
|
||||
import { store } from '../store/index.js'
|
||||
|
||||
class Counter extends LitElement {
|
||||
// Subscribe to store (like useSelector)
|
||||
#count = new StoreController(this, store, s => s.count)
|
||||
|
||||
static styles = css`
|
||||
button { padding: 1rem; font-size: 1.2rem; }
|
||||
`
|
||||
|
||||
render() {
|
||||
return html`
|
||||
<div>
|
||||
<p>Count: ${this.#count.value}</p>
|
||||
<button @click=${() => store.getState().increment()}>
|
||||
Increment
|
||||
</button>
|
||||
</div>
|
||||
`
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('my-counter', Counter)
|
||||
```
|
||||
|
||||
### 3. Use in HTML (no build step!)
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<script type="importmap">
|
||||
{
|
||||
"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 React/TSX
|
||||
|
||||
✅ **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
|
||||
|
||||
## See Also
|
||||
|
||||
- [tasks.md](./tasks.md) - Current issues and improvements
|
||||
- [Lit Documentation](https://lit.dev)
|
||||
- [Zustand Documentation](https://zustand.docs.pmnd.rs)
|
||||
- [Web Components](https://developer.mozilla.org/en-US/docs/Web/Web_Components)
|
||||
|
|
|
|||
|
|
@ -1,9 +0,0 @@
|
|||
{
|
||||
"imports": {
|
||||
"lit": "https://esm.sh/lit@3",
|
||||
"lit/decorators.js": "https://esm.sh/lit@3/decorators.js",
|
||||
"zustand": "https://esm.sh/zustand@5/vanilla",
|
||||
"zustand/middleware": "https://esm.sh/zustand@5/middleware",
|
||||
"idb-keyval": "https://esm.sh/idb-keyval@6"
|
||||
}
|
||||
}
|
||||
33
store/idb.js
Normal file
33
store/idb.js
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
// lib/idb.js
|
||||
import { createStore, get, set, del, entries, clear } from 'idb-keyval'
|
||||
|
||||
// Named stores — each maps to a distinct IDBObjectStore
|
||||
export const itemsStore = createStore('app-db', 'items')
|
||||
export const userStore = createStore('app-db', 'user')
|
||||
export const cacheStore = createStore('app-db', 'cache')
|
||||
|
||||
// Typed wrappers — keeps raw idb-keyval calls out of the rest of the app
|
||||
// and gives you one place to add validation, logging, or migration logic
|
||||
|
||||
export const db = {
|
||||
items: {
|
||||
getAll: () => entries(itemsStore),
|
||||
get: (id) => get(id, itemsStore),
|
||||
set: (id, value) => set(id, value, itemsStore),
|
||||
remove: (id) => del(id, itemsStore),
|
||||
clear: () => clear(itemsStore),
|
||||
},
|
||||
|
||||
user: {
|
||||
get: () => get('user', userStore),
|
||||
set: (value) => set('user', value, userStore),
|
||||
clear: () => del('user', userStore),
|
||||
},
|
||||
|
||||
cache: {
|
||||
get: (key) => get(key, cacheStore),
|
||||
set: (key, value) => set(key, value, cacheStore),
|
||||
remove: (key) => del(key, cacheStore),
|
||||
clear: () => clear(cacheStore),
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +1,19 @@
|
|||
import { createStore } from 'zustand/vanilla'
|
||||
import { persist } from 'zustand/middleware'
|
||||
import { idbStorage } from './middleware/persistence.js'
|
||||
import { persist, createJSONStorage } from 'zustand/middleware'
|
||||
import { get, set } from 'idb-keyval'
|
||||
|
||||
const storage = createJSONStorage(() => ({
|
||||
getItem: async (name) => {
|
||||
const value = await get(name)
|
||||
return value ?? null
|
||||
},
|
||||
setItem: async (name, value) => {
|
||||
await set(name, value)
|
||||
},
|
||||
removeItem: async (name) => {
|
||||
await del(name)
|
||||
},
|
||||
}))
|
||||
|
||||
export const store = createStore(
|
||||
persist(
|
||||
|
|
@ -16,9 +29,13 @@ export const store = createStore(
|
|||
}),
|
||||
{
|
||||
name: 'app-store',
|
||||
storage: idbStorage,
|
||||
onRehydrateStorage: () => (state) => {
|
||||
if (state) state._hydrated = true
|
||||
storage,
|
||||
onRehydrateStorage: () => {
|
||||
return (state, error) => {
|
||||
if (!error) {
|
||||
store.setState({ _hydrated: true })
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,8 +1,9 @@
|
|||
import { get, set, del } from 'idb-keyval'
|
||||
import { createJSONStorage } from 'zustand/middleware'
|
||||
// store/middleware/persistence.js
|
||||
import { db } from '../idb.js'
|
||||
|
||||
export const idbStorage = createJSONStorage(() => ({
|
||||
getItem: (name) => get(name),
|
||||
setItem: (name, value) => set(name, value),
|
||||
removeItem: (name) => del(name),
|
||||
export const makeIdbStorage = (storeName) =>
|
||||
createJSONStorage(() => ({
|
||||
getItem: (name) => db[storeName].get(name),
|
||||
setItem: (name, value) => db[storeName].set(name, value),
|
||||
removeItem: (name) => db[storeName].remove(name),
|
||||
}))
|
||||
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