finished pruning for lit-only demo
This commit is contained in:
parent
648412dd6d
commit
3736d7278b
10 changed files with 217 additions and 281 deletions
266
README.md
266
README.md
|
|
@ -1,168 +1,113 @@
|
||||||
# Lit + Zustand Architecture
|
# Lit-Only Architecture (No Build)
|
||||||
|
|
||||||
A simple (but modern & scalable) no-build web application architecture using Lit web components with Zustand state management and IndexedDB persistence.
|
A minimal, no-build web application using only Lit web components with local state management.
|
||||||
|
|
||||||
|
> **Note:** This is the `lit-only` branch. For the full-featured version with Zustand state management and IndexedDB persistence, see the `main` branch.
|
||||||
|
|
||||||
## For TSX/React Developers
|
## For TSX/React Developers
|
||||||
|
|
||||||
If you're coming from React/TSX, here's how this architecture maps to familiar concepts:
|
If you're coming from React/TSX, here's how this minimal architecture maps to familiar concepts:
|
||||||
|
|
||||||
| React/TSX Pattern | This Architecture |
|
| React/TSX Pattern | This Architecture |
|
||||||
|-------------------|-------------------|
|
|-------------------|-------------------|
|
||||||
| `useState` / `useReducer` | Zustand vanilla store |
|
| `useState` | Lit's `static properties` with `state: true` |
|
||||||
| `useEffect` + state subscription | `StoreController` (ReactiveController) |
|
| Props drilling | Property passing via `.prop=${value}` |
|
||||||
| Context API | Global Zustand store |
|
| Custom events | `CustomEvent` with `bubbles: true` |
|
||||||
| `localStorage` / `sessionStorage` | IndexedDB via persist middleware |
|
|
||||||
| JSX | Lit's `html` tagged template literals |
|
| JSX | Lit's `html` tagged template literals |
|
||||||
| CSS-in-JS / CSS Modules | Lit's `css` tagged template literals |
|
| CSS-in-JS / CSS Modules | Lit's `css` tagged template literals |
|
||||||
| React Router | Simple route state in store |
|
| React Router | Simple route state in root component |
|
||||||
| Build step (Vite/Webpack) | Import maps (no build!) |
|
| Build step (Vite/Webpack) | Import maps (no build!) |
|
||||||
|
|
||||||
### Key Differences
|
### Key Differences
|
||||||
|
|
||||||
1. **No Virtual DOM**: Lit uses native Web Components with efficient DOM updates
|
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
|
2. **No Build Step**: Import maps let you use npm packages directly from CDN
|
||||||
3. **Reactive Controllers**: Replace hooks - attach to component lifecycle
|
3. **Local State Only**: Each component manages its own state, parent manages shared state
|
||||||
4. **Tagged Templates**: Instead of JSX, use `html\`<div>...</div>\``
|
4. **Event-Based Communication**: Child components emit events, parent handles them
|
||||||
|
5. **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
|
* **Local state management** - Component properties and state
|
||||||
* **IndexedDB persistence** - Automatic state persistence with idb-keyval
|
* **Event-driven** - CustomEvents for child-to-parent communication
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
## Layout
|
|
||||||
|
|
||||||
```
|
```
|
||||||
src/
|
components/
|
||||||
store/
|
app-root.js ← Root component with shared state
|
||||||
index.js ← zustand store definition
|
nav-bar.js ← Navigation component
|
||||||
middleware/
|
page-home.js ← Home page component
|
||||||
persistence.js ← idb-keyval persist adapter
|
page-items.js ← Items page component
|
||||||
sync.js ← optional cross-tab broadcast
|
index.html ← Entry point with inline importmap
|
||||||
components/
|
README.md
|
||||||
app-root.js
|
tasks.md
|
||||||
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 Diagrams
|
## Data Flow Pattern
|
||||||
|
|
||||||
### Component-to-Store Pattern
|
### Parent-to-Child (Props)
|
||||||
|
|
||||||
```mermaid
|
```javascript
|
||||||
sequenceDiagram
|
// Parent passes data down
|
||||||
participant User
|
html`<child-component .items=${this.items}></child-component>`
|
||||||
participant LitComponent
|
|
||||||
participant StoreController
|
|
||||||
participant ZustandStore
|
|
||||||
participant IndexedDB
|
|
||||||
|
|
||||||
User->>LitComponent: Click button
|
// Child receives via properties
|
||||||
LitComponent->>ZustandStore: Call action (e.g., addItem)
|
static properties = {
|
||||||
ZustandStore->>ZustandStore: Update state
|
items: { type: Array }
|
||||||
ZustandStore->>IndexedDB: Persist (via middleware)
|
}
|
||||||
ZustandStore->>StoreController: Notify subscribers
|
|
||||||
StoreController->>LitComponent: requestUpdate()
|
|
||||||
LitComponent->>LitComponent: Re-render
|
|
||||||
LitComponent->>User: Show updated UI
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Store Subscription Pattern
|
### Child-to-Parent (Events)
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
// Child emits event
|
||||||
|
this.dispatchEvent(new CustomEvent('add-item', {
|
||||||
|
detail: { item: newItem },
|
||||||
|
bubbles: true,
|
||||||
|
composed: true
|
||||||
|
}))
|
||||||
|
|
||||||
|
// Parent listens
|
||||||
|
html`<child-component @add-item=${(e) => this.handleAdd(e.detail.item)}></child-component>`
|
||||||
|
```
|
||||||
|
|
||||||
|
## State Management Pattern
|
||||||
|
|
||||||
```mermaid
|
```mermaid
|
||||||
graph TD
|
graph TD
|
||||||
A[Zustand Store] -->|subscribe| B[StoreController]
|
A[app-root] -->|.user, .items, .route| B[nav-bar]
|
||||||
B -->|selector function| C[Extract specific state]
|
A -->|.user, .items| C[page-home]
|
||||||
C -->|value changed?| D{Compare}
|
A -->|.items| D[page-items]
|
||||||
D -->|Yes| E[host.requestUpdate]
|
B -->|@navigate event| A
|
||||||
D -->|No| F[Skip update]
|
D -->|@add-item event| A
|
||||||
E --> G[Lit re-renders component]
|
D -->|@remove-item event| A
|
||||||
|
|
||||||
style A fill:#f9f,stroke:#333,stroke-width:2px
|
style A fill:#f9f,stroke:#333,stroke-width:2px
|
||||||
style B fill:#bbf,stroke:#333,stroke-width:2px
|
style B fill:#bbf,stroke:#333,stroke-width:2px
|
||||||
style G fill:#bfb,stroke:#333,stroke-width:2px
|
style C fill:#bfb,stroke:#333,stroke-width:2px
|
||||||
```
|
style D 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
|
## Quick Start Example
|
||||||
|
|
||||||
### 1. Define Store (like Redux/Zustand)
|
### 1. Define a Component
|
||||||
|
|
||||||
```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
|
```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 {
|
||||||
// Subscribe to store (like useSelector)
|
static properties = {
|
||||||
#count = new StoreController(this, store, s => s.count)
|
count: { type: Number, state: true }
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
super()
|
||||||
|
this.count = 0
|
||||||
|
}
|
||||||
|
|
||||||
static styles = css`
|
static styles = css`
|
||||||
button { padding: 1rem; font-size: 1.2rem; }
|
button { padding: 1rem; font-size: 1.2rem; }
|
||||||
|
|
@ -171,8 +116,8 @@ class Counter extends LitElement {
|
||||||
render() {
|
render() {
|
||||||
return html`
|
return html`
|
||||||
<div>
|
<div>
|
||||||
<p>Count: ${this.#count.value}</p>
|
<p>Count: ${this.count}</p>
|
||||||
<button @click=${() => store.getState().increment()}>
|
<button @click=${() => this.count++}>
|
||||||
Increment
|
Increment
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -183,7 +128,7 @@ class Counter extends LitElement {
|
||||||
customElements.define('my-counter', Counter)
|
customElements.define('my-counter', Counter)
|
||||||
```
|
```
|
||||||
|
|
||||||
### 3. Use in HTML (no build step!)
|
### 2. Use in HTML (no build step!)
|
||||||
|
|
||||||
```html
|
```html
|
||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
|
|
@ -192,9 +137,7 @@ customElements.define('my-counter', Counter)
|
||||||
<script type="importmap">
|
<script type="importmap">
|
||||||
{
|
{
|
||||||
"imports": {
|
"imports": {
|
||||||
"lit": "https://esm.sh/lit@3",
|
"lit": "https://esm.sh/lit@3"
|
||||||
"zustand/vanilla": "https://esm.sh/zustand@5/vanilla",
|
|
||||||
"zustand/middleware": "https://esm.sh/zustand@5/middleware"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
@ -206,17 +149,88 @@ customElements.define('my-counter', Counter)
|
||||||
</html>
|
</html>
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Component Communication Patterns
|
||||||
|
|
||||||
|
### Pattern 1: Shared State in Root
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
class AppRoot extends LitElement {
|
||||||
|
static properties = {
|
||||||
|
items: { type: Array, state: true }
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
super()
|
||||||
|
this.items = []
|
||||||
|
}
|
||||||
|
|
||||||
|
addItem(item) {
|
||||||
|
this.items = [...this.items, item]
|
||||||
|
}
|
||||||
|
|
||||||
|
render() {
|
||||||
|
return html`
|
||||||
|
<child-component
|
||||||
|
.items=${this.items}
|
||||||
|
@add=${(e) => this.addItem(e.detail.item)}
|
||||||
|
></child-component>
|
||||||
|
`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Pattern 2: Local State in Component
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
class MyComponent extends LitElement {
|
||||||
|
static properties = {
|
||||||
|
_draft: { type: String, state: true }
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
super()
|
||||||
|
this._draft = ''
|
||||||
|
}
|
||||||
|
|
||||||
|
render() {
|
||||||
|
return html`
|
||||||
|
<input
|
||||||
|
.value=${this._draft}
|
||||||
|
@input=${e => this._draft = e.target.value}
|
||||||
|
/>
|
||||||
|
`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
## Benefits Over React/TSX
|
## Benefits Over React/TSX
|
||||||
|
|
||||||
✅ **No build step** - Edit and refresh, instant feedback
|
✅ **No build step** - Edit and refresh, instant feedback
|
||||||
|
✅ **Minimal dependencies** - Just Lit, nothing else
|
||||||
✅ **Smaller bundle** - No framework runtime, just standards
|
✅ **Smaller bundle** - No framework runtime, just standards
|
||||||
✅ **Better encapsulation** - Shadow DOM, scoped styles
|
✅ **Better encapsulation** - Shadow DOM, scoped styles
|
||||||
✅ **Framework agnostic** - Works anywhere, even in React apps
|
✅ **Framework agnostic** - Works anywhere, even in React apps
|
||||||
✅ **Future-proof** - Built on web standards
|
✅ **Future-proof** - Built on web standards
|
||||||
|
✅ **Easy to learn** - Simple mental model, no complex state management
|
||||||
|
|
||||||
|
## When to Use This vs. Full Stack
|
||||||
|
|
||||||
|
### Use Lit-Only When:
|
||||||
|
- Building small to medium apps
|
||||||
|
- Don't need persistence
|
||||||
|
- State is simple and hierarchical
|
||||||
|
- Want maximum simplicity
|
||||||
|
|
||||||
|
### Use Full Stack (main branch) When:
|
||||||
|
- Need IndexedDB persistence
|
||||||
|
- Complex state shared across many components
|
||||||
|
- Need cross-tab synchronization
|
||||||
|
- Want time-travel debugging
|
||||||
|
- Building larger applications
|
||||||
|
|
||||||
## See Also
|
## See Also
|
||||||
|
|
||||||
- [tasks.md](./tasks.md) - Current issues and improvements
|
- [tasks.md](./tasks.md) - Current issues and improvements
|
||||||
- [Lit Documentation](https://lit.dev)
|
- [Lit Documentation](https://lit.dev)
|
||||||
- [Zustand Documentation](https://zustand.docs.pmnd.rs)
|
|
||||||
- [Web Components](https://developer.mozilla.org/en-US/docs/Web/Web_Components)
|
- [Web Components](https://developer.mozilla.org/en-US/docs/Web/Web_Components)
|
||||||
|
- [Import Maps](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script/type/importmap)
|
||||||
|
|
|
||||||
|
|
@ -1,44 +1,64 @@
|
||||||
import { LitElement, html, css } from "lit";
|
import { LitElement, html, css } from "lit";
|
||||||
import { store} from "../store/index.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";
|
||||||
|
|
||||||
class AppRoot extends LitElement {
|
class AppRoot extends LitElement {
|
||||||
#hydrated = new StoreController(this, store, s => s._hydrated);
|
static properties = {
|
||||||
#user = new StoreController(this, store, s => s.user);
|
user: { type: Object, state: true },
|
||||||
#route = new StoreController(this, store, s => s.route);
|
route: { type: String, state: true },
|
||||||
|
items: { type: Array, state: true }
|
||||||
|
};
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
super();
|
||||||
|
this.user = null;
|
||||||
|
this.route = 'home';
|
||||||
|
this.items = [];
|
||||||
|
}
|
||||||
|
|
||||||
static styles = css`
|
static styles = css`
|
||||||
:host {
|
:host {
|
||||||
display: block;
|
display: block;
|
||||||
min-height: 100vh;
|
min-height: 100vh;
|
||||||
}
|
}
|
||||||
|
|
||||||
.loading {
|
|
||||||
display: grid;
|
|
||||||
place-items: center;
|
|
||||||
height: 100vh;
|
|
||||||
opacity: 0.4;
|
|
||||||
}
|
|
||||||
`;
|
`;
|
||||||
|
|
||||||
|
#navigate(route) {
|
||||||
|
this.route = route;
|
||||||
|
}
|
||||||
|
|
||||||
|
#addItem(item) {
|
||||||
|
this.items = [...this.items, item];
|
||||||
|
}
|
||||||
|
|
||||||
|
#removeItem(id) {
|
||||||
|
this.items = this.items.filter(i => i.id !== id);
|
||||||
|
}
|
||||||
|
|
||||||
render() {
|
render() {
|
||||||
if (!this.#hydrated.value) {
|
|
||||||
return html`<div class="loading">loading...</div>`;
|
|
||||||
}
|
|
||||||
return html`
|
return html`
|
||||||
<nav-bar .user=${this.#user.value}></nav-bar>
|
<nav-bar
|
||||||
|
.user=${this.user}
|
||||||
|
.route=${this.route}
|
||||||
|
@navigate=${(e) => this.#navigate(e.detail.route)}
|
||||||
|
></nav-bar>
|
||||||
<main>${this.#renderRoute()}</main>
|
<main>${this.#renderRoute()}</main>
|
||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
|
|
||||||
#renderRoute() {
|
#renderRoute() {
|
||||||
switch (this.#route.value) {
|
switch (this.route) {
|
||||||
case "home": return html`<page-home></page-home>`;
|
case "home":
|
||||||
case "items": return html`<page-items></page-items>`;
|
return html`<page-home .user=${this.user} .items=${this.items}></page-home>`;
|
||||||
default: return html`<page-home></page-home>`;
|
case "items":
|
||||||
|
return html`<page-items
|
||||||
|
.items=${this.items}
|
||||||
|
@add-item=${(e) => this.#addItem(e.detail.item)}
|
||||||
|
@remove-item=${(e) => this.#removeItem(e.detail.id)}
|
||||||
|
></page-items>`;
|
||||||
|
default:
|
||||||
|
return html`<page-home .user=${this.user} .items=${this.items}></page-home>`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,10 @@
|
||||||
// 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 { StoreController } from '../controllers/store.js'
|
|
||||||
|
|
||||||
class NavBar extends LitElement {
|
class NavBar extends LitElement {
|
||||||
#route = new StoreController(this, store, s => s.route)
|
|
||||||
|
|
||||||
static properties = {
|
static properties = {
|
||||||
user: { type: Object }
|
user: { type: Object },
|
||||||
|
route: { type: String }
|
||||||
}
|
}
|
||||||
|
|
||||||
static styles = css`
|
static styles = css`
|
||||||
|
|
@ -35,14 +32,18 @@ class NavBar extends LitElement {
|
||||||
|
|
||||||
#navigate(route, e) {
|
#navigate(route, e) {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
store.getState().navigate(route)
|
this.dispatchEvent(new CustomEvent('navigate', {
|
||||||
|
detail: { route },
|
||||||
|
bubbles: true,
|
||||||
|
composed: true
|
||||||
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
#link(route, label) {
|
#link(route, label) {
|
||||||
return html`
|
return html`
|
||||||
<a
|
<a
|
||||||
href="/${route}"
|
href="/${route}"
|
||||||
?active=${this.#route.value === route}
|
?active=${this.route === route}
|
||||||
@click=${(e) => this.#navigate(route, e)}
|
@click=${(e) => this.#navigate(route, e)}
|
||||||
>${label}</a>
|
>${label}</a>
|
||||||
`
|
`
|
||||||
|
|
@ -61,4 +62,4 @@ class NavBar extends LitElement {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
customElements.define('nav-bar', NavBar)
|
customElements.define('nav-bar', NavBar)
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,11 @@
|
||||||
// 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 { StoreController } from '../controllers/store.js'
|
|
||||||
|
|
||||||
class PageHome extends LitElement {
|
class PageHome extends LitElement {
|
||||||
#user = new StoreController(this, store, s => s.user)
|
static properties = {
|
||||||
#items = new StoreController(this, store, s => s.items)
|
user: { type: Object },
|
||||||
|
items: { type: Array }
|
||||||
|
}
|
||||||
|
|
||||||
static styles = css`
|
static styles = css`
|
||||||
:host { display: block; padding: 2rem 1.5rem; }
|
:host { display: block; padding: 2rem 1.5rem; }
|
||||||
|
|
@ -25,8 +25,8 @@ class PageHome extends LitElement {
|
||||||
`
|
`
|
||||||
|
|
||||||
render() {
|
render() {
|
||||||
const name = this.#user.value?.name ?? 'there'
|
const name = this.user?.name ?? 'there'
|
||||||
const count = this.#items.value.length
|
const count = this.items?.length ?? 0
|
||||||
|
|
||||||
return html`
|
return html`
|
||||||
<h1>Hey, ${name}</h1>
|
<h1>Hey, ${name}</h1>
|
||||||
|
|
@ -41,4 +41,4 @@ class PageHome extends LitElement {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
customElements.define('page-home', PageHome)
|
customElements.define('page-home', PageHome)
|
||||||
|
|
|
||||||
|
|
@ -1,16 +1,17 @@
|
||||||
// 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 { StoreController } from '../controllers/store.js'
|
|
||||||
|
|
||||||
class PageItems extends LitElement {
|
class PageItems extends LitElement {
|
||||||
#items = new StoreController(this, store, s => s.items)
|
|
||||||
|
|
||||||
static properties = {
|
static properties = {
|
||||||
|
items: { type: Array },
|
||||||
_draft: { type: String, state: true }
|
_draft: { type: String, state: true }
|
||||||
}
|
}
|
||||||
|
|
||||||
_draft = ''
|
constructor() {
|
||||||
|
super();
|
||||||
|
this.items = [];
|
||||||
|
this._draft = '';
|
||||||
|
}
|
||||||
|
|
||||||
static styles = css`
|
static styles = css`
|
||||||
:host { display: block; padding: 2rem 1.5rem; }
|
:host { display: block; padding: 2rem 1.5rem; }
|
||||||
|
|
@ -63,12 +64,22 @@ class PageItems extends LitElement {
|
||||||
#add() {
|
#add() {
|
||||||
const name = this._draft.trim()
|
const name = this._draft.trim()
|
||||||
if (!name) return
|
if (!name) return
|
||||||
store.getState().addItem({ id: crypto.randomUUID(), name })
|
|
||||||
|
this.dispatchEvent(new CustomEvent('add-item', {
|
||||||
|
detail: { item: { id: crypto.randomUUID(), name } },
|
||||||
|
bubbles: true,
|
||||||
|
composed: true
|
||||||
|
}))
|
||||||
|
|
||||||
this._draft = ''
|
this._draft = ''
|
||||||
}
|
}
|
||||||
|
|
||||||
#remove(id) {
|
#remove(id) {
|
||||||
store.getState().removeItem(id)
|
this.dispatchEvent(new CustomEvent('remove-item', {
|
||||||
|
detail: { id },
|
||||||
|
bubbles: true,
|
||||||
|
composed: true
|
||||||
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
#onKeydown(e) {
|
#onKeydown(e) {
|
||||||
|
|
@ -76,7 +87,7 @@ class PageItems extends LitElement {
|
||||||
}
|
}
|
||||||
|
|
||||||
render() {
|
render() {
|
||||||
const items = this.#items.value
|
const items = this.items ?? []
|
||||||
|
|
||||||
return html`
|
return html`
|
||||||
<h1>Items</h1>
|
<h1>Items</h1>
|
||||||
|
|
@ -108,4 +119,4 @@ class PageItems extends LitElement {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
customElements.define('page-items', PageItems)
|
customElements.define('page-items', PageItems)
|
||||||
|
|
|
||||||
|
|
@ -1,23 +0,0 @@
|
||||||
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?.() }
|
|
||||||
}
|
|
||||||
|
|
@ -8,10 +8,7 @@
|
||||||
{
|
{
|
||||||
"imports": {
|
"imports": {
|
||||||
"lit": "https://esm.sh/lit@3",
|
"lit": "https://esm.sh/lit@3",
|
||||||
"lit/decorators.js": "https://esm.sh/lit@3/decorators.js",
|
"lit/decorators.js": "https://esm.sh/lit@3/decorators.js"
|
||||||
"zustand/vanilla": "https://esm.sh/zustand@5/vanilla",
|
|
||||||
"zustand/middleware": "https://esm.sh/zustand@5/middleware",
|
|
||||||
"idb-keyval": "https://esm.sh/idb-keyval@6"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
|
||||||
33
store/idb.js
33
store/idb.js
|
|
@ -1,33 +0,0 @@
|
||||||
// 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,42 +0,0 @@
|
||||||
import { createStore } from 'zustand/vanilla'
|
|
||||||
import { persist, createJSONStorage } from 'zustand/middleware'
|
|
||||||
import { get, set, del } 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(
|
|
||||||
(set, get) => ({
|
|
||||||
_hydrated: false,
|
|
||||||
user: null,
|
|
||||||
items: [],
|
|
||||||
route: 'home',
|
|
||||||
setUser: (user) => set({ user }),
|
|
||||||
addItem: (item) => set(s => ({ items: [...s.items, item] })),
|
|
||||||
removeItem: (id) => set(s => ({ items: s.items.filter(i => i.id !== id) })),
|
|
||||||
navigate: (route) => set({ route }),
|
|
||||||
}),
|
|
||||||
{
|
|
||||||
name: 'app-store',
|
|
||||||
storage,
|
|
||||||
onRehydrateStorage: () => {
|
|
||||||
return (state, error) => {
|
|
||||||
if (!error) {
|
|
||||||
store.setState({ _hydrated: true })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
@ -1,9 +0,0 @@
|
||||||
// store/middleware/persistence.js
|
|
||||||
import { db } from '../idb.js'
|
|
||||||
|
|
||||||
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),
|
|
||||||
}))
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue