@hidemikimura/vanji 0.0.0-stage → 0.1.1

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/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()');
@@ -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, textNode, rowScope } from './list.js';
4
+ export { render as effect } from './signals.js';