@webjsdev/core 0.7.49 → 0.7.51

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.
Files changed (61) hide show
  1. package/dist/webjs-core-browser.js +5 -5
  2. package/dist/webjs-core-browser.js.map +3 -3
  3. package/dist/webjs-core-testing.js +21 -21
  4. package/dist/webjs-core-testing.js.map +3 -3
  5. package/dist/webjs-core.js +7 -7
  6. package/dist/webjs-core.js.map +3 -3
  7. package/index-browser.js +1 -1
  8. package/index.d.ts +1 -1
  9. package/index.js +1 -1
  10. package/package.json +1 -1
  11. package/src/attribute-reader.js +178 -0
  12. package/src/component/lifecycle.js +1481 -0
  13. package/src/component/reactive.js +171 -0
  14. package/src/component/server-element.js +248 -0
  15. package/src/component.d.ts +10 -0
  16. package/src/component.js +2 -1931
  17. package/src/html-entities.js +2179 -0
  18. package/src/render-client/parts.js +2007 -0
  19. package/src/render-client/reconciler.js +388 -0
  20. package/src/render-client/template-compiler.js +525 -0
  21. package/src/render-client.js +1 -2939
  22. package/src/render-server/attrs.js +160 -0
  23. package/src/render-server/dsd.js +445 -0
  24. package/src/render-server/html-scan.js +402 -0
  25. package/src/render-server/slots.js +213 -0
  26. package/src/render-server/stream.js +163 -0
  27. package/src/render-server/template-renderer.js +923 -0
  28. package/src/render-server/text.js +163 -0
  29. package/src/render-server.js +6 -2334
  30. package/src/router-client/anchors.js +44 -0
  31. package/src/router-client/boundaries.js +221 -0
  32. package/src/router-client/constants.js +187 -0
  33. package/src/router-client/diagnostics.js +377 -0
  34. package/src/router-client/dom-differ.js +709 -0
  35. package/src/router-client/dom-parse.js +150 -0
  36. package/src/router-client/events.js +139 -0
  37. package/src/router-client/fetch-apply.js +387 -0
  38. package/src/router-client/form-encoder.js +135 -0
  39. package/src/router-client/frames.js +329 -0
  40. package/src/router-client/head-merge.js +344 -0
  41. package/src/router-client/nav-error.js +105 -0
  42. package/src/router-client/navigator.js +781 -0
  43. package/src/router-client/prefetch.js +824 -0
  44. package/src/router-client/scroll.js +259 -0
  45. package/src/router-client/snapshot-cache.js +97 -0
  46. package/src/router-client/state.js +92 -0
  47. package/src/router-client/stream.js +206 -0
  48. package/src/router-client/swap.js +451 -0
  49. package/src/router-client/upgrade.js +261 -0
  50. package/src/router-client/view-transition.js +223 -0
  51. package/src/router-client.d.ts +10 -1
  52. package/src/router-client.js +75 -5345
  53. package/src/slot/assignment.js +304 -0
  54. package/src/slot/interception.js +558 -0
  55. package/src/slot/polyfills.js +365 -0
  56. package/src/slot/project.js +432 -0
  57. package/src/slot/sensors.js +303 -0
  58. package/src/slot/state.js +245 -0
  59. package/src/slot/symbols.js +85 -0
  60. package/src/slot.js +7 -2199
  61. package/src/webjs-config.d.ts +13 -2
@@ -1,2939 +1 @@
1
- import { isTemplate, MARKER } from './html.js';
2
- import { BINDING_PREFIXES, isBindingPrefix } from './binding-prefixes.js';
3
- import { escapeAttr } from './escape.js';
4
- import {
5
- assertNotFunctionActionAttr, assertNotFunctionReflectedActionProp,
6
- reconcileFormAction, isBoundFormAction, ABSENT, assertSubmitterHasNoName,
7
- assertSubmitterType, assertSubmitterHasNoValue, assertSubmitterHasNoStaticFormAction,
8
- assertSubmitterHasNoFormAttribute, assertSingleSubmitterAction,
9
- resolveBoundSubmitterAttrs, applyResolvedAttr, releaseSubmitterAttrs,
10
- assertConvergentSubmitter, isSubmitterReflectedProp,
11
- formActionId, assertIdentifiableAction, FORM_ACTION_FIELD,
12
- } from './form-action.js';
13
- import { isRepeat } from './repeat.js';
14
- import { isUnsafeHTML, isLive, isKeyed, isGuard, isTemplateContent, isRef, isCache, isUntil, isAsyncAppend, isAsyncReplace, isWatch } from './directives.js';
15
- import { Signal } from './signal.js';
16
- import {
17
- LIGHT_SLOT_ATTR,
18
- PROJECTION_ATTR,
19
- PROJECTION_FALLBACK,
20
- SLOT_FALLBACK_FRAG,
21
- SLOT_STATE,
22
- SLOT_OWNER,
23
- RENDERING,
24
- applySlotAssignments,
25
- rescueAssignedNodes,
26
- withRendererWrites,
27
- drainRendererBackstop,
28
- } from './slot.js';
29
-
30
- /**
31
- * Open the renderer-write window on a light-DOM host while `fn` commits into
32
- * it, so the host's patched slot-interception methods delegate to native and
33
- * a renderer commit is never mistaken for authored content. A no-op (just runs
34
- * `fn`) when `node` is not a slot host, so nested and non-host commits pay
35
- * nothing. Covers the ASYNC commit paths (async directives, streaming) that
36
- * run outside a synchronous render() call.
37
- */
38
- function commitInto(node, fn) {
39
- const host = node && /** @type {any} */ (node)[SLOT_STATE] ? node : null;
40
- if (!host) return fn();
41
- return withRendererWrites(host, fn);
42
- }
43
-
44
- /**
45
- * Client-side renderer with **fine-grained** updates.
46
- *
47
- * Each TemplateResult is compiled once (keyed by the tagged-template's
48
- * `strings` array identity, so reuse is free across renders) into:
49
- * - a `<template>` element with static HTML + marker comments/attributes
50
- * at each dynamic hole
51
- * - a list of `Part` descriptors (kind + DOM location + attr/event name)
52
- *
53
- * On first render the template is cloned into the container and each Part
54
- * is bound to the freshly-created node. Subsequent renders compare the new
55
- * values to the last-applied values and only touch parts that changed.
56
- * Text-position holes containing nested TemplateResults reuse the existing
57
- * child instance when the inner `strings` match; they only rebuild when the
58
- * template shape changes.
59
- *
60
- * Consequences worth knowing:
61
- * - Input focus, cursor position, selection, and scroll inside components
62
- * survive re-renders triggered by property assignments, signal changes,
63
- * or `requestUpdate()`.
64
- * - Event listeners are attached once and retargeted when the handler
65
- * reference changes (swap-in-place via a dispatch closure, so `addEventListener`
66
- * isn't churned every render).
67
- * - A plain `.map()` array reconciles POSITIONALLY (non-keyed), matching
68
- * lit-html: each index updates its item instance in place when the
69
- * template shape is unchanged, so DOM node identity (and the focus,
70
- * selection, scroll, and in-progress native drag it carries) survives an
71
- * item-level update. See `reconcileArray`. Keyed reordering still needs
72
- * the `repeat()` directive.
73
- */
74
-
75
- /**
76
- * One `method` / `enctype` hole on a candidate bound form. `statics` / `group`
77
- * are carried for a mixed attribute, whose value is the concatenation of its
78
- * static pieces and every one of its holes.
79
- *
80
- * @typedef {{ i: number, kind: string, statics?: string[], group?: number[] }} FormAttrPart
81
- */
82
-
83
- /**
84
- * What one `<form action=${...}>` in a template needs at reconcile time (#1155).
85
- * Every field is a property of the TEMPLATE, computed once per template literal
86
- * call site, so it cannot drift out of step with the live DOM.
87
- *
88
- * @typedef {{
89
- * actionIdxs: number[],
90
- * duplicateAction: boolean,
91
- * staticAction: boolean,
92
- * authoredName: boolean,
93
- * authoredValue: boolean,
94
- * authoredForm: boolean,
95
- * nameParts: {i: number, kind: string}[],
96
- * valueParts: {i: number, kind: string}[],
97
- * propAttrs: string[],
98
- * staticMethod: string | null,
99
- * staticEnctype: string | null,
100
- * methodParts: FormAttrPart[],
101
- * enctypeParts: FormAttrPart[],
102
- * }} FormActionRecord
103
- */
104
-
105
- /** @type {WeakMap<TemplateStringsArray | string[], { templateEl: HTMLTemplateElement, parts: PartDescriptor[], formActions: FormActionRecord[] | null }>} */
106
- const templateCache = new WeakMap();
107
- /**
108
- * Submitters this renderer stamped with an identity, so a later release removes
109
- * only the framework's own `name` / `value` and never an author's.
110
- * @type {WeakMap<Element, string>}
111
- */
112
- const submitterActionBindings = new WeakMap();
113
- const INSTANCE = Symbol.for('webjs.instance');
114
-
115
- /**
116
- * @typedef {{
117
- * kind: 'child' | 'attr' | 'attr-mixed' | 'event' | 'prop' | 'bool' | 'element' | 'slot' | 'noop',
118
- * path: number[],
119
- * name?: string,
120
- * statics?: string[],
121
- * group?: number[],
122
- * }} PartDescriptor
123
- *
124
- * @typedef {{
125
- * strings: TemplateStringsArray | string[],
126
- * bound: BoundPart[],
127
- * lastValues: unknown[],
128
- * startNode: Comment,
129
- * endNode: Comment,
130
- * }} TemplateInstance
131
- *
132
- * @typedef {
133
- * | { kind: 'child', marker: Comment, child?: TemplateInstance | ChildNode[] }
134
- * | { kind: 'attr', el: Element, name: string }
135
- * | { kind: 'attr-mixed', el: Element, name: string, statics: string[], group: number[] }
136
- * | { kind: 'event', el: Element, name: string, handler: ((e: Event) => void) | null, dispatcher: (e: Event) => void }
137
- * | { kind: 'prop', el: Element, name: string }
138
- * | { kind: 'bool', el: Element, name: string }
139
- * | { kind: 'element', el: Element, lastTarget?: any }
140
- * | { kind: 'slot', slotEl: HTMLSlotElement, applied: boolean }
141
- * | { kind: 'noop' }
142
- * } BoundPart
143
- */
144
-
145
- /**
146
- * The container the in-progress `render()` is committing into, or null
147
- * outside one. Every part created or applied during that render belongs to
148
- * THIS container's component, which is what an out-of-band commit needs to
149
- * know to reach the right error boundary. A structural parent walk cannot
150
- * work it out: `html`<child-el>${watch(sig)}</child-el>`` puts the part in the
151
- * PARENT's template but inside the child's tag, so the walk meets the child
152
- * first. Same reason `SLOT_OWNER` exists.
153
- * @type {any}
154
- */
155
- let currentRenderRoot = null;
156
-
157
- /**
158
- * The element carrying the error boundary for a render root. A ShadowRoot has
159
- * no boundary of its own; its `.host` is the component.
160
- * @param {any} root
161
- * @returns {any}
162
- */
163
- function boundaryOwnerOf(root) {
164
- if (!root) return null;
165
- if (root.nodeType === 11 && root.host) return root.host;
166
- return root;
167
- }
168
-
169
- /**
170
- * Run an OUT-OF-BAND commit (a `watch` notify microtask, an `until`
171
- * resolution) with the part's owner installed as the current render root.
172
- *
173
- * Without this the commit runs with no owner in scope, so any `watch` /
174
- * `until` nested INSIDE the template it commits is installed unstamped and
175
- * its own later throw escapes to the window. A directive nested in that
176
- * template belongs to the same component as the part committing it, which is
177
- * exactly the owner already recorded here.
178
- *
179
- * @param {Extract<BoundPart, {kind:'child'}>} part
180
- * @param {() => void} fn
181
- */
182
- function commitOutOfBand(part, fn) {
183
- const owner = /** @type any */ (part).__commitOwner;
184
- const prev = currentRenderRoot;
185
- if (owner) currentRenderRoot = owner;
186
- try {
187
- fn();
188
- } finally {
189
- currentRenderRoot = prev;
190
- }
191
- }
192
-
193
- /**
194
- * Render a value into a container, reusing DOM where possible.
195
- *
196
- * @param {unknown} value
197
- * @param {Element | DocumentFragment | ShadowRoot} container
198
- */
199
- export function render(value, container) {
200
- const host = /** @type any */ (container);
201
- // Open the renderer-write window for the whole commit: every host-receiver
202
- // write below (and in createInstance / updateInstance / clearInstance / all
203
- // part commits they reach synchronously) then bypasses the slot interception
204
- // that is patched onto a light host. This is the single discriminator
205
- // between a renderer commit and an author write.
206
- const prevRendering = host[RENDERING];
207
- host[RENDERING] = true;
208
- const prevRenderRoot = currentRenderRoot;
209
- currentRenderRoot = container;
210
- try {
211
- const prev = host[INSTANCE];
212
-
213
- if (isTemplate(value)) {
214
- const tr = /** @type {import('./html.js').TemplateResult} */ (value);
215
- if (prev && prev.strings === tr.strings) {
216
- updateInstance(prev, tr.values);
217
- return;
218
- }
219
- if (prev) clearInstance(prev, container);
220
-
221
- // Light DOM hydration: if container has SSR content (marked by
222
- // <!--webjs-hydrate-->), remove the marker and proceed with normal
223
- // rendering. The content will be replaced with identical output -
224
- // no visible flash because SSR and client render produce the same HTML.
225
- const firstChild = container.firstChild;
226
- if (firstChild && firstChild.nodeType === 8 && /** @type {Comment} */ (firstChild).data === 'webjs-hydrate') {
227
- firstChild.remove();
228
- }
229
-
230
- // Pre-set the symbol to an explicit null BEFORE the commit,
231
- // UNCONDITIONALLY: if createInstance throws after its replaceChildren
232
- // (e.g. inside the slot-part apply loop), the finally-drain must see
233
- // "rendered, no instance" (discard the commit's records), never
234
- // "never rendered" (fold and corrupt) and never a STALE cleared prev
235
- // instance on the template-swap path (whose bookends would misclassify
236
- // the half-committed new roots as unowned and fold them).
237
- host[INSTANCE] = null;
238
- const inst = createInstance(tr, container);
239
- host[INSTANCE] = inst;
240
- return;
241
- }
242
-
243
- // Non-template value: treat as a single text child.
244
- if (prev) clearInstance(prev, container);
245
- host[INSTANCE] = null;
246
- container.replaceChildren();
247
- if (value == null || value === false || value === true) return;
248
- if (Array.isArray(value)) {
249
- for (const v of value) {
250
- const text = document.createTextNode(String(v ?? ''));
251
- container.appendChild(text);
252
- }
253
- return;
254
- }
255
- container.appendChild(document.createTextNode(String(value)));
256
- } finally {
257
- currentRenderRoot = prevRenderRoot;
258
- host[RENDERING] = prevRendering;
259
- // Outermost window closing: drain this commit's childList records off the
260
- // slot backstop (drainRendererBackstop processes them with a renderer-output
261
- // skip when an instance exists, else discards), so the backstop never folds
262
- // renderer output. Mirrors withRendererWrites, used by the async paths.
263
- if (!prevRendering) drainRendererBackstop(host);
264
- }
265
- }
266
-
267
- /* ================================================================
268
- * Template compilation
269
- * ================================================================ */
270
-
271
- /** @param {import('./html.js').TemplateResult} tr */
272
- function compile(tr) {
273
- const { strings } = tr;
274
- let cached = templateCache.get(strings);
275
- if (cached) return cached;
276
-
277
- /** @type {PartDescriptor[]} */
278
- const parts = [];
279
- let html = '';
280
- let state = 'text';
281
- let attrName = '';
282
- let attrStart = 0;
283
- let attrQuote = '';
284
- let commentDashes = 0;
285
- /** @type {{ name: string, firstPartIdx: number } | null} */
286
- let mixedAttr = null;
287
- let currentTag = '';
288
- let rawTail = '';
289
-
290
- for (let i = 0; i < strings.length; i++) {
291
- const s = strings[i];
292
- for (let j = 0; j < s.length; j++) {
293
- const c = s[j];
294
- switch (state) {
295
- case 'text':
296
- html += c;
297
- if (c === '<') state = 'tag-open';
298
- break;
299
- case 'tag-open':
300
- html += c;
301
- if (c === '!') state = 'bang-1';
302
- else if (c === '/') { state = 'tag-name'; currentTag = ''; }
303
- else if (/[a-zA-Z]/.test(c)) { state = 'tag-name'; currentTag = c.toLowerCase(); }
304
- else state = 'text';
305
- break;
306
- case 'bang-1':
307
- html += c;
308
- state = c === '-' ? 'bang-dash' : 'tag-name';
309
- break;
310
- case 'bang-dash':
311
- html += c;
312
- if (c === '-') { state = 'comment'; commentDashes = 0; }
313
- else state = 'tag-name';
314
- break;
315
- case 'comment':
316
- html += c;
317
- if (c === '-') commentDashes += 1;
318
- else if (c === '>' && commentDashes >= 2) { state = 'text'; commentDashes = 0; }
319
- else commentDashes = 0;
320
- break;
321
- case 'tag-name':
322
- html += c;
323
- if (c === '>') {
324
- state = (currentTag === 'script' || currentTag === 'style') ? 'rawtext' : 'text';
325
- if (state === 'rawtext') rawTail = '';
326
- } else if (/\s/.test(c)) state = 'in-tag';
327
- else currentTag += c.toLowerCase();
328
- break;
329
- case 'in-tag':
330
- html += c;
331
- if (c === '>') {
332
- state = (currentTag === 'script' || currentTag === 'style') ? 'rawtext' : 'text';
333
- if (state === 'rawtext') rawTail = '';
334
- } else if (!/\s/.test(c) && c !== '/') {
335
- state = 'attr-name';
336
- attrName = c;
337
- attrStart = html.length - 1;
338
- }
339
- break;
340
- case 'rawtext':
341
- html += c;
342
- rawTail = (rawTail + c.toLowerCase()).slice(-9);
343
- if (rawTail.endsWith('</script>') || rawTail.endsWith('</style>')) {
344
- state = 'text';
345
- rawTail = '';
346
- currentTag = '';
347
- }
348
- break;
349
- case 'attr-name':
350
- if (c === '=') { state = 'after-eq'; html += c; }
351
- else if (/\s/.test(c)) { state = 'in-tag'; attrName = ''; html += c; }
352
- else if (c === '>') { state = 'text'; attrName = ''; html += c; }
353
- else { attrName += c; html += c; }
354
- break;
355
- case 'after-eq':
356
- if (c === '"' || c === "'") { state = 'attr-quoted'; attrQuote = c; html += c; }
357
- else if (/\s/.test(c)) { state = 'in-tag'; attrName = ''; html += c; }
358
- else if (c === '>') { state = 'text'; attrName = ''; html += c; }
359
- else { state = 'attr-unquoted'; html += c; }
360
- break;
361
- case 'attr-unquoted':
362
- if (/\s/.test(c)) { state = 'in-tag'; attrName = ''; html += c; }
363
- else if (c === '>') { state = 'text'; attrName = ''; html += c; }
364
- else html += c;
365
- break;
366
- case 'attr-quoted':
367
- html += c;
368
- if (c === attrQuote) { state = 'in-tag'; attrName = ''; }
369
- break;
370
- case 'skip-attr':
371
- // Consume mixed-attribute chars without appending to html.
372
- // The attribute was replaced with a sentinel on the first hole.
373
- if (c === attrQuote) {
374
- // Closing quote: finalize the attr-mixed part.
375
- if (mixedAttr) {
376
- const idx0 = mixedAttr.firstPartIdx;
377
- const group = [];
378
- for (let k = idx0; k < parts.length; k++) {
379
- if (parts[k].kind === 'noop' || parts[k].kind === 'attr-mixed') group.push(k);
380
- }
381
- // Build statics from the template strings array.
382
- // For `attr="a ${x} b ${y} c"`, group=[idx0,idx1].
383
- // statics[0] = tail of strings[idx0] after the `="`
384
- // statics[1] = strings[idx1] (between holes)
385
- // statics[n] = prefix of strings[last+1] up to closing quote
386
- const statics = [];
387
- const s0 = strings[group[0]];
388
- const qp = s0.lastIndexOf(attrQuote);
389
- statics.push(qp >= 0 ? s0.slice(qp + 1) : s0);
390
- for (let k = 1; k < group.length; k++) {
391
- statics.push(strings[group[k]]);
392
- }
393
- const sLast = strings[group[group.length - 1] + 1];
394
- const eq = sLast.indexOf(attrQuote);
395
- statics.push(eq >= 0 ? sLast.slice(0, eq) : sLast);
396
-
397
- parts[idx0] = {
398
- kind: 'attr-mixed',
399
- path: [],
400
- name: mixedAttr.name,
401
- statics,
402
- group,
403
- };
404
- // The mixed attribute is rebuilt from ALL its holes' values, but
405
- // it is anchored at a single part (group[0]). The later holes stay
406
- // `noop`, so a change confined to one of them would be skipped by
407
- // updateInstance's per-hole dirty-check and the attribute would go
408
- // stale. Point every non-anchor member back at the anchor so a
409
- // change to any hole re-applies the whole attribute.
410
- for (let m = 1; m < group.length; m++) {
411
- parts[group[m]] = { kind: 'noop', path: [], mixedAnchor: idx0 };
412
- }
413
- mixedAttr = null;
414
- }
415
- state = 'in-tag';
416
- attrName = '';
417
- }
418
- break;
419
- }
420
- }
421
-
422
- if (i < strings.length - 1) {
423
- const partIdx = parts.length;
424
- if (state === 'comment') {
425
- // Holes inside <!-- ... --> are dropped. Comments are inert and
426
- // the compile cache is keyed on `strings`, so per-render values
427
- // can't be baked in anyway.
428
- commentDashes = 0;
429
- parts.push({ kind: 'noop', path: [] });
430
- continue;
431
- }
432
- if (state === 'rawtext') {
433
- // Inside <script>/<style>: per-render interpolation isn't supported;
434
- // the compile cache would lock in whatever was first rendered. The
435
- // hole is dropped and authors should set body text via a child part
436
- // outside the raw-text container, or inline style/script directly.
437
- rawTail = '';
438
- parts.push({ kind: 'noop', path: [] });
439
- continue;
440
- }
441
- if (state === 'text') {
442
- // Child hole: insert a comment marker. Use bracketed markers so we can
443
- // later walk all comments and find ours without ambiguity.
444
- html += `<!--${MARKER}${partIdx}-->`;
445
- parts.push({ kind: 'child', path: [] });
446
- } else if (state === 'in-tag') {
447
- // Element-position hole: `<tag ${expr}>`. Used by the `ref` directive
448
- // (and any future element-bound directive). Emit a sentinel attribute
449
- // on the current open tag; at bind time the attribute is stripped
450
- // and the element is captured into the part.
451
- const sentinel = `data-${MARKER}${partIdx}`;
452
- html += `${sentinel}=""`;
453
- parts.push({ kind: 'element', path: [] });
454
- } else if (state === 'after-eq') {
455
- const prefix = attrName[0];
456
- const name = attrName.slice(1);
457
- if (isBindingPrefix(prefix)) {
458
- // Strip the attribute name+"=" from html and add a sentinel attr.
459
- html = html.slice(0, attrStart);
460
- const kind = BINDING_PREFIXES[prefix];
461
- const sentinel = `data-${MARKER}${partIdx}`;
462
- html += `${sentinel}=""`;
463
- parts.push({ kind, path: [], name });
464
- } else {
465
- // Regular attribute: rewrite to `attrName="__MARKER__"` and parse as attr.
466
- html = html.slice(0, attrStart);
467
- const sentinel = `data-${MARKER}${partIdx}`;
468
- html += `${sentinel}=""`;
469
- parts.push({ kind: 'attr', path: [], name: attrName });
470
- }
471
- state = 'in-tag';
472
- attrName = '';
473
- } else if (state === 'attr-quoted' || state === 'attr-unquoted') {
474
- // First hole inside a quoted attribute value: start mixed-attr tracking.
475
- // Replace the entire attribute with a sentinel (same as regular attr).
476
- html = html.slice(0, attrStart);
477
- const sentinel = `data-${MARKER}${partIdx}`;
478
- html += `${sentinel}=""`;
479
- mixedAttr = { name: attrName, firstPartIdx: partIdx };
480
- parts.push({ kind: 'noop', path: [] }); // patched to attr-mixed at close-quote
481
- state = 'skip-attr';
482
- } else if (state === 'skip-attr') {
483
- // Subsequent hole in the same mixed attribute.
484
- parts.push({ kind: 'noop', path: [] });
485
- }
486
- }
487
- }
488
-
489
- const templateEl = document.createElement('template');
490
- templateEl.innerHTML = html;
491
-
492
- // Mark every <slot> in the template for framework projection and
493
- // register a SLOT part for each so the slot-apply step can find them on
494
- // clones. This runs BEFORE assignPaths so the sentinel attributes the
495
- // discovery step adds are picked up in the same path-recording walk.
496
- discoverSlots(templateEl.content, parts);
497
-
498
- // Walk the parsed fragment and record DOM paths for each part. It also
499
- // returns the per-template form-action records (#1155), null when the
500
- // template contains no bound-form candidate, which is the overwhelmingly
501
- // common case and keeps the reconcile out of every other template's path.
502
- const formActions = assignPaths(templateEl.content, parts);
503
-
504
- cached = { templateEl, parts, formActions };
505
- templateCache.set(strings, cached);
506
- return cached;
507
- }
508
-
509
- /**
510
- * Walk the compiled template content for <slot> elements (the static ones
511
- * written into the template, not dynamically-inserted ones). For each:
512
- * 1. Add the `data-webjs-light` attribute so slot.js's polyfilled APIs
513
- * recognise it as a framework-managed light-DOM slot.
514
- * 2. Add a sentinel attribute (`data-MARKER<idx>`) so the subsequent
515
- * assignPaths walk records the slot's path into the new SLOT part.
516
- * 3. Move the slot's authored children into a `fallbackTemplate`
517
- * DocumentFragment stored on the PartDescriptor. The slot in the
518
- * cached template becomes empty, so every clone starts empty too.
519
- * bindPart clones a fresh fallback fragment per instance from this
520
- * template, giving each instance an independent fallback supply
521
- * that slot.js swaps in via the SLOT_FALLBACK_FRAG symbol.
522
- *
523
- * Fallback content with template holes (`<slot>fallback ${x}</slot>`)
524
- * is captured as a static-HTML snapshot of the template state at
525
- * compile time. Dynamic holes inside fallback content are not
526
- * re-bound per instance in v1; authors should put dynamic content
527
- * outside the slot.
528
- *
529
- * @param {DocumentFragment} root
530
- * @param {PartDescriptor[]} parts
531
- */
532
- function discoverSlots(root, parts) {
533
- const slots = root.querySelectorAll('slot');
534
- for (const slot of slots) {
535
- slot.setAttribute(LIGHT_SLOT_ATTR, '');
536
- const partIdx = parts.length;
537
- slot.setAttribute(`data-${MARKER}${partIdx}`, '');
538
- parts.push({ kind: 'slot', path: [] });
539
- }
540
- // NOTE: fallback content stays IN the slot's children in the cached
541
- // template. Each clone gets its own copy. For shadow-DOM components,
542
- // native browser projection uses those children as fallback content
543
- // when no light child matches. For light-DOM components, the slot's
544
- // apply step (run after the cloned template is in the live tree)
545
- // moves the cloned fallback into a per-instance holding fragment
546
- // owned by slot.js, so the slot is empty and ready to receive
547
- // projected children. Doing the strip at apply time, not at compile
548
- // time, lets a single cached template serve both DOM modes.
549
- }
550
-
551
- /**
552
- * Walk the template fragment and record the path (chain of child indices) to
553
- * each part's anchor node. We use marker comments for child parts and sentinel
554
- * attributes for everything else.
555
- *
556
- * @param {DocumentFragment} root
557
- * @param {PartDescriptor[]} parts
558
- */
559
- function assignPaths(root, parts) {
560
- /** @type {number[]} */
561
- const path = [];
562
- /** @type {FormActionRecord[]} */
563
- const formActions = [];
564
- /** @param {Node} node */
565
- function visit(node) {
566
- for (let i = 0; i < node.childNodes.length; i++) {
567
- const child = node.childNodes[i];
568
- path.push(i);
569
- // Comment marker?
570
- if (child.nodeType === 8) {
571
- const txt = /** @type Comment */ (child).data;
572
- if (txt.startsWith(MARKER)) {
573
- const idx = Number(txt.slice(MARKER.length));
574
- if (parts[idx] && parts[idx].kind === 'child') {
575
- parts[idx].path = path.slice();
576
- }
577
- }
578
- } else if (child.nodeType === 1) {
579
- const el = /** @type Element */ (child);
580
- // Sentinel attribute?
581
- const toRemove = [];
582
- /** Every part bound to THIS element, which only this walk can see. */
583
- /** @type {{ idx: number, kind: string, name: string }[]} */
584
- const onEl = [];
585
- for (const attr of el.attributes) {
586
- if (attr.name.startsWith(`data-${MARKER}`)) {
587
- const idx = Number(attr.name.slice(`data-${MARKER}`.length));
588
- if (parts[idx] && parts[idx].kind !== 'child') {
589
- parts[idx].path = path.slice();
590
- onEl.push({ idx, kind: parts[idx].kind, name: parts[idx].name || '' });
591
- }
592
- toRemove.push(attr.name);
593
- }
594
- }
595
- // #1155 / #1207: record what a bound form or submitter needs, while the
596
- // STATIC attributes and the element's part indices are both still
597
- // visible. This is the only point in compilation with that whole view,
598
- // and it runs once per template, so the record is a constant rather
599
- // than runtime memory that can drift out of step with the DOM. It is
600
- // also the only place a submitter's own `name` is still legible: by
601
- // reconcile time the renderer has written the identity over it.
602
- if (el.localName === 'form' || el.localName === 'button' || el.localName === 'input') {
603
- const rec = buildFormActionRecord(el, onEl, parts);
604
- if (rec) formActions.push(rec);
605
- }
606
- for (const a of toRemove) el.removeAttribute(a);
607
- visit(child);
608
- }
609
- path.pop();
610
- }
611
- }
612
- visit(root);
613
- return formActions.length ? formActions : null;
614
- }
615
-
616
- /**
617
- * Build the compile-time record for one `<form>` carrying an `action` hole, or
618
- * one submitter carrying a `formaction` hole.
619
- *
620
- * A CANDIDATE, not a decision: `<form action=${maybeString}>` compiles exactly
621
- * like a bound one, so whether the form is really bound is a runtime fact the
622
- * reconcile decides from the value. Everything recorded here is a property of
623
- * the TEMPLATE, which is why it cannot go stale the way remembering "did the
624
- * bind supply this attribute" at runtime did.
625
- *
626
- * `encoding` folds into `enctype` for a PROPERTY binding only: it is a legacy
627
- * IDL alias, so `.encoding=` writes the enctype content attribute. As a content
628
- * attribute `encoding=` is inert (a browser's `form.encoding` reads back
629
- * `enctype`), and SSR ignores it, so folding the attribute spelling too would
630
- * make the client honour a value the server never saw.
631
- *
632
- * The submitter fields (`authoredName` / `authoredValue` / `authoredForm`) are
633
- * read off the COMPILED template rather than the live element, for the same
634
- * reason: by reconcile time the renderer has written its own `name` / `value`
635
- * onto a bound submitter, so the live element can no longer say which of them
636
- * the author wrote. A hole-provided `name=${n}` leaves no attribute on the
637
- * compiled template at all, which is why `nameParts` is tracked separately.
638
- *
639
- * @param {Element} el
640
- * @param {{ idx: number, kind: string, name: string }[]} onEl parts bound to `el`
641
- * @param {PartDescriptor[]} parts
642
- * @returns {FormActionRecord | null}
643
- */
644
- function buildFormActionRecord(el, onEl, parts) {
645
- const isForm = el.localName === 'form';
646
- const targetAttr = isForm ? 'action' : 'formaction';
647
- // The submission pair, named per element (#1307). A form declares `method` /
648
- // `enctype`; a submitter declares `formmethod` / `formenctype`, and a bound
649
- // one receives them from the renderer exactly as a bound form does.
650
- const methodAttr = isForm ? 'method' : 'formmethod';
651
- const enctypeAttr = isForm ? 'enctype' : 'formenctype';
652
- const actionParts = onEl.filter((p) => p.kind === 'attr' && p.name.toLowerCase() === targetAttr);
653
- if (!actionParts.length) return null;
654
-
655
- /** @type {FormAttrPart[]} */
656
- const methodParts = [];
657
- /** @type {FormAttrPart[]} */
658
- const enctypeParts = [];
659
- /** Prop bindings that cannot converge with SSR; refused when actually bound. */
660
- const propAttrs = [];
661
- // `name` holes on a submitter, recorded WITH their kind. Whether one occupies
662
- // the identity's channel is not a property of the hole alone: SSR emits
663
- // `name=""` for an attribute hole whatever it resolved to, but emits nothing
664
- // at all for a FALSY boolean hole and nothing for an `@name` listener. Asking
665
- // only "is there a part called name" therefore refused templates SSR renders
666
- // happily, which is the render-on-the-server-throw-on-hydration direction.
667
- // The kinds travel with the record and `reconcileFormActions` resolves them.
668
- const nameParts = isForm ? [] : onEl
669
- .filter((p) => p.name.toLowerCase() === 'name'
670
- && (p.kind === 'attr' || p.kind === 'attr-mixed' || p.kind === 'bool'))
671
- .map((p) => ({ i: p.idx, kind: p.kind }));
672
- const authoredName = !isForm && el.hasAttribute('name');
673
- const authoredForm = !isForm && el.hasAttribute('form');
674
- const authoredValue = !isForm && el.hasAttribute('value');
675
- // `value` holes, recorded with their kind for the same reason as `name`: a
676
- // FALSY boolean hole emits nothing at SSR, so counting the part's mere
677
- // presence refused a template the server renders happily.
678
- const valueParts = isForm ? [] : onEl
679
- .filter((p) => p.name.toLowerCase() === 'value'
680
- && (p.kind === 'attr' || p.kind === 'attr-mixed' || p.kind === 'bool'))
681
- .map((p) => ({ i: p.idx, kind: p.kind }));
682
-
683
- for (const p of onEl) {
684
- const name = String(p.name).toLowerCase();
685
- if (p.kind === 'prop') {
686
- // On a FORM, the reflected attributes that decide submittability. On a
687
- // SUBMITTER, the ones that carry the identity or override the submission
688
- // (#1207). Either way a `.prop` is dropped at SSR and written to the
689
- // attribute in the browser, so it can never converge.
690
- if (isForm) {
691
- if (name === 'method' || name === 'enctype' || name === 'encoding') propAttrs.push(p.name);
692
- } else if (isSubmitterReflectedProp(name)) {
693
- propAttrs.push(p.name);
694
- }
695
- continue;
696
- }
697
- // #1307: a bound submitter carries its OWN submission attributes, so the
698
- // pair to capture depends on the element. `formmethod` / `formenctype` on a
699
- // button are exactly what `method` / `enctype` are on a form, and they flow
700
- // through the same resolution below untouched.
701
- if (name !== methodAttr && name !== enctypeAttr) continue;
702
- if (p.kind !== 'attr' && p.kind !== 'attr-mixed' && p.kind !== 'bool') continue;
703
- const d = /** @type any */ (parts[p.idx]);
704
- /** @type {FormAttrPart} */
705
- const entry = { i: p.idx, kind: p.kind };
706
- // A mixed attribute's value is `statics[0] + v0 + statics[1] + ...`, so the
707
- // pieces have to travel with the record; reading the anchor's value alone
708
- // is right only when the statics are empty.
709
- if (p.kind === 'attr-mixed') { entry.statics = d.statics || []; entry.group = d.group || []; }
710
- // Compared against `methodAttr`, NOT the literal 'method'. On a submitter
711
- // the pair is `formmethod` / `formenctype`, so a literal comparison sent
712
- // every hole-provided `formmethod` into `enctypeParts`: the client then
713
- // resolved it as the enctype, refused `formenctype="post"`, and threw on
714
- // hydration for a template SSR renders happily. That is the
715
- // render-on-the-server, crash-in-the-browser direction this module treats
716
- // as the one unacceptable failure.
717
- (name === methodAttr ? methodParts : enctypeParts).push(entry);
718
- }
719
-
720
- return {
721
- isForm,
722
- tag: el.localName,
723
- // EVERY action hole, not just the first. SSR refuses two holes whenever
724
- // ANY of them resolves to a bound action, so recording only the first would
725
- // let `<form action=${'/legacy'} action=${boundFn}>` slip through the
726
- // client's release path while SSR throws on the same template.
727
- actionIdxs: actionParts.map((p) => p.idx),
728
- duplicateAction: actionParts.length > 1,
729
- // A static `action="..."` / `formaction="..."` surviving alongside the hole.
730
- // The compiled template holds the hole as a sentinel attribute, so anything
731
- // read back under the real name here is the author's own second one.
732
- staticAction: el.getAttribute(targetAttr) != null,
733
- authoredName,
734
- authoredValue,
735
- authoredForm,
736
- propAttrs,
737
- nameParts,
738
- valueParts,
739
- staticMethod: el.getAttribute(methodAttr),
740
- staticEnctype: el.getAttribute(enctypeAttr),
741
- methodParts,
742
- enctypeParts,
743
- };
744
- }
745
-
746
- /**
747
- * Converge every candidate bound form and submitter in this template, after all
748
- * of its parts have committed. A no-op for the overwhelming majority of
749
- * templates, which carry no `<form action=${...}>` at all and therefore no
750
- * record.
751
- *
752
- * FORMS FIRST, submitters second, regardless of the order the records were
753
- * collected in. A submitter asks whether its enclosing form is bound, and the
754
- * cheapest true answer is the identity field the form's own reconcile just
755
- * inserted. Document order gets this right for a form and a button in the SAME
756
- * template, but not for a `<form>` whose submitter arrives through a nested
757
- * template, so the ordering is made explicit rather than relied upon.
758
- *
759
- * @param {FormActionRecord[] | null} formActions
760
- * @param {BoundPart[]} bound
761
- * @param {unknown[]} values
762
- */
763
- function reconcileFormActions(formActions, bound, values) {
764
- if (!formActions) return;
765
- // Forms first, then submitters. The original motivation was a boundness read
766
- // that is gone with #1307, but the ordering still makes a form's RELEASE run
767
- // before its submitters reconcile, so it is kept rather than churned.
768
- for (const pass of [true, false]) {
769
- for (const rec of formActions) {
770
- if (rec.isForm !== pass) continue;
771
- // With more than one action hole, the BOUND one decides, whichever
772
- // position it is written in. Picking `actionIdxs[0]` blindly would send
773
- // `<form action=${'/url'} action=${boundFn}>` down the release path and
774
- // ship the broken form SSR refuses outright.
775
- let idx = rec.actionIdxs[0];
776
- const targetAttr = rec.isForm ? 'action' : 'formaction';
777
- for (const i of rec.actionIdxs) {
778
- if (isBoundFormAction(resolveHoleValue(values[i]), targetAttr, rec.tag)) { idx = i; break; }
779
- }
780
- const part = bound[idx];
781
- if (!part || !part.el) continue;
782
- const val = resolveHoleValue(values[idx]);
783
- if (rec.isForm) {
784
- reconcileFormAction(
785
- /** @type any */ (part.el),
786
- val,
787
- effectiveFormAttr(rec.methodParts, rec.staticMethod, values),
788
- effectiveFormAttr(rec.enctypeParts, rec.staticEnctype, values),
789
- rec,
790
- );
791
- } else {
792
- // What SSR would have emitted for this pass. An attribute hole always
793
- // emits (even `name=${null}`, as `name=""`); a boolean hole emits only
794
- // when truthy. Both identity channels ask the same question, through
795
- // one predicate, so they cannot drift apart again.
796
- const emits = (parts) => parts.some((np) => (np.kind === 'bool'
797
- ? !!resolveHoleValue(values[np.i])
798
- : true));
799
- reconcileSubmitterAction(
800
- /** @type any */ (part.el), val, rec,
801
- emits(rec.nameParts), emits(rec.valueParts),
802
- effectiveFormAttr(rec.methodParts, rec.staticMethod, values),
803
- effectiveFormAttr(rec.enctypeParts, rec.staticEnctype, values),
804
- );
805
- }
806
- }
807
- }
808
- }
809
-
810
- /**
811
- * Remove the identity channel previously injected into a submitter.
812
- *
813
- * Only ours is removed. `submitterActionBindings` remembers the elements this
814
- * renderer stamped, and the `name` check covers an SSR'd button meeting its
815
- * template for the first time on hydration. A button that never carried a
816
- * binding is left alone, so an author's own `name` / `value` survives a
817
- * re-render that happens to pass a non-action value.
818
- *
819
- * @param {Element} el
820
- */
821
- function releaseSubmitterAction(el) {
822
- const injected = submitterActionBindings.has(el) || el.getAttribute('name') === FORM_ACTION_FIELD;
823
- if (!injected) return;
824
- if (el.getAttribute('name') === FORM_ACTION_FIELD) el.removeAttribute('name');
825
- el.removeAttribute('value');
826
- submitterActionBindings.delete(el);
827
- }
828
-
829
- /**
830
- * Converge a live submitter on what SSR emitted for `<button formaction=${fn}>`
831
- * (#1207, #1307): the `formaction` attribute gone, the identity in the button's
832
- * own `name` / `value` pair, and the submission the framework supplies in its
833
- * own `formmethod` / `formenctype`.
834
- *
835
- * There is no enclosing-form question here any more. It used to be the hard
836
- * part of this function, asked once per element and BEST EFFORT because a
837
- * fragment reconciling detached (a submitter inside a `repeat()` or an array
838
- * item, whose form lives in the parent template) has no answer to give. With
839
- * the submission attributes now on the button itself (#1307) the button needs
840
- * nothing from the form, so the question stopped mattering and the whole
841
- * asymmetry with SSR went with it.
842
- *
843
- * @param {Element} el
844
- * @param {unknown} value
845
- * @param {FormActionRecord} rec
846
- * @param {boolean} emitsName whether SSR would emit a `name` attribute this pass
847
- * @param {boolean} emitsValue whether SSR would emit a `value` attribute this pass
848
- * @param {string | typeof ABSENT} authoredFormMethod what the template supplies for `formmethod`
849
- * @param {string | typeof ABSENT} authoredFormEnctype what the template supplies for `formenctype`
850
- */
851
- function reconcileSubmitterAction(
852
- el, value, rec, emitsName, emitsValue, authoredFormMethod, authoredFormEnctype,
853
- ) {
854
- const id = typeof value === 'function' ? formActionId(value) : null;
855
- if (!id) {
856
- // A function that was MEANT as an action still refuses, so a button never
857
- // silently submits the form's action instead of its own.
858
- if (typeof value === 'function') assertIdentifiableAction(null, el.localName);
859
- releaseSubmitterAction(el);
860
- // The submission attributes the framework supplied go with the identity, or
861
- // a released button keeps a `formmethod` / `formenctype` SSR does not emit
862
- // for the same template (#1307).
863
- releaseSubmitterAttrs(el, authoredFormMethod, authoredFormEnctype, rec.propAttrs);
864
- return;
865
- }
866
- // Template-shaped refusals first, from the compiled record, because the live
867
- // element may already carry this renderer's own `name` / `value`.
868
- assertSingleSubmitterAction(rec.duplicateAction, el.localName);
869
- assertConvergentSubmitter(rec.propAttrs, el.localName);
870
- if (rec.staticAction) assertSubmitterHasNoStaticFormAction(el.localName);
871
- if (rec.authoredValue || emitsValue) assertSubmitterHasNoValue(el.localName);
872
- if (rec.authoredName || emitsName) {
873
- // Judged on the PART, not on what it resolved to this pass. `name=${null}`
874
- // leaves no attribute here while SSR emits `name=""` beside the identity,
875
- // so reading the live value back returned '' and waved through a template
876
- // SSR refuses. The template supplying a `name` channel at all is the
877
- // conflict, whatever today's value happens to be.
878
- assertSubmitterHasNoName(el.getAttribute('name') || FORM_ACTION_FIELD, el.localName, false);
879
- }
880
- if (rec.authoredForm || el.hasAttribute('form')) assertSubmitterHasNoFormAttribute(el.localName);
881
- assertSubmitterType(el.localName, el.getAttribute('type'));
882
-
883
- // The submission decision, made from the TEMPLATE rather than by reading the
884
- // DOM back, exactly as `reconcileFormAction` makes it for a bound form. The
885
- // distinction the DOM cannot preserve is the same one: `?formmethod=${false}`
886
- // and `formmethod=${null}` both leave no attribute, and SSR resolves them to
887
- // opposite answers.
888
- const resolved = resolveBoundSubmitterAttrs(
889
- el.localName, authoredFormMethod, authoredFormEnctype,
890
- );
891
- el.removeAttribute('formaction');
892
- el.setAttribute('name', FORM_ACTION_FIELD);
893
- el.setAttribute('value', id);
894
- // AFTER the identity, matching SSR's byte order: the identity replaces the
895
- // `formaction=` hole in place and the submission pair is appended at the `>`.
896
- // The differential parity suite compares these two renderers byte for byte,
897
- // so the order is part of the contract, not a detail.
898
- applyResolvedAttr(el, 'formmethod', authoredFormMethod, resolved.formMethod);
899
- applyResolvedAttr(el, 'formenctype', authoredFormEnctype, resolved.formEnctype);
900
- submitterActionBindings.set(el, id);
901
- }
902
-
903
- /* ================================================================
904
- * Instance lifecycle
905
- * ================================================================ */
906
-
907
- /**
908
- * @param {import('./html.js').TemplateResult} tr
909
- * @param {Element | DocumentFragment | ShadowRoot} container
910
- */
911
- function createInstance(tr, container) {
912
- const { templateEl, parts, formActions } = compile(tr);
913
- const frag = /** @type DocumentFragment */ (templateEl.content.cloneNode(true));
914
-
915
- // Bookend markers bound the instance so we can tear it down cleanly.
916
- const startNode = document.createComment(`${MARKER}s`);
917
- const endNode = document.createComment(`${MARKER}e`);
918
-
919
- const bound = parts.map((p) => bindPart(p, frag));
920
- const lastValues = [];
921
- for (let i = 0; i < tr.values.length; i++) {
922
- applyPart(bound[i], tr.values[i], undefined, tr.values);
923
- lastValues.push(tr.values[i]);
924
- }
925
- reconcileFormActions(formActions, bound, tr.values);
926
-
927
- /** @type any */ (container).replaceChildren(startNode, ...frag.childNodes, endNode);
928
-
929
- // Slot parts have no value-hole to drive applyPart from the loop above.
930
- // Apply them once now that the fragment is inserted into the live
931
- // container, so each slot can locate its host by walking parents and
932
- // schedule the first projection through slot.js. Stamp each slot with the
933
- // host whose TEMPLATE produced it (this container), so a FORWARDED slot
934
- // (rendered here but nested inside a child component) routes to this host
935
- // rather than to the child the structural walk would pick. Only an element
936
- // container is a host; a fragment/shadow container leaves the structural
937
- // path in place.
938
- const ownerHost =
939
- /** @type {any} */ (container).nodeType === 1 && /** @type {any} */ (container)[SLOT_STATE]
940
- ? container
941
- : null;
942
- for (const part of bound) {
943
- if (part.kind === 'slot') {
944
- if (ownerHost && part.slotEl) /** @type {any} */ (part.slotEl)[SLOT_OWNER] = ownerHost;
945
- applyPart(part, undefined, undefined, []);
946
- }
947
- }
948
-
949
- return { strings: tr.strings, bound, lastValues, startNode, endNode };
950
- }
951
-
952
- /**
953
- * @param {PartDescriptor} p
954
- * @param {DocumentFragment | Element} root
955
- * @returns {BoundPart}
956
- */
957
- function bindPart(p, root) {
958
- if (p.kind === 'noop') return /** @type any */ ({ kind: 'noop', mixedAnchor: /** @type any */ (p).mixedAnchor });
959
- let node = /** @type Node */ (root);
960
- for (const i of p.path) node = node.childNodes[i];
961
- if (p.kind === 'child') {
962
- return { kind: 'child', marker: /** @type Comment */ (node) };
963
- }
964
- const el = /** @type Element */ (node);
965
- if (p.kind === 'event') {
966
- /** @type {BoundPart} */
967
- const part = {
968
- kind: 'event',
969
- el,
970
- name: p.name || '',
971
- handler: null,
972
- // The dispatcher is the registered listener; handler swaps behind it.
973
- dispatcher(ev) { part.handler?.(ev); },
974
- };
975
- el.addEventListener(part.name, part.dispatcher);
976
- return part;
977
- }
978
- if (p.kind === 'attr') return { kind: 'attr', el, name: p.name || '' };
979
- if (p.kind === 'attr-mixed') return { kind: 'attr-mixed', el, name: p.name || '', statics: p.statics || [], group: p.group || [] };
980
- if (p.kind === 'prop') return { kind: 'prop', el, name: p.name || '' };
981
- if (p.kind === 'bool') return { kind: 'bool', el, name: p.name || '' };
982
- if (p.kind === 'element') return { kind: 'element', el };
983
- if (p.kind === 'slot') {
984
- const slotEl = /** @type {HTMLSlotElement} */ (el);
985
- // Defer fallback-strip and SLOT_FALLBACK_FRAG installation to apply
986
- // time so we know whether the slot is light or shadow at the point
987
- // where the decision matters. At bind time the cloned slot still
988
- // holds its fallback content from the template clone; we just
989
- // record the slot ref.
990
- return { kind: 'slot', slotEl, applied: false };
991
- }
992
- throw new Error(`unknown part kind ${/** @type any */(p).kind}`);
993
- }
994
-
995
- /**
996
- * Sentinel parked in `lastValues` for a hole whose commit threw, so the next
997
- * render cannot mistake the un-advanced entry for "already applied". Never
998
- * equal (by `Object.is`) to anything an author can pass through a template.
999
- */
1000
- const COMMIT_FAILED = Symbol('webjs.commitFailed');
1001
-
1002
- /**
1003
- * @param {TemplateInstance} inst
1004
- * @param {unknown[]} values
1005
- */
1006
- function updateInstance(inst, values) {
1007
- for (let i = 0; i < values.length; i++) {
1008
- const next = values[i];
1009
- if (Object.is(next, inst.lastValues[i])) continue;
1010
- const bp = inst.bound[i];
1011
- // A hole that belongs to a mixed attribute (`class="a ${x} b ${y}"`) is a
1012
- // `noop` pointing at the attribute's anchor part; re-apply the anchor so the
1013
- // whole attribute is rebuilt from every hole's current value, not just the
1014
- // anchor hole's. Without this, a change confined to a non-anchor hole is
1015
- // dropped (the attribute goes stale).
1016
- const anchor = /** @type any */ (bp).mixedAnchor;
1017
- try {
1018
- if (bp.kind === 'noop' && anchor != null) {
1019
- applyPart(inst.bound[anchor], values[anchor], inst.lastValues[anchor], values);
1020
- } else {
1021
- applyPart(bp, next, inst.lastValues[i], values);
1022
- }
1023
- } catch (err) {
1024
- // A commit that throws leaves `lastValues` for THIS hole un-advanced,
1025
- // still holding the value from before the throw. That is almost always
1026
- // the value the recovering render supplies, so the `Object.is` skip at
1027
- // the top of this loop would skip the hole FOREVER. Harmless for an
1028
- // attribute (its commit stringifies before touching the DOM, so nothing
1029
- // changed), and permanently destructive for a child position, whose
1030
- // commit tears the old content down BEFORE the step that throws: the
1031
- // region is left empty and never re-rendered.
1032
- //
1033
- // Poison the entry with a sentinel no author value can ever be, so the
1034
- // next render always re-applies this hole. The value is deliberately
1035
- // NOT advanced to `next` either, since `next` was never committed.
1036
- inst.lastValues[i] = COMMIT_FAILED;
1037
- if (bp.kind === 'noop' && anchor != null) inst.lastValues[anchor] = COMMIT_FAILED;
1038
- throw err;
1039
- }
1040
- inst.lastValues[i] = next;
1041
- }
1042
- // Unconditional, and NOT inside the loop above: a form's correctness depends
1043
- // on holes other than its own, and the `Object.is` skip means the action hole
1044
- // may not have been re-applied at all this pass.
1045
- reconcileFormActions(templateCache.get(inst.strings)?.formActions ?? null, inst.bound, values);
1046
- }
1047
-
1048
- /**
1049
- * @param {TemplateInstance} inst
1050
- * @param {Element | DocumentFragment | ShadowRoot} container
1051
- */
1052
- function clearInstance(inst, container) {
1053
- // Dispose event listeners on event parts, unbind active refs on
1054
- // element parts, and rescue any projected children sitting inside
1055
- // slot parts so they survive teardown of a collapsing conditional
1056
- // fragment.
1057
- for (const p of inst.bound) {
1058
- if (p.kind === 'event') p.el.removeEventListener(p.name, p.dispatcher);
1059
- if (p.kind === 'element') {
1060
- // Guarded for the same reason as the sibling in `disposeInstance`, and
1061
- // the stakes are higher here: this is the container-level teardown
1062
- // `render()` runs before a template swap, so a throw skips the rest of
1063
- // this loop AND the `replaceChildren()` below, leaving the old DOM in
1064
- // place with `host[INSTANCE]` never reassigned. Since `lastTarget` is
1065
- // cleared only after the write, every later swap of that container
1066
- // then throws at the same part, permanently.
1067
- const prev = /** @type any */ (p).lastTarget;
1068
- if (prev) {
1069
- if (typeof prev === 'function') {
1070
- try { prev(undefined); } catch { /* swallow */ }
1071
- } else if (typeof prev === 'object') {
1072
- try { prev.value = undefined; } catch { /* swallow */ }
1073
- }
1074
- /** @type any */ (p).lastTarget = undefined;
1075
- /** @type any */ (p).__lastEl = undefined;
1076
- }
1077
- }
1078
- if (p.kind === 'slot') {
1079
- // Detach record-owned children before the teardown disposes the
1080
- // slot subtree; the record keeps the refs, so a re-created slot
1081
- // re-places the SAME nodes (children are values, #1015).
1082
- const host = findSlotHost(p.slotEl);
1083
- if (host) rescueAssignedNodes(host, p.slotEl);
1084
- }
1085
- }
1086
- /** @type any */ (container).replaceChildren();
1087
- }
1088
-
1089
- /* ================================================================
1090
- * Part application
1091
- * ================================================================ */
1092
-
1093
-
1094
- /**
1095
- * Resolve what SSR would have emitted for one attribute of a candidate form.
1096
- *
1097
- * The per-kind rules mirror `render-server.js` exactly, which is the whole
1098
- * point: a boolean hole emits nothing when falsy (`if (val) out += name+'=""'`)
1099
- * while an attribute hole emits an EMPTY value for null (`String(val ?? '')`).
1100
- * Those two produce the same DOM and opposite verdicts, so only the template
1101
- * can tell them apart.
1102
- *
1103
- * @param {FormAttrPart[]} attrParts
1104
- * @param {string | null} staticValue
1105
- * @param {unknown[]} values
1106
- * @returns {string | typeof ABSENT}
1107
- */
1108
- function effectiveFormAttr(attrParts, staticValue, values) {
1109
- for (const p of attrParts) {
1110
- if (p.kind === 'bool') return resolveHoleValue(values[p.i]) ? '' : ABSENT;
1111
- if (p.kind === 'attr') {
1112
- const v = resolveHoleValue(values[p.i]);
1113
- return v == null ? '' : String(v);
1114
- }
1115
- // A mixed attribute is the concatenation of its static pieces and EVERY one
1116
- // of its holes, so the anchor's own value is only part of the answer.
1117
- const statics = p.statics || [];
1118
- const group = p.group || [];
1119
- let out = statics[0] || '';
1120
- for (let j = 0; j < group.length; j++) {
1121
- out += String(resolveHoleValue(values[group[j]]) ?? '');
1122
- out += statics[j + 1] || '';
1123
- }
1124
- return out;
1125
- }
1126
- return staticValue == null ? ABSENT : staticValue;
1127
- }
1128
-
1129
- /**
1130
- * Unwrap a hole's value the same way `applyPart` does, so the reconcile judges
1131
- * what was actually committed. `live()` in particular wraps its value, and
1132
- * reading the wrapper would make a bound action look like a plain object.
1133
- *
1134
- * @param {unknown} v
1135
- * @returns {unknown}
1136
- */
1137
- function resolveHoleValue(v) {
1138
- return isLive(v) ? /** @type any */ (v).value : v;
1139
- }
1140
-
1141
- /**
1142
- * @param {BoundPart} part
1143
- * @param {unknown} value
1144
- * @param {unknown} _prev
1145
- */
1146
- function applyPart(part, value, _prev, allValues) {
1147
- // Unwrap live() to dirty-check against the live DOM value, not the
1148
- // last rendered value. Essential for <input> two-way binding.
1149
- if (isLive(value)) {
1150
- const liveVal = /** @type any */ (value).value;
1151
- if (part.kind === 'prop' && /** @type any */ (part.el)[part.name] === liveVal) return;
1152
- if (part.kind === 'attr' && part.el.getAttribute(part.name) === String(liveVal)) return;
1153
- if (part.kind === 'bool' && part.el.hasAttribute(part.name) === !!liveVal) return;
1154
- value = liveVal;
1155
- }
1156
-
1157
- switch (part.kind) {
1158
- case 'child':
1159
- applyChild(part, value);
1160
- break;
1161
- case 'attr': {
1162
- if (value == null || value === false) part.el.removeAttribute(part.name);
1163
- else if (isBoundFormAction(value, part.name, part.el.localName)) {
1164
- // #1155: the ONE supported form-action binding, applied to the live
1165
- // form exactly as SSR wrote it. A component that ships re-renders its
1166
- // whole template on hydration, so without this the SSR'd hidden field
1167
- // would be replaced by an `action` attribute holding a stringified
1168
- // function, and the form would post to a garbage url.
1169
- //
1170
- // Nothing happens here. The whole decision (identity, the submit
1171
- // attributes, the hidden field) is made at the end of the pass by
1172
- // `reconcileFormAction`, because it depends on holes that have not
1173
- // committed yet when this one does.
1174
- } else {
1175
- // #1154: refuse to stringify a function into action=/formaction=
1176
- // (mirrors the SSR guard, so a client re-render cannot write a
1177
- // server action's source into the live DOM).
1178
- assertNotFunctionActionAttr(value, part.name, part.el.localName);
1179
- part.el.setAttribute(part.name, String(value));
1180
- }
1181
- break;
1182
- }
1183
- case 'prop':
1184
- // `.action=${fn}` is a leak too, not just the attribute form, but only
1185
- // where the property is a REFLECTED IDL attribute: assigning a function
1186
- // to `form.action` (or `.formAction` on a button/input) stringifies it
1187
- // into that element's own content attribute in a real browser. On any
1188
- // other native tag it is a plain expando that reflects nothing, and on a
1189
- // custom element it is an author-defined property, so a function is
1190
- // legitimate in both. The helper owns that distinction.
1191
- //
1192
- // Not covered here, because it is not a commit: a custom element's prop
1193
- // declared `reflect: true` reflects from its own setter. That path used
1194
- // to write String(value) and leak the source. #1169 made it remove the
1195
- // attribute instead (an array carrying one included, via the same
1196
- // `carriesFunction` predicate this file's guard uses), so it is guarded
1197
- // at the setter rather than here. One carve-out stays the author's call:
1198
- // a prop supplying its own `converter.toAttribute` runs that converter
1199
- // first and is left alone, so it still writes whatever the author
1200
- // returns for a function.
1201
- assertNotFunctionReflectedActionProp(value, part.name, part.el.localName);
1202
- /** @type any */ (part.el)[part.name] = value;
1203
- break;
1204
- case 'bool':
1205
- // #1154: never leaked (a boolean binding stringifies nothing), but
1206
- // `?action=${fn}` is meaningless in every case, and refusing it keeps
1207
- // this renderer agreeing with both SSR machines.
1208
- assertNotFunctionActionAttr(value, part.name, part.el.localName);
1209
- if (value) part.el.setAttribute(part.name, '');
1210
- else part.el.removeAttribute(part.name);
1211
- break;
1212
- case 'event':
1213
- // NOT guarded, deliberately. An event binding never stringifies its
1214
- // value, and a function is the legitimate thing to pass one, so
1215
- // `<my-el @action=${handler}>` has to keep working.
1216
- part.handler = typeof value === 'function' ? /** @type any */ (value) : null;
1217
- break;
1218
- case 'element':
1219
- applyElement(part, value);
1220
- break;
1221
- case 'attr-mixed': {
1222
- // Reconstruct the attribute from static pieces + all dynamic values.
1223
- const mp = /** @type {{ statics: string[], group: number[] }} */ (/** @type any */ (part));
1224
- let val = mp.statics[0];
1225
- for (let j = 0; j < mp.group.length; j++) {
1226
- const piece = allValues ? allValues[mp.group[j]] : value;
1227
- // #1154: same function guard for each piece of a mixed attribute.
1228
- assertNotFunctionActionAttr(piece, part.name, part.el.localName);
1229
- val += String(piece ?? '');
1230
- val += mp.statics[j + 1] || '';
1231
- }
1232
- part.el.setAttribute(part.name, val);
1233
- break;
1234
- }
1235
- case 'slot': {
1236
- // Slot parts have no template-hole value to apply. The "apply" is
1237
- // a one-shot trigger that runs after the template fragment has
1238
- // been inserted into the host's render root. At this point the
1239
- // slot's parent chain reveals whether it lives inside a shadow
1240
- // root (browser native projection) or in light DOM (framework
1241
- // projection). For shadow-DOM slots we leave the cloned fallback
1242
- // in place. For light-DOM slots we move the fallback into a
1243
- // per-slot holding fragment owned by slot.js (via the
1244
- // SLOT_FALLBACK_FRAG symbol) so the slot can receive projected
1245
- // children, and we kick off projection.
1246
- //
1247
- // For NESTED templates (a slot inside `${cond ? html`<slot/>` : ''}`),
1248
- // the slot's parent chain at first apply may still lead through
1249
- // an unattached fragment. findSlotHost returns null then; we
1250
- // retry on the next microtask, by which point the outer's
1251
- // replaceChildren has placed the entire tree into the host.
1252
- if (part.applied) break;
1253
- const slotEl = part.slotEl;
1254
- const finalize = () => {
1255
- const host = findSlotHost(slotEl);
1256
- if (!host) {
1257
- part.applied = true;
1258
- return; // truly orphan slot (no owner, no structural host)
1259
- }
1260
- // A FORWARDED slot's owner is known immediately (the SLOT_OWNER
1261
- // stamp) but the child component has not yet PLACED the slot into
1262
- // the owner's subtree, so the owner's apply cannot find it yet.
1263
- // Re-defer until the child places it (host.contains becomes true);
1264
- // the child WILL place it, or the owner disconnects and the retries
1265
- // stop. A normal own slot is already inside its host, so this passes
1266
- // on the first call with no extra deferral.
1267
- if (!host.contains(slotEl)) {
1268
- if (host.isConnected) queueMicrotask(finalize);
1269
- else part.applied = true;
1270
- return;
1271
- }
1272
- part.applied = true;
1273
- // Shadow DOM: native projection. Leave fallback in place.
1274
- if (isInShadowRootEl(slotEl)) return;
1275
- // Light DOM: harvest the cloned fallback into a holding
1276
- // fragment, then place the host's slot record (#1015). The
1277
- // application is deferred one microtask so the documented
1278
- // lifecycle timing holds: firstUpdated() sees the <slot>
1279
- // element itself, the populated content lands right after.
1280
- const frag = document.createDocumentFragment();
1281
- while (slotEl.firstChild) frag.appendChild(slotEl.firstChild);
1282
- /** @type {any} */ (slotEl)[SLOT_FALLBACK_FRAG] = frag;
1283
- queueMicrotask(() => applySlotAssignments(host));
1284
- };
1285
- const directHost = findSlotHost(slotEl);
1286
- if (directHost && directHost.contains(slotEl)) {
1287
- finalize();
1288
- } else {
1289
- queueMicrotask(finalize);
1290
- }
1291
- break;
1292
- }
1293
- case 'noop':
1294
- // intentionally empty: used for holes inside HTML comments
1295
- break;
1296
- }
1297
- }
1298
-
1299
- /**
1300
- * Walk a slot element's parent chain looking for a WebComponent host
1301
- * (an element that has slot state initialised). Used by the slot-part's
1302
- * apply and teardown steps to coordinate with slot.js.
1303
- *
1304
- * @param {HTMLSlotElement} slotEl
1305
- * @returns {Element | null}
1306
- */
1307
- function findSlotHost(slotEl) {
1308
- // Template-owner stamp wins (a forwarded slot's true host), else the
1309
- // nearest SLOT_STATE ancestor structurally.
1310
- const owner = /** @type any */ (slotEl)[SLOT_OWNER];
1311
- if (owner && owner.isConnected) return owner;
1312
- let p = slotEl.parentElement;
1313
- while (p) {
1314
- if (/** @type any */ (p)[SLOT_STATE]) return p;
1315
- p = p.parentElement;
1316
- }
1317
- return null;
1318
- }
1319
-
1320
- /**
1321
- * True when an element is inside a shadow root (so native browser slot
1322
- * projection applies). Mirrors slot.js's helper; duplicated here to
1323
- * avoid the round trip through the slot.js public surface for this
1324
- * hot path.
1325
- * @param {Element} el
1326
- * @returns {boolean}
1327
- */
1328
- function isInShadowRootEl(el) {
1329
- let n = /** @type {Node} */ (el);
1330
- for (let depth = 0; depth < 128; depth++) {
1331
- const parent = n.parentNode;
1332
- if (!parent) return false;
1333
- if (parent === n) return false;
1334
- // A real ShadowRoot is a DocumentFragment (nodeType 11) exposing its
1335
- // owner as `.host`. Checking `.host` truthiness ALONE misfires on
1336
- // ordinary elements: HTMLAnchorElement/HTMLAreaElement expose a
1337
- // URL-derived `.host` ('example.com'), so a slot nested inside an
1338
- // <a> card was misread as shadow DOM and its light-DOM application
1339
- // silently skipped (surfaced by #1015's removal of the redundant
1340
- // observer repair paths that used to mask it).
1341
- if (parent.nodeType === 11 && /** @type any */ (parent).host) return true;
1342
- n = parent;
1343
- }
1344
- return false;
1345
- }
1346
-
1347
- /**
1348
- * Child (text-position) part. Replace the marker's surrounding nodes with the
1349
- * new value's rendered form. Nested TemplateResults get an instance with its
1350
- * own parts; we reuse on `strings` identity.
1351
- *
1352
- * @param {Extract<BoundPart, {kind:'child'}>} part
1353
- * @param {unknown} value
1354
- */
1355
- /**
1356
- * Apply a value at an element-position part (`<tag ${expr}>`). The
1357
- * sole supported directive here is `ref(refOrCallback)` and
1358
- * `createRef()`. Other values are ignored so a stray non-ref hole
1359
- * doesn't crash. Tracks the prior target so a change from one ref to
1360
- * another correctly unsets the old target before binding the new one.
1361
- *
1362
- * @param {Extract<BoundPart, {kind:'element'}>} part
1363
- * @param {unknown} value
1364
- */
1365
- function applyElement(part, value) {
1366
- // Matches lit-html's RefDirective.update():
1367
- // 1. If the ref target changed since last render, unbind the prior one.
1368
- // 2. If the ref target OR the element identity changed, bind the new
1369
- // (ref, element) pair. If both are stable, skip entirely.
1370
- // For callback refs, an unset-before-bind cycle runs whenever the
1371
- // same callback is now pointing at a different element.
1372
- const partAny = /** @type any */ (part);
1373
- const nextTarget = isRef(value) ? /** @type any */ (value).target : undefined;
1374
- const prevTarget = partAny.__refTarget;
1375
- const refChanged = nextTarget !== prevTarget;
1376
-
1377
- if (refChanged && prevTarget) {
1378
- if (typeof prevTarget === 'function') {
1379
- try { prevTarget(undefined); } catch { /* swallow */ }
1380
- } else if (typeof prevTarget === 'object') {
1381
- prevTarget.value = undefined;
1382
- }
1383
- }
1384
-
1385
- if (refChanged || partAny.__refElement !== part.el) {
1386
- partAny.__refTarget = nextTarget;
1387
- if (nextTarget) {
1388
- if (typeof nextTarget === 'function') {
1389
- // Same callback now pointing at a different element: deliver
1390
- // an `undefined` cleanup for the prior element first.
1391
- if (!refChanged && partAny.__refElement !== undefined) {
1392
- try { nextTarget(undefined); } catch { /* swallow */ }
1393
- }
1394
- try { nextTarget(part.el); } catch { /* swallow */ }
1395
- } else if (typeof nextTarget === 'object') {
1396
- nextTarget.value = part.el;
1397
- }
1398
- }
1399
- partAny.__refElement = part.el;
1400
- // Keep the legacy `lastTarget` field in sync for clearInstance /
1401
- // disposeInstance which read it for template-disposal cleanup.
1402
- part.lastTarget = nextTarget;
1403
- }
1404
- }
1405
-
1406
- function applyChild(part, value) {
1407
- // Drop directive state from prior renders when the new value is for a
1408
- // different directive (or no directive at all). Keeps __untilState
1409
- // from leaking across replacements, __guardDeps from causing a stale
1410
- // short-circuit, etc. Done once per outermost applyChild call; the
1411
- // directive handlers recurse via applyChildInner (no re-clear) so
1412
- // their own state survives the recursion.
1413
- clearStaleDirectiveState(part, value);
1414
- return applyChildInner(part, value);
1415
- }
1416
-
1417
- /**
1418
- * Internal dispatch. Used both by `applyChild` (which first clears
1419
- * stale per-part directive state) and by directive handlers that
1420
- * recurse with a different value at the same part. Recursing via
1421
- * `applyChild` would clear the directive state that was just set,
1422
- * because the inner value almost always isn't itself a directive.
1423
- *
1424
- * @param {Extract<BoundPart, {kind:'child'}>} part
1425
- * @param {unknown} value
1426
- */
1427
- function applyChildInner(part, value) {
1428
- // Open the renderer-write window around this commit. Most calls are
1429
- // synchronous inside render() (the window is already open, this nests
1430
- // harmlessly), but the async directive paths (until, watch, asyncAppend /
1431
- // asyncReplace, streaming) re-enter here from a promise / microtask OUTSIDE
1432
- // any render() window, so this is where those commits into a light host are
1433
- // marked as renderer writes rather than authored content.
1434
- return commitInto(part.marker && part.marker.parentNode, () =>
1435
- applyChildInnerRaw(part, value),
1436
- );
1437
- }
1438
-
1439
- /**
1440
- * @param {Extract<BoundPart, {kind:'child'}>} part
1441
- * @param {unknown} value
1442
- */
1443
- function applyChildInnerRaw(part, value) {
1444
- const marker = part.marker;
1445
-
1446
- // unsafeHTML directive: inject raw HTML string as DOM nodes.
1447
- if (isUnsafeHTML(value)) {
1448
- teardownChild(part);
1449
- const htmlStr = String(/** @type any */ (value).value ?? '');
1450
- const template = document.createElement('template');
1451
- template.innerHTML = htmlStr;
1452
- const nodes = [...template.content.childNodes];
1453
- const frag = document.createDocumentFragment();
1454
- for (const n of nodes) frag.appendChild(n);
1455
- marker.parentNode?.insertBefore(frag, marker);
1456
- part.child = nodes;
1457
- return;
1458
- }
1459
-
1460
- // keyed directive: when key changes, tear down and remount fresh DOM.
1461
- // When the key matches, recurse so the standard template-reconciliation
1462
- // path can update the existing DOM in place.
1463
- if (isKeyed(value)) {
1464
- const v = /** @type any */ (value);
1465
- const prevKey = /** @type any */ (part).__keyedKey;
1466
- if (prevKey !== undefined && !Object.is(prevKey, v.key)) {
1467
- teardownChild(part);
1468
- }
1469
- /** @type any */ (part).__keyedKey = v.key;
1470
- applyChildInner(part, v.value);
1471
- return;
1472
- }
1473
-
1474
- // guard directive: skip re-evaluation when the deps array is shallow-
1475
- // equal to the prior call. Stored deps live on the part so they
1476
- // persist across renders that reuse the same template (and thus the
1477
- // same part).
1478
- if (isGuard(value)) {
1479
- const v = /** @type any */ (value);
1480
- const prevDeps = /** @type any */ (part).__guardDeps;
1481
- const nextDeps = v.deps;
1482
- // Accept any value for deps. When deps is an array, compare shallowly.
1483
- // When it's a primitive (number, string, undefined), compare with
1484
- // Object.is. Mirrors lit-html's tolerance for non-array deps so user
1485
- // code like `guard(this.id, () => ...)` works without crashing.
1486
- if (prevDeps !== undefined) {
1487
- const equal = Array.isArray(prevDeps) && Array.isArray(nextDeps)
1488
- ? shallowEqualArray(prevDeps, nextDeps)
1489
- : Object.is(prevDeps, nextDeps);
1490
- if (equal) return;
1491
- }
1492
- // Snapshot the deps BEFORE running `fn` (so a fn that mutates the array
1493
- // it was handed cannot rewrite what we record), but RECORD them only
1494
- // after the commit succeeds. Recording first meant a throw part-way
1495
- // through the commit left the region torn down with the NEW deps already
1496
- // stored, so every later render with the same deps hit the `equal`
1497
- // short-circuit above and skipped the region forever. Renders are always
1498
- // microtask-scheduled (`_scheduleUpdate`), so `fn()` cannot re-enter this
1499
- // part synchronously and see the stale deps.
1500
- const depsSnapshot = Array.isArray(nextDeps) ? nextDeps.slice() : nextDeps;
1501
- applyChildInner(part, v.fn());
1502
- /** @type any */ (part).__guardDeps = depsSnapshot;
1503
- return;
1504
- }
1505
-
1506
- // templateContent directive: clone the content of a <template> element.
1507
- if (isTemplateContent(value)) {
1508
- teardownChild(part);
1509
- const tpl = /** @type any */ (value).template;
1510
- if (tpl && tpl.content) {
1511
- const frag = tpl.content.cloneNode(true);
1512
- const nodes = [...frag.childNodes];
1513
- marker.parentNode?.insertBefore(frag, marker);
1514
- part.child = nodes;
1515
- }
1516
- return;
1517
- }
1518
-
1519
- // ref directive in a child position: no DOM produced. Element-position
1520
- // refs are bound via element parts; a stray ref() in a child position
1521
- // is a no-op for compatibility.
1522
- if (isRef(value)) {
1523
- return;
1524
- }
1525
-
1526
- // cache directive: real DOM retention. When the inner value changes
1527
- // to a different template shape, detach (rather than destroy) the
1528
- // current DOM and stash it keyed by its template strings. When a
1529
- // previously-cached shape returns, re-attach it before the marker
1530
- // and reconcile values. Preserves input state, scroll, focus across
1531
- // toggles between sub-templates (e.g. tab interfaces).
1532
- if (isCache(value)) {
1533
- return applyCache(part, /** @type any */ (value).value);
1534
- }
1535
-
1536
- // until directive: render the highest-priority resolved value among
1537
- // the candidates. Synchronous values are rendered immediately; Promises
1538
- // are awaited in the background and applied if no higher-priority
1539
- // candidate has resolved yet. When the marker is torn down, in-flight
1540
- // priorities are cleared so late resolves cannot overwrite later DOM.
1541
- if (isUntil(value)) {
1542
- return applyUntil(part, /** @type any */ (value).args);
1543
- }
1544
-
1545
- // watch directive: bind a part to a signal. Reads the signal at
1546
- // render time and subscribes the part to changes. When the signal
1547
- // fires, only this part updates; the host component's render() does
1548
- // not re-run. The signal read inside the watcher's observe is
1549
- // tracked against the part's private Watcher, NOT the host's render
1550
- // watcher (so the host doesn't subscribe to a full re-render too).
1551
- if (isWatch(value)) {
1552
- return applyWatch(part, /** @type any */ (value).signal);
1553
- }
1554
-
1555
- // asyncAppend / asyncReplace: subscribe to the AsyncIterable. Each
1556
- // yielded value is mapped (optional) and appended (asyncAppend) or
1557
- // replaces (asyncReplace) the prior content. Teardown aborts the
1558
- // iteration so leaked iterators do not keep references to detached
1559
- // DOM.
1560
- if (isAsyncAppend(value)) {
1561
- return applyAsyncAppend(part, /** @type any */ (value));
1562
- }
1563
- if (isAsyncReplace(value)) {
1564
- return applyAsyncReplace(part, /** @type any */ (value));
1565
- }
1566
-
1567
- // Repeat directive: keyed reconciliation. Keep previous state when both
1568
- // old and new are repeats; otherwise tear down and rebuild.
1569
- if (isRepeat(value)) {
1570
- if (part.child && /** @type any */ (part.child).kind === 'repeat') {
1571
- reconcileRepeat(part, value);
1572
- return;
1573
- }
1574
- teardownChild(part);
1575
- const state = { kind: 'repeat', map: new Map() };
1576
- part.child = state;
1577
- applyRepeatFresh(marker, state, value);
1578
- return;
1579
- }
1580
-
1581
- // Plain array (a `.map()` / list interpolation): positional, non-keyed
1582
- // reconciliation. Update each position's instance IN PLACE when its
1583
- // template shape is unchanged, so DOM node identity survives an item
1584
- // update (focus, selection, scroll, and an in-progress native drag all
1585
- // survive). Mirrors lit-html's non-keyed array child part. Without this,
1586
- // flipping one item's binding rebuilt the WHOLE list and detached every
1587
- // node, which cancels a native drag mid-gesture. Use `repeat()` for keyed
1588
- // reordering.
1589
- if (Array.isArray(value)) {
1590
- if (part.child && /** @type any */ (part.child).kind === 'array') {
1591
- reconcileArray(part, value);
1592
- return;
1593
- }
1594
- teardownChild(part);
1595
- const arrState = { kind: 'array', items: [] };
1596
- part.child = arrState;
1597
- applyArrayFresh(marker, /** @type any */ (arrState), value);
1598
- return;
1599
- }
1600
-
1601
- // Remove previously rendered nodes between marker and its next sibling we own.
1602
- if (part.child) {
1603
- const c = /** @type any */ (part.child);
1604
- if (c.kind === 'repeat') {
1605
- teardownRepeat(c);
1606
- part.child = undefined;
1607
- } else if (c.kind === 'array') {
1608
- teardownArray(/** @type any */ (c));
1609
- part.child = undefined;
1610
- } else if (c.kind === 'async-stream') {
1611
- teardownAsyncStream(c);
1612
- part.child = undefined;
1613
- } else if ('strings' in /** @type any */ (part.child)) {
1614
- // Previous was a TemplateInstance.
1615
- const inst = /** @type TemplateInstance */ (part.child);
1616
- if (isTemplate(value) && inst.strings === /** @type any */ (value).strings) {
1617
- updateInstance(inst, /** @type any */ (value).values);
1618
- return;
1619
- }
1620
- removeBetween(inst.startNode, inst.endNode);
1621
- part.child = undefined;
1622
- } else {
1623
- // Previous was ChildNode[]: remove each node we inserted.
1624
- for (const n of /** @type ChildNode[] */ (part.child)) {
1625
- if (n.parentNode) n.parentNode.removeChild(n);
1626
- }
1627
- part.child = undefined;
1628
- }
1629
- }
1630
-
1631
- if (value == null || value === false || value === true) return;
1632
-
1633
- if (isTemplate(value)) {
1634
- const tr = /** @type any */ (value);
1635
- const { templateEl, parts, formActions } = compile(tr);
1636
- const frag = /** @type DocumentFragment */ (templateEl.content.cloneNode(true));
1637
- const startNode = document.createComment(`${MARKER}s`);
1638
- const endNode = document.createComment(`${MARKER}e`);
1639
- const bound = parts.map((p) => bindPart(p, frag));
1640
- const lastValues = [];
1641
- for (let i = 0; i < tr.values.length; i++) {
1642
- applyPart(bound[i], tr.values[i], undefined, tr.values);
1643
- lastValues.push(tr.values[i]);
1644
- }
1645
- reconcileFormActions(formActions, bound, tr.values);
1646
- const nodes = [startNode, ...frag.childNodes, endNode];
1647
- marker.parentNode?.insertBefore(nodesToFrag(nodes), marker);
1648
- // Slot parts in this nested template need their one-shot apply just
1649
- // like createInstance does for top-level templates. The slot is now
1650
- // in the live tree (insertBefore above) so its parent walk can
1651
- // reach the host. Without this loop, conditional / nested templates
1652
- // with <slot> inside never trigger projection.
1653
- for (const p of bound) {
1654
- if (p.kind === 'slot') applyPart(p, undefined, undefined, []);
1655
- }
1656
- part.child = { strings: tr.strings, bound, lastValues, startNode, endNode };
1657
- return;
1658
- }
1659
-
1660
- const node = document.createTextNode(String(value));
1661
- marker.parentNode?.insertBefore(node, marker);
1662
- part.child = [node];
1663
- }
1664
-
1665
- /** @param {ChildNode[]} nodes */
1666
- function nodesToFrag(nodes) {
1667
- const frag = document.createDocumentFragment();
1668
- for (const n of nodes) frag.appendChild(n);
1669
- return frag;
1670
- }
1671
-
1672
- /**
1673
- * Remove a template instance's whole range, its bookend markers INCLUDED.
1674
- *
1675
- * Every caller discards the instance right after: the map entry or slot that
1676
- * held it is dropped, and a replacement, where there is one, is built with
1677
- * markers of its own. So this is a REMOVE, never lit's clear-and-reuse. A
1678
- * caller that wants to keep the bookends and render into them again needs its
1679
- * OWN function, because the two want opposite answers for the end marker.
1680
- *
1681
- * `parent` is read BEFORE the walk because the walk removes `start` on its
1682
- * first iteration, which nulls `start.parentNode`. Reading it afterwards
1683
- * compared the end marker's live parent against `null`, so the guard could
1684
- * never fire and every teardown left one `wjm-e` comment in the document,
1685
- * unbounded for the life of the region.
1686
- *
1687
- * The `end.parentNode === parent` comparison is a refusal, not a formality. A
1688
- * marker moved under a different parent is not this region's to remove, and
1689
- * `parent.removeChild(end)` on it throws NotFoundError from inside a teardown
1690
- * that has to stay total.
1691
- *
1692
- * The walk assumes the range is INTACT: it steps `nextSibling` from `start`
1693
- * and stops on `end`, so a range whose end no longer follows its start runs
1694
- * off the child list and takes the part's own marker with it. That is not
1695
- * something this function defends against, before or after the parent capture,
1696
- * and the consequence is spelled out where it bites, on `reconcileRepeat`'s
1697
- * catch below. The guard is the narrower promise: whatever the walk did, a
1698
- * marker that is somewhere else is left alone.
1699
- *
1700
- * @param {Node} start @param {Node} end
1701
- */
1702
- function removeBetween(start, end) {
1703
- const parent = start.parentNode;
1704
- if (!parent) return;
1705
- let n = start;
1706
- while (n && n !== end) {
1707
- const next = n.nextSibling;
1708
- n.parentNode?.removeChild(n);
1709
- n = next;
1710
- }
1711
- if (end.parentNode === parent) parent.removeChild(end);
1712
- }
1713
-
1714
- /* ================================================================
1715
- * Keyed list (repeat) support
1716
- * ================================================================ */
1717
-
1718
- /**
1719
- * Build a TemplateInstance whose nodes (including bookends) live in a
1720
- * document fragment that the caller will insert wherever it wants.
1721
- * @param {import('./html.js').TemplateResult} tr
1722
- * @returns {{ inst: TemplateInstance, frag: DocumentFragment }}
1723
- */
1724
- function buildDetached(tr) {
1725
- const { templateEl, parts, formActions } = compile(tr);
1726
- const frag = /** @type DocumentFragment */ (templateEl.content.cloneNode(true));
1727
- const startNode = document.createComment(`${MARKER}s`);
1728
- const endNode = document.createComment(`${MARKER}e`);
1729
- const bound = parts.map((p) => bindPart(p, frag));
1730
- const lastValues = [];
1731
- for (let i = 0; i < tr.values.length; i++) {
1732
- applyPart(bound[i], tr.values[i], undefined, tr.values);
1733
- lastValues.push(tr.values[i]);
1734
- }
1735
- reconcileFormActions(formActions, bound, tr.values);
1736
- // Slot parts need their one-shot apply exactly like createInstance and the
1737
- // nested-template path. The fragment is still detached here, so the
1738
- // slot-part's own deferred finalize (a one-microtask retry when the parent
1739
- // walk cannot reach a host yet) carries it: every caller inserts the
1740
- // returned fragment synchronously in the same task, so the retry lands in
1741
- // the live tree. Without this loop a <slot> inside a repeat() / array item
1742
- // never finalizes and its content is never placeable.
1743
- for (const p of bound) {
1744
- if (p.kind === 'slot') applyPart(p, undefined, undefined, []);
1745
- }
1746
- const outFrag = document.createDocumentFragment();
1747
- outFrag.appendChild(startNode);
1748
- while (frag.firstChild) outFrag.appendChild(frag.firstChild);
1749
- outFrag.appendChild(endNode);
1750
- return {
1751
- inst: { strings: tr.strings, bound, lastValues, startNode, endNode },
1752
- frag: outFrag,
1753
- };
1754
- }
1755
-
1756
- /** @param {TemplateInstance} inst */
1757
- function disposeInstance(inst) {
1758
- for (const p of inst.bound) {
1759
- if (p.kind === 'event') p.el.removeEventListener(p.name, p.dispatcher);
1760
- if (p.kind === 'element') {
1761
- // Unbind any active ref so the user observes the element being
1762
- // removed (callback receives undefined / Ref.value cleared).
1763
- // Mirrors lit-html's cleanup-on-disconnect for element parts.
1764
- //
1765
- // BOTH branches swallow, and lit is not the reason: lit's ref directive
1766
- // guards neither, so a throw there propagates. The reason is that a
1767
- // teardown has to be TOTAL. `lastTarget` is cleared only AFTER these
1768
- // writes, so a throw leaves the part still pointing at the ref and
1769
- // every later teardown of the same instance throws at the same line
1770
- // forever. It also aborts the rest of this loop, so the remaining
1771
- // parts keep their listeners and their refs bound. A teardown has no
1772
- // retry either (a commit has the COMMIT_FAILED sentinel and a next
1773
- // render; this does not), so there is nothing a propagated error could
1774
- // usefully repair.
1775
- //
1776
- // The object branch is the one this adds. The callback branch was
1777
- // already guarded here AND on the commit path (`applyElement` wraps
1778
- // every `nextTarget(...)` / `prevTarget(undefined)` call), so a
1779
- // throwing ref CALLBACK has always been swallowed everywhere. What was
1780
- // inconsistent is the object ref, guarded on neither. This makes the
1781
- // two agree on TEARDOWN, which is where the totality argument bites.
1782
- // It does NOT touch the commit path, so `applyElement`'s object-ref
1783
- // writes still propagate to the component boundary, which has a route
1784
- // for the error and a next render to repair it.
1785
- const prev = /** @type any */ (p).lastTarget;
1786
- if (prev) {
1787
- if (typeof prev === 'function') {
1788
- try { prev(undefined); } catch { /* swallow */ }
1789
- } else if (typeof prev === 'object') {
1790
- try { prev.value = undefined; } catch { /* swallow */ }
1791
- }
1792
- /** @type any */ (p).lastTarget = undefined;
1793
- /** @type any */ (p).__lastEl = undefined;
1794
- }
1795
- }
1796
- }
1797
- }
1798
-
1799
- /**
1800
- * Initial fresh render of a repeat directive. Inserts all items' nodes
1801
- * immediately before the part's marker comment.
1802
- *
1803
- * @param {Comment} marker
1804
- * @param {{ kind: 'repeat', map: Map<any, TemplateInstance> }} state
1805
- * @param {any} value
1806
- */
1807
- function applyRepeatFresh(marker, state, value) {
1808
- const { items, keyFn, templateFn } = value;
1809
- const parent = marker.parentNode;
1810
- if (!parent) return;
1811
- const bulk = document.createDocumentFragment();
1812
- for (let i = 0; i < items.length; i++) {
1813
- const key = keyFn(items[i], i);
1814
- const tr = templateFn(items[i], i);
1815
- if (!isTemplate(tr)) continue;
1816
- const { inst, frag } = buildDetached(/** @type any */ (tr));
1817
- state.map.set(key, inst);
1818
- bulk.appendChild(frag);
1819
- }
1820
- parent.insertBefore(bulk, marker);
1821
- }
1822
-
1823
- /**
1824
- * Keyed reconciliation. For each key in the new list:
1825
- * - hit: update the existing instance in place (if template shape matches),
1826
- * then move its nodes into position
1827
- * - miss: build a new instance and insert
1828
- * Finally drop instances whose keys aren't in the new list.
1829
- *
1830
- * @param {Extract<BoundPart, {kind:'child'}>} part
1831
- * @param {any} value
1832
- */
1833
- function reconcileRepeat(part, value) {
1834
- const marker = part.marker;
1835
- const parent = marker.parentNode;
1836
- if (!parent) return;
1837
- const state = /** @type {{ kind: 'repeat', map: Map<any, TemplateInstance> }} */ (part.child);
1838
- const { items, keyFn, templateFn } = value;
1839
-
1840
- const newMap = new Map();
1841
-
1842
- try {
1843
- // Walk the new list and position each item's nodes immediately before the marker.
1844
- for (let i = 0; i < items.length; i++) {
1845
- const key = keyFn(items[i], i);
1846
- const tr = templateFn(items[i], i);
1847
- if (!isTemplate(tr)) continue;
1848
- const existing = state.map.get(key);
1849
- if (existing && existing.strings === /** @type any */ (tr).strings) {
1850
- updateInstance(existing, /** @type any */ (tr).values);
1851
- // Move nodes before marker preserving element identity.
1852
- moveRange(existing.startNode, existing.endNode, parent, marker);
1853
- newMap.set(key, existing);
1854
- state.map.delete(key);
1855
- } else {
1856
- if (existing) {
1857
- // Unmapped BEFORE the row is touched, for the reason spelled out
1858
- // in the leftover loop below: a key kept across a refused removal
1859
- // points at a half-removed row, and reusing that row later walks
1860
- // the removal off the end of the region. Same ordering, same
1861
- // trade, and the two have to agree or the invariant the catch
1862
- // relies on holds on one branch and not the other.
1863
- state.map.delete(key);
1864
- disposeInstance(existing);
1865
- removeBetween(existing.startNode, existing.endNode);
1866
- }
1867
- const { inst, frag } = buildDetached(/** @type any */ (tr));
1868
- parent.insertBefore(frag, marker);
1869
- newMap.set(key, inst);
1870
- }
1871
- }
1872
-
1873
- // Remove any keys that remain in the old map. The key leaves the map
1874
- // BEFORE its row is touched and the removal is in a `finally`, so at any
1875
- // throw point `state.map` holds exactly the leftovers this pass has not
1876
- // reached, and a row whose dispose threw still leaves the document.
1877
- // Iterating a snapshot keeps the delete obviously safe rather than
1878
- // relying on the reader knowing that deleting during a Map iteration is
1879
- // legal.
1880
- for (const [k, inst] of [...state.map]) {
1881
- state.map.delete(k);
1882
- try {
1883
- disposeInstance(inst);
1884
- } finally {
1885
- removeBetween(inst.startNode, inst.endNode);
1886
- }
1887
- }
1888
- state.map = newMap;
1889
- } catch (err) {
1890
- // The walk moves DOM and drains `state.map` incrementally while the
1891
- // replacement map is accumulated locally, so a throw part-way through
1892
- // leaves NEITHER map describing what is on screen: the already-processed
1893
- // keys sit only in `newMap`, which is about to be discarded, while their
1894
- // nodes stay in the document tracked by nothing. The next (perfectly
1895
- // valid) render then rebuilds those keys from scratch and the orphaned
1896
- // originals are never removed, so the list shows duplicated rows forever
1897
- // with nothing logged after the first throw.
1898
- //
1899
- // Re-unite every instance still in the document under `state.map` (the
1900
- // two maps are disjoint: a key lands in `newMap` only after being deleted
1901
- // from `state.map`), so the map describes the DOM again and nothing is
1902
- // orphaned. That is the whole repair. The next render is then an ORDINARY
1903
- // reconcile against a truthful map, which repositions every row and
1904
- // re-applies whatever the throw skipped.
1905
- //
1906
- // That claim covers the REMOVAL loop as well as the walk, and only
1907
- // because the loop was written to earn it. It drops each key before
1908
- // touching that row and removes the nodes in a `finally`, so a throw
1909
- // mid-removal cannot merge `newMap` over a `state.map` still holding
1910
- // disposed, detached rows. That was the failure: the row the app DELETED
1911
- // stayed on screen, the survivors reordered, and a later render that
1912
- // re-added that key reinserted the detached instance. The invariant, at
1913
- // any throw point on either branch: every instance this pass has not
1914
- // destructively touched is described by exactly one of the two maps,
1915
- // `newMap` for the processed new keys and `state.map` for the leftovers
1916
- // not reached yet, which is what makes the merge below correct. The
1917
- // exception is the row named in the residual just below, whose removal
1918
- // refused part-way; that one is in neither map, by choice.
1919
- //
1920
- // The residual is a throw from `removeBetween` ITSELF, which only calls
1921
- // `removeChild` on nodes the renderer owns, so it takes a throwing DOM to
1922
- // reach. That row is already unmapped, so its remaining nodes stay in the
1923
- // document tracked by nothing and a later re-add of that key builds a
1924
- // second row beside them. Unmapping AFTER the removal instead would keep
1925
- // that key, and it is measurably worse rather than better: the row is
1926
- // half removed, its start marker gone and its end marker still in place,
1927
- // so the re-add hits the reuse branch and `moveRange` re-attaches the
1928
- // lone start marker AFTER the end marker. The next removal of that key
1929
- // then walks forward from a start that never reaches its end, taking the
1930
- // repeat part's own marker and every following sibling with it, and the
1931
- // region is dead for good. One untracked row beats a destroyed list.
1932
- //
1933
- // Deliberately NOT a teardown-and-rebuild of the region. Rebuilding is
1934
- // the obvious defensive move and it is measurably worse: it discards node
1935
- // identity for every row, which is the exact cost keyed reconciliation
1936
- // exists to avoid (see the plain-array note below, a rebuild cancels an
1937
- // in-progress native drag). It is also unnecessary, because this map is
1938
- // restored to the truth rather than left describing a DOM that moved, so
1939
- // there is nothing to guess and no partial DOM move to unwind.
1940
- //
1941
- // That is only half of it, and the other half does NOT live here: the row
1942
- // whose own commit threw is repaired by the COMMIT_FAILED sentinel in
1943
- // `updateInstance`, not by anything below. Without it the failed hole
1944
- // compares EQUAL on the next render (its `lastValues` entry never
1945
- // advanced past the throw, so it still holds the value that render
1946
- // supplies) and is skipped forever, which for a child position means the
1947
- // row stays permanently blank. Do not remove the sentinel on the theory
1948
- // that a half-updated instance heals itself; it does not.
1949
- for (const [k, inst] of newMap) state.map.set(k, inst);
1950
- throw err;
1951
- }
1952
- }
1953
-
1954
- /** @param {{ kind: 'repeat', map: Map<any, TemplateInstance> }} state */
1955
- function teardownRepeat(state) {
1956
- // Same delete-as-you-go shape as the leftover loop in `reconcileRepeat`,
1957
- // for the same reason: a throw part-way must not leave already-removed
1958
- // instances in the map. The trailing `clear()` stays as a no-op safety net.
1959
- for (const [k, inst] of [...state.map]) {
1960
- state.map.delete(k);
1961
- try {
1962
- disposeInstance(inst);
1963
- } finally {
1964
- removeBetween(inst.startNode, inst.endNode);
1965
- }
1966
- }
1967
- state.map.clear();
1968
- }
1969
-
1970
- /* ================================================================
1971
- * Plain array (.map) support: positional, non-keyed reconciliation
1972
- * ================================================================ */
1973
-
1974
- /**
1975
- * One rendered slot of a plain array. A `tpl` carries a detached template
1976
- * instance (bookended by its own markers), a `text` carries a single text
1977
- * node, and an `empty` slot (a nullish / boolean element) renders nothing
1978
- * but still holds the position so index-based reconciliation stays aligned.
1979
- * @typedef {{ type: 'tpl', inst: TemplateInstance } | { type: 'text', node: Text } | { type: 'empty' }} ArrayItem
1980
- */
1981
-
1982
- /** @param {ArrayItem} item @returns {ChildNode | null} */
1983
- function arrayItemFirstNode(item) {
1984
- if (item.type === 'tpl') return item.inst.startNode;
1985
- if (item.type === 'text') return item.node;
1986
- return null;
1987
- }
1988
-
1989
- /** @param {ArrayItem} item */
1990
- function removeArrayItem(item) {
1991
- if (item.type === 'tpl') {
1992
- disposeInstance(item.inst);
1993
- removeBetween(item.inst.startNode, item.inst.endNode);
1994
- } else if (item.type === 'text') {
1995
- item.node.parentNode?.removeChild(item.node);
1996
- }
1997
- }
1998
-
1999
- /**
2000
- * Build the slot for one array element, plus the fragment to insert (null
2001
- * for an empty slot). A TemplateResult becomes a detached instance, a
2002
- * primitive becomes a text node, and nullish / boolean renders nothing.
2003
- * @param {unknown} v
2004
- * @returns {{ item: ArrayItem, frag: Node | null }}
2005
- */
2006
- function buildArrayItem(v) {
2007
- if (isTemplate(v)) {
2008
- const { inst, frag } = buildDetached(/** @type any */ (v));
2009
- return { item: { type: 'tpl', inst }, frag };
2010
- }
2011
- if (v != null && v !== false && v !== true) {
2012
- const node = document.createTextNode(String(v));
2013
- return { item: { type: 'text', node }, frag: node };
2014
- }
2015
- return { item: { type: 'empty' }, frag: null };
2016
- }
2017
-
2018
- /**
2019
- * Initial render of a plain array: insert every slot's nodes before the marker.
2020
- * @param {Comment} marker
2021
- * @param {{ kind: 'array', items: ArrayItem[] }} state
2022
- * @param {unknown[]} value
2023
- */
2024
- function applyArrayFresh(marker, state, value) {
2025
- const parent = marker.parentNode;
2026
- if (!parent) return;
2027
- const bulk = document.createDocumentFragment();
2028
- /** @type {ArrayItem[]} */
2029
- const items = [];
2030
- for (const v of value) {
2031
- const { item, frag } = buildArrayItem(v);
2032
- if (frag) bulk.appendChild(frag);
2033
- items.push(item);
2034
- }
2035
- parent.insertBefore(bulk, marker);
2036
- state.items = items;
2037
- }
2038
-
2039
- /**
2040
- * Positional (non-keyed) reconciliation. For each index, update the slot
2041
- * in place when its shape is unchanged (preserving DOM node identity),
2042
- * otherwise replace it; grow or shrink at the tail. There is no key
2043
- * matching, so a reorder reduces to a series of in-place value updates;
2044
- * reach for `repeat()` when element identity must follow a moved key.
2045
- * @param {Extract<BoundPart, {kind:'child'}>} part
2046
- * @param {unknown[]} value
2047
- */
2048
- function reconcileArray(part, value) {
2049
- const marker = part.marker;
2050
- const parent = marker.parentNode;
2051
- if (!parent) return;
2052
- const state = /** @type {{ kind: 'array', items: ArrayItem[] }} */ (part.child);
2053
- const old = state.items;
2054
- /** @type {ArrayItem[]} */
2055
- const next = [];
2056
- // How many slots of `old` are fully processed. Tracked rather than inferred
2057
- // from `next.length`, because the shrink loop below advances through `old`
2058
- // while `next` stops growing, so the two part company there. The catch is
2059
- // the only reader.
2060
- let consumed = 0;
2061
-
2062
- try {
2063
- for (let i = 0; i < value.length; i++) {
2064
- const v = value[i];
2065
- const o = old[i];
2066
- if (isTemplate(v)) {
2067
- const tr = /** @type any */ (v);
2068
- if (o && o.type === 'tpl' && o.inst.strings === tr.strings) {
2069
- updateInstance(o.inst, tr.values);
2070
- next.push(o);
2071
- consumed = i + 1;
2072
- continue;
2073
- }
2074
- } else if (v != null && v !== false && v !== true) {
2075
- if (o && o.type === 'text') {
2076
- const str = String(v);
2077
- if (o.node.data !== str) o.node.data = str;
2078
- next.push(o);
2079
- consumed = i + 1;
2080
- continue;
2081
- }
2082
- } else {
2083
- // Empty slot: drop any prior nodes that occupied this position.
2084
- // Deliberately NOT reordered like the branch below. That reorder
2085
- // exists to keep a slot that was already BUILT and INSERTED tracked,
2086
- // and this branch builds and inserts nothing, so pushing first would
2087
- // only mean a throw from the removal leaves a phantom empty slot at
2088
- // this index AND `old[i]` spliced in at the next one, shifting every
2089
- // later slot by one in a POSITIONAL reconciler. Removing first, a
2090
- // throw here leaves `old[i]` describing its own position, which is
2091
- // still exactly where its nodes are.
2092
- if (o) removeArrayItem(o);
2093
- next.push({ type: 'empty' });
2094
- consumed = i + 1;
2095
- continue;
2096
- }
2097
- // Shape changed, or the array grew past the old length. Build fresh,
2098
- // insert at this position (before the current / next still-attached
2099
- // old node, else the marker), then drop the old slot it replaced.
2100
- // The push sits BEFORE the removal, which is a pure reordering on the
2101
- // success path and means a slot that has already been built and
2102
- // inserted is never untracked at any throw point.
2103
- const { item, frag } = buildArrayItem(v);
2104
- if (frag) parent.insertBefore(frag, nextArrayAnchor(old, i, marker));
2105
- next.push(item);
2106
- if (o) removeArrayItem(o);
2107
- consumed = i + 1;
2108
- }
2109
-
2110
- // Shrink: remove slots beyond the new length.
2111
- for (let i = value.length; i < old.length; i++) {
2112
- removeArrayItem(old[i]);
2113
- consumed = i + 1;
2114
- }
2115
- state.items = next;
2116
- } catch (err) {
2117
- // `state.items` is committed only after the whole walk, so a throw part
2118
- // way through discards `next` entirely: the map of slots keeps describing
2119
- // positions whose nodes were already removed, while the freshly built and
2120
- // inserted ones are in the document tracked by nothing. Nothing is logged
2121
- // after the first throw, and the orphan outlives even a render of an EMPTY
2122
- // array, because the only code that could remove it walks `state.items`.
2123
- //
2124
- // Splice the untouched tail of `old` onto what `next` accumulated, so the
2125
- // bookkeeping describes the DOM again. The invariant that holds at any
2126
- // throw point: every live node is described by exactly one slot, the
2127
- // slots below `next.length` being the rebuilt or reused ones and the rest
2128
- // the part of `old` this pass never reached. Index alignment survives
2129
- // because this reconciler is POSITIONAL, so a slot's index IS its
2130
- // identity, which is also why the boundary has to come from `consumed`
2131
- // rather than `next.length`: during the shrink loop those differ, and
2132
- // splicing from `next.length` would re-describe slots already removed.
2133
- // A later render that grew the array would then match a live value
2134
- // against a DETACHED slot with the same `strings`, update it in place,
2135
- // and that row would silently never appear.
2136
- //
2137
- // Deliberately NOT a teardown-and-rebuild of the region, for the reason
2138
- // recorded on `reconcileRepeat`'s catch above: it discards node identity
2139
- // for every row, which cancels an in-progress native drag and drops focus
2140
- // and scroll.
2141
- //
2142
- // The residual is a throw from the removal step itself, which takes a
2143
- // throwing DOM to reach (the teardown it calls is total, so only
2144
- // `removeBetween` is left, and that calls `removeChild` solely on nodes
2145
- // the renderer owns). State it rather than deny it: `removeBetween`
2146
- // takes the start marker first and then early-returns for good once that
2147
- // marker is gone, so a row whose removal refused part-way can never be
2148
- // removed afterwards. Its remaining nodes stay in the document, and an
2149
- // EMPTY render will not clear them. Tracked or not, they are there for
2150
- // the life of the region, the same residual `reconcileRepeat`'s catch
2151
- // names. What this repair buys is that there is only ONE such row and
2152
- // every other slot still reconciles, where before the whole pass was
2153
- // discarded.
2154
- state.items = next.concat(old.slice(consumed));
2155
- throw err;
2156
- }
2157
- }
2158
-
2159
- /**
2160
- * The node a freshly-built slot at index `i` inserts before: the first
2161
- * node of the current or next still-attached old slot, else the part
2162
- * marker (a tail append).
2163
- * @param {ArrayItem[]} old @param {number} i @param {Comment} marker
2164
- * @returns {ChildNode}
2165
- */
2166
- function nextArrayAnchor(old, i, marker) {
2167
- for (let j = i; j < old.length; j++) {
2168
- const f = arrayItemFirstNode(old[j]);
2169
- if (f && f.parentNode) return f;
2170
- }
2171
- return marker;
2172
- }
2173
-
2174
- /** @param {{ kind: 'array', items: ArrayItem[] }} state */
2175
- function teardownArray(state) {
2176
- for (const it of state.items) removeArrayItem(it);
2177
- state.items = [];
2178
- }
2179
-
2180
- /**
2181
- * Collect [start .. end] (inclusive) and insert immediately before `anchor`.
2182
- * Browsers treat insertBefore of an already-connected node as a move and
2183
- * preserve element identity + focus.
2184
- *
2185
- * @param {Node} start
2186
- * @param {Node} end
2187
- * @param {Node} parent
2188
- * @param {Node} anchor
2189
- */
2190
- function moveRange(start, end, parent, anchor) {
2191
- // No-op if the range is already immediately before the anchor.
2192
- if (end.nextSibling === anchor && start.parentNode === parent) return;
2193
- const frag = document.createDocumentFragment();
2194
- let n = start;
2195
- while (n) {
2196
- const next = n.nextSibling;
2197
- frag.appendChild(n);
2198
- if (n === end) break;
2199
- n = next;
2200
- }
2201
- parent.insertBefore(frag, anchor);
2202
- }
2203
-
2204
- /**
2205
- * Shallow array equality (Object.is on each element). Used by the
2206
- * `guard` directive to skip re-evaluation when deps are unchanged.
2207
- * @param {readonly unknown[]} a
2208
- * @param {readonly unknown[]} b
2209
- */
2210
- function shallowEqualArray(a, b) {
2211
- if (a === b) return true;
2212
- if (!a || !b || a.length !== b.length) return false;
2213
- for (let i = 0; i < a.length; i++) {
2214
- if (!Object.is(a[i], b[i])) return false;
2215
- }
2216
- return true;
2217
- }
2218
-
2219
- /** @param {Extract<BoundPart, {kind:'child'}>} part */
2220
- function teardownChild(part) {
2221
- // Always abort any in-flight directive state on the part, even if
2222
- // `part.child` itself is something else (e.g. an `until` directive
2223
- // installed __untilState but applyChild's recursion overwrote
2224
- // part.child to the rendered fallback shape).
2225
- const partAny = /** @type any */ (part);
2226
- if (partAny.__untilState) {
2227
- partAny.__untilState.aborted = true;
2228
- partAny.__untilState = undefined;
2229
- }
2230
- if (partAny.__watchSub) {
2231
- teardownWatch(partAny);
2232
- }
2233
-
2234
- if (!part.child) return;
2235
- const c = /** @type any */ (part.child);
2236
- if (c.kind === 'repeat') {
2237
- teardownRepeat(c);
2238
- } else if (c.kind === 'array') {
2239
- teardownArray(c);
2240
- } else if (c.kind === 'async-stream') {
2241
- teardownAsyncStream(c);
2242
- } else if ('strings' in c) {
2243
- const inst = /** @type TemplateInstance */ (part.child);
2244
- disposeInstance(inst);
2245
- removeBetween(inst.startNode, inst.endNode);
2246
- } else {
2247
- for (const n of /** @type ChildNode[] */ (part.child)) {
2248
- if (n.parentNode) n.parentNode.removeChild(n);
2249
- }
2250
- }
2251
- part.child = undefined;
2252
- }
2253
-
2254
- /**
2255
- * Clear per-part directive state slots that don't apply to the value
2256
- * currently being rendered. Prevents stale `__guardDeps` from short-
2257
- * circuiting a render when the directive at this position is no longer
2258
- * a guard, stale `__cacheMap` from accumulating across non-cache
2259
- * renders, and stale `__untilState` from letting a prior Promise
2260
- * resolution overwrite newer DOM.
2261
- *
2262
- * @param {Extract<BoundPart, {kind:'child'}>} part
2263
- * @param {unknown} value
2264
- */
2265
- function clearStaleDirectiveState(part, value) {
2266
- const partAny = /** @type any */ (part);
2267
- if (partAny.__untilState && !isUntil(value)) {
2268
- partAny.__untilState.aborted = true;
2269
- partAny.__untilState = undefined;
2270
- }
2271
- if (partAny.__guardDeps !== undefined && !isGuard(value)) {
2272
- partAny.__guardDeps = undefined;
2273
- }
2274
- if (partAny.__cacheMap && !isCache(value)) {
2275
- partAny.__cacheMap = undefined;
2276
- }
2277
- if (partAny.__keyedKey !== undefined && !isKeyed(value)) {
2278
- partAny.__keyedKey = undefined;
2279
- }
2280
- if (partAny.__watchSub && !isWatch(value)) {
2281
- teardownWatch(partAny);
2282
- }
2283
- }
2284
-
2285
- /* ================================================================
2286
- * Cache directive: detach + retain prior template instances so that
2287
- * toggling between sub-templates preserves their DOM state.
2288
- * ================================================================ */
2289
-
2290
- /**
2291
- * Apply the `cache` directive at a child position. The cache is stored
2292
- * on the part as `__cacheMap: Map<strings, { inst, holderFrag }>`.
2293
- *
2294
- * When the new inner value is a template whose `strings` already lives
2295
- * in the cache map, re-attach the stashed nodes before the marker and
2296
- * reconcile values against the new template. When the new inner is a
2297
- * template whose strings aren't cached, stash the currently-attached
2298
- * instance (if any) into the cache map before rendering the new one.
2299
- *
2300
- * Non-template inner values fall through to the generic applyChild path
2301
- * (after first stashing any currently-attached cached instance).
2302
- *
2303
- * @param {Extract<BoundPart, {kind:'child'}>} part
2304
- * @param {unknown} inner
2305
- */
2306
- function applyCache(part, inner) {
2307
- const marker = part.marker;
2308
- const partAny = /** @type any */ (part);
2309
- /** @type {Map<TemplateStringsArray, { inst: TemplateInstance, holder: DocumentFragment }>} */
2310
- let cacheMap = partAny.__cacheMap;
2311
- if (!cacheMap) {
2312
- cacheMap = new Map();
2313
- partAny.__cacheMap = cacheMap;
2314
- }
2315
-
2316
- const currentChild = /** @type any */ (part.child);
2317
- const currentIsInstance = currentChild && 'strings' in currentChild;
2318
-
2319
- // If the currently-attached child IS a template instance, decide
2320
- // whether to update-in-place, stash for later, or destroy.
2321
- if (currentIsInstance) {
2322
- const currentInst = /** @type TemplateInstance */ (currentChild);
2323
-
2324
- // Same template structure: reconcile values, no detach/re-attach.
2325
- if (isTemplate(inner) && currentInst.strings === /** @type any */ (inner).strings) {
2326
- updateInstance(currentInst, /** @type any */ (inner).values);
2327
- return;
2328
- }
2329
-
2330
- // Different shape: detach the current instance into a holder fragment
2331
- // and store it in the cache map. We keep the existing instance, slot
2332
- // markers, and rendered nodes; only the parent changes. moveRange's
2333
- // null anchor means "append to parent".
2334
- const holder = document.createDocumentFragment();
2335
- moveRange(currentInst.startNode, currentInst.endNode, holder, null);
2336
- cacheMap.set(currentInst.strings, { inst: currentInst, holder });
2337
- part.child = undefined;
2338
- }
2339
-
2340
- // Now part.child is either undefined or some non-instance shape (rare;
2341
- // happens when prior render had a string / array / etc.). For non-
2342
- // instance shapes, fall through to the generic teardown via applyChild.
2343
-
2344
- // If the new inner is a template AND we've cached an instance for its
2345
- // strings, re-attach it.
2346
- if (isTemplate(inner)) {
2347
- const tr = /** @type any */ (inner);
2348
- const cached = cacheMap.get(tr.strings);
2349
- if (cached) {
2350
- cacheMap.delete(tr.strings);
2351
- // Tear down any non-instance child currently attached (a string /
2352
- // array of text nodes from a prior cache(non-template) render).
2353
- // Without this the prior nodes remain in the DOM alongside the
2354
- // re-attached cached template.
2355
- if (part.child) {
2356
- teardownChild(part);
2357
- }
2358
- // Move the cached nodes back before the marker.
2359
- moveRange(cached.inst.startNode, cached.inst.endNode, /** @type Node */ (marker.parentNode), marker);
2360
- // Reconcile values so any state changes since detachment apply.
2361
- updateInstance(cached.inst, tr.values);
2362
- part.child = cached.inst;
2363
- // A re-attached instance may carry ALREADY-APPLIED slot parts, whose
2364
- // finalize will never fire again, while the host's record moved on
2365
- // during the stash (content for these slots was parked when an apply
2366
- // ran with the slot unreachable). Re-run the apply for each owning
2367
- // host so parked content is pulled back out. The collection walks the
2368
- // re-attached DOM RANGE (not the instance tree): slot parts live on
2369
- // whatever template level contains the <slot> (nested holes, repeat /
2370
- // array items, streamed chunks), so a structural DOM walk is the only
2371
- // shape that covers every composition uniformly. moveRange already
2372
- // ran, so the range is live and each slot's parent walk reaches its
2373
- // host.
2374
- const hosts = new Set();
2375
- for (
2376
- let n = cached.inst.startNode.nextSibling;
2377
- n && n !== cached.inst.endNode;
2378
- n = n.nextSibling
2379
- ) {
2380
- if (n.nodeType !== 1) continue;
2381
- const el = /** @type {Element} */ (n);
2382
- if (el.matches('slot[data-webjs-light]')) {
2383
- const h = findSlotHost(el);
2384
- if (h) hosts.add(h);
2385
- }
2386
- for (const s of el.querySelectorAll('slot[data-webjs-light]')) {
2387
- const h = findSlotHost(s);
2388
- if (h) hosts.add(h);
2389
- }
2390
- }
2391
- for (const h of hosts) applySlotAssignments(h);
2392
- return;
2393
- }
2394
- }
2395
-
2396
- // No cached instance available. Render the new inner value via the
2397
- // standard applyChild path. The currentIsInstance branch already
2398
- // handled detaching the prior instance; if part.child still holds a
2399
- // non-instance shape, applyChild will tear it down generically.
2400
- applyChildInner(part, inner);
2401
- }
2402
-
2403
- /* ================================================================
2404
- * Until directive: render highest-priority resolved candidate.
2405
- * ================================================================ */
2406
-
2407
- /**
2408
- * Apply the `until` directive at a child position.
2409
- *
2410
- * Priority is left-to-right: args[0] has the highest priority. The
2411
- * highest-priority synchronous candidate (if any) renders immediately.
2412
- * Strictly-higher-priority Promises are awaited in the background; when
2413
- * one resolves AND no higher-priority Promise has already resolved, its
2414
- * result becomes the rendered value.
2415
- *
2416
- * The directive's state lives on `part.__untilState` (a stable slot
2417
- * that survives `applyChild`'s overwrites of `part.child`). When a new
2418
- * render replaces the directive, the prior state's `aborted` flag flips
2419
- * to `true` so any in-flight Promise resolutions short-circuit instead
2420
- * of overwriting newer DOM.
2421
- *
2422
- * @param {Extract<BoundPart, {kind:'child'}>} part
2423
- * @param {readonly unknown[]} args
2424
- */
2425
- function applyUntil(part, args) {
2426
- // Carry forward the prior render's `highestResolved` ONLY when the
2427
- // args list is unchanged. When any argument identity changes, prior
2428
- // priorities no longer apply (a Promise that won at index 0 may now
2429
- // sit at a different index, or have been replaced entirely); the
2430
- // state must reset to Infinity so the new args' Promises can compete.
2431
- //
2432
- // For TemplateResult args, compare by `strings` array identity rather
2433
- // than the wrapper object identity. `html\`loading...\`` evaluates to
2434
- // a fresh TemplateResult on every call but the strings array is
2435
- // interned per call site, so the conceptual value is unchanged.
2436
- const partAny = /** @type any */ (part);
2437
- // Same as applyWatch: the promise handlers below commit with no render on
2438
- // the stack, so the owning component is recorded here while it is knowable.
2439
- if (currentRenderRoot) partAny.__commitOwner = boundaryOwnerOf(currentRenderRoot);
2440
- const prevState = partAny.__untilState;
2441
- const prevArgs = partAny.__untilArgs;
2442
- const argEq = (a, b) => {
2443
- if (Object.is(a, b)) return true;
2444
- if (isTemplate(a) && isTemplate(b)
2445
- && /** @type any */ (a).strings === /** @type any */ (b).strings) return true;
2446
- return false;
2447
- };
2448
- const argsEqual = prevArgs && prevArgs.length === args.length
2449
- && prevArgs.every((a, i) => argEq(a, args[i]));
2450
- const carriedHighest = argsEqual && prevState ? prevState.highestResolved : Infinity;
2451
- if (prevState) prevState.aborted = true;
2452
- partAny.__untilArgs = args.slice();
2453
-
2454
- /** @type {{aborted:boolean, highestResolved:number}} */
2455
- const state = { aborted: false, highestResolved: carriedHighest };
2456
- partAny.__untilState = state;
2457
-
2458
- // Highest-priority synchronous candidate. If found, render it now
2459
- // and cap further Promise subscription to strictly-higher priorities.
2460
- let firstSyncIdx = -1;
2461
- let firstSyncVal = undefined;
2462
- for (let i = 0; i < args.length; i++) {
2463
- const a = args[i];
2464
- if (!a || typeof (/** @type any */ (a).then) !== 'function') {
2465
- firstSyncIdx = i;
2466
- firstSyncVal = a;
2467
- break;
2468
- }
2469
- }
2470
-
2471
- if (firstSyncIdx !== -1 && firstSyncIdx <= state.highestResolved) {
2472
- // The sync candidate beats any previously-rendered Promise value
2473
- // (when firstSyncIdx < state.highestResolved) OR re-renders the
2474
- // sync fallback at the same priority slot (when ===), in case its
2475
- // value changed between renders.
2476
- applyChildInner(part, firstSyncVal);
2477
- state.highestResolved = firstSyncIdx;
2478
- } else if (firstSyncIdx === -1 && !partAny.__untilEverRendered) {
2479
- // First-ever render of this part with all-Promise args: render
2480
- // empty as the initial fallback while Promises settle.
2481
- applyChildInner(part, '');
2482
- }
2483
- // Else: either there is no sync candidate but the part has rendered
2484
- // before (preserve existing DOM until a Promise resolves), OR the
2485
- // sync candidate is lower-priority than what's already rendered.
2486
- // Either way: leave the existing DOM in place. This prevents the
2487
- // "all-Promises wipes prior content" flash on re-renders.
2488
- partAny.__untilEverRendered = true;
2489
-
2490
- // Subscribe to Promises with priority strictly less than what's
2491
- // currently rendered. (Lower index = higher priority in lit's model.)
2492
- // Each subscription wraps in Promise.resolve() so synchronous
2493
- // thenables get a microtask boundary, matching lit's contract that
2494
- // all Promise/thenable resolutions are deferred.
2495
- const cap = firstSyncIdx === -1
2496
- ? Math.min(args.length, state.highestResolved)
2497
- : Math.min(firstSyncIdx, state.highestResolved);
2498
- for (let i = 0; i < cap; i++) {
2499
- const a = args[i];
2500
- if (!a || typeof (/** @type any */ (a).then) !== 'function') continue;
2501
-
2502
- Promise.resolve(/** @type Promise<unknown> */ (a)).then(
2503
- (resolved) => {
2504
- if (state.aborted) return;
2505
- if (i >= state.highestResolved) return;
2506
- // Commit FIRST, record the new priority only once it succeeded.
2507
- // Advancing `highestResolved` up front meant a commit throw left the
2508
- // region torn down while the state claimed index `i` had won, so
2509
- // every later resolution at a lower priority was refused and the
2510
- // region stayed empty. Committing first also keeps the throw inside
2511
- // the try, where it can reach the component boundary.
2512
- try {
2513
- commitOutOfBand(part, () => applyChildInner(part, resolved));
2514
- } catch (err) {
2515
- reportOutOfBandCommitError(part, err);
2516
- return;
2517
- }
2518
- state.highestResolved = i;
2519
- },
2520
- () => {
2521
- // Swallow rejection. A rejected Promise is treated as "no value";
2522
- // the existing render stays in place.
2523
- },
2524
- );
2525
- }
2526
- }
2527
-
2528
- /**
2529
- * Route a throw from an OUT-OF-BAND commit to the owning component's
2530
- * render-error boundary.
2531
- *
2532
- * `watch`'s notify microtask and `until`'s Promise resolution commit from
2533
- * outside `component.js`'s update cycle, so none of the boundaries that wrap
2534
- * every other render path are on the stack. Left alone, a commit throw there
2535
- * escapes as a window-level `error` / unhandled rejection instead of the
2536
- * per-component `renderError()` the sync and async render paths both route
2537
- * to, which breaks per-component error isolation for exactly these two
2538
- * directives.
2539
- *
2540
- * Reads the owner stamped on the part when the directive was installed. See
2541
- * the note in the body for why this is not a walk up the parent chain.
2542
- *
2543
- * @param {Extract<BoundPart, {kind:'child'}>} part
2544
- * @param {unknown} error
2545
- */
2546
- function reportOutOfBandCommitError(part, error) {
2547
- let err;
2548
- try {
2549
- err = error instanceof Error ? error : new Error(String(error));
2550
- } catch {
2551
- // The thrown value's own `toString` threw. That is the exact class of
2552
- // value that makes a commit throw in the first place, so it is reachable
2553
- // here; do not let stringifying it mask the original failure.
2554
- err = new Error('render error (unstringifiable thrown value)');
2555
- }
2556
- // The owner stamped when the directive was installed, which is the
2557
- // component whose TEMPLATE holds this part. Never walk the parent chain
2558
- // for this: `_handleRenderError` lives on WebComponent's prototype, so
2559
- // every upgraded element on the way up carries one, and the FIRST one a
2560
- // structural walk meets is the innermost element the part happens to sit
2561
- // inside, not the template that owns it. Routing there is not merely the
2562
- // wrong log line: a light-DOM component's renderError() commits into the
2563
- // component itself, which would replace the very children holding this
2564
- // part's markers and silently kill every later update through it.
2565
- const owner = /** @type any */ (part).__commitOwner;
2566
- if (owner && typeof owner._handleRenderError === 'function') {
2567
- owner._handleRenderError(err);
2568
- return;
2569
- }
2570
- // No component boundary owns this part (a bare `render()` into a plain
2571
- // container). Nothing can contain the error, so surface it rather than
2572
- // swallow it.
2573
- throw err;
2574
- }
2575
-
2576
- /**
2577
- * Abort an `until` directive's in-flight Promise tracking. Called from
2578
- * `teardownChild` when the part is being reset.
2579
- * @param {{aborted:boolean}} state
2580
- */
2581
- function teardownUntil(state) {
2582
- state.aborted = true;
2583
- }
2584
-
2585
- /* ================================================================
2586
- * watch (signal binding): fine-grained reactive part.
2587
- * ================================================================ */
2588
-
2589
- /**
2590
- * Bind a child part to a signal. Reads the signal once and writes its
2591
- * value into the part. Installs a per-part `Signal.subtle.Watcher`
2592
- * that, on signal change, re-reads and re-applies the value WITHOUT
2593
- * re-running the host component's render(). When the part is torn
2594
- * down (teardownChild) the watcher is disposed.
2595
- *
2596
- * The signal read happens inside the watcher's `observe()`, so the
2597
- * dependency edge connects the signal to THIS watcher. The host's
2598
- * own render watcher is outside the active stack here, so the host
2599
- * does not also subscribe to the signal (which would double-fire as
2600
- * both a full re-render and a watch update).
2601
- *
2602
- * @param {Extract<BoundPart, {kind:'child'}>} part
2603
- * @param {{ get: () => unknown, __isSignal: true }} sig
2604
- */
2605
- function applyWatch(part, sig) {
2606
- const partAny = /** @type any */ (part);
2607
- // Record the owning component while we are still inside its render(), the
2608
- // only moment it is knowable. The notify microtask below commits with no
2609
- // render on the stack and no way to derive it. Keep a prior stamp if this
2610
- // somehow runs outside a render, rather than clearing a good owner.
2611
- if (currentRenderRoot) partAny.__commitOwner = boundaryOwnerOf(currentRenderRoot);
2612
- // Same signal as last render: refresh dep tracking via observe (the
2613
- // spec-aligned Watcher fires once per arm, so re-observing re-arms).
2614
- if (partAny.__watchSig === sig && partAny.__watchSub) {
2615
- let value;
2616
- partAny.__watchSub.observe(() => { value = sig.get(); });
2617
- applyChildInner(part, value);
2618
- return;
2619
- }
2620
- // Signal changed (or first render). Tear down any prior watcher.
2621
- if (partAny.__watchSub) {
2622
- partAny.__watchSub.dispose();
2623
- partAny.__watchSub = undefined;
2624
- }
2625
- partAny.__watchSig = sig;
2626
- // Notify defers to a microtask because the spec forbids signal reads
2627
- // inside the notify itself. The microtask re-observes (re-arms + re-
2628
- // records the dep) and applies the new value to the part.
2629
- const watcher = new Signal.subtle.Watcher(() => {
2630
- queueMicrotask(() => {
2631
- if (partAny.__watchSub !== watcher) return; // disposed mid-flight
2632
- let v;
2633
- // Nothing above this microtask catches: it runs outside the host's
2634
- // update cycle, so a commit throw here would surface at the window
2635
- // instead of the component's renderError(). Route it explicitly.
2636
- try {
2637
- watcher.observe(() => { v = sig.get(); });
2638
- commitOutOfBand(part, () => applyChildInner(part, v));
2639
- } catch (err) {
2640
- reportOutOfBandCommitError(part, err);
2641
- }
2642
- });
2643
- });
2644
- partAny.__watchSub = watcher;
2645
- let initial;
2646
- watcher.observe(() => { initial = sig.get(); });
2647
- applyChildInner(part, initial);
2648
- }
2649
-
2650
- /**
2651
- * Dispose a `watch` directive's per-part watcher. Called from
2652
- * `teardownChild` and from `clearStaleDirectiveState` when the value
2653
- * at the part is no longer a watch.
2654
- * @param {any} partAny
2655
- */
2656
- function teardownWatch(partAny) {
2657
- if (partAny.__watchSub) {
2658
- partAny.__watchSub.dispose();
2659
- partAny.__watchSub = undefined;
2660
- partAny.__watchSig = undefined;
2661
- }
2662
- }
2663
-
2664
- /* ================================================================
2665
- * asyncAppend / asyncReplace: stream from AsyncIterable.
2666
- * ================================================================ */
2667
-
2668
- /**
2669
- * Apply `asyncAppend(iterable, mapper?)` at a child position.
2670
- *
2671
- * Iterates the AsyncIterable in the background. Each yielded value is
2672
- * mapped (optional) and rendered as a node group, appended before the
2673
- * marker. The state is stored on `part.child` so `teardownChild` can
2674
- * abort the iteration when the part is reset.
2675
- *
2676
- * @param {Extract<BoundPart, {kind:'child'}>} part
2677
- * @param {{ iterable: AsyncIterable<unknown>, mapper?: (v: unknown, i: number) => unknown }} dir
2678
- */
2679
- function applyAsyncAppend(part, dir) {
2680
- const partAny = /** @type any */ (part);
2681
- // Record the owning component while we are still inside its render(), the
2682
- // only moment it is knowable, exactly as `applyWatch` / `applyUntil` do.
2683
- // Chunks commit from an async loop with no render on the stack, so without
2684
- // this both the chunk's own commit throw and any directive nested inside a
2685
- // chunk have no owner to route to. Stamped ABOVE the short-circuit so a
2686
- // re-render that returns early still refreshes the owner, and guarded so a
2687
- // re-install outside a render keeps a previously good one.
2688
- if (currentRenderRoot) partAny.__commitOwner = boundaryOwnerOf(currentRenderRoot);
2689
- // Same-iterable short-circuit: if the prior render's iterable identity
2690
- // matches, the existing iterator is still consuming it. Re-subscribing
2691
- // would start a fresh iterator that misses already-yielded values.
2692
- // Matches lit-html's behavior.
2693
- const currentChild = /** @type any */ (part.child);
2694
- if (currentChild && currentChild.kind === 'async-stream'
2695
- && currentChild.mode === 'append'
2696
- && currentChild.iterable === dir.iterable) {
2697
- return;
2698
- }
2699
-
2700
- teardownChild(part);
2701
-
2702
- const iterator = /** @type AsyncIterator<unknown> */ (
2703
- dir.iterable[Symbol.asyncIterator]()
2704
- );
2705
- /** @type {AsyncStreamState} */
2706
- const state = {
2707
- kind: 'async-stream',
2708
- mode: 'append',
2709
- aborted: false,
2710
- iterable: dir.iterable,
2711
- iterator,
2712
- /** @type {ChildNode[]} */ nodes: [],
2713
- };
2714
- part.child = state;
2715
-
2716
- consumeAsyncStream(state, part, dir);
2717
- }
2718
-
2719
- /**
2720
- * Apply `asyncReplace(iterable, mapper?)` at a child position. Same as
2721
- * `applyAsyncAppend` but each new value replaces the previous content.
2722
- *
2723
- * @param {Extract<BoundPart, {kind:'child'}>} part
2724
- * @param {{ iterable: AsyncIterable<unknown>, mapper?: (v: unknown, i: number) => unknown }} dir
2725
- */
2726
- function applyAsyncReplace(part, dir) {
2727
- const partAny = /** @type any */ (part);
2728
- // Owner stamp: see comment in applyAsyncAppend. Above the short-circuit.
2729
- if (currentRenderRoot) partAny.__commitOwner = boundaryOwnerOf(currentRenderRoot);
2730
- // Same-iterable short-circuit: see comment in applyAsyncAppend.
2731
- const currentChild = /** @type any */ (part.child);
2732
- if (currentChild && currentChild.kind === 'async-stream'
2733
- && currentChild.mode === 'replace'
2734
- && currentChild.iterable === dir.iterable) {
2735
- return;
2736
- }
2737
-
2738
- teardownChild(part);
2739
-
2740
- const iterator = /** @type AsyncIterator<unknown> */ (
2741
- dir.iterable[Symbol.asyncIterator]()
2742
- );
2743
- /** @type {AsyncStreamState} */
2744
- const state = {
2745
- kind: 'async-stream',
2746
- mode: 'replace',
2747
- aborted: false,
2748
- iterable: dir.iterable,
2749
- iterator,
2750
- /** @type {ChildNode[]} */ nodes: [],
2751
- };
2752
- part.child = state;
2753
-
2754
- consumeAsyncStream(state, part, dir);
2755
- }
2756
-
2757
- /**
2758
- * @typedef {{
2759
- * kind: 'async-stream',
2760
- * mode: 'append' | 'replace',
2761
- * aborted: boolean,
2762
- * iterable: AsyncIterable<unknown>,
2763
- * iterator: AsyncIterator<unknown>,
2764
- * nodes: ChildNode[],
2765
- * }} AsyncStreamState
2766
- */
2767
-
2768
- /**
2769
- * Consume an AsyncIterable for `asyncAppend` / `asyncReplace`. Drives
2770
- * the iterator with an explicit `.next()` loop (rather than `for await`)
2771
- * so that `teardownAsyncStream` can call `iterator.return()` to break
2772
- * a generator parked on an `await`. The `aborted` flag is also checked
2773
- * after every `next()` resolve to short-circuit if abortion happened
2774
- * while the iterator was suspended.
2775
- *
2776
- * Each pass carries TWO try spans, and which failure lands in which is the
2777
- * load-bearing part. SPAN A is the author's own code, the iterable AND the
2778
- * `mapper` it was given, and a throw from either is logged to the console and
2779
- * ends the stream, on the long-standing reasoning that an author's iterable
2780
- * should handle its own errors. SPAN B is the chunk COMMIT, which is a render
2781
- * failure of the component whose template holds the binding, so it routes to
2782
- * that component's `renderError()` and stops the stream.
2783
- *
2784
- * Scope note: only a throw from the COMMIT can stop the stream from here. A
2785
- * directive nested INSIDE a committed chunk (a `watch` whose signal changes
2786
- * later) throws from its own handler, outside this loop entirely, so it
2787
- * reaches the boundary but this loop knows nothing about it and keeps
2788
- * pulling. That is the same for any directive nested anywhere else. lit is no authority
2789
- * either way here (it has no per-component boundary, and both failures become
2790
- * unhandled rejections at the window), so this follows the
2791
- * per-component error isolation WebJs has instead.
2792
- *
2793
- * @param {AsyncStreamState} state
2794
- * @param {Extract<BoundPart, {kind:'child'}>} part
2795
- * @param {{ iterable: AsyncIterable<unknown>, mapper?: (v: unknown, i: number) => unknown }} dir
2796
- */
2797
- async function consumeAsyncStream(state, part, dir) {
2798
- const marker = part.marker;
2799
- let i = 0;
2800
- while (!state.aborted) {
2801
- /** @type {IteratorResult<unknown>} */
2802
- let result;
2803
- /** @type {unknown} */
2804
- let mapped;
2805
- // SPAN A, the author's iterable. A throw here is the author's generator
2806
- // failing, not a render, so it keeps the long-standing console.error and
2807
- // ends the stream. It is a separate span from the commit below on purpose
2808
- // rather than a flag the one catch inspects, because the distinction is
2809
- // the whole point: `reportOutOfBandCommitError` RETHROWS for a part with
2810
- // no owner, and a single enclosing try would hand that rethrow straight
2811
- // back to this swallow, which is the escape this split exists to stop.
2812
- try {
2813
- result = await state.iterator.next();
2814
- if (state.aborted) break;
2815
- if (result.done) break;
2816
- mapped = dir.mapper ? dir.mapper(result.value, i) : result.value;
2817
- } catch (err) {
2818
- // Note this ENDS the stream, and always has: the catch used to sit
2819
- // outside the loop, so there has never been a resume path here.
2820
- if (typeof console !== 'undefined') console.error('[webjs] asyncStream error:', err);
2821
- return;
2822
- }
2823
-
2824
- // SPAN B, the chunk commit. This is a render of the component whose
2825
- // TEMPLATE holds the binding, so a throw is that component's render
2826
- // failure and routes to its `renderError()`, the same as `watch` and
2827
- // `until` already do from their own out-of-band commits. `renderToNodes`
2828
- // is INSIDE the wrap because that is where a nested directive is
2829
- // installed and reads `currentRenderRoot`; without it, a `watch()` inside
2830
- // a chunk is stamped with no owner and its later throw escapes.
2831
- // `commitInto` is a different concern (the renderer-write window for a
2832
- // light slot host), so the two nest rather than replace each other.
2833
- try {
2834
- commitOutOfBand(part, () => {
2835
- const newNodes = renderToNodes(mapped);
2836
-
2837
- // This chunk commit runs in an async loop OUTSIDE any render() window,
2838
- // so open the renderer-write window explicitly: without it, committing a
2839
- // stream chunk into a light slot host would hit the patched insertBefore /
2840
- // removeChild and fold the renderer's own output into `authored`.
2841
- commitInto(marker.parentNode, () => {
2842
- if (state.mode === 'replace') {
2843
- for (const n of state.nodes) {
2844
- if (n.parentNode) n.parentNode.removeChild(n);
2845
- }
2846
- state.nodes = [];
2847
- }
2848
-
2849
- const frag = document.createDocumentFragment();
2850
- for (const n of newNodes) frag.appendChild(n);
2851
- marker.parentNode?.insertBefore(frag, marker);
2852
- state.nodes.push(...newNodes);
2853
- });
2854
- });
2855
- } catch (err) {
2856
- // Stop the stream. The boundary is about to render an error state, and
2857
- // appending later chunks into a region it may have replaced is not a
2858
- // recovery. The rendered nodes are left alone: blanking the region is a
2859
- // separate decision, and `teardownAsyncStream` is for the part being
2860
- // reset, not for this.
2861
- state.aborted = true;
2862
- try { state.iterator.return?.()?.catch?.(() => {}); } catch { /* best effort */ }
2863
- // Rethrows when nothing can receive the error, which for a bare
2864
- // `render()` into a plain container is an owner that carries no
2865
- // `_handleRenderError` (the stamp records the container itself, so the
2866
- // owner is present, just not a component). Surfacing beats swallowing
2867
- // there, and it matches `watch` and `until`, which rethrow from their
2868
- // own out-of-band handlers for the same reason. The exact shape differs
2869
- // by site rather than being one thing: this rejects the loop's
2870
- // promise, `until` rejects from its `.then`, and `watch` throws inside
2871
- // a `queueMicrotask`, which is an uncaught error rather than a
2872
- // rejection.
2873
- reportOutOfBandCommitError(part, err);
2874
- return;
2875
- }
2876
-
2877
- i++;
2878
- }
2879
- }
2880
-
2881
- /**
2882
- * Render a single value into a flat list of DOM nodes for insertion via
2883
- * insertBefore. Handles strings, numbers, TemplateResult, and arrays.
2884
- * @param {unknown} value
2885
- * @returns {ChildNode[]}
2886
- */
2887
- function renderToNodes(value) {
2888
- if (value == null || value === false || value === true) return [];
2889
- if (isTemplate(value)) {
2890
- const tr = /** @type any */ (value);
2891
- const { templateEl, parts, formActions } = compile(tr);
2892
- const frag = /** @type DocumentFragment */ (templateEl.content.cloneNode(true));
2893
- const bound = parts.map((p) => bindPart(p, frag));
2894
- for (let i = 0; i < tr.values.length; i++) {
2895
- applyPart(bound[i], tr.values[i], undefined, tr.values);
2896
- }
2897
- reconcileFormActions(formActions, bound, tr.values);
2898
- // Slot parts need their one-shot apply here too (same contract as
2899
- // createInstance / nested templates / buildDetached): the caller
2900
- // (consumeAsyncStream) inserts these nodes synchronously in the same
2901
- // task, so the slot-part's one-microtask finalize retry lands in the
2902
- // live tree. Without this, a <slot> inside streamed chunk content never
2903
- // finalizes and its name suppresses parking forever.
2904
- for (const p of bound) {
2905
- if (p.kind === 'slot') applyPart(p, undefined, undefined, []);
2906
- }
2907
- return [...frag.childNodes];
2908
- }
2909
- if (Array.isArray(value)) {
2910
- const nodes = [];
2911
- for (const v of value) nodes.push(...renderToNodes(v));
2912
- return nodes;
2913
- }
2914
- return [document.createTextNode(String(value))];
2915
- }
2916
-
2917
- /**
2918
- * Abort an async-stream directive. Sets `aborted = true` (so the next
2919
- * `await iterator.next()` resolution short-circuits), removes all nodes
2920
- * rendered so far, and explicitly calls `iterator.return()` so a
2921
- * generator parked on `await` can unwind via its `finally` blocks
2922
- * instead of leaking.
2923
- * @param {AsyncStreamState} state
2924
- */
2925
- function teardownAsyncStream(state) {
2926
- state.aborted = true;
2927
- for (const n of state.nodes) {
2928
- if (n.parentNode) n.parentNode.removeChild(n);
2929
- }
2930
- state.nodes = [];
2931
- // Best-effort iterator cleanup. `.return()` is optional on AsyncIterators;
2932
- // generators built via `async function*` provide it and run their
2933
- // `finally` blocks. Swallow any rejection so teardown can't throw.
2934
- try {
2935
- state.iterator.return?.()?.catch?.(() => {});
2936
- } catch {
2937
- // ignore
2938
- }
2939
- }
1
+ export { render } from './render-client/reconciler.js';