clarusjs 0.2.0 → 0.3.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/README.md +0 -10
- package/dist/compiler/emit-client.js +88 -17
- package/dist/compiler/emit-server.js +30 -24
- package/dist/compiler/html-expr.d.ts +29 -0
- package/dist/compiler/html-expr.js +85 -0
- package/dist/compiler/ir.d.ts +38 -0
- package/dist/compiler/ir.js +144 -32
- package/dist/compiler/parse.d.ts +34 -0
- package/dist/compiler/parse.js +199 -4
- package/dist/compiler/script.d.ts +17 -2
- package/dist/compiler/script.js +66 -6
- package/dist/runtime/attrs.d.ts +5 -0
- package/dist/runtime/attrs.js +56 -0
- package/dist/runtime/dom.d.ts +61 -5
- package/dist/runtime/dom.js +257 -17
- package/dist/runtime/html.d.ts +10 -0
- package/dist/runtime/html.js +30 -0
- package/dist/runtime/index.d.ts +4 -2
- package/dist/runtime/index.js +4 -2
- package/dist/runtime/loader.d.ts +7 -2
- package/dist/runtime/loader.js +125 -28
- package/dist/runtime/serialize.d.ts +8 -0
- package/dist/runtime/serialize.js +93 -0
- package/dist/runtime/server.d.ts +9 -4
- package/dist/runtime/server.js +13 -24
- package/dist/runtime/signals.d.ts +12 -0
- package/dist/runtime/signals.js +44 -1
- package/dist/vite/plugin.js +30 -3
- package/package.json +1 -1
package/dist/runtime/dom.js
CHANGED
|
@@ -1,8 +1,26 @@
|
|
|
1
|
-
// Attach helpers: find
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
1
|
+
// Attach helpers: find markers in server HTML and keep them updated. Browser only. Never re-renders existing HTML;
|
|
2
|
+
// only @if branches and @for rows that did not exist on the server are rendered here.
|
|
3
|
+
import { attrValue } from './attrs.js';
|
|
4
|
+
import { effect, onDispose, scope, state, untrack } from './signals.js';
|
|
5
|
+
const rootOf = (ctx) => ('root' in ctx ? ctx.root : ctx);
|
|
6
|
+
/** Is `node` inside `ctx` (always true for a whole island)? */
|
|
7
|
+
function inside(ctx, node) {
|
|
8
|
+
if (!('root' in ctx))
|
|
9
|
+
return true;
|
|
10
|
+
return !!(ctx.start.compareDocumentPosition(node) & Node.DOCUMENT_POSITION_FOLLOWING) &&
|
|
11
|
+
!!(ctx.end.compareDocumentPosition(node) & Node.DOCUMENT_POSITION_PRECEDING);
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Find every marker in `ctx`, skipping nested islands:
|
|
15
|
+
* holes `<!--[N-->`, @if blocks `<!--[bN:K-->`, @for lists `<!--[fN-->` with rows `<!--[r-->` and `<!--[e-->`,
|
|
16
|
+
* all closed by `<!--]-->`.
|
|
17
|
+
*/
|
|
18
|
+
function scan(ctx) {
|
|
19
|
+
const root = rootOf(ctx);
|
|
20
|
+
const holes = [];
|
|
21
|
+
const blocks = [];
|
|
22
|
+
const fors = [];
|
|
23
|
+
const regions = [];
|
|
6
24
|
const open = [];
|
|
7
25
|
const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT, {
|
|
8
26
|
acceptNode: (n) => n.nodeType === 8 ? NodeFilter.FILTER_ACCEPT
|
|
@@ -10,15 +28,216 @@ export function holes(root) {
|
|
|
10
28
|
: NodeFilter.FILTER_SKIP,
|
|
11
29
|
});
|
|
12
30
|
for (let n = walker.nextNode(); n; n = walker.nextNode()) {
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
31
|
+
if (!inside(ctx, n))
|
|
32
|
+
continue;
|
|
33
|
+
const c = n;
|
|
34
|
+
const data = c.data;
|
|
35
|
+
let m;
|
|
36
|
+
const push = (kind, index = 0, k = 0) => open.push({ kind, index, k, start: c, rows: [], empty: null });
|
|
37
|
+
if ((m = /^\[(\d+)$/.exec(data)))
|
|
38
|
+
push('hole', Number(m[1]));
|
|
39
|
+
else if ((m = /^\[b(\d+):(-?\d+)$/.exec(data)))
|
|
40
|
+
push('block', Number(m[1]), Number(m[2]));
|
|
41
|
+
else if ((m = /^\[f(\d+)$/.exec(data)))
|
|
42
|
+
push('for', Number(m[1]));
|
|
43
|
+
else if ((m = /^\[c(\d+)$/.exec(data)))
|
|
44
|
+
push('region', Number(m[1]));
|
|
45
|
+
else if (data === '[r')
|
|
46
|
+
push('row');
|
|
47
|
+
else if (data === '[e')
|
|
48
|
+
push('empty');
|
|
16
49
|
else if (data === ']' && open.length) {
|
|
17
|
-
const
|
|
18
|
-
|
|
50
|
+
const o = open.pop();
|
|
51
|
+
const parent = open[open.length - 1];
|
|
52
|
+
if (o.kind === 'hole')
|
|
53
|
+
holes[o.index] = { start: o.start, end: c };
|
|
54
|
+
else if (o.kind === 'block')
|
|
55
|
+
blocks[o.index] = { start: o.start, end: c, k: o.k };
|
|
56
|
+
else if (o.kind === 'for')
|
|
57
|
+
fors[o.index] = { start: o.start, end: c, rows: o.rows, empty: o.empty };
|
|
58
|
+
else if (o.kind === 'region')
|
|
59
|
+
regions[o.index] = { start: o.start, end: c };
|
|
60
|
+
else if (parent?.kind === 'for') {
|
|
61
|
+
if (o.kind === 'row')
|
|
62
|
+
parent.rows.push({ start: o.start, end: c });
|
|
63
|
+
else
|
|
64
|
+
parent.empty = { start: o.start, end: c };
|
|
65
|
+
}
|
|
19
66
|
}
|
|
20
67
|
}
|
|
21
|
-
return
|
|
68
|
+
return { holes, blocks, fors, regions };
|
|
69
|
+
}
|
|
70
|
+
/** Hole markers in `ctx`, by index. */
|
|
71
|
+
export function holes(ctx) {
|
|
72
|
+
return scan(ctx).holes;
|
|
73
|
+
}
|
|
74
|
+
/** @if block markers in `ctx`, by index. */
|
|
75
|
+
export function blocks(ctx) {
|
|
76
|
+
return scan(ctx).blocks;
|
|
77
|
+
}
|
|
78
|
+
/** Turn HTML into nodes and put them before `end`; returns the first and last inserted node. */
|
|
79
|
+
function insertHtml(html, end) {
|
|
80
|
+
const t = document.createElement('template');
|
|
81
|
+
t.innerHTML = html;
|
|
82
|
+
const first = t.content.firstChild;
|
|
83
|
+
const last = t.content.lastChild;
|
|
84
|
+
end.parentNode.insertBefore(t.content, end);
|
|
85
|
+
// Child islands in the new HTML attach like the ones on the page (the loader registers this hook).
|
|
86
|
+
const attachIslands = globalThis.__clAttach;
|
|
87
|
+
if (attachIslands && end.parentNode)
|
|
88
|
+
attachIslands(end.parentNode);
|
|
89
|
+
return { first, last };
|
|
90
|
+
}
|
|
91
|
+
/** The nodes from `start` to `end`, both included. */
|
|
92
|
+
function rangeNodes(start, end) {
|
|
93
|
+
const nodes = [];
|
|
94
|
+
for (let n = start; n; n = n.nextSibling) {
|
|
95
|
+
nodes.push(n);
|
|
96
|
+
if (n === end)
|
|
97
|
+
break;
|
|
98
|
+
}
|
|
99
|
+
return nodes;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* An @if block. `which()` picks the branch (-1 for none). The server-rendered branch is wired in place; a change
|
|
103
|
+
* removes the old branch (disposing its effects and handlers), inserts the new branch's HTML and wires it.
|
|
104
|
+
*/
|
|
105
|
+
export function block(ctx, index, which, branches) {
|
|
106
|
+
const b = blocks(ctx)[index];
|
|
107
|
+
if (!b)
|
|
108
|
+
return;
|
|
109
|
+
let current = b.k;
|
|
110
|
+
let dispose = null;
|
|
111
|
+
let first = true;
|
|
112
|
+
onDispose(() => dispose?.()); // removing the enclosing branch or row removes this one's too
|
|
113
|
+
effect(() => {
|
|
114
|
+
const k = which();
|
|
115
|
+
untrack(() => {
|
|
116
|
+
if (!first && k === current)
|
|
117
|
+
return;
|
|
118
|
+
if (k !== current) {
|
|
119
|
+
dispose?.();
|
|
120
|
+
while (b.start.nextSibling && b.start.nextSibling !== b.end)
|
|
121
|
+
b.start.nextSibling.remove();
|
|
122
|
+
if (k >= 0)
|
|
123
|
+
insertHtml(branches[k].html(), b.end);
|
|
124
|
+
current = k;
|
|
125
|
+
}
|
|
126
|
+
first = false;
|
|
127
|
+
dispose = k >= 0 ? scope(() => branches[k].wire()) : null;
|
|
128
|
+
});
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* A child component inside an island whose props or content read state. `html()` renders it with the current
|
|
133
|
+
* values; when anything it read changes, the old HTML is disposed and replaced, and `wire()` wires the island's own
|
|
134
|
+
* holes and events in the child's slot content again. A stateful child is remounted with its new props.
|
|
135
|
+
*/
|
|
136
|
+
export function region(ctx, index, html, wire) {
|
|
137
|
+
const r = scan(ctx).regions[index];
|
|
138
|
+
if (!r)
|
|
139
|
+
return;
|
|
140
|
+
let dispose = null;
|
|
141
|
+
let first = true;
|
|
142
|
+
onDispose(() => dispose?.());
|
|
143
|
+
effect(() => {
|
|
144
|
+
const next = html();
|
|
145
|
+
untrack(() => {
|
|
146
|
+
if (!first) {
|
|
147
|
+
dispose?.();
|
|
148
|
+
while (r.start.nextSibling && r.start.nextSibling !== r.end)
|
|
149
|
+
r.start.nextSibling.remove();
|
|
150
|
+
insertHtml(next, r.end);
|
|
151
|
+
}
|
|
152
|
+
first = false;
|
|
153
|
+
dispose = scope(wire);
|
|
154
|
+
});
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* A @for list. Rows the server rendered are adopted in place. When the list changes, rows are matched by key:
|
|
159
|
+
* kept rows keep their DOM nodes (moved only when out of order) and get the new item and index through their
|
|
160
|
+
* signals; new rows are rendered and wired; removed rows are disposed and removed. `@empty` content is shown while
|
|
161
|
+
* the list is empty.
|
|
162
|
+
*/
|
|
163
|
+
export function forBlock(ctx, index, list, keyOf, row, empty) {
|
|
164
|
+
const f = scan(ctx).fors[index];
|
|
165
|
+
if (!f)
|
|
166
|
+
return;
|
|
167
|
+
const root = rootOf(ctx);
|
|
168
|
+
let rows = [];
|
|
169
|
+
let emptyRange = null;
|
|
170
|
+
let first = true;
|
|
171
|
+
const wireRow = (range, key, item, i) => {
|
|
172
|
+
const itemS = state(item);
|
|
173
|
+
const indexS = state(i);
|
|
174
|
+
const dispose = scope(() => row.wire({ root, ...range }, itemS, indexS));
|
|
175
|
+
return { ...range, key, item: itemS, index: indexS, dispose };
|
|
176
|
+
};
|
|
177
|
+
const wireEmpty = (range) => ({ ...range, dispose: empty ? scope(() => empty.wire({ root, ...range })) : () => { } });
|
|
178
|
+
onDispose(() => {
|
|
179
|
+
for (const r of rows)
|
|
180
|
+
r.dispose();
|
|
181
|
+
emptyRange?.dispose();
|
|
182
|
+
});
|
|
183
|
+
effect(() => {
|
|
184
|
+
const items = [...(list() ?? [])];
|
|
185
|
+
untrack(() => {
|
|
186
|
+
// Keys, made unique: a repeated key would make two rows share one identity.
|
|
187
|
+
const seen = new Set();
|
|
188
|
+
const keys = items.map((item, i) => {
|
|
189
|
+
let key = keyOf(item, i);
|
|
190
|
+
if (seen.has(key)) {
|
|
191
|
+
console.warn(`[clarusjs] @for: duplicate key ${String(key)}; rows with repeated keys are matched by position`);
|
|
192
|
+
key = `${String(key)}\u0000${i}`;
|
|
193
|
+
}
|
|
194
|
+
seen.add(key);
|
|
195
|
+
return key;
|
|
196
|
+
});
|
|
197
|
+
if (first) {
|
|
198
|
+
first = false;
|
|
199
|
+
rows = f.rows.map((range, i) => wireRow(range, keys[i], items[i], i));
|
|
200
|
+
if (f.empty)
|
|
201
|
+
emptyRange = wireEmpty(f.empty);
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
const old = new Map(rows.map((r) => [r.key, r]));
|
|
205
|
+
const next = items.map((item, i) => {
|
|
206
|
+
const kept = old.get(keys[i]);
|
|
207
|
+
if (kept) {
|
|
208
|
+
old.delete(keys[i]);
|
|
209
|
+
kept.item.set(item);
|
|
210
|
+
kept.index.set(i);
|
|
211
|
+
return kept;
|
|
212
|
+
}
|
|
213
|
+
const { first: start, last: end } = insertHtml(`<!--[r-->${row.html(item, i)}<!--]-->`, f.end);
|
|
214
|
+
return wireRow({ start: start, end: end }, keys[i], item, i);
|
|
215
|
+
});
|
|
216
|
+
for (const r of old.values()) {
|
|
217
|
+
r.dispose();
|
|
218
|
+
for (const n of rangeNodes(r.start, r.end))
|
|
219
|
+
n.parentNode?.removeChild(n);
|
|
220
|
+
}
|
|
221
|
+
// Put rows in order, moving only those that are not already right after the previous one.
|
|
222
|
+
let anchor = f.start;
|
|
223
|
+
for (const r of next) {
|
|
224
|
+
if (anchor.nextSibling !== r.start)
|
|
225
|
+
anchor.after(...rangeNodes(r.start, r.end));
|
|
226
|
+
anchor = r.end;
|
|
227
|
+
}
|
|
228
|
+
rows = next;
|
|
229
|
+
if (items.length && emptyRange) {
|
|
230
|
+
emptyRange.dispose();
|
|
231
|
+
for (const n of rangeNodes(emptyRange.start, emptyRange.end))
|
|
232
|
+
n.parentNode?.removeChild(n);
|
|
233
|
+
emptyRange = null;
|
|
234
|
+
}
|
|
235
|
+
else if (!items.length && !emptyRange && empty) {
|
|
236
|
+
const { first: start, last: end } = insertHtml(`<!--[e-->${empty.html()}<!--]-->`, f.end);
|
|
237
|
+
emptyRange = wireEmpty({ start: start, end: end });
|
|
238
|
+
}
|
|
239
|
+
});
|
|
240
|
+
});
|
|
22
241
|
}
|
|
23
242
|
/** Keep exactly one text node between the hole's markers, set to `fn()`. */
|
|
24
243
|
export function text(hole, fn) {
|
|
@@ -40,11 +259,13 @@ const registry = new WeakMap();
|
|
|
40
259
|
// These don't bubble, so they are caught on the way down instead.
|
|
41
260
|
const CAPTURE = new Set(['focus', 'blur']);
|
|
42
261
|
/**
|
|
43
|
-
* Register a handler for elements marked `data-cl-e="index"` inside
|
|
262
|
+
* Register a handler for elements marked `data-cl-e="index"` inside `ctx`.
|
|
44
263
|
* One listener per island per event type; it walks from the target up to the island root, running handlers
|
|
45
|
-
* innermost first and stopping when one calls `stopPropagation()`.
|
|
264
|
+
* innermost first and stopping when one calls `stopPropagation()`. A handler registered for a @for row only fires
|
|
265
|
+
* for elements in that row.
|
|
46
266
|
*/
|
|
47
|
-
export function on(
|
|
267
|
+
export function on(ctx, index, type, fn) {
|
|
268
|
+
const root = rootOf(ctx);
|
|
48
269
|
let types = registry.get(root);
|
|
49
270
|
if (!types)
|
|
50
271
|
registry.set(root, (types = new Map()));
|
|
@@ -57,8 +278,9 @@ export function on(root, index, type, fn) {
|
|
|
57
278
|
const i = el.getAttribute?.('data-cl-e');
|
|
58
279
|
if (i === null || i === undefined || el.closest('cl-island') !== root)
|
|
59
280
|
continue;
|
|
60
|
-
for (const h of own.get(Number(i)) ?? [])
|
|
61
|
-
h
|
|
281
|
+
for (const h of [...(own.get(Number(i)) ?? [])])
|
|
282
|
+
if (inside(h.ctx, el))
|
|
283
|
+
h.fn(e);
|
|
62
284
|
if (e.cancelBubble)
|
|
63
285
|
break;
|
|
64
286
|
}
|
|
@@ -66,5 +288,23 @@ export function on(root, index, type, fn) {
|
|
|
66
288
|
}
|
|
67
289
|
if (!handlers.has(index))
|
|
68
290
|
handlers.set(index, []);
|
|
69
|
-
handlers.get(index)
|
|
291
|
+
const list = handlers.get(index);
|
|
292
|
+
const handler = { fn, ctx };
|
|
293
|
+
list.push(handler);
|
|
294
|
+
onDispose(() => { const at = list.indexOf(handler); if (at !== -1)
|
|
295
|
+
list.splice(at, 1); }); // a removed branch or row stops listening
|
|
296
|
+
}
|
|
297
|
+
/** Keep attribute `name` of the element marked `data-cl-a="index"` in `ctx` in sync with `fn()`. */
|
|
298
|
+
export function attr(ctx, index, name, fn, tag) {
|
|
299
|
+
const root = rootOf(ctx);
|
|
300
|
+
const el = [...root.querySelectorAll(`[data-cl-a="${index}"]`)].find((e) => e.closest('cl-island') === root && inside(ctx, e));
|
|
301
|
+
if (!el)
|
|
302
|
+
return;
|
|
303
|
+
effect(() => {
|
|
304
|
+
const v = attrValue(name, fn(), tag);
|
|
305
|
+
if (v === null)
|
|
306
|
+
el.removeAttribute(name);
|
|
307
|
+
else
|
|
308
|
+
el.setAttribute(name, v === true ? '' : v);
|
|
309
|
+
});
|
|
70
310
|
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** Escape a value for HTML text or a double-quoted attribute. null/undefined render as ''. */
|
|
2
|
+
export declare function escape(value: unknown): string;
|
|
3
|
+
/** ` name="value"`, ` name` (true) or '' (false/null/undefined), escaped and URL-checked. */
|
|
4
|
+
export declare function attrHtml(name: string, value: unknown, tag?: string): string;
|
|
5
|
+
/** An @if block inside an island: markers record which branch (k, or -1 for none) was rendered. */
|
|
6
|
+
export declare function blockHtml(index: number, k: number, branches: (() => string)[]): string;
|
|
7
|
+
/** A @for list inside an island: one marker pair around the list, one per row, one around @empty content. */
|
|
8
|
+
export declare function forHtml(index: number, list: unknown, row: (item: any, i: number) => string, empty: (() => string) | null): string;
|
|
9
|
+
/** A child component inside an island that the browser may re-render: markers around its HTML. */
|
|
10
|
+
export declare function regionHtml(index: number, html: () => string): string;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// HTML-string helpers used by compiled code on the server (render) and in the browser (branch HTML for @if).
|
|
2
|
+
import { attrValue } from './attrs.js';
|
|
3
|
+
const ENTITIES = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };
|
|
4
|
+
/** Escape a value for HTML text or a double-quoted attribute. null/undefined render as ''. */
|
|
5
|
+
export function escape(value) {
|
|
6
|
+
if (value == null)
|
|
7
|
+
return '';
|
|
8
|
+
return String(value).replace(/[&<>"']/g, (ch) => ENTITIES[ch]);
|
|
9
|
+
}
|
|
10
|
+
/** ` name="value"`, ` name` (true) or '' (false/null/undefined), escaped and URL-checked. */
|
|
11
|
+
export function attrHtml(name, value, tag) {
|
|
12
|
+
const v = attrValue(name, value, tag);
|
|
13
|
+
return v === null ? '' : v === true ? ` ${name}` : ` ${name}="${escape(v)}"`;
|
|
14
|
+
}
|
|
15
|
+
/** An @if block inside an island: markers record which branch (k, or -1 for none) was rendered. */
|
|
16
|
+
export function blockHtml(index, k, branches) {
|
|
17
|
+
return `<!--[b${index}:${k}-->${k >= 0 ? branches[k]() : ''}<!--]-->`;
|
|
18
|
+
}
|
|
19
|
+
/** A @for list inside an island: one marker pair around the list, one per row, one around @empty content. */
|
|
20
|
+
export function forHtml(index, list, row, empty) {
|
|
21
|
+
const items = [...(list ?? [])];
|
|
22
|
+
const body = items.length
|
|
23
|
+
? items.map((item, i) => `<!--[r-->${row(item, i)}<!--]-->`).join('')
|
|
24
|
+
: empty ? `<!--[e-->${empty()}<!--]-->` : '';
|
|
25
|
+
return `<!--[f${index}-->${body}<!--]-->`;
|
|
26
|
+
}
|
|
27
|
+
/** A child component inside an island that the browser may re-render: markers around its HTML. */
|
|
28
|
+
export function regionHtml(index, html) {
|
|
29
|
+
return `<!--[c${index}-->${html()}<!--]-->`;
|
|
30
|
+
}
|
package/dist/runtime/index.d.ts
CHANGED
|
@@ -1,2 +1,4 @@
|
|
|
1
|
-
export { state, derived, effect, type Signal, type ReadSignal } from './signals.ts';
|
|
2
|
-
export { holes, text, on, type Hole } from './dom.ts';
|
|
1
|
+
export { state, derived, shared, effect, scope, onDispose, untrack, type Signal, type ReadSignal } from './signals.ts';
|
|
2
|
+
export { holes, blocks, text, on, attr, block, forBlock, region, type Hole, type Block, type Ctx } from './dom.ts';
|
|
3
|
+
export { escape, attrHtml, blockHtml, forHtml, regionHtml } from './html.ts';
|
|
4
|
+
export { parse as parseIslandData } from './serialize.ts';
|
package/dist/runtime/index.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
1
|
// Browser runtime used by compiled attach() functions.
|
|
2
|
-
export { state, derived, effect } from './signals.js';
|
|
3
|
-
export { holes, text, on } from './dom.js';
|
|
2
|
+
export { state, derived, shared, effect, scope, onDispose, untrack } from './signals.js';
|
|
3
|
+
export { holes, blocks, text, on, attr, block, forBlock, region } from './dom.js';
|
|
4
|
+
export { escape, attrHtml, blockHtml, forHtml, regionHtml } from './html.js';
|
|
5
|
+
export { parse as parseIslandData } from './serialize.js';
|
package/dist/runtime/loader.d.ts
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
type IslandModule = {
|
|
2
|
-
attach(root: Element, props: Record<string, unknown>): void;
|
|
2
|
+
attach(root: Element, props: Record<string, unknown>, state?: Record<string, unknown>): void;
|
|
3
3
|
};
|
|
4
|
-
|
|
4
|
+
type Load = (src: string) => Promise<IslandModule>;
|
|
5
|
+
/**
|
|
6
|
+
* Attach every island under `root` that isn't attached yet. Resolves once the islands that attach right away
|
|
7
|
+
* (the default, attach="load") are done; idle, visible and interaction islands attach later on their own.
|
|
8
|
+
*/
|
|
9
|
+
export declare function attachAll(root?: ParentNode, load?: Load): Promise<void>;
|
|
5
10
|
export {};
|
package/dist/runtime/loader.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
// Island loader: finds <cl-island> elements, loads each one's chunk, calls attach()
|
|
1
|
+
// Island loader: finds <cl-island> elements, loads each one's chunk when its attach mode says so, calls attach(),
|
|
2
|
+
// and replays what the visitor did before that. Browser only.
|
|
2
3
|
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
3
4
|
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
4
5
|
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
@@ -7,36 +8,132 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
|
|
|
7
8
|
}
|
|
8
9
|
return path;
|
|
9
10
|
};
|
|
10
|
-
|
|
11
|
+
import { parse } from './serialize.js';
|
|
12
|
+
// Islands scheduled or loading. `data-cl-ready` is set only after attach() succeeds.
|
|
11
13
|
const loading = new WeakSet();
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
14
|
+
let lastLoad = (src) => import(__rewriteRelativeImportExtension(/* @vite-ignore */ src));
|
|
15
|
+
// Events recorded until an island attaches, then replayed. Clicks and submits are held back (no navigation, no
|
|
16
|
+
// form post) so the island can handle them once it is ready.
|
|
17
|
+
const REPLAY = ['click', 'submit', 'input', 'change', 'keydown'];
|
|
18
|
+
const HOLD = new Set(['click', 'submit']);
|
|
19
|
+
// What counts as using an island, for attach="interaction".
|
|
20
|
+
const INTERACTION = ['pointerdown', 'keydown', 'focusin', 'input', 'click', 'submit'];
|
|
21
|
+
/** Record events aimed at this island (not at an island nested in it) until stop() is called. */
|
|
22
|
+
function record(el) {
|
|
23
|
+
const events = [];
|
|
24
|
+
const listener = (e) => {
|
|
25
|
+
const target = e.target;
|
|
26
|
+
if (!target || target.closest?.('cl-island') !== el)
|
|
25
27
|
return;
|
|
28
|
+
if (HOLD.has(e.type))
|
|
29
|
+
e.preventDefault();
|
|
30
|
+
events.push({ type: e.type, target, key: e.key });
|
|
31
|
+
};
|
|
32
|
+
for (const type of REPLAY)
|
|
33
|
+
el.addEventListener(type, listener, true);
|
|
34
|
+
return { events, stop: () => { for (const type of REPLAY)
|
|
35
|
+
el.removeEventListener(type, listener, true); } };
|
|
36
|
+
}
|
|
37
|
+
/** Do again what the visitor did before the island attached, now that its handlers are listening. */
|
|
38
|
+
function replay(events) {
|
|
39
|
+
for (const { type, target, key } of events) {
|
|
40
|
+
if (!target.isConnected)
|
|
41
|
+
continue;
|
|
42
|
+
if (type === 'click')
|
|
43
|
+
target.click?.();
|
|
44
|
+
else if (type === 'submit') {
|
|
45
|
+
const form = target;
|
|
46
|
+
if (typeof form.requestSubmit === 'function')
|
|
47
|
+
form.requestSubmit();
|
|
48
|
+
else
|
|
49
|
+
form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
|
|
26
50
|
}
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
51
|
+
else if (type === 'keydown')
|
|
52
|
+
target.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true }));
|
|
53
|
+
else
|
|
54
|
+
target.dispatchEvent(new Event(type, { bubbles: true }));
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
/** Run `go` when the island's attach mode (`a` attribute) says: now, when idle, when visible, or on first use. */
|
|
58
|
+
function schedule(el, go) {
|
|
59
|
+
const mode = el.getAttribute('a') ?? 'load';
|
|
60
|
+
if (mode === 'idle') {
|
|
61
|
+
const idle = globalThis.requestIdleCallback;
|
|
62
|
+
if (idle)
|
|
63
|
+
idle(go);
|
|
64
|
+
else
|
|
65
|
+
setTimeout(go, 200);
|
|
66
|
+
}
|
|
67
|
+
else if (mode === 'visible' && typeof IntersectionObserver === 'function') {
|
|
68
|
+
const io = new IntersectionObserver((entries) => {
|
|
69
|
+
if (entries.some((entry) => entry.isIntersecting)) {
|
|
70
|
+
io.disconnect();
|
|
71
|
+
go();
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
io.observe(el);
|
|
75
|
+
}
|
|
76
|
+
else if (mode === 'interaction') {
|
|
77
|
+
const start = () => { for (const type of INTERACTION)
|
|
78
|
+
el.removeEventListener(type, start, true); go(); };
|
|
79
|
+
for (const type of INTERACTION)
|
|
80
|
+
el.addEventListener(type, start, true);
|
|
81
|
+
}
|
|
82
|
+
else {
|
|
83
|
+
go();
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
async function attachOne(el, load, recorded) {
|
|
87
|
+
let mod;
|
|
88
|
+
let props;
|
|
89
|
+
let state;
|
|
90
|
+
try {
|
|
91
|
+
mod = await load(el.getAttribute('src'));
|
|
92
|
+
props = parse(el.getAttribute('p') ?? '{}');
|
|
93
|
+
const s = el.getAttribute('s');
|
|
94
|
+
state = s === null ? undefined : parse(s);
|
|
95
|
+
}
|
|
96
|
+
catch (err) {
|
|
97
|
+
recorded.stop();
|
|
98
|
+
loading.delete(el); // network or parse failure: the next attachAll() retries
|
|
99
|
+
console.error(`[clarusjs] island "${el.getAttribute('c')}" failed to load`, err);
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
try {
|
|
103
|
+
mod.attach(el, props, state);
|
|
104
|
+
el.setAttribute('data-cl-ready', '');
|
|
105
|
+
}
|
|
106
|
+
catch (err) {
|
|
107
|
+
el.setAttribute('data-cl-error', ''); // attach may have wired some listeners already: never retry
|
|
108
|
+
console.error(`[clarusjs] island "${el.getAttribute('c')}" failed to attach`, err);
|
|
109
|
+
}
|
|
110
|
+
finally {
|
|
111
|
+
loading.delete(el);
|
|
112
|
+
}
|
|
113
|
+
recorded.stop();
|
|
114
|
+
if (el.hasAttribute('data-cl-ready'))
|
|
115
|
+
replay(recorded.events);
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Attach every island under `root` that isn't attached yet. Resolves once the islands that attach right away
|
|
119
|
+
* (the default, attach="load") are done; idle, visible and interaction islands attach later on their own.
|
|
120
|
+
*/
|
|
121
|
+
export async function attachAll(root = document, load = lastLoad) {
|
|
122
|
+
lastLoad = load;
|
|
123
|
+
const islands = [...root.querySelectorAll('cl-island:not([data-cl-ready]):not([data-cl-error])')].filter((el) => !loading.has(el));
|
|
124
|
+
const now = [];
|
|
125
|
+
for (const el of islands) {
|
|
126
|
+
loading.add(el);
|
|
127
|
+
const recorded = record(el);
|
|
128
|
+
if ((el.getAttribute('a') ?? 'load') === 'load')
|
|
129
|
+
now.push(attachOne(el, load, recorded));
|
|
130
|
+
else
|
|
131
|
+
schedule(el, () => void attachOne(el, load, recorded));
|
|
132
|
+
}
|
|
133
|
+
await Promise.all(now);
|
|
40
134
|
}
|
|
135
|
+
// Islands inserted later (an @if branch, a @for row, a re-rendered child) are attached through this hook.
|
|
136
|
+
;
|
|
137
|
+
globalThis.__clAttach = (root) => void attachAll(root);
|
|
41
138
|
if (typeof document !== 'undefined')
|
|
42
139
|
attachAll();
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* JSON plus Date, Map, Set, undefined, NaN, ±Infinity, -0 and BigInt. Objects that themselves have a `$cl` key are
|
|
3
|
+
* wrapped so data is never mistaken for a tag. Functions, symbols, class instances and cycles are rejected with the
|
|
4
|
+
* path to the bad value.
|
|
5
|
+
*/
|
|
6
|
+
export declare function stringify(value: unknown): string;
|
|
7
|
+
/** The inverse of stringify(). */
|
|
8
|
+
export declare function parse(text: string): unknown;
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// Island props and state go from server HTML to the browser as JSON, with tags for what JSON can't hold.
|
|
2
|
+
// Shared by the server (stringify) and the browser (parse).
|
|
3
|
+
const TAG = '$cl';
|
|
4
|
+
/**
|
|
5
|
+
* JSON plus Date, Map, Set, undefined, NaN, ±Infinity, -0 and BigInt. Objects that themselves have a `$cl` key are
|
|
6
|
+
* wrapped so data is never mistaken for a tag. Functions, symbols, class instances and cycles are rejected with the
|
|
7
|
+
* path to the bad value.
|
|
8
|
+
*/
|
|
9
|
+
export function stringify(value) {
|
|
10
|
+
return JSON.stringify(encode(value, '', new Set()));
|
|
11
|
+
}
|
|
12
|
+
function encode(value, path, seen) {
|
|
13
|
+
const at = (key) => (path ? `${path}.${key}` : String(key));
|
|
14
|
+
const fail = (what) => {
|
|
15
|
+
throw new TypeError(`[clarusjs] cannot send ${path || 'the value'} to the browser: ${what}`);
|
|
16
|
+
};
|
|
17
|
+
switch (typeof value) {
|
|
18
|
+
case 'undefined':
|
|
19
|
+
return { [TAG]: 'u' };
|
|
20
|
+
case 'number':
|
|
21
|
+
if (Number.isFinite(value) && !Object.is(value, -0))
|
|
22
|
+
return value;
|
|
23
|
+
return { [TAG]: 'n', v: Object.is(value, -0) ? '-0' : String(value) };
|
|
24
|
+
case 'bigint':
|
|
25
|
+
return { [TAG]: 'b', v: value.toString() };
|
|
26
|
+
case 'function':
|
|
27
|
+
case 'symbol':
|
|
28
|
+
return fail(`it is a ${typeof value}`);
|
|
29
|
+
case 'object': {
|
|
30
|
+
if (value === null)
|
|
31
|
+
return null;
|
|
32
|
+
if (seen.has(value))
|
|
33
|
+
return fail('circular reference');
|
|
34
|
+
seen.add(value);
|
|
35
|
+
try {
|
|
36
|
+
if (Array.isArray(value)) {
|
|
37
|
+
const out = [];
|
|
38
|
+
for (let i = 0; i < value.length; i++)
|
|
39
|
+
out.push(encode(value[i], at(i), seen));
|
|
40
|
+
return out;
|
|
41
|
+
}
|
|
42
|
+
if (value instanceof Date)
|
|
43
|
+
return { [TAG]: 'd', v: Number.isNaN(value.getTime()) ? null : value.toISOString() };
|
|
44
|
+
if (value instanceof Map)
|
|
45
|
+
return { [TAG]: 'm', v: [...value].map(([k, v], i) => [encode(k, at(`key${i}`), seen), encode(v, at(i), seen)]) };
|
|
46
|
+
if (value instanceof Set)
|
|
47
|
+
return { [TAG]: 's', v: [...value].map((v, i) => encode(v, at(i), seen)) };
|
|
48
|
+
const proto = Object.getPrototypeOf(value);
|
|
49
|
+
if (proto !== Object.prototype && proto !== null) {
|
|
50
|
+
return fail(`it is a ${proto?.constructor?.name ?? 'class instance'}; only plain objects, arrays, Date, Map and Set can be sent`);
|
|
51
|
+
}
|
|
52
|
+
const out = {};
|
|
53
|
+
for (const [k, v] of Object.entries(value))
|
|
54
|
+
out[k] = encode(v, at(k), seen);
|
|
55
|
+
return TAG in out ? { [TAG]: 'o', v: out } : out;
|
|
56
|
+
}
|
|
57
|
+
finally {
|
|
58
|
+
seen.delete(value);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
default:
|
|
62
|
+
return value; // string, boolean
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
/** The inverse of stringify(). */
|
|
66
|
+
export function parse(text) {
|
|
67
|
+
return decode(JSON.parse(text));
|
|
68
|
+
}
|
|
69
|
+
function decode(value) {
|
|
70
|
+
if (Array.isArray(value))
|
|
71
|
+
return value.map(decode);
|
|
72
|
+
if (value === null || typeof value !== 'object')
|
|
73
|
+
return value;
|
|
74
|
+
if (TAG in value) {
|
|
75
|
+
const { [TAG]: tag, v } = value;
|
|
76
|
+
switch (tag) {
|
|
77
|
+
case 'u': return undefined;
|
|
78
|
+
case 'n': return v === '-0' ? -0 : Number(v);
|
|
79
|
+
case 'b': return BigInt(v);
|
|
80
|
+
case 'd': return new Date(v === null ? NaN : v);
|
|
81
|
+
case 'm': return new Map(v.map(([k, x]) => [decode(k), decode(x)]));
|
|
82
|
+
case 's': return new Set(v.map(decode));
|
|
83
|
+
case 'o': return decodeObject(v);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return decodeObject(value);
|
|
87
|
+
}
|
|
88
|
+
function decodeObject(value) {
|
|
89
|
+
const out = {};
|
|
90
|
+
for (const [k, v] of Object.entries(value))
|
|
91
|
+
out[k] = decode(v);
|
|
92
|
+
return out;
|
|
93
|
+
}
|