@hidemikimura/vanji 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +245 -2
- package/compiler/ast.js +48 -0
- package/compiler/index.d.ts +21 -0
- package/compiler/index.js +155 -0
- package/compiler/list.js +163 -0
- package/compiler/parse-html.js +278 -0
- package/compiler/template.js +391 -0
- package/compiler/vite.d.ts +31 -0
- package/compiler/vite.js +35 -0
- package/llms.txt +143 -0
- package/package.json +61 -4
- package/skills/vanji/SKILL.md +231 -0
- package/skills/vanji/references/patterns.md +241 -0
- package/src/dev.js +3 -0
- package/src/dom.js +308 -0
- package/src/index.d.ts +85 -0
- package/src/index.js +17 -0
- package/src/internal.js +4 -0
- package/src/list.js +272 -0
- package/src/signals.js +287 -0
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
# vanji patterns
|
|
2
|
+
|
|
3
|
+
Complete, working examples. Each one follows the rule: a hole that calls a function is reactive.
|
|
4
|
+
|
|
5
|
+
## Contents
|
|
6
|
+
|
|
7
|
+
1. Todo app with filters and localStorage
|
|
8
|
+
2. Loading data (fetch) with loading / error states
|
|
9
|
+
3. Forms and validation
|
|
10
|
+
4. Child components and shared state
|
|
11
|
+
5. Third-party widgets (editor, chart) in onMount
|
|
12
|
+
6. Tables with selection and sorting
|
|
13
|
+
7. Testing with Vitest
|
|
14
|
+
|
|
15
|
+
## 1. Todo app with filters and localStorage
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import { html, signal, computed, effect, each, when, mount } from '@hidemikimura/vanji';
|
|
19
|
+
|
|
20
|
+
type Todo = { id: number; title: string; done: boolean };
|
|
21
|
+
type Filter = 'all' | 'active' | 'done';
|
|
22
|
+
|
|
23
|
+
const saved = JSON.parse(localStorage.getItem('todos') ?? '[]') as Todo[];
|
|
24
|
+
const todos = signal<Todo[]>(saved);
|
|
25
|
+
const filter = signal<Filter>('all');
|
|
26
|
+
const text = signal('');
|
|
27
|
+
let nextId = Math.max(0, ...saved.map(t => t.id)) + 1;
|
|
28
|
+
|
|
29
|
+
const visible = computed(() => {
|
|
30
|
+
const f = filter();
|
|
31
|
+
return todos().filter(t => (f === 'all' ? true : f === 'done' ? t.done : !t.done));
|
|
32
|
+
});
|
|
33
|
+
const left = computed(() => todos().filter(t => !t.done).length);
|
|
34
|
+
|
|
35
|
+
effect(() => localStorage.setItem('todos', JSON.stringify(todos()))); // side effect: persist
|
|
36
|
+
|
|
37
|
+
const add = (e: Event) => {
|
|
38
|
+
e.preventDefault();
|
|
39
|
+
const title = text().trim();
|
|
40
|
+
if (!title) return;
|
|
41
|
+
todos.update(l => [...l, { id: nextId++, title, done: false }]);
|
|
42
|
+
text.set('');
|
|
43
|
+
};
|
|
44
|
+
const toggle = (id: number) => todos.update(l => l.map(t => (t.id === id ? { ...t, done: !t.done } : t)));
|
|
45
|
+
const remove = (id: number) => todos.update(l => l.filter(t => t.id !== id));
|
|
46
|
+
|
|
47
|
+
const FilterButton = (f: Filter) =>
|
|
48
|
+
html`<button class=${filter() === f ? 'active' : ''} @click=${() => filter.set(f)}>${f}</button>`;
|
|
49
|
+
|
|
50
|
+
const App = () => html`
|
|
51
|
+
<section>
|
|
52
|
+
<form @submit=${add}>
|
|
53
|
+
<input placeholder="What needs doing?" .value=${text()}
|
|
54
|
+
@input=${(e: Event) => text.set((e.target as HTMLInputElement).value)} />
|
|
55
|
+
</form>
|
|
56
|
+
<ul>${each(visible(), t => html`
|
|
57
|
+
<li class=${t.done ? 'done' : ''}>
|
|
58
|
+
<input type="checkbox" .checked=${t.done} @change=${() => toggle(t.id)} />
|
|
59
|
+
<span>${t.title}</span>
|
|
60
|
+
<button @click=${() => remove(t.id)}>×</button>
|
|
61
|
+
</li>`, { key: 'id' })}</ul>
|
|
62
|
+
<footer>
|
|
63
|
+
<span>${left()} left</span>
|
|
64
|
+
${FilterButton('all')} ${FilterButton('active')} ${FilterButton('done')}
|
|
65
|
+
${when(todos().length === 0, html`<p>Nothing to do.</p>`)}
|
|
66
|
+
</footer>
|
|
67
|
+
</section>`;
|
|
68
|
+
|
|
69
|
+
mount(App, document.getElementById('app')!);
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Notes: `FilterButton` is called once per button; its `class` hole reads `filter()`, so it updates by
|
|
73
|
+
itself. `visible()` is a computed, so the list only diffs when the todos or the filter change.
|
|
74
|
+
|
|
75
|
+
## 2. Loading data with loading / error states
|
|
76
|
+
|
|
77
|
+
```ts
|
|
78
|
+
type User = { id: number; name: string; email: string };
|
|
79
|
+
|
|
80
|
+
const UserList = () => {
|
|
81
|
+
const users = signal<User[]>([]);
|
|
82
|
+
const loading = signal(true);
|
|
83
|
+
const error = signal<string | null>(null);
|
|
84
|
+
|
|
85
|
+
onMount(async () => {
|
|
86
|
+
try {
|
|
87
|
+
const res = await fetch('/api/users');
|
|
88
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
89
|
+
users.set(await res.json());
|
|
90
|
+
} catch (e) {
|
|
91
|
+
error.set(e instanceof Error ? e.message : 'Failed to load');
|
|
92
|
+
} finally {
|
|
93
|
+
loading.set(false);
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
return html`<div>
|
|
98
|
+
${loading() ? html`<p>Loading…</p>` : ''}
|
|
99
|
+
${error() ? html`<p class="error">${error()}</p>` : ''}
|
|
100
|
+
<ul>${each(users(), u => html`<li>${u.name} <small>${u.email}</small></li>`, { key: 'id' })}</ul>
|
|
101
|
+
</div>`;
|
|
102
|
+
};
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
`await` is not allowed inside a hole; do the async work in `onMount` (or an event handler) and set
|
|
106
|
+
signals. To reload when a parameter changes, use an `effect` that reads the parameter signal and starts
|
|
107
|
+
the request; ignore responses that arrive after a newer request started.
|
|
108
|
+
|
|
109
|
+
## 3. Forms and validation
|
|
110
|
+
|
|
111
|
+
```ts
|
|
112
|
+
const SignupForm = () => {
|
|
113
|
+
const email = signal('');
|
|
114
|
+
const password = signal('');
|
|
115
|
+
const touched = signal(false);
|
|
116
|
+
const emailError = computed(() => (/^\S+@\S+\.\S+$/.test(email()) ? '' : 'Enter a valid email'));
|
|
117
|
+
const passwordError = computed(() => (password().length >= 8 ? '' : 'At least 8 characters'));
|
|
118
|
+
const valid = computed(() => !emailError() && !passwordError());
|
|
119
|
+
const value = (e: Event) => (e.target as HTMLInputElement).value;
|
|
120
|
+
|
|
121
|
+
const submit = (e: Event) => {
|
|
122
|
+
e.preventDefault();
|
|
123
|
+
touched.set(true);
|
|
124
|
+
if (valid()) console.info('submit', { email: email() });
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
return html`<form @submit=${submit} novalidate>
|
|
128
|
+
<label>Email <input type="email" .value=${email()} @input=${(e: Event) => email.set(value(e))} /></label>
|
|
129
|
+
${touched() && emailError() ? html`<p class="error">${emailError()}</p>` : ''}
|
|
130
|
+
<label>Password <input type="password" .value=${password()} @input=${(e: Event) => password.set(value(e))} /></label>
|
|
131
|
+
${touched() && passwordError() ? html`<p class="error">${passwordError()}</p>` : ''}
|
|
132
|
+
<button ?disabled=${touched() && !valid()}>Sign up</button>
|
|
133
|
+
</form>`;
|
|
134
|
+
};
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
## 4. Child components and shared state
|
|
138
|
+
|
|
139
|
+
```ts
|
|
140
|
+
// src/store.ts — shared state lives in modules
|
|
141
|
+
import { signal, computed } from '@hidemikimura/vanji';
|
|
142
|
+
export const cart = signal<{ id: number; name: string; qty: number }[]>([]);
|
|
143
|
+
export const cartCount = computed(() => cart().reduce((n, i) => n + i.qty, 0));
|
|
144
|
+
export const addToCart = (id: number, name: string) =>
|
|
145
|
+
cart.update(l => (l.some(i => i.id === id) ? l.map(i => (i.id === id ? { ...i, qty: i.qty + 1 } : i)) : [...l, { id, name, qty: 1 }]));
|
|
146
|
+
|
|
147
|
+
// src/Header.ts — a child reads shared signals itself
|
|
148
|
+
import { html } from '@hidemikimura/vanji';
|
|
149
|
+
import { cartCount } from './store';
|
|
150
|
+
export const Header = (title: string) => html`<header><h1>${title}</h1><span>Cart: ${cartCount()}</span></header>`;
|
|
151
|
+
|
|
152
|
+
// src/ProductCard.ts — props that change are passed as signals / getters
|
|
153
|
+
export const ProductCard = (p: { id: number; name: string }, onAdd: (id: number, name: string) => void) =>
|
|
154
|
+
html`<article><h2>${p.name}</h2><button @click=${() => onAdd(p.id, p.name)}>Add</button></article>`;
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
A component runs once. If a prop changes over time, pass the signal (`Header(titleSignal)` and read
|
|
158
|
+
`title()` inside), or a getter (`() => x()`).
|
|
159
|
+
|
|
160
|
+
## 5. Third-party widgets in onMount
|
|
161
|
+
|
|
162
|
+
```ts
|
|
163
|
+
import { html, effect, onMount, onCleanup } from '@hidemikimura/vanji';
|
|
164
|
+
import { EditorView, basicSetup } from 'codemirror';
|
|
165
|
+
|
|
166
|
+
export const Editor = (doc: { (): string; set(v: string): void }) => {
|
|
167
|
+
const host = html`<div class="editor"></div>` as HTMLElement; // one root: this is the element; empty: the library owns its children
|
|
168
|
+
let view: EditorView | undefined;
|
|
169
|
+
onMount(() => {
|
|
170
|
+
view = new EditorView({
|
|
171
|
+
doc: doc(),
|
|
172
|
+
parent: host,
|
|
173
|
+
extensions: [basicSetup, EditorView.updateListener.of(u => {
|
|
174
|
+
if (u.docChanged) doc.set(u.state.doc.toString()); // editor -> signal
|
|
175
|
+
})],
|
|
176
|
+
});
|
|
177
|
+
});
|
|
178
|
+
effect(() => { // signal -> editor
|
|
179
|
+
const v = doc();
|
|
180
|
+
if (view && v !== view.state.doc.toString())
|
|
181
|
+
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: v } });
|
|
182
|
+
});
|
|
183
|
+
onCleanup(() => view?.destroy());
|
|
184
|
+
return host;
|
|
185
|
+
};
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
The same pattern fits charts and maps: create in `onMount`, sync with an `effect`, destroy in
|
|
189
|
+
`onCleanup`. Inside list rows the widget survives item updates (rows are kept while their key stays).
|
|
190
|
+
|
|
191
|
+
## 6. Tables with selection and sorting
|
|
192
|
+
|
|
193
|
+
```ts
|
|
194
|
+
type Row = { id: number; name: string; score: number };
|
|
195
|
+
const rows = signal<Row[]>([]);
|
|
196
|
+
const selected = signal(0);
|
|
197
|
+
const sortKey = signal<keyof Row>('name');
|
|
198
|
+
const sorted = computed(() => {
|
|
199
|
+
const k = sortKey();
|
|
200
|
+
return rows().slice().sort((a, b) => (a[k] < b[k] ? -1 : a[k] > b[k] ? 1 : 0));
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
const Table = () => html`<table>
|
|
204
|
+
<thead><tr>
|
|
205
|
+
<th @click=${() => sortKey.set('name')}>Name</th>
|
|
206
|
+
<th @click=${() => sortKey.set('score')}>Score</th>
|
|
207
|
+
</tr></thead>
|
|
208
|
+
<tbody>${each(sorted(), r => html`
|
|
209
|
+
<tr class=${selected() === r.id ? 'selected' : ''} @click=${() => selected.set(r.id)}>
|
|
210
|
+
<td>${r.name}</td><td>${r.score}</td>
|
|
211
|
+
</tr>`, { key: 'id' })}</tbody>
|
|
212
|
+
</table>`;
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
`<tr>` must be inside `<tbody>` / `<thead>`. Sorting creates a new array; rows are moved, not rebuilt.
|
|
216
|
+
The `selected() === r.id` form is optimised to touch only the two affected rows.
|
|
217
|
+
|
|
218
|
+
## 7. Testing with Vitest
|
|
219
|
+
|
|
220
|
+
```ts
|
|
221
|
+
// vitest.config.ts
|
|
222
|
+
import { defineConfig } from 'vitest/config';
|
|
223
|
+
import vanji from '@hidemikimura/vanji/vite';
|
|
224
|
+
export default defineConfig({ plugins: [vanji()], test: { environment: 'jsdom' } });
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
```ts
|
|
228
|
+
// src/counter.test.ts
|
|
229
|
+
import { test, expect } from 'vitest';
|
|
230
|
+
import { html, signal, mount } from '@hidemikimura/vanji';
|
|
231
|
+
|
|
232
|
+
test('counter increments', () => {
|
|
233
|
+
const count = signal(0);
|
|
234
|
+
const el = document.createElement('div');
|
|
235
|
+
mount(() => html`<button @click=${() => count.update(n => n + 1)}>${count()}</button>`, el);
|
|
236
|
+
el.querySelector('button')!.click();
|
|
237
|
+
expect(el.textContent).toBe('1'); // updates are synchronous
|
|
238
|
+
});
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
Updates are synchronous, so assertions can run right after `set` / a click without waiting.
|
package/src/dev.js
ADDED
package/src/dom.js
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
// vanji DOM runtime. Everything here except `mount` is called by compiled templates
|
|
2
|
+
// (imported from "@hidemikimura/vanji/internal"); `each` / `when` in a template hole compile to these.
|
|
3
|
+
import { signal, computed, bind, root, untrack, onCleanup, scope, runIn, dispose } from './signals.js';
|
|
4
|
+
import { DEV } from './dev.js';
|
|
5
|
+
|
|
6
|
+
const isArray = Array.isArray;
|
|
7
|
+
|
|
8
|
+
const resolve = v => {
|
|
9
|
+
while (typeof v === 'function') v = v();
|
|
10
|
+
return v;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
// kind bits: 1 = several root nodes (returns a DocumentFragment), 2 = SVG fragment,
|
|
14
|
+
// 4 = contains custom elements (importNode so they upgrade before properties are set)
|
|
15
|
+
export const template = (html, kind = 0) => {
|
|
16
|
+
let proto;
|
|
17
|
+
return () => {
|
|
18
|
+
proto ||= make(html, kind);
|
|
19
|
+
return kind & 4 ? document.importNode(proto, true) : proto.cloneNode(true);
|
|
20
|
+
};
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
const make = (html, kind) => {
|
|
24
|
+
const t = document.createElement('template');
|
|
25
|
+
t.innerHTML = kind & 2 ? `<svg>${html}</svg>` : html;
|
|
26
|
+
let c = t.content;
|
|
27
|
+
if (kind & 2) {
|
|
28
|
+
const svg = c.firstChild;
|
|
29
|
+
c = document.createDocumentFragment();
|
|
30
|
+
c.append(...svg.childNodes);
|
|
31
|
+
}
|
|
32
|
+
return kind & 1 ? c : c.firstChild;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
const flat = (arr, out) => {
|
|
36
|
+
for (let i = 0; i < arr.length; i++) {
|
|
37
|
+
const v = resolve(arr[i]);
|
|
38
|
+
if (isArray(v)) flat(v, out);
|
|
39
|
+
else if (v != null && typeof v !== 'boolean') {
|
|
40
|
+
if (v.nodeType === 11) out.push(...v.childNodes);
|
|
41
|
+
else out.push(v.nodeType ? v : document.createTextNode(v));
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return out;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
// set by each(): a = its node list (known to be flat), p = the list it replaces, h/t = unchanged head/tail counts
|
|
48
|
+
const hint = { a: null, p: null, h: 0, t: 0 };
|
|
49
|
+
|
|
50
|
+
// true when `arr` already is a plain list of nodes (then it is used as-is, without a copy)
|
|
51
|
+
const isFlat = arr => {
|
|
52
|
+
for (let i = 0; i < arr.length; i++) {
|
|
53
|
+
const v = arr[i];
|
|
54
|
+
if (v == null || typeof v !== 'object' || !v.nodeType || v.nodeType === 11) return false;
|
|
55
|
+
}
|
|
56
|
+
return true;
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
// Move the DOM from node list `a` to node list `b` (both live before `end`).
|
|
60
|
+
const reconcile = (parent, a, b, end, head, tail) => {
|
|
61
|
+
let a0 = head, b0 = head, a1 = a.length - tail, b1 = b.length - tail, i;
|
|
62
|
+
if (!b.length) {
|
|
63
|
+
if (end) for (i = 0; i < a1; i++) a[i].remove();
|
|
64
|
+
else parent.textContent = '';
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
while (a0 < a1 && b0 < b1) {
|
|
68
|
+
if (a[a0] === b[b0]) a0++, b0++;
|
|
69
|
+
else if (a[a1 - 1] === b[b1 - 1]) a1--, b1--;
|
|
70
|
+
else if (a[a0] === b[b1 - 1] && a[a1 - 1] === b[b0]) {
|
|
71
|
+
// the two ends swapped places
|
|
72
|
+
const after = a[--a1].nextSibling;
|
|
73
|
+
parent.insertBefore(a[a1], a[a0]);
|
|
74
|
+
parent.insertBefore(a[a0++], after);
|
|
75
|
+
b0++, b1--;
|
|
76
|
+
} else break;
|
|
77
|
+
}
|
|
78
|
+
const next = b1 < b.length ? b[b1] : end;
|
|
79
|
+
if (a0 === a1) {
|
|
80
|
+
for (; b0 < b1; b0++) parent.insertBefore(b[b0], next);
|
|
81
|
+
} else if (b0 === b1) {
|
|
82
|
+
for (; a0 < a1; a0++) a[a0].remove();
|
|
83
|
+
} else {
|
|
84
|
+
const keep = new Set();
|
|
85
|
+
for (i = b0; i < b1; i++) keep.add(b[i]);
|
|
86
|
+
let kept = 0;
|
|
87
|
+
for (i = a0; i < a1; i++) if (keep.has(a[i])) kept++;
|
|
88
|
+
if (!kept && !end && a1 - a0 === a.length) parent.textContent = ''; // nothing survives: one DOM call
|
|
89
|
+
else if (kept < a1 - a0) for (i = a0; i < a1; i++) if (!keep.has(a[i])) a[i].remove();
|
|
90
|
+
let ref = next;
|
|
91
|
+
for (i = b1 - 1; i >= b0; i--) {
|
|
92
|
+
const n = b[i];
|
|
93
|
+
if (n.parentNode !== parent || n.nextSibling !== ref) parent.insertBefore(n, ref);
|
|
94
|
+
ref = n;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
// Put `v` where `cur` was. Returns what is now in the DOM: undefined | Node | Node[]
|
|
100
|
+
export const place = (parent, v, cur, marker) => {
|
|
101
|
+
v = resolve(v);
|
|
102
|
+
const t = typeof v;
|
|
103
|
+
if (t === 'string' || t === 'number' || t === 'bigint') {
|
|
104
|
+
if (cur && cur.nodeType === 3) {
|
|
105
|
+
cur.data = v;
|
|
106
|
+
return cur;
|
|
107
|
+
}
|
|
108
|
+
v = document.createTextNode(v);
|
|
109
|
+
} else if (v == null || t === 'boolean') v = undefined;
|
|
110
|
+
else if (isArray(v)) {
|
|
111
|
+
if (v !== hint.a && !isFlat(v)) v = flat(v, []);
|
|
112
|
+
}
|
|
113
|
+
else if (v.nodeType === 11) v = [...v.childNodes];
|
|
114
|
+
else if (!v.nodeType) v = document.createTextNode(v);
|
|
115
|
+
|
|
116
|
+
if (v === cur) return cur;
|
|
117
|
+
if (isArray(cur) || isArray(v)) {
|
|
118
|
+
// each() reports how many leading / trailing nodes are untouched (valid only against its own last output)
|
|
119
|
+
const known = v === hint.a && cur === hint.p;
|
|
120
|
+
reconcile(parent, isArray(cur) ? cur : cur ? [cur] : [], isArray(v) ? v : v ? [v] : [], marker, known ? hint.h : 0, known ? hint.t : 0);
|
|
121
|
+
} else if (cur) {
|
|
122
|
+
v ? parent.replaceChild(v, cur) : cur.remove();
|
|
123
|
+
} else if (v) parent.insertBefore(v, marker);
|
|
124
|
+
return v;
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
const hInsert = n => {
|
|
128
|
+
n.v = place(n.a, n.f, n.v, n.b);
|
|
129
|
+
};
|
|
130
|
+
const hAttr = n => setAttr(n.a, n.b, n.f());
|
|
131
|
+
const hBool = n => n.a.toggleAttribute(n.b, !!n.f());
|
|
132
|
+
|
|
133
|
+
/** Insert a value before `marker` (or as the only content of `parent`). Functions/arrays are reactive. */
|
|
134
|
+
export const insert = (parent, value, marker = null) => {
|
|
135
|
+
const t = typeof value;
|
|
136
|
+
if (t === 'function' || isArray(value)) bind(hInsert, value, parent, marker);
|
|
137
|
+
else if (marker === null && (t === 'string' || t === 'number')) parent.textContent = value;
|
|
138
|
+
else place(parent, value, undefined, marker);
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
export const setAttr = (el, name, v) => (v == null ? el.removeAttribute(name) : el.setAttribute(name, v));
|
|
142
|
+
|
|
143
|
+
export const attr = (el, name, v) => {
|
|
144
|
+
typeof v === 'function' ? bind(hAttr, v, el, name) : setAttr(el, name, v);
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
export const bool = (el, name, v) => {
|
|
148
|
+
typeof v === 'function' ? bind(hBool, v, el, name) : el.toggleAttribute(name, !!v);
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
// part of a multi-part attribute value: class="a ${x} b"
|
|
152
|
+
export const str = v => ((v = resolve(v)) == null ? '' : v);
|
|
153
|
+
|
|
154
|
+
// --- holes at a template's root: the template returns an array, these are its dynamic parts ---
|
|
155
|
+
// A fragment is emptied when inserted, so a root hole cannot keep inserting into it. Instead the part is
|
|
156
|
+
// resolved by whatever renders the array (a parent hole, each, when, mount), which re-flattens the array
|
|
157
|
+
// when a part changes, so nodes are never left behind.
|
|
158
|
+
|
|
159
|
+
/** A root hole that calls a function: its nodes, rebuilt only when what it read changes. */
|
|
160
|
+
export const memo = fn => computed(() => flat([fn()], []));
|
|
161
|
+
|
|
162
|
+
/** A root hole that does not: its nodes, made once (a function value stays reactive, as elsewhere). */
|
|
163
|
+
export const nodes = v => (typeof v === 'function' ? memo(v) : flat([v], []));
|
|
164
|
+
|
|
165
|
+
/** A component call in a template hole, `${Card(x)}`: arguments are tracked, the component body is not. */
|
|
166
|
+
export const c = (component, ...args) => untrack(() => component(...args));
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Keyed list, for rows the compiler cannot turn into a fast list (src/list.js): each row has its own
|
|
170
|
+
* scope, and rows are moved, not re-rendered, when the order changes.
|
|
171
|
+
* Compiled from `${each(items, row, { key })}`: `list` is `() => items`. `flags`: 1 = the row takes an
|
|
172
|
+
* index, 2 = "live" rows: the compiler rewrote an inline row function to read its item and index
|
|
173
|
+
* through getters, so a row is kept while its key stays (a replaced item / changed index only sets
|
|
174
|
+
* the row's signals). Without 2 (a named row function, a destructured item), a row is created again
|
|
175
|
+
* when its item object or its index changes.
|
|
176
|
+
*/
|
|
177
|
+
export const each = (list, row, opts, flags = 0) => {
|
|
178
|
+
const k = opts && opts.key;
|
|
179
|
+
const key = k == null ? v => v : typeof k === 'function' ? k : v => v[k];
|
|
180
|
+
// key -> row scope: v = item (live: a signal of it), a = DOM node(s), b = index (live: a signal), h = visit stamp
|
|
181
|
+
const map = new Map();
|
|
182
|
+
let prev = [], prevItems = [], prevNodes = [], stamp = 0, multi = 0;
|
|
183
|
+
const live = flags & 2, withIndex = flags & 1 || row.length > 1; // (row.length misses defaults)
|
|
184
|
+
const itemOf = live ? e => e.v.v : e => e.v;
|
|
185
|
+
onCleanup(() => {
|
|
186
|
+
for (let i = 0; i < prev.length; i++) dispose(prev[i]);
|
|
187
|
+
});
|
|
188
|
+
const single = a => a != null && a.nodeType > 0 && a.nodeType !== 11;
|
|
189
|
+
// tell place()/reconcile() what is already known, so they do not rescan the whole list
|
|
190
|
+
const done = (nodes, from, head, tail) => {
|
|
191
|
+
hint.a = multi ? null : nodes;
|
|
192
|
+
hint.p = from;
|
|
193
|
+
hint.h = head;
|
|
194
|
+
hint.t = tail;
|
|
195
|
+
return nodes;
|
|
196
|
+
};
|
|
197
|
+
const diff = items => {
|
|
198
|
+
const n = items.length, pn = prev.length;
|
|
199
|
+
const min = n < pn ? n : pn;
|
|
200
|
+
let start = 0, end = n, pend = pn, i, e, k;
|
|
201
|
+
// 1. unchanged head and tail: plain array compares, no row object is touched
|
|
202
|
+
while (start < min && items[start] === prevItems[start]) start++;
|
|
203
|
+
if (start === n && n === pn) return done(prevNodes, prevNodes, 0, 0);
|
|
204
|
+
// with an index, tail rows keep their index only when the length is unchanged
|
|
205
|
+
while (end > start && pend > start && (!withIndex || live || n === pn) && items[end - 1] === prevItems[pend - 1]) end--, pend--;
|
|
206
|
+
const head = start, tail = n - end;
|
|
207
|
+
const mid = new Array(end - start), midNodes = new Array(end - start);
|
|
208
|
+
// 2. inside the changed window: rows that only swapped ends (a <-> b) need no lookup either
|
|
209
|
+
let s = start, e2 = end, pe = pend;
|
|
210
|
+
while (s < e2 && s < pe) {
|
|
211
|
+
if (items[s] === prevItems[s]) {
|
|
212
|
+
mid[s - start] = prev[s];
|
|
213
|
+
midNodes[s - start] = prevNodes[s];
|
|
214
|
+
s++;
|
|
215
|
+
} else if (withIndex && !live) break; // the moves below change indexes: rows are matched (and recreated) by key
|
|
216
|
+
else if (items[e2 - 1] === prevItems[pe - 1]) {
|
|
217
|
+
e = mid[--e2 - start] = prev[--pe];
|
|
218
|
+
midNodes[e2 - start] = prevNodes[pe];
|
|
219
|
+
if (withIndex) e.b.set(e2);
|
|
220
|
+
} else if (items[s] === prevItems[pe - 1] && items[e2 - 1] === prevItems[s]) {
|
|
221
|
+
e = mid[--e2 - start] = prev[s];
|
|
222
|
+
midNodes[e2 - start] = prevNodes[s];
|
|
223
|
+
if (withIndex) e.b.set(e2);
|
|
224
|
+
e = mid[s - start] = prev[--pe];
|
|
225
|
+
midNodes[s - start] = prevNodes[pe];
|
|
226
|
+
if (withIndex) e.b.set(s);
|
|
227
|
+
s++;
|
|
228
|
+
} else break;
|
|
229
|
+
}
|
|
230
|
+
// 3. whatever is left is matched by key
|
|
231
|
+
const fresh = map.size === 0;
|
|
232
|
+
stamp++;
|
|
233
|
+
for (i = s; i < e2; i++) {
|
|
234
|
+
const item = items[i];
|
|
235
|
+
k = key(item, i);
|
|
236
|
+
e = fresh ? undefined : map.get(k);
|
|
237
|
+
if (live && e !== undefined && e.h !== stamp) {
|
|
238
|
+
if (e.v.v !== item) e.v.set(item);
|
|
239
|
+
if (withIndex) e.b.set(i);
|
|
240
|
+
} else if (live || e === undefined || e.v !== item || e.h === stamp || (withIndex && e.b !== i)) {
|
|
241
|
+
e = scope();
|
|
242
|
+
if (live) {
|
|
243
|
+
e.v = signal(item);
|
|
244
|
+
e.b = withIndex ? signal(i) : i;
|
|
245
|
+
} else {
|
|
246
|
+
e.v = item;
|
|
247
|
+
e.b = i;
|
|
248
|
+
}
|
|
249
|
+
const r = runIn(e, row, e.v, e.b);
|
|
250
|
+
if (!single((e.a = r && r.nodeType === 11 ? [...r.childNodes] : r))) multi++;
|
|
251
|
+
map.set(k, e);
|
|
252
|
+
}
|
|
253
|
+
e.h = stamp;
|
|
254
|
+
mid[i - start] = e;
|
|
255
|
+
midNodes[i - start] = e.a;
|
|
256
|
+
}
|
|
257
|
+
// old rows of the window that were not visited are gone
|
|
258
|
+
if (!n) map.clear();
|
|
259
|
+
for (i = s; i < pe; i++) {
|
|
260
|
+
e = prev[i];
|
|
261
|
+
if (e.h !== stamp) {
|
|
262
|
+
if (n && map.get((k = key(itemOf(e), i))) === e) map.delete(k);
|
|
263
|
+
if (!single(e.a)) multi--;
|
|
264
|
+
dispose(e);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
if (map.size !== n) {
|
|
268
|
+
const seen = new Set();
|
|
269
|
+
for (i = 0; i < n; i++) {
|
|
270
|
+
if (seen.has((k = key(items[i], i))))
|
|
271
|
+
throw new Error(DEV ? `[vanji] each(): duplicate key "${String(k)}". Keys must be unique.` : 'vanji: duplicate key');
|
|
272
|
+
seen.add(k);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
// live rows after the window moved by the length change: their index signal follows
|
|
276
|
+
if (live && withIndex && n !== pn) for (i = pend; i < pn; i++) prev[i].b.set(i + n - pn);
|
|
277
|
+
const from = prevNodes;
|
|
278
|
+
// native copies for the untouched parts
|
|
279
|
+
prev = prev.slice(0, head).concat(mid, prev.slice(pend));
|
|
280
|
+
prevNodes = from.slice(0, head).concat(midNodes, from.slice(pend));
|
|
281
|
+
prevItems = items.slice();
|
|
282
|
+
return done(prevNodes, from, head, tail);
|
|
283
|
+
};
|
|
284
|
+
return () => untrack(diff, resolve(list) || []);
|
|
285
|
+
};
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* Conditional rendering. The branch is rebuilt only when the truthiness of the condition flips.
|
|
289
|
+
* Compiled from `${when(cond, yes, no)}`: every argument arrives as a function.
|
|
290
|
+
*/
|
|
291
|
+
export const when = (cond, yes, no) => {
|
|
292
|
+
const c = computed(() => !!resolve(cond));
|
|
293
|
+
return () => {
|
|
294
|
+
const branch = c() ? yes : no;
|
|
295
|
+
return branch ? untrack(() => resolve(branch)) : undefined;
|
|
296
|
+
};
|
|
297
|
+
};
|
|
298
|
+
|
|
299
|
+
/** Render `component` into `target` (replacing its content). Returns an unmount function. */
|
|
300
|
+
export const mount = (component, target) =>
|
|
301
|
+
root(dispose => {
|
|
302
|
+
target.textContent = '';
|
|
303
|
+
insert(target, typeof component === 'function' ? component() : component);
|
|
304
|
+
return () => {
|
|
305
|
+
dispose();
|
|
306
|
+
target.textContent = '';
|
|
307
|
+
};
|
|
308
|
+
});
|
package/src/index.d.ts
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/** A readable reactive value. Call it to read (and subscribe when inside an effect/template). */
|
|
2
|
+
export interface ReadSignal<T> {
|
|
3
|
+
(): T;
|
|
4
|
+
/** Read without subscribing. */
|
|
5
|
+
peek(): T;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/** A writable reactive value. */
|
|
9
|
+
export interface Signal<T> extends ReadSignal<T> {
|
|
10
|
+
/** Replace the value. No-op when `Object.is(old, value)`. Always pass a NEW object/array. */
|
|
11
|
+
set(value: T): void;
|
|
12
|
+
/** Replace the value with `fn(current)`. */
|
|
13
|
+
update(fn: (current: T) => T): void;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Anything a template hole accepts in a text position. */
|
|
17
|
+
export type Renderable =
|
|
18
|
+
| Node
|
|
19
|
+
| string
|
|
20
|
+
| number
|
|
21
|
+
| bigint
|
|
22
|
+
| boolean
|
|
23
|
+
| null
|
|
24
|
+
| undefined
|
|
25
|
+
| Renderable[]
|
|
26
|
+
| (() => Renderable);
|
|
27
|
+
|
|
28
|
+
/** Create a writable signal. */
|
|
29
|
+
export function signal<T>(value: T): Signal<T>;
|
|
30
|
+
export function signal<T = undefined>(): Signal<T | undefined>;
|
|
31
|
+
|
|
32
|
+
/** Create a derived, cached, read-only signal. Dependents update only when the result changes. */
|
|
33
|
+
export function computed<T>(fn: () => T): ReadSignal<T>;
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Run `fn` now and again whenever a signal it read changes (synchronously after the write).
|
|
37
|
+
* `fn` may return a cleanup function. Returns a function that stops the effect.
|
|
38
|
+
*/
|
|
39
|
+
export function effect(fn: () => void | (() => void)): () => void;
|
|
40
|
+
|
|
41
|
+
/** Group several writes so effects run once, after `fn` returns. */
|
|
42
|
+
export function batch<T>(fn: () => T): T;
|
|
43
|
+
|
|
44
|
+
/** Read signals inside `fn` without subscribing. */
|
|
45
|
+
export function untrack<T>(fn: () => T): T;
|
|
46
|
+
|
|
47
|
+
/** Create a scope that owns the effects created inside `fn`; call `dispose` to tear them down. */
|
|
48
|
+
export function root<T>(fn: (dispose: () => void) => T): T;
|
|
49
|
+
|
|
50
|
+
/** Run `fn` when the current scope (component, effect run, or list row) is torn down. */
|
|
51
|
+
export function onCleanup(fn: () => void): void;
|
|
52
|
+
|
|
53
|
+
/** Run `fn` once after the current render work, when the component's DOM is in the document. */
|
|
54
|
+
export function onMount(fn: () => void): void;
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Template tag (compiled at build time). Returns the element itself for a single root element, a
|
|
58
|
+
* DocumentFragment for several root nodes, and an array (nodes and live parts) when a hole is at the
|
|
59
|
+
* root: html`${title()}<p>…</p>`. Use the result in a hole, each(), when() or mount().
|
|
60
|
+
*/
|
|
61
|
+
export function html(strings: TemplateStringsArray, ...values: unknown[]): Renderable;
|
|
62
|
+
|
|
63
|
+
/** Options of each(). `key`: a property name of the items, or a function of the item. Default: the item itself. */
|
|
64
|
+
export interface EachOptions<T> {
|
|
65
|
+
key?: (keyof T & string) | ((item: T) => unknown);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Keyed list. Write it directly in a template hole: `${each(todos(), t => html`<li>…</li>`, { key: 'id' })}`.
|
|
70
|
+
* Items are plain values updated immutably: a replaced item updates its row; `index` is a plain number.
|
|
71
|
+
*/
|
|
72
|
+
export function each<T>(
|
|
73
|
+
items: readonly T[] | null | undefined,
|
|
74
|
+
row: (item: T, index: number) => Renderable,
|
|
75
|
+
options?: EachOptions<T>
|
|
76
|
+
): Renderable;
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Conditional content. Write it directly in a template hole: `${when(open(), html`<dialog>…</dialog>`)}`.
|
|
80
|
+
* A branch is rebuilt only when the truthiness of `cond` flips.
|
|
81
|
+
*/
|
|
82
|
+
export function when(cond: unknown, yes: Renderable, no?: Renderable): Renderable;
|
|
83
|
+
|
|
84
|
+
/** Render a component into `target`, replacing its content. Returns an unmount function. */
|
|
85
|
+
export function mount(component: (() => Renderable) | Node, target: Element | ShadowRoot): () => void;
|
package/src/index.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export { signal, computed, effect, batch, untrack, root, onCleanup, onMount } from './signals.js';
|
|
2
|
+
export { mount } from './dom.js';
|
|
3
|
+
import { DEV } from './dev.js';
|
|
4
|
+
|
|
5
|
+
const notCompiled = name => () => {
|
|
6
|
+
throw new Error(
|
|
7
|
+
!DEV ? 'vanji: not compiled' : `[vanji] ${name} was not compiled. Add the plugin to your build: import vanji from "@hidemikimura/vanji/vite" -> plugins: [vanji()]` +
|
|
8
|
+
(name === 'html`...`' ? '' : `, and write ${name} directly in a template hole: html\`<ul>\${${name.slice(0, -2)}(…)}</ul>\``)
|
|
9
|
+
);
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
/** Template tag. Compiled away by the vanji build plugin; reaching this at runtime is a setup error. */
|
|
13
|
+
export const html = notCompiled('html`...`');
|
|
14
|
+
/** Keyed list, written directly in a template hole. Compiled away by the build plugin. */
|
|
15
|
+
export const each = notCompiled('each()');
|
|
16
|
+
/** Conditional content, written directly in a template hole. Compiled away by the build plugin. */
|
|
17
|
+
export const when = notCompiled('when()');
|
package/src/internal.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// Helpers imported by compiled templates. Not part of the public API.
|
|
2
|
+
export { template, insert, attr, setAttr, bool, str, c, each, when, place, memo, nodes } from './dom.js';
|
|
3
|
+
export { list, text, rowScope } from './list.js';
|
|
4
|
+
export { render as effect } from './signals.js';
|