@symbiotejs/symbiote 3.8.3 → 3.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/README.md +52 -2
  2. package/core/AppRouter.js +97 -58
  3. package/core/PubSub.js +42 -11
  4. package/core/Symbiote.js +90 -59
  5. package/core/itemizeProcessor-keyed.js +88 -188
  6. package/core/itemizeProcessor.js +1 -12
  7. package/core/itemizeSetup.js +26 -3
  8. package/core/ownElements.js +1 -4
  9. package/core/resolveTemplate.js +12 -0
  10. package/core/tpl-processors.js +3 -3
  11. package/docs/README.md +5 -4
  12. package/docs/html-app-vs-htmx.md +55 -0
  13. package/docs/lifecycle.md +2 -0
  14. package/docs/list-rendering.md +10 -2
  15. package/docs/properties.md +28 -1
  16. package/docs/pubsub.md +3 -0
  17. package/docs/routing.md +15 -4
  18. package/docs/security.md +41 -12
  19. package/docs/templates.md +29 -0
  20. package/html-app/BaseClass.js +203 -0
  21. package/html-app/README.md +369 -0
  22. package/html-app/action-data.js +168 -0
  23. package/html-app/actions.js +366 -0
  24. package/html-app/collection-actions.js +104 -0
  25. package/html-app/collection-data.js +234 -0
  26. package/html-app/collection-items.js +45 -0
  27. package/html-app/conditions.js +42 -0
  28. package/html-app/context-data.js +185 -0
  29. package/html-app/context-requests.js +374 -0
  30. package/html-app/context-storage.js +376 -0
  31. package/html-app/declarations.js +55 -0
  32. package/html-app/examples/assets/actions.html +56 -0
  33. package/html-app/examples/assets/collections.html +72 -0
  34. package/html-app/examples/assets/components.html +25 -0
  35. package/html-app/examples/assets/conditional.html +29 -0
  36. package/html-app/examples/assets/data.html +31 -0
  37. package/html-app/examples/assets/guide.html +4 -0
  38. package/html-app/examples/assets/imports.html +11 -0
  39. package/html-app/examples/assets/not-found.html +4 -0
  40. package/html-app/examples/assets/routes.json +58 -0
  41. package/html-app/examples/assets/routing.html +27 -0
  42. package/html-app/examples/assets/state.html +32 -0
  43. package/html-app/examples/assets/storage.html +28 -0
  44. package/html-app/examples/assets/tasks.json +25 -0
  45. package/html-app/examples/full-app.html +147 -0
  46. package/html-app/examples/todo-ref.html +37 -0
  47. package/html-app/fetch-source.js +147 -0
  48. package/html-app/fragment-content.js +29 -0
  49. package/html-app/fragment-source.js +169 -0
  50. package/html-app/index.js +34 -0
  51. package/html-app/initial-data.js +88 -0
  52. package/html-app/pub-map.js +93 -0
  53. package/html-app/router-data.js +50 -0
  54. package/html-app/router-navigation.js +70 -0
  55. package/html-app/storage-revisions.js +130 -0
  56. package/html-app/sym-collection.js +142 -0
  57. package/html-app/sym-component.js +20 -0
  58. package/html-app/sym-conditional.js +141 -0
  59. package/html-app/sym-context.js +176 -0
  60. package/html-app/sym-import.js +218 -0
  61. package/html-app/sym-router.js +107 -0
  62. package/package.json +18 -8
  63. package/scripts/check-html-app-package.js +117 -0
  64. package/scripts/check-html-app-size.js +91 -0
  65. package/scripts/update-exports.js +4 -0
  66. package/skills/symbiote/SKILL.md +197 -0
  67. package/skills/symbiote/agents/openai.yaml +3 -0
  68. package/types/core/AppRouter.d.ts +13 -4
  69. package/types/core/AppRouter.d.ts.map +1 -1
  70. package/types/core/PubSub.d.ts +1 -1
  71. package/types/core/PubSub.d.ts.map +1 -1
  72. package/types/core/Symbiote.d.ts +6 -2
  73. package/types/core/Symbiote.d.ts.map +1 -1
  74. package/types/core/itemizeProcessor-keyed.d.ts.map +1 -1
  75. package/types/core/itemizeProcessor.d.ts.map +1 -1
  76. package/types/core/itemizeSetup.d.ts +1 -0
  77. package/types/core/itemizeSetup.d.ts.map +1 -1
  78. package/types/core/ownElements.d.ts +1 -1
  79. package/types/core/ownElements.d.ts.map +1 -1
  80. package/types/core/resolveTemplate.d.ts +2 -0
  81. package/types/core/resolveTemplate.d.ts.map +1 -0
  82. package/types/html-app/BaseClass.d.ts +24 -0
  83. package/types/html-app/BaseClass.d.ts.map +1 -0
  84. package/types/html-app/action-data.d.ts +15 -0
  85. package/types/html-app/action-data.d.ts.map +1 -0
  86. package/types/html-app/actions.d.ts +104 -0
  87. package/types/html-app/actions.d.ts.map +1 -0
  88. package/types/html-app/collection-actions.d.ts +12 -0
  89. package/types/html-app/collection-actions.d.ts.map +1 -0
  90. package/types/html-app/collection-data.d.ts +13 -0
  91. package/types/html-app/collection-data.d.ts.map +1 -0
  92. package/types/html-app/collection-items.d.ts +7 -0
  93. package/types/html-app/collection-items.d.ts.map +1 -0
  94. package/types/html-app/conditions.d.ts +5 -0
  95. package/types/html-app/conditions.d.ts.map +1 -0
  96. package/types/html-app/context-data.d.ts +31 -0
  97. package/types/html-app/context-data.d.ts.map +1 -0
  98. package/types/html-app/context-requests.d.ts +97 -0
  99. package/types/html-app/context-requests.d.ts.map +1 -0
  100. package/types/html-app/context-storage.d.ts +102 -0
  101. package/types/html-app/context-storage.d.ts.map +1 -0
  102. package/types/html-app/declarations.d.ts +3 -0
  103. package/types/html-app/declarations.d.ts.map +1 -0
  104. package/types/html-app/fetch-source.d.ts +23 -0
  105. package/types/html-app/fetch-source.d.ts.map +1 -0
  106. package/types/html-app/fragment-content.d.ts +6 -0
  107. package/types/html-app/fragment-content.d.ts.map +1 -0
  108. package/types/html-app/fragment-source.d.ts +14 -0
  109. package/types/html-app/fragment-source.d.ts.map +1 -0
  110. package/types/html-app/index.d.ts +9 -0
  111. package/types/html-app/index.d.ts.map +1 -0
  112. package/types/html-app/initial-data.d.ts +8 -0
  113. package/types/html-app/initial-data.d.ts.map +1 -0
  114. package/types/html-app/pub-map.d.ts +19 -0
  115. package/types/html-app/pub-map.d.ts.map +1 -0
  116. package/types/html-app/router-data.d.ts +4 -0
  117. package/types/html-app/router-data.d.ts.map +1 -0
  118. package/types/html-app/router-navigation.d.ts +3 -0
  119. package/types/html-app/router-navigation.d.ts.map +1 -0
  120. package/types/html-app/storage-revisions.d.ts +11 -0
  121. package/types/html-app/storage-revisions.d.ts.map +1 -0
  122. package/types/html-app/sym-collection.d.ts +16 -0
  123. package/types/html-app/sym-collection.d.ts.map +1 -0
  124. package/types/html-app/sym-component.d.ts +5 -0
  125. package/types/html-app/sym-component.d.ts.map +1 -0
  126. package/types/html-app/sym-conditional.d.ts +10 -0
  127. package/types/html-app/sym-conditional.d.ts.map +1 -0
  128. package/types/html-app/sym-context.d.ts +16 -0
  129. package/types/html-app/sym-context.d.ts.map +1 -0
  130. package/types/html-app/sym-import.d.ts +19 -0
  131. package/types/html-app/sym-import.d.ts.map +1 -0
  132. package/types/html-app/sym-router.d.ts +12 -0
  133. package/types/html-app/sym-router.d.ts.map +1 -0
  134. package/docs/llms-index.md +0 -49
  135. package/llms-full.txt +0 -5432
  136. package/llms.txt +0 -49
  137. package/scripts/build-llms.js +0 -56
package/core/Symbiote.js CHANGED
@@ -7,6 +7,7 @@ import { prepareStyleSheet } from '../utils/prepareStyleSheet.js';
7
7
  import { parseProp } from './parseProp.js';
8
8
 
9
9
  import PROCESSORS from './tpl-processors.js';
10
+ import { resolveTemplate } from './resolveTemplate.js';
10
11
  import { parseCssPropertyValue } from '../utils/parseCssPropertyValue.js';
11
12
 
12
13
  export { html } from './html.js';
@@ -33,6 +34,7 @@ export class Symbiote extends HTMLElement {
33
34
  /** @type {Boolean} */
34
35
  #dataCtxInitialized;
35
36
  #destroyTimeout;
37
+ #destroyed = false;
36
38
  #cssDataCache;
37
39
  #computedStyle;
38
40
  #boundCssProps;
@@ -97,10 +99,7 @@ export class Symbiote extends HTMLElement {
97
99
  if (this.allowCustomTemplate) {
98
100
  let customTplSelector = this.getAttribute(DICT.USE_TPL_ATTR);
99
101
  if (customTplSelector) {
100
- let root = this.getRootNode();
101
- /** @type {HTMLTemplateElement} */
102
- // @ts-expect-error
103
- let customTpl = root?.querySelector(customTplSelector) || document.querySelector(customTplSelector);
102
+ let customTpl = resolveTemplate(this, customTplSelector);
104
103
  if (customTpl) {
105
104
  // @ts-expect-error
106
105
  template = customTpl.content.cloneNode(true);
@@ -269,40 +268,57 @@ export class Symbiote extends HTMLElement {
269
268
  */
270
269
  sub(prop, handler, init = true) {
271
270
  let subCb = (val) => {
272
- if (this.#noInit) {
273
- return;
271
+ if (!this.#noInit) {
272
+ handler(val);
274
273
  }
275
- handler(val);
276
274
  };
275
+ /** @type {{ remove(): void } | null} */
276
+ let subscription = null;
277
+ /** @type {(() => void) | undefined} */
278
+ let pending;
279
+ let ctxName = '';
280
+ let removed = false;
281
+ let release = {
282
+ remove: () => {
283
+ if (removed) { return; }
284
+ removed = true;
285
+ subscription?.remove();
286
+ let callbacks = PubSub.pendingDeps.get(ctxName);
287
+ let index = callbacks?.indexOf(pending) ?? -1;
288
+ if (index !== -1) {
289
+ callbacks.splice(index, 1);
290
+ if (!callbacks.length) { PubSub.pendingDeps.delete(ctxName); }
291
+ }
292
+ this.allSubs.delete(release);
293
+ },
294
+ };
295
+ this.allSubs.add(release);
277
296
  let parsed = Symbiote.parseProp(/** @type {string} */ (prop), this);
278
- if (!parsed) {
279
- // Named context not found — defer subscription
280
- let slashIdx = /** @type {string} */ (prop).indexOf('/');
281
- if (slashIdx !== -1) {
282
- let ctxName = /** @type {string} */ (prop).slice(0, slashIdx);
283
- let propName = /** @type {string} */ (prop).slice(slashIdx + 1);
284
- if (!PubSub.pendingDeps.has(ctxName)) {
285
- PubSub.pendingDeps.set(ctxName, []);
297
+ if (parsed) {
298
+ subscription = parsed.ctx.sub(parsed.name, subCb, init, true);
299
+ if (removed) { subscription?.remove(); }
300
+ } else {
301
+ let slash = String(prop).indexOf('/');
302
+ if (slash === -1) {
303
+ release.remove();
304
+ return release;
305
+ }
306
+ ctxName = String(prop).slice(0, slash);
307
+ let name = String(prop).slice(slash + 1);
308
+ pending = () => {
309
+ if (removed) { return; }
310
+ let context = PubSub.getCtx(ctxName, false);
311
+ if (context) {
312
+ subscription = context.sub(name, subCb, init, true);
313
+ if (removed) { subscription?.remove(); }
286
314
  }
287
- PubSub.pendingDeps.get(ctxName).push(() => {
288
- let ctx = PubSub.getCtx(ctxName, false);
289
- if (!ctx) return;
290
- let sub = ctx.sub(propName, subCb, init);
291
- if (sub) {
292
- this.allSubs.add(sub);
293
- }
294
- });
315
+ };
316
+ if (!PubSub.pendingDeps.has(ctxName)) {
317
+ PubSub.pendingDeps.set(ctxName, []);
295
318
  }
296
- return;
297
- }
298
- if (!parsed.ctx.has(parsed.name)) {
299
- // Avoid *prop binding race:
300
- window.queueMicrotask(() => {
301
- this.allSubs.add(parsed.ctx.sub(parsed.name, subCb, init));
302
- });
303
- } else {
304
- this.allSubs.add(parsed.ctx.sub(parsed.name, subCb, init));
319
+ PubSub.pendingDeps.get(ctxName).push(pending);
305
320
  }
321
+ return release;
306
322
  }
307
323
 
308
324
  /** @param {String} prop */
@@ -341,6 +357,23 @@ export class Symbiote extends HTMLElement {
341
357
  }
342
358
  }
343
359
 
360
+ /**
361
+ * @param {Partial<S>} kvObj
362
+ * @param {Boolean} [forcePrimitives] Force update callbacks for primitive types
363
+ */
364
+ set$(kvObj, forcePrimitives = false) {
365
+ for (let key in kvObj) {
366
+ let val = kvObj[key];
367
+ /** @type {unknown[]} */
368
+ let primArr = [String, Number, Boolean];
369
+ if (forcePrimitives || !primArr.includes(val?.constructor)) {
370
+ this.localCtx.pub(key, val);
371
+ } else {
372
+ this.localCtx.read(key) !== val && this.localCtx.pub(key, val);
373
+ }
374
+ }
375
+ }
376
+
344
377
  /** @returns {S} */
345
378
  get $() {
346
379
  if (!this.#stateProxy) {
@@ -373,20 +406,10 @@ export class Symbiote extends HTMLElement {
373
406
  }
374
407
 
375
408
  /**
376
- * @param {Partial<S>} kvObj
377
- * @param {Boolean} [forcePrimitives] Force update callbacks for primitive types
409
+ * @param {Partial<S>} stateObj
378
410
  */
379
- set$(kvObj, forcePrimitives = false) {
380
- for (let key in kvObj) {
381
- let val = kvObj[key];
382
- /** @type {unknown[]} */
383
- let primArr = [String, Number, Boolean];
384
- if (forcePrimitives || !primArr.includes(val?.constructor)) {
385
- this.localCtx.pub(key, val);
386
- } else {
387
- this.localCtx.read(key) !== val && this.localCtx.pub(key, val);
388
- }
389
- }
411
+ set $(stateObj) {
412
+ this.add$(stateObj, true);
390
413
  }
391
414
 
392
415
  initAttributeObserver() {
@@ -471,6 +494,7 @@ export class Symbiote extends HTMLElement {
471
494
  if (this.#destroyTimeout) {
472
495
  window.clearTimeout(this.#destroyTimeout);
473
496
  }
497
+ this.#destroyed = false;
474
498
  if (!this.connectedOnce) {
475
499
  let ctxNameAttrVal = this.getAttribute(DICT.CTX_NAME_ATTR)?.trim();
476
500
  if (ctxNameAttrVal) {
@@ -589,20 +613,27 @@ export class Symbiote extends HTMLElement {
589
613
  if (this.#destroyTimeout) {
590
614
  window.clearTimeout(this.#destroyTimeout);
591
615
  }
592
- this.#destroyTimeout = window.setTimeout(() => {
593
- this.destroyCallback();
594
- if (this.attributeMutationObserver) {
595
- this.attributeMutationObserver.disconnect();
596
- }
597
- for (let sub of this.allSubs) {
598
- sub.remove();
599
- this.allSubs.delete(sub);
600
- }
601
- this.#localCtx = null;
602
- for (let proc of this.templateProcessors) {
603
- this.templateProcessors.delete(proc);
604
- }
605
- }, this.destructionDelay);
616
+ this.#destroyTimeout = window.setTimeout(() => this.destroy(), this.destructionDelay);
617
+ }
618
+
619
+ /**
620
+ * Finish disconnection cleanup immediately. Connected or uninitialized owners
621
+ * are unaffected; repeated calls before reconnection are harmless.
622
+ */
623
+ destroy() {
624
+ if (this.isConnected || !this.connectedOnce || this.#destroyed) {
625
+ return;
626
+ }
627
+ this.#destroyed = true;
628
+ window.clearTimeout(this.#destroyTimeout);
629
+ this.destroyCallback();
630
+ this.attributeMutationObserver?.disconnect();
631
+ for (let sub of this.allSubs) {
632
+ sub.remove();
633
+ }
634
+ this.allSubs.clear();
635
+ this.#localCtx = null;
636
+ this.templateProcessors.clear();
606
637
  }
607
638
 
608
639
  /**
@@ -1,217 +1,117 @@
1
1
  import { animateOut } from './animateOut.js';
2
2
  import { warnMsg } from './warn.js';
3
- import { setupItemize } from './itemizeSetup.js';
3
+ import { setupItemize, setItemWebMCPMetadata } from './itemizeSetup.js';
4
4
 
5
5
  /**
6
- * Optimized itemize template processor.
7
- *
8
- * Drop-in replacement for the default itemizeProcessor with:
9
- * - Reference-equality fast paths for append, truncate, and no-op
10
- * - Key-based reconciliation (using `_KEY_` or `id` properties) for efficient reordering
11
- * - Skip-if-same optimization for index-based patching
12
- *
13
- * Usage:
14
- * ```js
15
- * import { itemizeProcessor } from '@symbiotejs/symbiote/core/itemizeProcessor-keyed.js';
16
- * import { itemizeProcessor as defaultProcessor } from '@symbiotejs/symbiote/core/itemizeProcessor.js';
17
- *
18
- * class MyList extends Symbiote {
19
- * constructor() {
20
- * super();
21
- * // Swap default for keyed version
22
- * this.templateProcessors.delete(defaultProcessor);
23
- * this.templateProcessors = new Set([itemizeProcessor, ...this.templateProcessors]);
24
- * }
25
- * }
26
- * ```
27
- *
6
+ * Optional Itemize processor with stable keyed identity.
7
+ * Keyed records always keep their element, including complete reversals.
28
8
  * @template {import('./Symbiote.js').Symbiote} T
29
9
  * @param {DocumentFragment} fr
30
10
  * @param {T} fnCtx
31
11
  */
32
12
  export function itemizeProcessor(fr, fnCtx) {
33
- setupItemize(fr, fnCtx, ({ el, itemClass, repeatDataKey, clientSSR, isLazy }) => {
34
- /** @type {*[]} */
35
- let prevData = [];
13
+ setupItemize(fr, fnCtx, ({
14
+ el,
15
+ itemClass,
16
+ repeatDataKey,
17
+ clientSSR,
18
+ isLazy,
19
+ }) => {
20
+ /** @type {any[]} */
21
+ let previous = [];
22
+ let hydrating = clientSSR;
23
+ /** @type {any[]} */
24
+ let active = [
25
+ ...el.children,
26
+ ];
36
27
 
37
28
  fnCtx.sub(repeatDataKey, (data) => {
38
- if (!data) {
39
- while (el.firstChild) {
40
- el.firstChild.remove();
29
+ /** @type {any[]} */
30
+ let items = [];
31
+ if (data) {
32
+ if (Array.isArray(data)) {
33
+ items = data;
34
+ } else if (data.constructor === Object) {
35
+ items = Object.entries(data).map(([
36
+ key,
37
+ value,
38
+ ]) => ({
39
+ ...value,
40
+ _KEY_: key,
41
+ }));
42
+ } else {
43
+ warnMsg(16, fnCtx.localName, typeof data, data);
44
+ return;
41
45
  }
42
- prevData = [];
43
- return;
44
46
  }
45
-
46
- /** @type {*[]} */
47
- let items;
48
- if (data.constructor === Array) {
49
- items = data;
50
- } else if (data.constructor === Object) {
51
- items = [];
52
- for (let itemKey in data) {
53
- let init = data[itemKey];
54
- Object.defineProperty(init, '_KEY_', {
55
- value: itemKey,
56
- enumerable: true,
57
- });
58
- items.push(init);
59
- }
60
- } else {
61
- warnMsg(16, fnCtx.localName, typeof data, data);
47
+ if (items === previous) {
62
48
  return;
63
49
  }
64
-
65
- let children = el.children;
66
- let prevLen = children.length;
67
- let newLen = items.length;
68
-
69
- // ── Fast path: no-op (same array reference) ──
70
- if (data === prevData || items === prevData) {
71
- return;
50
+ let keyProp = items[0]?.id !== undefined && Array.isArray(data) ? 'id'
51
+ : items[0]?._KEY_ !== undefined ? '_KEY_' : null;
52
+ let keys = keyProp ? items.map((item) => item[keyProp]) : [];
53
+ if (keyProp && (keys.some((key) => key === undefined) || new Set(keys).size !== keys.length)) {
54
+ throw new TypeError('Keyed Itemize requires unique keys on every record.');
72
55
  }
73
-
74
- // ── Fast path: simple truncate (tail removal) ──
75
- if (newLen < prevLen && newLen > 0) {
76
- if (items[0] === prevData[0] && items[newLen - 1] === prevData[newLen - 1]) {
77
- for (let i = prevLen - 1; i >= newLen; i--) {
78
- animateOut(children[i]);
79
- }
80
- prevData = items;
81
- return;
82
- }
56
+ let byKey = new Map();
57
+ if (keyProp) {
58
+ previous.forEach((item, index) => byKey.set(item[keyProp], index));
83
59
  }
84
-
85
- // ── Fast path: simple append ──
86
- if (newLen > prevLen && prevLen > 0) {
87
- if (items[0] === prevData[0] && items[prevLen - 1] === prevData[prevLen - 1]) {
88
- let fragment = document.createDocumentFragment();
89
- for (let i = prevLen; i < newLen; i++) {
90
- let repeatItem = new itemClass();
91
- if (isLazy) {
92
- repeatItem.lazyMode = true;
93
- }
94
- Object.assign((repeatItem?.init$ || repeatItem), items[i]);
95
- fragment.appendChild(repeatItem);
96
- }
97
- el.appendChild(fragment);
98
- prevData = items;
99
- return;
100
- }
101
- }
102
-
103
- // ── Full reconciliation ──
104
- let keyProp = items[0]?._KEY_ !== undefined ? '_KEY_' : (items[0]?.id !== undefined ? 'id' : null);
105
-
106
- if (keyProp && prevLen > 0) {
107
- /** @type {Map<*, number>} */
108
- let prevKeyToIdx = new Map();
109
- for (let i = 0; i < prevLen; i++) {
110
- let key = prevData[i]?.[keyProp];
111
- if (key !== undefined) {
112
- prevKeyToIdx.set(key, i);
113
- }
114
- }
115
-
116
- // Count out-of-order moves to decide strategy
117
- let movesNeeded = 0;
118
- let lastReusedIdx = -1;
119
-
120
- for (let i = 0; i < newLen; i++) {
121
- let prevIdx = prevKeyToIdx.get(items[i][keyProp]);
122
- if (prevIdx !== undefined) {
123
- if (prevIdx < lastReusedIdx) {
124
- movesNeeded++;
125
- }
126
- lastReusedIdx = prevIdx;
127
- }
128
- }
129
-
130
- // DOM reorder only when few moves needed; otherwise patch in-place
131
- if (movesNeeded < newLen * 0.3) {
132
- let newChildren = [];
133
- let toRemove = new Set(prevKeyToIdx.keys());
134
-
135
- for (let i = 0; i < newLen; i++) {
136
- let item = items[i];
137
- let key = item[keyProp];
138
- let prevIdx = prevKeyToIdx.get(key);
139
-
140
- if (prevIdx !== undefined) {
141
- let existing = children[prevIdx];
142
- if (item !== prevData[prevIdx]) {
143
- // @ts-expect-error
144
- if (existing.set$) {
145
- // @ts-expect-error
146
- existing.set$(item);
147
- } else {
148
- for (let k in item) {
149
- existing[k] = item[k];
150
- }
151
- }
152
- }
153
- toRemove.delete(key);
154
- newChildren.push(existing);
155
- } else {
156
- let repeatItem = new itemClass();
157
- if (isLazy) {
158
- repeatItem.lazyMode = true;
159
- }
160
- Object.assign((repeatItem?.init$ || repeatItem), item);
161
- newChildren.push(repeatItem);
162
- }
163
- }
164
-
165
- let removeEls = [...toRemove].map((key) => children[prevKeyToIdx.get(key)]);
166
- for (let el of removeEls) {
167
- animateOut(el);
168
- }
169
-
170
- for (let i = 0; i < newChildren.length; i++) {
171
- if (children[i] !== newChildren[i]) {
172
- el.insertBefore(newChildren[i], children[i] || null);
173
- }
174
- }
175
-
176
- prevData = items;
177
- return;
178
- }
179
- }
180
-
181
- // ── Index-based patching (fallback, same as default + skip-if-same) ──
182
- let fragment;
183
- for (let i = 0; i < newLen; i++) {
184
- if (i < prevLen) {
185
- if (items[i] !== prevData[i]) {
186
- let child = children[i];
187
- // @ts-expect-error
60
+ let retained = new Set();
61
+ let next = items.map((item, index) => {
62
+ let previousIndex = hydrating ? index : keyProp ? byKey.get(item[keyProp]) : index;
63
+ let child = previousIndex === undefined ? null : active[previousIndex];
64
+ if (child) {
65
+ retained.add(child);
66
+ if (hydrating) {
67
+ child.ssrMode = true;
68
+ child.$ = item;
69
+ } else if (item !== previous[previousIndex]) {
188
70
  if (child.set$) {
189
- // @ts-expect-error
190
- child.set$(items[i]);
71
+ child.set$(item);
191
72
  } else {
192
- for (let k in items[i]) {
193
- child[k] = items[i][k];
194
- }
73
+ Object.assign(child, item);
195
74
  }
196
75
  }
197
76
  } else {
198
- if (!fragment) {
199
- fragment = document.createDocumentFragment();
200
- }
201
- let repeatItem = new itemClass();
77
+ child = new itemClass();
202
78
  if (isLazy) {
203
- repeatItem.lazyMode = true;
79
+ child.lazyMode = true;
80
+ }
81
+ Object.assign(child.init$ || child, item);
82
+ }
83
+ setItemWebMCPMetadata(child, item, index, keyProp ? item[keyProp] : undefined);
84
+ return child;
85
+ });
86
+ // Leaving elements are excluded from future reconciliation immediately.
87
+ for (let child of active) {
88
+ if (!retained.has(child)) {
89
+ child.setAttribute('inert', '');
90
+ animateOut(child);
91
+ }
92
+ }
93
+ let focused = el.ownerDocument.activeElement;
94
+ for (let index = 0; index < next.length; index++) {
95
+ let child = next[index];
96
+ let before = el.children[index] || null;
97
+ if (before !== child) {
98
+ let moveBefore = Reflect.get(el, 'moveBefore');
99
+ if (typeof moveBefore === 'function' && child.parentElement === el && el.isConnected) {
100
+ moveBefore.call(el, child, before);
101
+ } else {
102
+ el.insertBefore(child, before);
204
103
  }
205
- Object.assign((repeatItem?.init$ || repeatItem), items[i]);
206
- fragment.appendChild(repeatItem);
207
104
  }
208
105
  }
209
- fragment && el.appendChild(fragment);
210
- for (let i = prevLen - 1; i >= newLen; i--) {
211
- animateOut(children[i]);
106
+ if (focused instanceof HTMLElement && focused.isConnected
107
+ && el.contains(focused) && el.ownerDocument.activeElement !== focused) {
108
+ focused.focus({
109
+ preventScroll: true,
110
+ });
212
111
  }
213
-
214
- prevData = items;
215
- }, !clientSSR);
112
+ hydrating = false;
113
+ previous = items;
114
+ active = next;
115
+ });
216
116
  });
217
117
  }
@@ -1,17 +1,6 @@
1
1
  import { animateOut } from './animateOut.js';
2
2
  import { warnMsg } from './warn.js';
3
- import { setupItemize } from './itemizeSetup.js';
4
- import { DICT } from './dictionary.js';
5
-
6
- function setItemWebMCPMetadata(itemEl, item, idx) {
7
- if (!itemEl) return;
8
- itemEl[DICT.MCP_ITEM_INDEX_KEY] = idx;
9
- if (item && Object.prototype.hasOwnProperty.call(item, '_KEY_')) {
10
- itemEl[DICT.MCP_ITEM_KEY_KEY] = item._KEY_;
11
- } else {
12
- delete itemEl[DICT.MCP_ITEM_KEY_KEY];
13
- }
14
- }
3
+ import { setupItemize, setItemWebMCPMetadata } from './itemizeSetup.js';
15
4
 
16
5
  /**
17
6
  * @template {import('./Symbiote.js').Symbiote} T
@@ -1,6 +1,24 @@
1
1
  import { DICT } from './dictionary.js';
2
2
  import { ownElements } from './ownElements.js';
3
3
  import { initPropFallback } from './initPropFallback.js';
4
+ import { resolveTemplate } from './resolveTemplate.js';
5
+ import { warnMsg } from './warn.js';
6
+
7
+ /**
8
+ * @param {any} itemEl
9
+ * @param {any} item
10
+ * @param {number} idx
11
+ * @param {unknown} [key]
12
+ */
13
+ export function setItemWebMCPMetadata(itemEl, item, idx, key = item && Object.hasOwn(item, '_KEY_') ? item._KEY_ : undefined) {
14
+ if (!itemEl) { return; }
15
+ itemEl[DICT.MCP_ITEM_INDEX_KEY] = idx;
16
+ if (key !== undefined) {
17
+ itemEl[DICT.MCP_ITEM_KEY_KEY] = key;
18
+ } else {
19
+ delete itemEl[DICT.MCP_ITEM_KEY_KEY];
20
+ }
21
+ }
4
22
 
5
23
  /**
6
24
  * @typedef {Object} ItemizeDescriptor
@@ -29,6 +47,11 @@ export function setupItemize(fr, fnCtx, handler) {
29
47
  }).forEach((el) => {
30
48
  let itemTag = el.getAttribute(DICT.LIST_ITEM_TAG_ATTR);
31
49
  let repeatDataKey = el.getAttribute(DICT.LIST_ATTR);
50
+ let selector = el.getAttribute(DICT.USE_TPL_ATTR);
51
+ let selected = selector ? resolveTemplate(el, selector) : null;
52
+ if (selector && !selected) {
53
+ warnMsg(5, fnCtx.localName, selector);
54
+ }
32
55
  let itemClass;
33
56
  if (itemTag) {
34
57
  itemClass = window.customElements.get(itemTag);
@@ -53,8 +76,8 @@ export function setupItemize(fr, fnCtx, handler) {
53
76
  let staticEl = tpl.content.querySelector(
54
77
  `[${DICT.LIST_ATTR}="${repeatDataKey}"]`
55
78
  );
56
- itemClass.template = staticEl?.querySelector('template')?.innerHTML
57
- || el.children[0].innerHTML;
79
+ itemClass.template = selected?.innerHTML ?? (staticEl?.querySelector('template')?.innerHTML
80
+ || el.children[0].innerHTML);
58
81
  itemClass.reg(ssrTag);
59
82
  }
60
83
  } else {
@@ -66,7 +89,7 @@ export function setupItemize(fr, fnCtx, handler) {
66
89
  }
67
90
  }
68
91
  };
69
- itemClass.template = el.querySelector('template')?.innerHTML || el.innerHTML;
92
+ itemClass.template = selected?.innerHTML ?? (el.querySelector('template')?.innerHTML || el.innerHTML);
70
93
  itemClass.reg(itemTag);
71
94
  }
72
95
  }
@@ -9,9 +9,6 @@
9
9
  */
10
10
  export function ownElements(fr, selector) {
11
11
  let all = [...fr.querySelectorAll(selector)];
12
- if (!(fr instanceof HTMLElement) || !fr.localName?.includes('-')) {
13
- return all;
14
- }
15
12
  return all.filter((el) => {
16
13
  let parent = el.parentElement;
17
14
  while (parent && parent !== fr) {
@@ -25,7 +22,7 @@ export function ownElements(fr, selector) {
25
22
  /**
26
23
  * Check if a node belongs to `root` and not to a nested custom element.
27
24
  * @param {Node} node
28
- * @param {Element} root
25
+ * @param {Element | DocumentFragment} root
29
26
  * @returns {boolean}
30
27
  */
31
28
  export function isOwnNode(node, root) {
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Native use-template lookup: the containing root takes precedence.
3
+ * @param {Element} element
4
+ * @param {string} selector
5
+ * @returns {HTMLTemplateElement | null}
6
+ */
7
+ export function resolveTemplate(element, selector) {
8
+ let root = /** @type {Document | ShadowRoot | DocumentFragment} */ (element.getRootNode());
9
+ return /** @type {HTMLTemplateElement | null} */ (
10
+ root.querySelector?.(selector) || element.ownerDocument.querySelector(selector)
11
+ );
12
+ }
@@ -175,7 +175,8 @@ function domBindProcessor(fr, fnCtx) {
175
175
  el.setAttribute(prop, val);
176
176
  }
177
177
  } else {
178
- if (!setNestedProp(el, prop, val)) {
178
+ // A direct $ assignment on an unupgraded child would shadow its state accessor.
179
+ if ((prop === '$' && !('$' in el)) || !setNestedProp(el, prop, val)) {
179
180
  // Custom element instances are not constructed properly at this moment, so:
180
181
  if (!el[DICT.SET_LATER_KEY]) {
181
182
  el[DICT.SET_LATER_KEY] = Object.create(null);
@@ -193,11 +194,10 @@ function domBindProcessor(fr, fnCtx) {
193
194
  }
194
195
 
195
196
  function getTextNodesWithTokens(el) {
196
- let isCustomEl = el instanceof HTMLElement && el.localName?.includes('-');
197
197
  let node;
198
198
  let result = [];
199
199
  let acceptNode = (txt) => {
200
- if (isCustomEl && !isOwnNode(txt, el)) return NodeFilter.FILTER_REJECT;
200
+ if (!isOwnNode(txt, el)) return NodeFilter.FILTER_REJECT;
201
201
  return !txt.parentElement?.hasAttribute(DICT.TEXT_NODE_SKIP_ATTR)
202
202
  && txt.textContent.includes(DICT.TEXT_NODE_OPEN_TOKEN)
203
203
  && txt.textContent.includes(DICT.TEXT_NODE_CLOSE_TOKEN)