@barqjs/universal 0.0.0-stage → 0.2.0-next.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.
@@ -0,0 +1,1059 @@
1
+ /**
2
+ * A renderer over any tree of nodes a host can create and arrange.
3
+ *
4
+ * `@barqjs/core` owns control flow and decides when a range of nodes changes;
5
+ * this file is the node layer under it, written against `HostOps` instead of
6
+ * the document: the `RangeHost` control flow writes through, the list reorder
7
+ * `each` hands it, and the entry points compiled code calls.
8
+ */
9
+
10
+ import {
11
+ type BoundaryKind,
12
+ type COUNT,
13
+ type JSXElement,
14
+ type Maybe,
15
+ type RevealOrder,
16
+ type Scope,
17
+ createEffect,
18
+ getOwner,
19
+ isBlock,
20
+ NotReadyError,
21
+ onCleanup,
22
+ ownRange,
23
+ readSlot,
24
+ rootScope,
25
+ runWithOwner,
26
+ untrack,
27
+ } from "@barqjs/core";
28
+ import type { Block, Cell } from "@barqjs/core";
29
+ import {
30
+ CONTEXT_MISS,
31
+ LIVE_EDGES,
32
+ LIVE_ROWS,
33
+ NOTHING,
34
+ activate,
35
+ boundaryIn,
36
+ branchIn,
37
+ cellSlot,
38
+ disposeScope,
39
+ eachIn,
40
+ effectUnder,
41
+ mountTree,
42
+ internalMemo,
43
+ isNodes,
44
+ islandIn,
45
+ jsxAsValue,
46
+ longestIncreasingSubsequence,
47
+ lookupContext,
48
+ nextActivation,
49
+ offerDefaultHost,
50
+ provideHost,
51
+ provideOn,
52
+ revealIn,
53
+ standingRow,
54
+ standingRows,
55
+ teardown,
56
+ underScope,
57
+ withoutClaim,
58
+ type RangeHost,
59
+ type Row,
60
+ type Site,
61
+ type SyncRows,
62
+ } from "@barqjs/core/internal";
63
+
64
+ /**
65
+ * What a host gives the renderer. `N` is the host's node; the renderer never
66
+ * looks inside one.
67
+ *
68
+ * `insertNode` MOVES a node that already has a parent, the way the document's
69
+ * `insertBefore` does: a reorder is an insert of a node that is already in
70
+ * the tree, and the renderer never removes it first.
71
+ */
72
+ export interface HostOps<N extends object> {
73
+ createElement(tag: string): N;
74
+ createTextNode(value: string): N;
75
+ replaceText(node: N, value: string): void;
76
+ isTextNode(node: N): boolean;
77
+ /** `prev` is the value this name was last set to on this node, `undefined` the first time. */
78
+ setProperty(node: N, name: string, value: unknown, prev: unknown): void;
79
+ /** Put `node` under `parent` before `anchor`, or last when `anchor` is `null`. */
80
+ insertNode(parent: N, node: N, anchor: N | null): void;
81
+ removeNode(parent: N, node: N): void;
82
+ getParentNode(node: N): N | null | undefined;
83
+ getFirstChild(node: N): N | null | undefined;
84
+ getNextSibling(node: N): N | null | undefined;
85
+ /** A node that renders nothing, to anchor a range against. Defaults to an empty text node. */
86
+ createSentinel?(): N;
87
+ /**
88
+ * A detached node that holds children, for content built while it is not
89
+ * shown: a `<Loading>` boundary's body while its fallback stands, or a range
90
+ * built before anything placed it. Defaults to `createElement("#container")`.
91
+ */
92
+ createContainer?(): N;
93
+ /**
94
+ * Hand a `ref` what it should hold for `node`, in place of the node itself.
95
+ * A host whose node stands for an object it builds later (once a property
96
+ * the object's constructor needs has arrived) calls `deliver` with that
97
+ * object when it exists and again each time it is replaced, and returns the
98
+ * function that stops delivering. Without it a ref is handed the node, once.
99
+ */
100
+ attachRef?(node: N, deliver: (value: unknown) => void): () => void;
101
+ /**
102
+ * Told once a batch of inserts under `parent` is done: the nodes a list
103
+ * placed, a hole filled, a range moved. A host that keeps its own order of
104
+ * children cheaply by appending during the batch puts them in order here,
105
+ * so nothing reads them in the wrong order.
106
+ */
107
+ placed?(parent: N): void;
108
+ }
109
+
110
+ /** What `render` accepts besides the tree and the node it is mounted into. */
111
+ export interface RenderOptions {
112
+ /** Parents the root, so the tree reads that owner's contexts and is disposed with it. */
113
+ readonly owner?: Scope | null;
114
+ readonly renderId?: string;
115
+ }
116
+
117
+ export interface PortalProps<N extends object> {
118
+ /** The node the children mount into. Defaults to the node the tree was rendered into. */
119
+ mount?: N | null | (() => N | null | undefined);
120
+ children: unknown;
121
+ }
122
+
123
+ /** What a `dynamic` source may answer with: a tag name or a function of one props object. */
124
+ export type DynamicTag = string | ((props: never) => unknown);
125
+
126
+ export type Spreadable = Record<string, unknown> | (() => Record<string, unknown>);
127
+
128
+ /**
129
+ * What `createRenderer` returns. Every member is a function of its arguments
130
+ * alone, so a renderer module destructures them into its exports.
131
+ */
132
+ export interface Renderer<N extends object> {
133
+ /**
134
+ * Build `code` under a new root and put what it renders into `root`. The
135
+ * returned function disposes the root and removes what it placed.
136
+ */
137
+ render: (code: (() => JSXElement) | JSXElement, root: N, options?: RenderOptions) => () => void;
138
+ createElement: (tag: string) => N;
139
+ createTextNode: (value: string) => N;
140
+ insertNode: (parent: N, node: N, anchor?: N | null) => void;
141
+ /** Writes one property and returns `value`, so a binding can keep it as its previous value. */
142
+ setProp: <T>(node: N, name: string, value: T, prev?: unknown) => T;
143
+ insert: (parent: N, value: unknown, anchor?: N | null) => void;
144
+ spread: (node: N, props: Spreadable, later?: readonly string[]) => void;
145
+ branch: <K>(
146
+ parent: N | null,
147
+ anchor: N | null,
148
+ key: Cell<K>,
149
+ bodies: Block<unknown> | readonly (Block<unknown> | null | undefined)[],
150
+ flags?: number,
151
+ ) => N | N[] | null;
152
+ each: <T>(
153
+ parent: N | null,
154
+ anchor: N | null,
155
+ src: Cell<Maybe<readonly T[]>> | Cell<number>,
156
+ carrier: ((item: T) => unknown) | false | null | typeof COUNT | Cell<unknown>,
157
+ row: Block<unknown, never[]>,
158
+ flags?: number,
159
+ fallback?: Block<unknown> | null,
160
+ ) => N | N[] | null;
161
+ boundary: (
162
+ parent: N | null,
163
+ anchor: N | null,
164
+ kind: BoundaryKind,
165
+ fallback: Block<unknown> | null | undefined,
166
+ body: Block<unknown>,
167
+ flags?: number,
168
+ on?: Cell<unknown>,
169
+ ) => N | N[] | null;
170
+ island: (parent: N | null, anchor: N | null, block: Block<unknown>, flags?: number) => N | null;
171
+ reveal: (
172
+ order: Cell<RevealOrder | undefined>,
173
+ collapsed: Cell<boolean | undefined>,
174
+ block: Block<unknown>,
175
+ ) => N[];
176
+ portal: (target: Cell<N | null | undefined>, block: Block<unknown>, flags?: number) => N;
177
+ /** Solid 2.0's factory for a component chosen at run time: a tag name or a component. */
178
+ dynamic: (
179
+ source: () => DynamicTag | null | undefined | false,
180
+ ) => (props: Record<string, unknown>) => JSXElement;
181
+ Portal: (props: PortalProps<N>) => JSXElement;
182
+ /** The host control flow writes through, for a construct written by hand. */
183
+ host: RangeHost<N>;
184
+ /** The list reorder `each` hands control flow, over the same operations. */
185
+ syncRows: SyncRows<N>;
186
+ }
187
+
188
+ const NO_ARGS: readonly unknown[] = [];
189
+
190
+ /** The node a tree was rendered into, for a portal that names no target. */
191
+ const RENDER_ROOT: unique symbol = Symbol("render-root");
192
+
193
+ /** What a live hole resolved to: text it writes through, or the nodes it owns. */
194
+ type Resolved<N> = string | number | N[];
195
+
196
+ const UNRESOLVED: unique symbol = Symbol("barq-unresolved");
197
+
198
+ /** A child that is neither a node, a function, an array nor nothing: text. */
199
+ function asText(value: unknown): string {
200
+ if (typeof value === "string") return value;
201
+ if (typeof value === "number" || typeof value === "bigint") return String(value);
202
+ return typeof value === "symbol" ? value.toString() : "";
203
+ }
204
+
205
+ export function createRenderer<N extends object>(ops: HostOps<N>): Renderer<N> {
206
+ const isTextNode = (node: N): boolean => ops.isTextNode(node);
207
+ const removeNode = (parent: N, node: N): void => ops.removeNode(parent, node);
208
+ const setProperty = (node: N, name: string, value: unknown, prev: unknown): void =>
209
+ ops.setProperty(node, name, value, prev);
210
+ const createSentinel =
211
+ ops.createSentinel === undefined ? () => createTextNode("") : () => ops.createSentinel!();
212
+ const createContainer =
213
+ ops.createContainer === undefined
214
+ ? () => ops.createElement("#container")
215
+ : () => ops.createContainer!();
216
+ const attachRef =
217
+ ops.attachRef === undefined
218
+ ? undefined
219
+ : (node: N, deliver: (value: unknown) => void) => ops.attachRef!(node, deliver);
220
+ const placed =
221
+ ops.placed === undefined ? (_parent: N): void => {} : (parent: N) => ops.placed!(parent);
222
+
223
+ // The text each text node was created with or last set to. The host has no
224
+ // operation to read it back, and a hole that rewrites the same string keeps
225
+ // its node only if the comparison can be made here.
226
+ const texts = new WeakMap<N, string>();
227
+ const parks = new WeakSet<N>();
228
+ // A container's children leave it when it is placed. Read twice, it answers
229
+ // with what it held, as a document fragment's drained content is kept.
230
+ const drained = new WeakMap<N, N[]>();
231
+
232
+ function createTextNode(value: string): N {
233
+ const node = ops.createTextNode(value);
234
+ texts.set(node, value);
235
+ return node;
236
+ }
237
+
238
+ function writeText(node: N, value: string): void {
239
+ if (texts.get(node) === value) return;
240
+ ops.replaceText(node, value);
241
+ texts.set(node, value);
242
+ }
243
+
244
+ function parentOf(node: N): N | null {
245
+ return ops.getParentNode(node) ?? null;
246
+ }
247
+
248
+ function nextOf(node: N): N | null {
249
+ return ops.getNextSibling(node) ?? null;
250
+ }
251
+
252
+ function firstOf(parent: N): N | null {
253
+ return ops.getFirstChild(parent) ?? null;
254
+ }
255
+
256
+ function insertNode(parent: N, node: N, anchor: N | null = null): void {
257
+ ops.insertNode(parent, node, anchor);
258
+ }
259
+
260
+ function detach(node: N): void {
261
+ const parent = parentOf(node);
262
+ if (parent !== null) removeNode(parent, node);
263
+ }
264
+
265
+ /** `insertNode` that does nothing when the node is already there. */
266
+ function place(parent: N, node: N, before: N | null): void {
267
+ if (parentOf(node) === parent && nextOf(node) === before) return;
268
+ insertNode(parent, node, before);
269
+ }
270
+
271
+ function park(): N {
272
+ const node = createContainer();
273
+ parks.add(node);
274
+ return node;
275
+ }
276
+
277
+ function drain(container: N): N[] {
278
+ const first = firstOf(container);
279
+ if (first === null) return drained.get(container)?.slice() ?? [];
280
+ const nodes: N[] = [];
281
+ for (let node: N | null = first; node !== null; node = nextOf(node)) nodes.push(node);
282
+ for (const node of nodes) removeNode(container, node);
283
+ drained.set(container, nodes);
284
+ return nodes.slice();
285
+ }
286
+
287
+ // ==========================================================================
288
+ // Children into nodes
289
+ // ==========================================================================
290
+
291
+ /**
292
+ * A Block is a construction and runs untracked. One that suspends is run
293
+ * again tracked: nothing was built and an untracked read registered nothing,
294
+ * so the position could never wake.
295
+ */
296
+ function buildChild(value: (owner: unknown) => unknown, owner: Scope | null): unknown {
297
+ if (!isBlock(value)) return value(owner);
298
+ try {
299
+ return untrack(() => value(owner));
300
+ } catch (error) {
301
+ if (!(error instanceof NotReadyError)) throw error;
302
+ return value(owner);
303
+ }
304
+ }
305
+
306
+ /** What a Cell comes to once every Cell it yields has been read as well. */
307
+ function yielded(value: unknown, owner: Scope | null): unknown {
308
+ while (typeof value === "function" && !isBlock(value)) {
309
+ value = (value as (owner: unknown) => unknown)(owner);
310
+ }
311
+ return value;
312
+ }
313
+
314
+ function toNodes(child: unknown, scope: Scope | null): N[] {
315
+ if (child === null || child === undefined || typeof child === "boolean") return [];
316
+ if (typeof child === "function") {
317
+ if (!isBlock(child)) return liveHole(child as (owner: unknown) => unknown, scope);
318
+ return toNodes(buildChild(child as (owner: unknown) => unknown, scope), scope);
319
+ }
320
+ if (Array.isArray(child)) {
321
+ const nodes: N[] = [];
322
+ for (let i = 0; i < child.length; i++) {
323
+ const inner = toNodes(child[i], scope);
324
+ for (let j = 0; j < inner.length; j++) nodes.push(inner[j]);
325
+ }
326
+ return nodes;
327
+ }
328
+ if (typeof child === "object") {
329
+ return parks.has(child as N) ? drain(child as N) : [child as N];
330
+ }
331
+ return [createTextNode(asText(child))];
332
+ }
333
+
334
+ /**
335
+ * Flatten a child to nodes for a hole that already holds `prev`, reusing a
336
+ * text node at the same position whose text is unchanged.
337
+ */
338
+ function normalize(value: unknown, prev: readonly N[], scope: Scope | null): N[] {
339
+ const out: N[] = [];
340
+ const visit = (child: unknown): void => {
341
+ if (child === null || child === undefined || typeof child === "boolean") return;
342
+ if (typeof child === "function") {
343
+ if (isBlock(child)) {
344
+ visit(buildChild(child as (owner: unknown) => unknown, scope));
345
+ return;
346
+ }
347
+ for (const node of liveHole(child as (owner: unknown) => unknown, scope)) out.push(node);
348
+ return;
349
+ }
350
+ if (Array.isArray(child)) {
351
+ for (let i = 0; i < child.length; i++) visit(child[i]);
352
+ return;
353
+ }
354
+ if (typeof child === "object") {
355
+ if (parks.has(child as N)) {
356
+ for (const node of drain(child as N)) out.push(node);
357
+ } else {
358
+ out.push(child as N);
359
+ }
360
+ return;
361
+ }
362
+ const text = asText(child);
363
+ const candidate = prev[out.length];
364
+ if (candidate !== undefined && isTextNode(candidate) && texts.get(candidate) === text) {
365
+ out.push(candidate);
366
+ } else {
367
+ out.push(createTextNode(text));
368
+ }
369
+ };
370
+ visit(value);
371
+ return out;
372
+ }
373
+
374
+ /**
375
+ * A Cell that is not the whole value of a hole: one entry of a children
376
+ * array, or a body with no element around it. It gets an effect and a text
377
+ * node of its own, so it updates where it stands without anything around it
378
+ * being asked again. The text node is the value when the value is text, and
379
+ * the edge its nodes are placed before when it is not.
380
+ */
381
+ function liveHole(cell: (owner: unknown) => unknown, given: Scope | null): N[] {
382
+ let tail: N | null = null;
383
+ let current: N[] = [];
384
+ let initial = UNRESOLVED as Resolved<N> | typeof UNRESOLVED;
385
+ let written = false;
386
+ let standing = false;
387
+
388
+ const write = (resolved: Resolved<N>): void => {
389
+ if (typeof resolved !== "object") {
390
+ const text = String(resolved);
391
+ if (tail === null) {
392
+ tail = createTextNode(text);
393
+ return;
394
+ }
395
+ if (current.length > 0) {
396
+ removeAll(current);
397
+ current = [];
398
+ }
399
+ writeText(tail, text);
400
+ return;
401
+ }
402
+ if (tail === null) {
403
+ tail = createTextNode("");
404
+ current = resolved;
405
+ return;
406
+ }
407
+ writeText(tail, "");
408
+ const parent = parentOf(tail);
409
+ current = parent === null ? resolved : placeInsert(parent, resolved, current, tail);
410
+ };
411
+
412
+ effectUnder<Resolved<N>>(
413
+ given,
414
+ "insert",
415
+ () => {
416
+ const owner = getOwner();
417
+ const resolved = resolve(yielded(cell(owner), owner), current, given);
418
+ if (!standing) initial = resolved;
419
+ return resolved;
420
+ },
421
+ (resolved) => {
422
+ if (!standing) {
423
+ written = true;
424
+ return;
425
+ }
426
+ const first = resolved === initial;
427
+ initial = UNRESOLVED;
428
+ if (!first) write(resolved);
429
+ },
430
+ );
431
+ standing = true;
432
+ const took = initial;
433
+ if (written) initial = UNRESOLVED;
434
+ if (took !== UNRESOLVED) write(took);
435
+ const edge: N = tail ?? createTextNode("");
436
+ LIVE_EDGES.add(edge);
437
+ return current.length === 0 ? [edge] : [...current, edge];
438
+ }
439
+
440
+ function resolve(value: unknown, current: readonly N[], scope: Scope | null): Resolved<N> {
441
+ if (typeof value === "string" || typeof value === "number") return value;
442
+ return normalize(value, current, scope);
443
+ }
444
+
445
+ // ==========================================================================
446
+ // Placing a hole's nodes
447
+ // ==========================================================================
448
+
449
+ // Last node first: a host keeping children in an array finds each one at
450
+ // its end and removes it without moving the rest.
451
+ function removeAll(nodes: readonly N[]): void {
452
+ for (let i = nodes.length - 1; i >= 0; i--) detach(nodes[i]);
453
+ }
454
+
455
+ /**
456
+ * Put `value` into `parent` in place of `current`, before `marker`, and
457
+ * return what the hole holds now.
458
+ */
459
+ function placeInsert(parent: N, value: Resolved<N>, current: N[], marker: N | null): N[] {
460
+ let next: N[];
461
+ if (typeof value === "string" || typeof value === "number") {
462
+ const text = String(value);
463
+ if (current.length === 1 && isTextNode(current[0])) {
464
+ writeText(current[0], text);
465
+ return current;
466
+ }
467
+ next = [createTextNode(text)];
468
+ } else {
469
+ next = value;
470
+ }
471
+ if (current.length === 0) {
472
+ for (let i = 0; i < next.length; i++) insertNode(parent, next[i], marker);
473
+ placed(parent);
474
+ return next;
475
+ }
476
+ if (next.length === 0) {
477
+ removeAll(current);
478
+ return [];
479
+ }
480
+ const into = parentOf(current[0]) ?? parent;
481
+ reconcile(into, current, next, marker);
482
+ placed(into);
483
+ return next;
484
+ }
485
+
486
+ /**
487
+ * Reconcile two node arrays by identity: common prefix and suffix, the swap
488
+ * of two ends, then a map of what is left. Adapted from udomdiff, as the
489
+ * document renderer's is.
490
+ */
491
+ function reconcile(parent: N, a: N[], b: N[], after: N | null): void {
492
+ const bLength = b.length;
493
+ let aEnd = a.length;
494
+ let bEnd = bLength;
495
+ let aStart = 0;
496
+ let bStart = 0;
497
+ let map: Map<N, number> | null = null;
498
+
499
+ while (aStart < aEnd || bStart < bEnd) {
500
+ if (a[aStart] === b[bStart]) {
501
+ aStart++;
502
+ bStart++;
503
+ continue;
504
+ }
505
+ while (a[aEnd - 1] === b[bEnd - 1]) {
506
+ aEnd--;
507
+ bEnd--;
508
+ }
509
+ if (aEnd === aStart) {
510
+ const anchor = bEnd < bLength ? (bStart ? nextOf(b[bStart - 1]) : b[bEnd - bStart]) : after;
511
+ while (bStart < bEnd) insertNode(parent, b[bStart++], anchor);
512
+ } else if (bEnd === bStart) {
513
+ while (aStart < aEnd) {
514
+ if (!map || !map.has(a[aStart])) detach(a[aStart]);
515
+ aStart++;
516
+ }
517
+ } else if (a[aStart] === b[bEnd - 1] && b[bStart] === a[aEnd - 1]) {
518
+ const node = nextOf(a[--aEnd]);
519
+ insertNode(parent, b[bStart++], nextOf(a[aStart++]));
520
+ insertNode(parent, b[--bEnd], node);
521
+ a[aEnd] = b[bEnd];
522
+ } else {
523
+ if (!map) {
524
+ map = new Map();
525
+ for (let i = bStart; i < bEnd; i++) map.set(b[i], i);
526
+ }
527
+ const index = map.get(a[aStart]);
528
+ if (index === undefined) {
529
+ detach(a[aStart++]);
530
+ } else if (index < bStart || index >= bEnd) {
531
+ aStart++;
532
+ } else {
533
+ let sequence = 1;
534
+ let t: number | undefined;
535
+ while (
536
+ aStart + sequence < aEnd &&
537
+ (t = map.get(a[aStart + sequence])) !== undefined &&
538
+ t === index + sequence
539
+ ) {
540
+ sequence++;
541
+ }
542
+ if (sequence > index - bStart) {
543
+ const node = a[aStart];
544
+ while (bStart < index) insertNode(parent, b[bStart++], node);
545
+ } else {
546
+ const replaced = a[aStart++];
547
+ insertNode(parent, b[bStart++], replaced);
548
+ removeNode(parent, replaced);
549
+ }
550
+ }
551
+ }
552
+ }
553
+ }
554
+
555
+ // ==========================================================================
556
+ // The host control flow writes through
557
+ // ==========================================================================
558
+
559
+ /**
560
+ * What a list row of these nodes stands on. A row holding a live edge is
561
+ * given a node to start at, so it is read off the tree as it stands when it
562
+ * moves rather than as it was built.
563
+ */
564
+ function asRow(nodes: N[]): N[] {
565
+ for (let i = 0; i < nodes.length; i++) {
566
+ if (!LIVE_EDGES.has(nodes[i])) continue;
567
+ const row = [createSentinel(), ...nodes];
568
+ LIVE_ROWS.add(row);
569
+ return row;
570
+ }
571
+ return nodes;
572
+ }
573
+
574
+ const host: RangeHost<N> = {
575
+ sentinel: createSentinel,
576
+ park,
577
+ isPark: (node) => parks.has(node),
578
+ parentOf,
579
+ nextOf,
580
+ prevOf(node) {
581
+ const parent = parentOf(node);
582
+ if (parent === null) return null;
583
+ let previous: N | null = null;
584
+ for (let at = firstOf(parent); at !== null && at !== node; at = nextOf(at)) previous = at;
585
+ return previous;
586
+ },
587
+ firstOf,
588
+ lastOf(parent) {
589
+ let last: N | null = null;
590
+ for (let at = firstOf(parent); at !== null; at = nextOf(at)) last = at;
591
+ return last;
592
+ },
593
+ row: asRow,
594
+ toNodes,
595
+ insertRange(parent, nodes, before) {
596
+ let anchor = before;
597
+ for (let i = nodes.length; i--;) {
598
+ place(parent, nodes[i], anchor);
599
+ anchor = nodes[i];
600
+ }
601
+ placed(parent);
602
+ },
603
+ removeRange: removeAll,
604
+ };
605
+
606
+ // ==========================================================================
607
+ // The list reorder
608
+ // ==========================================================================
609
+
610
+ function rowFirst(row: Row<N>): N | undefined {
611
+ return isNodes(row) ? row[0] : row;
612
+ }
613
+
614
+ function nodesOf(row: Row<N>): readonly N[] {
615
+ return isNodes(row) ? standingRow(host, row) : [row];
616
+ }
617
+
618
+ /**
619
+ * One list update. The rows both lists start and end with stay where they
620
+ * are, two ends that traded places are two moves, and what is left is
621
+ * placed against the longest run that already stands in order.
622
+ */
623
+ const syncRows: SyncRows<N> = (parent, anchor, current, next) => {
624
+ const shared = Math.min(current.length, next.length);
625
+ let head = 0;
626
+ while (head < shared && current[head] === next[head]) head++;
627
+ let was = current.length;
628
+ let now = next.length;
629
+ while (was > head && now > head && current[was - 1] === next[now - 1]) {
630
+ was--;
631
+ now--;
632
+ }
633
+ while (
634
+ was - head > 1 &&
635
+ now - head > 1 &&
636
+ current[head] === next[now - 1] &&
637
+ next[head] === current[was - 1] &&
638
+ swapEnds(parent, current[head], current[was - 1])
639
+ ) {
640
+ head++;
641
+ was--;
642
+ now--;
643
+ while (head < was && head < now && current[head] === next[head]) head++;
644
+ while (was > head && now > head && current[was - 1] === next[now - 1]) {
645
+ was--;
646
+ now--;
647
+ }
648
+ }
649
+ const leaving = head === 0 && was === current.length ? current : current.slice(head, was);
650
+ const arriving = head === 0 && now === next.length ? next : next.slice(head, now);
651
+
652
+ if (leaving.length > 0) {
653
+ if (arriving.length === 0) {
654
+ removeAll(standingRows(host, leaving));
655
+ } else {
656
+ const kept = new Set(arriving);
657
+ for (const row of leaving) {
658
+ if (!kept.has(row)) removeAll(nodesOf(row));
659
+ }
660
+ }
661
+ }
662
+
663
+ if (arriving.length > 0) {
664
+ let after = anchor;
665
+ for (let i = now; i < next.length; i++) {
666
+ const lead = rowFirst(next[i]);
667
+ if (lead === undefined) continue;
668
+ after = lead;
669
+ break;
670
+ }
671
+ orderRows(parent, after, leaving, arriving);
672
+ }
673
+ placed(parent);
674
+ };
675
+
676
+ function swapEnds(parent: N, low: Row<N>, high: Row<N>): boolean {
677
+ const lowNodes = nodesOf(low);
678
+ const highNodes = nodesOf(high);
679
+ if (lowNodes.length === 0 || highNodes.length === 0) return false;
680
+ const afterHigh = nextOf(highNodes[highNodes.length - 1]);
681
+ const lowFirst = lowNodes[0];
682
+ for (let i = 0; i < highNodes.length; i++) insertNode(parent, highNodes[i], lowFirst);
683
+ for (let i = 0; i < lowNodes.length; i++) insertNode(parent, lowNodes[i], afterHigh);
684
+ return true;
685
+ }
686
+
687
+ function orderRows(
688
+ parent: N,
689
+ anchor: N | null,
690
+ previous: readonly Row<N>[],
691
+ next: readonly Row<N>[],
692
+ ): void {
693
+ if (previous.length === 0) {
694
+ let before = anchor;
695
+ for (let i = next.length - 1; i >= 0; i--) {
696
+ const row = nodesOf(next[i]);
697
+ for (let j = row.length - 1; j >= 0; j--) {
698
+ place(parent, row[j], before);
699
+ before = row[j];
700
+ }
701
+ }
702
+ return;
703
+ }
704
+
705
+ const previousIndex = new Map<Row<N>, number>();
706
+ for (let i = 0; i < previous.length; i++) previousIndex.set(previous[i], i);
707
+ const sources: number[] = new Array(next.length);
708
+ for (let i = 0; i < next.length; i++) sources[i] = previousIndex.get(next[i]) ?? -1;
709
+ const lis = longestIncreasingSubsequence(sources.filter((source) => source !== -1));
710
+
711
+ let lisIndex = lis.length - 1;
712
+ let before: N | null = anchor;
713
+ for (let i = next.length - 1; i >= 0; i--) {
714
+ const row = next[i];
715
+ const first = rowFirst(row);
716
+ if (first === undefined) continue;
717
+ if (sources[i] !== -1 && lisIndex >= 0 && lis[lisIndex] === sources[i]) {
718
+ lisIndex--;
719
+ } else {
720
+ // First to last, each before the same node, keeps a row of several
721
+ // nodes in its own order.
722
+ const nodes = nodesOf(row);
723
+ for (let j = 0; j < nodes.length; j++) insertNode(parent, nodes[j], before);
724
+ }
725
+ before = first;
726
+ }
727
+ }
728
+
729
+ // ==========================================================================
730
+ // What compiled code calls
731
+ // ==========================================================================
732
+
733
+ function insert(parent: N, value: unknown, marker?: N | null): void {
734
+ const given = getOwner();
735
+ const anchor = marker ?? null;
736
+ if (typeof value === "function" && isBlock(value)) {
737
+ value = buildChild(value as (owner: unknown) => unknown, given);
738
+ if (typeof value === "function") {
739
+ insert(parent, value, marker);
740
+ return;
741
+ }
742
+ }
743
+ if (typeof value === "function") {
744
+ insertLive(parent, value as (owner: unknown) => unknown, anchor, given);
745
+ return;
746
+ }
747
+ if (value === null || value === undefined || typeof value === "boolean") return;
748
+ const nodes = toNodes(value, given);
749
+ for (let i = 0; i < nodes.length; i++) insertNode(parent, nodes[i], anchor);
750
+ placed(parent);
751
+ }
752
+
753
+ function insertLive(
754
+ parent: N,
755
+ value: (owner: unknown) => unknown,
756
+ anchor: N | null,
757
+ given: Scope | null,
758
+ ): void {
759
+ let current: N[] = [];
760
+ effectUnder<Resolved<N>>(
761
+ given,
762
+ "insert",
763
+ () => {
764
+ const owner = getOwner();
765
+ return resolve(yielded(buildChild(value, owner), owner), current, given);
766
+ },
767
+ (resolved) => {
768
+ current = placeInsert(parent, resolved, current, anchor);
769
+ },
770
+ );
771
+ }
772
+
773
+ function setProp<T>(node: N, name: string, value: T, prev?: unknown): T {
774
+ if (name === "ref") {
775
+ ref(node, value);
776
+ return value;
777
+ }
778
+ setProperty(node, name, value, prev);
779
+ return value;
780
+ }
781
+
782
+ function refuseBlock(target: unknown, origin: string, returned = false): void {
783
+ if (isBlock(target)) throw jsxAsValue(origin, returned);
784
+ }
785
+
786
+ /**
787
+ * A ref registration owned by the scope the node belongs to: a callback that
788
+ * returns a function has it run when that scope goes.
789
+ */
790
+ function ref(node: N, value: unknown): void {
791
+ const owner = getOwner();
792
+ const undo: (() => void)[] = [];
793
+ const one = (target: unknown): void => {
794
+ refuseBlock(target, "A `ref`");
795
+ if (typeof target === "function") {
796
+ if (attachRef === undefined) {
797
+ const back: unknown = target(node);
798
+ refuseBlock(back, "A `ref`", true);
799
+ if (typeof back === "function") undo.push(back as () => void);
800
+ return;
801
+ }
802
+ let release: (() => void) | undefined;
803
+ const stop = attachRef(node, (held) => {
804
+ release?.();
805
+ const back: unknown = target(held);
806
+ refuseBlock(back, "A `ref`", true);
807
+ release = typeof back === "function" ? (back as () => void) : undefined;
808
+ });
809
+ undo.push(() => {
810
+ stop();
811
+ release?.();
812
+ });
813
+ } else if (typeof target === "object" && target !== null && "current" in target) {
814
+ if (attachRef === undefined) {
815
+ target.current = node;
816
+ return;
817
+ }
818
+ undo.push(
819
+ attachRef(node, (held) => {
820
+ target.current = held;
821
+ }),
822
+ );
823
+ }
824
+ };
825
+ if (Array.isArray(value)) {
826
+ for (const target of value) one(target);
827
+ } else {
828
+ one(value);
829
+ }
830
+ if (undo.length === 0 || owner === null) return;
831
+ underScope(owner, "ref", () => {
832
+ onCleanup(() => {
833
+ for (const fn of undo) fn();
834
+ });
835
+ });
836
+ }
837
+
838
+ const isHandlerKey = (key: string): boolean =>
839
+ key.charCodeAt(0) === 111 && key.charCodeAt(1) === 110;
840
+
841
+ /**
842
+ * A props object onto a node, diffed against what was last applied, with a
843
+ * property that vanished set to `undefined`. A getter is read in the
844
+ * tracked half, so the write half sees values only; a handler and a `ref`
845
+ * are functions that are not getters and pass through as they are.
846
+ * `children` is not a property: the element's own children are placed by
847
+ * whoever built it.
848
+ */
849
+ function spread(node: N, props: Spreadable, later?: readonly string[]): void {
850
+ const given = getOwner();
851
+ const applied: Record<string, unknown> = {};
852
+ let first = true;
853
+
854
+ const read = (): Record<string, unknown> => {
855
+ const next = typeof props === "function" ? props() : props;
856
+ const resolved: Record<string, unknown> = {};
857
+ for (const key in next) {
858
+ if (key === "children") continue;
859
+ if (later !== undefined && later.includes(key)) continue;
860
+ const value = next[key];
861
+ if (key === "ref" || isHandlerKey(key)) {
862
+ resolved[key] = value;
863
+ continue;
864
+ }
865
+ refuseBlock(value, `The \`${key}\` prop in a spread`);
866
+ resolved[key] = typeof value === "function" ? (value as () => unknown)() : value;
867
+ }
868
+ return resolved;
869
+ };
870
+
871
+ effectUnder<Record<string, unknown>>(given, "spread", read, (next) => {
872
+ for (const key in applied) {
873
+ if (key in next) continue;
874
+ setProperty(node, key, undefined, applied[key]);
875
+ delete applied[key];
876
+ }
877
+ for (const key in next) {
878
+ const value = next[key];
879
+ if (key === "ref") {
880
+ if (first) runWithOwner(given, () => ref(node, value));
881
+ continue;
882
+ }
883
+ if (key in applied && applied[key] === value) continue;
884
+ setProperty(node, key, value, applied[key]);
885
+ applied[key] = value;
886
+ }
887
+ first = false;
888
+ });
889
+ }
890
+
891
+ /** One element by tag name, its props spread and its children inserted. */
892
+ function element(tag: string, props: Record<string, unknown>): N {
893
+ const node = ops.createElement(tag);
894
+ spread(node, props);
895
+ const children = props.children;
896
+ if (children !== undefined && children !== null) insert(node, children);
897
+ return node;
898
+ }
899
+
900
+ // ==========================================================================
901
+ // Components that need a host
902
+ // ==========================================================================
903
+
904
+ function portal(target: Cell<N | null | undefined>, block: Block<unknown>): N {
905
+ const given = getOwner();
906
+ cellSlot(target, "Portal.mount");
907
+ cellSlot(untrack(target), "Portal.mount", true);
908
+ const marker = createSentinel();
909
+ underScope(given, "portal", () => {
910
+ let instance = NOTHING;
911
+ let request = 0;
912
+ const site: Site = { host, parent: null, anchor: null };
913
+ const clear = (): void => {
914
+ if (instance !== NOTHING) {
915
+ teardown(host, instance);
916
+ instance = NOTHING;
917
+ }
918
+ site.parent = null;
919
+ };
920
+ // An effect, so the mount happens once the pass that built the marker
921
+ // has committed, and is held with the rest of a boundary's content while
922
+ // the boundary shows its fallback.
923
+ createEffect(
924
+ () => {
925
+ const requested = target();
926
+ cellSlot(requested, "Portal.mount", true);
927
+ return requested;
928
+ },
929
+ (requested) => {
930
+ clear();
931
+ const mine = ++request;
932
+ const mount = (): void => {
933
+ if (mine !== request) return;
934
+ if (requested !== null && requested !== undefined && typeof requested !== "object") {
935
+ throw new TypeError(
936
+ `\`<Portal mount>\` was given ${JSON.stringify(requested)}, and on a custom host it ` +
937
+ "takes a node of that host. A selector is something only the document can look " +
938
+ "up: pass the node itself, or leave `mount` out to mount into the render root.",
939
+ );
940
+ }
941
+ const into = requested ?? renderRootOf(given);
942
+ if (into === null) return;
943
+ site.parent = into;
944
+ nextActivation();
945
+ instance = activate(given, site, block, NO_ARGS, 0, "portal");
946
+ };
947
+ // A portal nothing owns has no scope to build under, and the engine
948
+ // refuses one made from inside an effect's write.
949
+ if (given === null) queueMicrotask(mount);
950
+ else mount();
951
+ },
952
+ );
953
+ onCleanup(clear);
954
+ });
955
+ return marker;
956
+ }
957
+
958
+ function renderRootOf(owner: Scope | null): N | null {
959
+ const found = lookupContext(owner, RENDER_ROOT);
960
+ return found === CONTEXT_MISS ? null : (found as N);
961
+ }
962
+
963
+ function Portal(props: PortalProps<N>): JSXElement {
964
+ return portal(
965
+ () => readSlot(props.mount, "Portal.mount") as N | null | undefined,
966
+ props.children as Block<unknown>,
967
+ );
968
+ }
969
+
970
+ function dynamic(
971
+ source: () => DynamicTag | null | undefined | false,
972
+ ): (props: Record<string, unknown>) => JSXElement {
973
+ return (props) => {
974
+ const component = internalMemo(source);
975
+ return branch(null, null, component, () => {
976
+ const resolved = untrack(component);
977
+ if (resolved === null || resolved === undefined || resolved === false) return null;
978
+ if (typeof resolved === "string") return element(resolved, props);
979
+ return (resolved as (props: Record<string, unknown>) => unknown)(props);
980
+ });
981
+ };
982
+ }
983
+
984
+ // ==========================================================================
985
+ // Control flow over this host
986
+ // ==========================================================================
987
+
988
+ function branch<K>(
989
+ parent: N | null,
990
+ anchor: N | null,
991
+ key: Cell<K>,
992
+ bodies: Block<unknown> | readonly (Block<unknown> | null | undefined)[],
993
+ flags?: number,
994
+ ): N | N[] | null {
995
+ return branchIn(host, parent, anchor, key, bodies, flags);
996
+ }
997
+
998
+ // ==========================================================================
999
+ // Mounting
1000
+ // ==========================================================================
1001
+
1002
+ function render(
1003
+ code: (() => JSXElement) | JSXElement,
1004
+ root: N,
1005
+ options?: RenderOptions,
1006
+ ): () => void {
1007
+ const scope = rootScope(options?.owner ?? null, options?.renderId);
1008
+ // Provided on the root, so a component called inside this tree renders
1009
+ // through this host whatever the default is: an app that renders into the
1010
+ // document as well has two hosts, and only the root knows which is whose.
1011
+ // A document renderer's control flow reads it too, for a component that
1012
+ // compiled for the document and is rendered here.
1013
+ provideHost(scope, { host, sync: syncRows });
1014
+ provideOn(scope, RENDER_ROOT, root);
1015
+ ownRange(scope, () => {
1016
+ for (let child = firstOf(root); child !== null; child = firstOf(root)) {
1017
+ removeNode(root, child);
1018
+ }
1019
+ });
1020
+ // A host has no server markup, so a tree mounted while a page hydrates,
1021
+ // as a canvas component mounting its scene does, claims nothing.
1022
+ withoutClaim(() => {
1023
+ mountTree(() => {
1024
+ runWithOwner(scope, () => {
1025
+ insert(root, typeof code === "function" ? code() : code);
1026
+ });
1027
+ });
1028
+ });
1029
+ return () => {
1030
+ disposeScope(scope);
1031
+ };
1032
+ }
1033
+
1034
+ // A component called outside any tree this renderer mounted finds a host
1035
+ // through the default, which this fills only when nothing else has.
1036
+ offerDefaultHost(host, syncRows);
1037
+
1038
+ return {
1039
+ render,
1040
+ createElement: (tag) => ops.createElement(tag),
1041
+ createTextNode,
1042
+ insertNode,
1043
+ setProp,
1044
+ insert,
1045
+ spread,
1046
+ branch,
1047
+ each: (parent, anchor, src, carrier, row, flags, fallback) =>
1048
+ eachIn(host, syncRows, parent, anchor, src, carrier, row, flags, fallback),
1049
+ boundary: (parent, anchor, kind, fallback, body, flags, on) =>
1050
+ boundaryIn(host, parent, anchor, kind, fallback, body, flags, on),
1051
+ island: (parent, anchor, block, flags) => islandIn(host, parent, anchor, block, flags),
1052
+ reveal: (order, collapsed, block) => revealIn(host, order, collapsed, block),
1053
+ portal,
1054
+ dynamic,
1055
+ Portal,
1056
+ host,
1057
+ syncRows,
1058
+ };
1059
+ }