updated/consolidated lit+zustand
This commit is contained in:
parent
648412dd6d
commit
2178304c76
7 changed files with 83 additions and 307 deletions
224
README.md
224
README.md
|
|
@ -1,63 +1,25 @@
|
|||
# Lit + Zustand Architecture
|
||||
# zulip
|
||||
|
||||
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>\``
|
||||
A modern, no-build web application using Lit web components with Zustand state management.
|
||||
|
||||
## 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
|
||||
* **StoreController** - Reactive controller that bridges Zustand and Lit
|
||||
|
||||
|
||||
## Layout
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
src/
|
||||
store/
|
||||
index.js ← zustand store definition
|
||||
middleware/
|
||||
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>)
|
||||
components/ -> standard lit components, including top-level "app-root"
|
||||
controllers/ -> lit reactive controllers (such as Zustand<->Lit bridge)
|
||||
store/ -> defines specific accessor sets
|
||||
index.html -> entry point with inline importmap and app-root
|
||||
README.md
|
||||
```
|
||||
|
||||
## Data Flow Diagrams
|
||||
|
||||
### Component-to-Store Pattern
|
||||
## Data Flow Diagram
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
|
|
@ -65,94 +27,61 @@ sequenceDiagram
|
|||
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
|
||||
```
|
||||
|
||||
### Store Subscription Pattern
|
||||
## Example
|
||||
|
||||
```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)
|
||||
### 1. Define Store (Zustand Vanilla)
|
||||
|
||||
```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' }
|
||||
)
|
||||
)
|
||||
export const store = createStore((set, get) => ({
|
||||
count: 0,
|
||||
increment: () => set(s => ({ count: s.count + 1 })),
|
||||
decrement: () => set(s => ({ count: s.count - 1 })),
|
||||
}))
|
||||
```
|
||||
|
||||
### 2. Create Component (like React component)
|
||||
### 2. Create StoreController (Bridge)
|
||||
|
||||
```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
|
||||
// components/counter.js
|
||||
|
|
@ -165,16 +94,15 @@ class Counter extends LitElement {
|
|||
#count = new StoreController(this, store, s => s.count)
|
||||
|
||||
static styles = css`
|
||||
button { padding: 1rem; font-size: 1.2rem; }
|
||||
button { padding: 1rem; font-size: 1.2rem; margin: 0.5rem; }
|
||||
`
|
||||
|
||||
render() {
|
||||
return html`
|
||||
<div>
|
||||
<p>Count: ${this.#count.value}</p>
|
||||
<button @click=${() => store.getState().increment()}>
|
||||
Increment
|
||||
</button>
|
||||
<button @click=${() => store.getState().decrement()}>-</button>
|
||||
<button @click=${() => store.getState().increment()}>+</button>
|
||||
</div>
|
||||
`
|
||||
}
|
||||
|
|
@ -183,40 +111,32 @@ class Counter extends LitElement {
|
|||
customElements.define('my-counter', Counter)
|
||||
```
|
||||
|
||||
### 3. Use in HTML (no build step!)
|
||||
### 4. Instantiate in parent (such as app-root)
|
||||
|
||||
```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"
|
||||
}
|
||||
```js
|
||||
import counter from "./counter.js":
|
||||
|
||||
class AppRoot extends LitElement {
|
||||
render() {
|
||||
return html`
|
||||
<counter></counter>
|
||||
`;
|
||||
}
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<script type="module" src="components/counter.js"></script>
|
||||
<my-counter></my-counter>
|
||||
</body>
|
||||
</html>
|
||||
}
|
||||
```
|
||||
|
||||
## Benefits Over React/TSX
|
||||
## Benefits Over 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
|
||||
1. **No build step** - Edit and refresh, instant feedback
|
||||
|
||||
## See Also
|
||||
1. **Smaller bundle** - No framework runtime, just standards
|
||||
|
||||
- [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. **Better encapsulation** - Shadow DOM, scoped styles
|
||||
|
||||
1. **Framework agnostic** - Works anywhere, even in React apps
|
||||
|
||||
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
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue