@symbiotejs/symbiote 3.9.0 → 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 (131) hide show
  1. package/README.md +12 -0
  2. package/core/AppRouter.js +97 -58
  3. package/core/PubSub.js +42 -11
  4. package/core/Symbiote.js +70 -46
  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 +1 -2
  11. package/docs/README.md +2 -0
  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/pubsub.md +3 -0
  16. package/docs/routing.md +15 -4
  17. package/html-app/BaseClass.js +203 -0
  18. package/html-app/README.md +369 -0
  19. package/html-app/action-data.js +168 -0
  20. package/html-app/actions.js +366 -0
  21. package/html-app/collection-actions.js +104 -0
  22. package/html-app/collection-data.js +234 -0
  23. package/html-app/collection-items.js +45 -0
  24. package/html-app/conditions.js +42 -0
  25. package/html-app/context-data.js +185 -0
  26. package/html-app/context-requests.js +374 -0
  27. package/html-app/context-storage.js +376 -0
  28. package/html-app/declarations.js +55 -0
  29. package/html-app/examples/assets/actions.html +56 -0
  30. package/html-app/examples/assets/collections.html +72 -0
  31. package/html-app/examples/assets/components.html +25 -0
  32. package/html-app/examples/assets/conditional.html +29 -0
  33. package/html-app/examples/assets/data.html +31 -0
  34. package/html-app/examples/assets/guide.html +4 -0
  35. package/html-app/examples/assets/imports.html +11 -0
  36. package/html-app/examples/assets/not-found.html +4 -0
  37. package/html-app/examples/assets/routes.json +58 -0
  38. package/html-app/examples/assets/routing.html +27 -0
  39. package/html-app/examples/assets/state.html +32 -0
  40. package/html-app/examples/assets/storage.html +28 -0
  41. package/html-app/examples/assets/tasks.json +25 -0
  42. package/html-app/examples/full-app.html +147 -0
  43. package/html-app/examples/todo-ref.html +37 -0
  44. package/html-app/fetch-source.js +147 -0
  45. package/html-app/fragment-content.js +29 -0
  46. package/html-app/fragment-source.js +169 -0
  47. package/html-app/index.js +34 -0
  48. package/html-app/initial-data.js +88 -0
  49. package/html-app/pub-map.js +93 -0
  50. package/html-app/router-data.js +50 -0
  51. package/html-app/router-navigation.js +70 -0
  52. package/html-app/storage-revisions.js +130 -0
  53. package/html-app/sym-collection.js +142 -0
  54. package/html-app/sym-component.js +20 -0
  55. package/html-app/sym-conditional.js +141 -0
  56. package/html-app/sym-context.js +176 -0
  57. package/html-app/sym-import.js +218 -0
  58. package/html-app/sym-router.js +107 -0
  59. package/package.json +18 -6
  60. package/scripts/check-html-app-package.js +117 -0
  61. package/scripts/check-html-app-size.js +91 -0
  62. package/scripts/update-exports.js +4 -0
  63. package/skills/symbiote/SKILL.md +64 -15
  64. package/skills/symbiote/agents/openai.yaml +1 -1
  65. package/types/core/AppRouter.d.ts +13 -4
  66. package/types/core/AppRouter.d.ts.map +1 -1
  67. package/types/core/PubSub.d.ts +1 -1
  68. package/types/core/PubSub.d.ts.map +1 -1
  69. package/types/core/Symbiote.d.ts +4 -1
  70. package/types/core/Symbiote.d.ts.map +1 -1
  71. package/types/core/itemizeProcessor-keyed.d.ts.map +1 -1
  72. package/types/core/itemizeProcessor.d.ts.map +1 -1
  73. package/types/core/itemizeSetup.d.ts +1 -0
  74. package/types/core/itemizeSetup.d.ts.map +1 -1
  75. package/types/core/ownElements.d.ts +1 -1
  76. package/types/core/ownElements.d.ts.map +1 -1
  77. package/types/core/resolveTemplate.d.ts +2 -0
  78. package/types/core/resolveTemplate.d.ts.map +1 -0
  79. package/types/core/tpl-processors.d.ts.map +1 -1
  80. package/types/html-app/BaseClass.d.ts +24 -0
  81. package/types/html-app/BaseClass.d.ts.map +1 -0
  82. package/types/html-app/action-data.d.ts +15 -0
  83. package/types/html-app/action-data.d.ts.map +1 -0
  84. package/types/html-app/actions.d.ts +104 -0
  85. package/types/html-app/actions.d.ts.map +1 -0
  86. package/types/html-app/collection-actions.d.ts +12 -0
  87. package/types/html-app/collection-actions.d.ts.map +1 -0
  88. package/types/html-app/collection-data.d.ts +13 -0
  89. package/types/html-app/collection-data.d.ts.map +1 -0
  90. package/types/html-app/collection-items.d.ts +7 -0
  91. package/types/html-app/collection-items.d.ts.map +1 -0
  92. package/types/html-app/conditions.d.ts +5 -0
  93. package/types/html-app/conditions.d.ts.map +1 -0
  94. package/types/html-app/context-data.d.ts +31 -0
  95. package/types/html-app/context-data.d.ts.map +1 -0
  96. package/types/html-app/context-requests.d.ts +97 -0
  97. package/types/html-app/context-requests.d.ts.map +1 -0
  98. package/types/html-app/context-storage.d.ts +102 -0
  99. package/types/html-app/context-storage.d.ts.map +1 -0
  100. package/types/html-app/declarations.d.ts +3 -0
  101. package/types/html-app/declarations.d.ts.map +1 -0
  102. package/types/html-app/fetch-source.d.ts +23 -0
  103. package/types/html-app/fetch-source.d.ts.map +1 -0
  104. package/types/html-app/fragment-content.d.ts +6 -0
  105. package/types/html-app/fragment-content.d.ts.map +1 -0
  106. package/types/html-app/fragment-source.d.ts +14 -0
  107. package/types/html-app/fragment-source.d.ts.map +1 -0
  108. package/types/html-app/index.d.ts +9 -0
  109. package/types/html-app/index.d.ts.map +1 -0
  110. package/types/html-app/initial-data.d.ts +8 -0
  111. package/types/html-app/initial-data.d.ts.map +1 -0
  112. package/types/html-app/pub-map.d.ts +19 -0
  113. package/types/html-app/pub-map.d.ts.map +1 -0
  114. package/types/html-app/router-data.d.ts +4 -0
  115. package/types/html-app/router-data.d.ts.map +1 -0
  116. package/types/html-app/router-navigation.d.ts +3 -0
  117. package/types/html-app/router-navigation.d.ts.map +1 -0
  118. package/types/html-app/storage-revisions.d.ts +11 -0
  119. package/types/html-app/storage-revisions.d.ts.map +1 -0
  120. package/types/html-app/sym-collection.d.ts +16 -0
  121. package/types/html-app/sym-collection.d.ts.map +1 -0
  122. package/types/html-app/sym-component.d.ts +5 -0
  123. package/types/html-app/sym-component.d.ts.map +1 -0
  124. package/types/html-app/sym-conditional.d.ts +10 -0
  125. package/types/html-app/sym-conditional.d.ts.map +1 -0
  126. package/types/html-app/sym-context.d.ts +16 -0
  127. package/types/html-app/sym-context.d.ts.map +1 -0
  128. package/types/html-app/sym-import.d.ts +19 -0
  129. package/types/html-app/sym-import.d.ts.map +1 -0
  130. package/types/html-app/sym-router.d.ts +12 -0
  131. package/types/html-app/sym-router.d.ts.map +1 -0
package/README.md CHANGED
@@ -80,6 +80,18 @@ npx skills add symbiotejs/symbiote.js --skill symbiote
80
80
 
81
81
  The [skills CLI](https://skills.sh/docs/cli) lets you choose your coding agent. Add `--global` to install across projects. The skill covers templates, state bindings, contexts, SSR, WebMCP, and security boundaries, with links to the detailed documentation.
82
82
 
83
+ ## HTML-only applications
84
+
85
+ **Build a working app in HTML, without writing application JavaScript.** The [HTML-app foundation](./html-app/README.md) lets a form create records, checkboxes update them, and filtered lists react immediately. Navigation, reusable views and browser saving can live in the markup too. You can also [define your own custom elements entirely in HTML](./html-app/README.md#reusable-component-declarations), including their data, templates and declarative actions.
86
+
87
+ Compose applications from [portable HTML chunks](./html-app/README.md#html-fragments), combining imported sections, reusable templates and custom elements in the layout you need. Bind the same chunk to different data contexts and reuse it across views.
88
+
89
+ Mix those chunks with Markdown in a host that preserves embedded HTML, keeping explanations and interactive controls in one document. Reusing declarative actions instead of generating event handlers and state-management boilerplate can reduce AI output token consumption.
90
+
91
+ Load one module, declare your data as JSON, and connect your controls with Symbiote bindings. You can build an interactive tool on a static server, then connect JSON endpoints when it needs shared data. HTML-app is an optional entry that works alongside ordinary Symbiote components; the library core stays independent.
92
+
93
+ Start with the [compact Todo](./html-app/examples/todo-ref.html), explore the [feature guide](./html-app/examples/full-app.html), or see [how HTML-app compares with htmx](./docs/html-app-vs-htmx.md).
94
+
83
95
  ## Core concepts
84
96
 
85
97
  ### Runtime Agnostic Templates (RAT)
package/core/AppRouter.js CHANGED
@@ -44,6 +44,7 @@ export class AppRouter {
44
44
  static #usePathMode = false;
45
45
  /** @type {Array<{regex: RegExp, keys: string[], route: string}>} */
46
46
  static #compiledPatterns = [];
47
+ static #navigationVersion = 0;
47
48
 
48
49
  static get #isBrowser() {
49
50
  return typeof window !== 'undefined' && !globalThis.__SYMBIOTE_SSR;
@@ -63,52 +64,68 @@ export class AppRouter {
63
64
  return typeof title === 'function' ? title() : title;
64
65
  }
65
66
 
66
- /** @param {Object<string, {}>} map */
67
- static setRoutingMap(map) {
68
- Object.assign(this.appMap, map);
69
- for (let route in this.appMap) {
70
- let desc = this.appMap[route];
71
- if (!this.defaultRoute && desc.default === true) {
72
- this.defaultRoute = route;
73
- } else if (!this.errorRoute && desc.error === true) {
74
- this.errorRoute = route;
75
- }
76
- if (desc.pattern) {
77
- this.#usePathMode = true;
67
+ /**
68
+ * @param {Object<string, RouteDescriptor>} map
69
+ * @param {boolean} [replace]
70
+ */
71
+ static setRoutingMap(map, replace = false) {
72
+ let nextMap = Object.assign(Object.create(null), replace ? {} : this.appMap, map);
73
+ let defaultRoute = replace ? undefined : this.defaultRoute;
74
+ let errorRoute = replace ? undefined : this.errorRoute;
75
+ let usePathMode = false;
76
+ for (let route in nextMap) {
77
+ let desc = nextMap[route];
78
+ if (!defaultRoute && desc.default === true) {
79
+ defaultRoute = route;
80
+ } else if (!errorRoute && desc.error === true) {
81
+ errorRoute = route;
78
82
  }
83
+ usePathMode ||= !!desc.pattern;
79
84
  }
80
- if (this.#usePathMode) {
81
- this.#compilePatterns();
85
+ // Compile before publishing configuration so malformed patterns are atomic.
86
+ let patterns = usePathMode ? this.#compilePatterns(nextMap) : [];
87
+ if (replace) {
88
+ this.appMap = nextMap;
89
+ this.#currentState = null;
90
+ } else {
91
+ Object.assign(this.appMap, map);
82
92
  }
93
+ this.defaultRoute = defaultRoute;
94
+ this.errorRoute = errorRoute;
95
+ this.#usePathMode = usePathMode;
96
+ this.#compiledPatterns = patterns;
97
+ this.#navigationVersion++;
83
98
  }
84
99
 
85
100
  /**
86
101
  * Compiles route patterns into regex matchers.
87
102
  * Pattern syntax: `/users/:id/posts/:postId` → regex with named groups
103
+ * @param {Object<string, RouteDescriptor>} map
88
104
  */
89
- static #compilePatterns() {
90
- this.#compiledPatterns = [];
91
- for (let route in this.appMap) {
92
- let desc = this.appMap[route];
105
+ static #compilePatterns(map) {
106
+ let patterns = [];
107
+ for (let route in map) {
108
+ let desc = map[route];
93
109
  if (!desc.pattern) continue;
94
110
  let keys = [];
95
111
  let regexStr = desc.pattern.replace(/:([^/]+)/g, (_, key) => {
96
112
  keys.push(key);
97
113
  return '([^/]+)';
98
114
  });
99
- this.#compiledPatterns.push({
115
+ patterns.push({
100
116
  regex: new RegExp(`^${regexStr}$`),
101
117
  keys,
102
118
  route,
103
119
  });
104
120
  }
105
121
  // Sort by specificity: longer patterns first, patterns without params first
106
- this.#compiledPatterns.sort((a, b) => {
122
+ patterns.sort((a, b) => {
107
123
  if (a.keys.length !== b.keys.length) {
108
124
  return a.keys.length - b.keys.length;
109
125
  }
110
126
  return b.regex.source.length - a.regex.source.length;
111
127
  });
128
+ return patterns;
112
129
  }
113
130
 
114
131
  /** @param {String} name */
@@ -122,34 +139,41 @@ export class AppRouter {
122
139
  return this.#routingEventName || 'sym-on-route';
123
140
  }
124
141
 
125
- static readAddressBar() {
126
- if (this.#usePathMode) {
127
- return this.#readPath();
142
+ /** @param {Pick<Location, 'search' | 'pathname'>} [address] */
143
+ static readAddressBar(address = window.location) {
144
+ try {
145
+ return this.#usePathMode ? this.#readPath(address) : this.#readQuery(address);
146
+ } catch (error) {
147
+ if (!(error instanceof URIError)) throw error;
148
+ return {
149
+ route: null,
150
+ options: {},
151
+ };
128
152
  }
129
- return this.#readQuery();
130
153
  }
131
154
 
132
- static #readQuery() {
155
+ /** @param {Pick<Location, 'search'>} address */
156
+ static #readQuery(address) {
133
157
  let result = {
134
158
  route: null,
135
159
  options: {},
136
160
  };
137
- let paramsArr = window.location.search.split(this.separator);
161
+ let paramsArr = address.search.replace(/^\?/, '').split(this.separator);
162
+ result.route = decodeURIComponent(paramsArr.shift() || '') || null;
138
163
  paramsArr.forEach((part) => {
139
- if (part.includes('?')) {
140
- result.route = part.replace('?', '');
141
- } else if (part.includes('=')) {
142
- let pair = part.split('=');
143
- result.options[pair[0]] = decodeURI(pair[1]);
164
+ if (part.includes('=')) {
165
+ let index = part.indexOf('=');
166
+ result.options[decodeURIComponent(part.slice(0, index))] = decodeURIComponent(part.slice(index + 1));
144
167
  } else if (part) {
145
- result.options[part] = true;
168
+ result.options[decodeURIComponent(part)] = true;
146
169
  }
147
170
  });
148
171
  return result;
149
172
  }
150
173
 
151
- static #readPath() {
152
- let pathname = window.location.pathname;
174
+ /** @param {Pick<Location, 'search' | 'pathname'>} address */
175
+ static #readPath(address) {
176
+ let pathname = address.pathname;
153
177
  let result = {
154
178
  route: null,
155
179
  options: {},
@@ -163,7 +187,7 @@ export class AppRouter {
163
187
  result.options[compiled.keys[i]] = decodeURIComponent(match[i + 1]);
164
188
  }
165
189
  // Also parse query string for additional options
166
- let searchParams = new URLSearchParams(window.location.search);
190
+ let searchParams = new URLSearchParams(address.search);
167
191
  searchParams.forEach((value, key) => {
168
192
  result.options[key] = value;
169
193
  });
@@ -187,8 +211,10 @@ export class AppRouter {
187
211
  }
188
212
  }
189
213
 
214
+ /** @returns {Promise<void>} */
190
215
  static async notify() {
191
216
  if (!this.#isBrowser) return;
217
+ let version = ++this.#navigationVersion;
192
218
  let routeBase = this.readAddressBar();
193
219
  let routeScheme = this.appMap[routeBase.route];
194
220
 
@@ -196,19 +222,17 @@ export class AppRouter {
196
222
  // Path mode: null = no pattern matched = 404
197
223
  // Query mode: null = empty URL = go to default
198
224
  if (this.#usePathMode && this.errorRoute) {
199
- this.navigate(this.errorRoute);
225
+ return this.navigate(this.errorRoute);
200
226
  } else if (this.defaultRoute) {
201
- this.navigate(this.defaultRoute);
227
+ return this.navigate(this.defaultRoute);
202
228
  } else {
203
229
  this.#print('No route matched and no default/error route configured.');
204
230
  }
205
231
  return;
206
232
  } else if (!routeScheme && this.errorRoute) {
207
- this.navigate(this.errorRoute);
208
- return;
233
+ return this.navigate(this.errorRoute);
209
234
  } else if (!routeScheme && this.defaultRoute) {
210
- this.navigate(this.defaultRoute);
211
- return;
235
+ return this.navigate(this.defaultRoute);
212
236
  } else if (!routeScheme) {
213
237
  this.#print(`Route "${routeBase.route}" not found...`);
214
238
  return;
@@ -217,10 +241,10 @@ export class AppRouter {
217
241
  // Run guards
218
242
  if (this.#guards.length) {
219
243
  let guardResult = await this.#runGuards(routeBase);
244
+ if (version !== this.#navigationVersion) return;
220
245
  if (guardResult === false) return;
221
246
  if (typeof guardResult === 'string') {
222
- this.navigate(guardResult);
223
- return;
247
+ return this.navigate(guardResult);
224
248
  }
225
249
  }
226
250
 
@@ -228,11 +252,13 @@ export class AppRouter {
228
252
  if (routeScheme.load && !routeScheme.__loaded) {
229
253
  try {
230
254
  await routeScheme.load();
255
+ if (version !== this.#navigationVersion) return;
231
256
  routeScheme.__loaded = true;
232
257
  } catch (err) {
258
+ if (version !== this.#navigationVersion) return;
233
259
  this.#print(`Failed to load route "${routeBase.route}": ${err}`);
234
260
  if (this.errorRoute) {
235
- this.navigate(this.errorRoute);
261
+ return this.navigate(this.errorRoute);
236
262
  }
237
263
  return;
238
264
  }
@@ -272,6 +298,10 @@ export class AppRouter {
272
298
  return;
273
299
  }
274
300
 
301
+ // Path substitution consumes keys; caller-owned data must remain unchanged.
302
+ options = {
303
+ ...options,
304
+ };
275
305
  let url;
276
306
  if (this.#usePathMode && routeScheme.pattern) {
277
307
  url = routeScheme.pattern.replace(/:([^/]+)/g, (_, key) => {
@@ -287,12 +317,12 @@ export class AppRouter {
287
317
  ).join('&');
288
318
  }
289
319
  } else {
290
- url = '?' + route;
320
+ url = '?' + encodeURIComponent(route);
291
321
  for (let prop in options) {
292
322
  if (options[prop] === true) {
293
- url += this.separator + prop;
323
+ url += this.separator + encodeURIComponent(prop);
294
324
  } else {
295
- url += this.separator + prop + '=' + `${options[prop]}`;
325
+ url += this.separator + encodeURIComponent(prop) + '=' + encodeURIComponent(`${options[prop]}`);
296
326
  }
297
327
  }
298
328
  }
@@ -309,10 +339,11 @@ export class AppRouter {
309
339
  /**
310
340
  * @param {String} route
311
341
  * @param {Object<string, any>} [options]
342
+ * @returns {Promise<void>}
312
343
  */
313
344
  static navigate(route, options = {}) {
314
345
  this.reflect(route, options);
315
- this.notify();
346
+ return this.notify();
316
347
  }
317
348
 
318
349
  /**
@@ -345,27 +376,35 @@ export class AppRouter {
345
376
  /**
346
377
  * @param {String} ctxName
347
378
  * @param {Object<string, RouteDescriptor>} routingMap
379
+ * @param {{ signal?: AbortSignal }} [options]
348
380
  * @returns {PubSub}
349
381
  */
350
- static initRoutingCtx(ctxName, routingMap) {
382
+ static initRoutingCtx(ctxName, routingMap, options = {}) {
351
383
  this.setRoutingMap(routingMap);
352
- let routingCtx = PubSub.registerCtx(
353
- {
354
- route: null,
355
- options: null,
356
- title: null,
357
- },
358
- ctxName
359
- );
384
+ let initial = {
385
+ route: null,
386
+ options: null,
387
+ title: null,
388
+ };
389
+ let routingCtx = PubSub.getCtx(ctxName, false) || PubSub.registerCtx(initial, ctxName);
390
+ for (let [
391
+ key,
392
+ value,
393
+ ] of Object.entries(initial)) {
394
+ routingCtx.add(key, value);
395
+ }
360
396
  if (this.#isBrowser) {
397
+ if (options.signal?.aborted) return routingCtx;
361
398
  window.addEventListener(this.routingEventName, (/** @type {CustomEvent} */ e) => {
362
399
  routingCtx.multiPub({
363
400
  options: e.detail.options,
364
401
  title: this.#resolveTitle(e.detail.options?.title) || this.#resolveTitle(this.defaultTitle) || '',
365
402
  route: e.detail.route,
366
403
  });
404
+ }, {
405
+ signal: options.signal,
367
406
  });
368
- AppRouter.notify();
407
+ void AppRouter.notify();
369
408
  this.#initPopstateListener();
370
409
  } else if (this.defaultRoute) {
371
410
  let defaultDesc = this.appMap[this.defaultRoute];
package/core/PubSub.js CHANGED
@@ -124,12 +124,13 @@ export class PubSub {
124
124
  if (!PubSub.pendingDeps.has(ctxName)) {
125
125
  PubSub.pendingDeps.set(ctxName, []);
126
126
  }
127
- PubSub.pendingDeps.get(ctxName).push(() => {
127
+ let pending = () => {
128
+ if (!this.has(compProp)) { return; }
128
129
  let resolvedCtx = PubSub.getCtx(ctxName, false);
129
130
  if (!resolvedCtx) return;
130
131
  let sub = resolvedCtx.sub(propName, () => {
131
132
  this.#recalcComputed(compProp);
132
- }, false);
133
+ }, false, true);
133
134
  if (sub) {
134
135
  if (!this.#externalSubs[compProp]) {
135
136
  this.#externalSubs[compProp] = [];
@@ -137,13 +138,24 @@ export class PubSub {
137
138
  this.#externalSubs[compProp].push(sub);
138
139
  }
139
140
  this.#recalcComputed(compProp);
141
+ };
142
+ PubSub.pendingDeps.get(ctxName).push(pending);
143
+ this.#externalSubs[compProp].push({
144
+ remove: () => {
145
+ let callbacks = PubSub.pendingDeps.get(ctxName);
146
+ let index = callbacks?.indexOf(pending) ?? -1;
147
+ if (index !== -1) {
148
+ callbacks.splice(index, 1);
149
+ if (!callbacks.length) { PubSub.pendingDeps.delete(ctxName); }
150
+ }
151
+ },
140
152
  });
141
153
  continue;
142
154
  }
143
155
 
144
156
  let sub = extCtx.sub(propName, () => {
145
157
  this.#recalcComputed(compProp);
146
- }, false);
158
+ }, false, true);
147
159
 
148
160
  if (sub) {
149
161
  this.#externalSubs[compProp].push(sub);
@@ -252,7 +264,12 @@ export class PubSub {
252
264
  return;
253
265
  }
254
266
  this.store[prop] = val;
255
- this.notify(prop, val);
267
+ if (String(prop).startsWith(DICT.COMPUTED_PX) && this.callbackMap[prop]) {
268
+ if (this.__computedMap) { delete this.__computedMap[prop]; }
269
+ this.read(prop);
270
+ } else {
271
+ this.notify(prop, val);
272
+ }
256
273
  globalThis[DICT.MCP_PUBSUB_CHANGED_KEY]?.(this, prop);
257
274
  }
258
275
 
@@ -274,7 +291,12 @@ export class PubSub {
274
291
  warnMsg(2, String(this.uid || 'local'), String(prop), typeof this.store[prop], typeof val, JSON.stringify(this.store[prop]), JSON.stringify(val));
275
292
  }
276
293
  this.store[prop] = val;
277
- this.notify(prop, val);
294
+ if (String(prop).startsWith(DICT.COMPUTED_PX) && this.callbackMap[prop]) {
295
+ if (this.__computedMap) { delete this.__computedMap[prop]; }
296
+ this.read(prop);
297
+ } else {
298
+ this.notify(prop, val);
299
+ }
278
300
  globalThis[DICT.MCP_PUBSUB_CHANGED_KEY]?.(this, prop);
279
301
  }
280
302
 
@@ -309,6 +331,13 @@ export class PubSub {
309
331
  return;
310
332
  }
311
333
  delete this.store[prop];
334
+ if (String(prop).startsWith(DICT.COMPUTED_PX)) {
335
+ delete this.__computedMap?.[prop];
336
+ let name = String(prop);
337
+ delete this.#localDeps[name];
338
+ this.#externalSubs[name]?.forEach((subscription) => subscription.remove());
339
+ delete this.#externalSubs[name];
340
+ }
312
341
  this.notify(prop, null);
313
342
  globalThis[DICT.MCP_PUBSUB_CHANGED_KEY]?.(this, prop);
314
343
  }
@@ -324,7 +353,8 @@ export class PubSub {
324
353
  this.callbackMap[prop].forEach((callback) => {
325
354
  callback(val);
326
355
  });
327
- if (isComputed) {
356
+ if (isComputed && this.has(String(prop))) {
357
+ this.__computedMap ??= {};
328
358
  this.__computedMap[prop] = val;
329
359
  }
330
360
  }
@@ -339,9 +369,10 @@ export class PubSub {
339
369
  * @param {keyof T} prop
340
370
  * @param {(val: unknown) => void} callback
341
371
  * @param {Boolean} [init]
372
+ * @param {Boolean} [wait] Subscribe before the key is registered.
342
373
  */
343
- sub(prop, callback, init = true) {
344
- if (!this.#storeIsProxy && !(prop in this.store)) {
374
+ sub(prop, callback, init = true, wait = false) {
375
+ if (!wait && !this.#storeIsProxy && !(prop in this.store)) {
345
376
  PubSub.#warn('subscribe', prop);
346
377
  return null;
347
378
  }
@@ -349,13 +380,13 @@ export class PubSub {
349
380
  this.callbackMap[prop] = new Set();
350
381
  }
351
382
  this.callbackMap[prop].add(callback);
352
- if (init) {
383
+ if (init && (this.#storeIsProxy || prop in this.store)) {
353
384
  callback(this.read(prop));
354
385
  }
355
386
  return {
356
387
  remove: () => {
357
- this.callbackMap[prop].delete(callback);
358
- if (!this.callbackMap[prop].size) {
388
+ this.callbackMap[prop]?.delete(callback);
389
+ if (this.callbackMap[prop] && !this.callbackMap[prop].size) {
359
390
  delete this.callbackMap[prop];
360
391
  }
361
392
  },
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 */
@@ -478,6 +494,7 @@ export class Symbiote extends HTMLElement {
478
494
  if (this.#destroyTimeout) {
479
495
  window.clearTimeout(this.#destroyTimeout);
480
496
  }
497
+ this.#destroyed = false;
481
498
  if (!this.connectedOnce) {
482
499
  let ctxNameAttrVal = this.getAttribute(DICT.CTX_NAME_ATTR)?.trim();
483
500
  if (ctxNameAttrVal) {
@@ -596,20 +613,27 @@ export class Symbiote extends HTMLElement {
596
613
  if (this.#destroyTimeout) {
597
614
  window.clearTimeout(this.#destroyTimeout);
598
615
  }
599
- this.#destroyTimeout = window.setTimeout(() => {
600
- this.destroyCallback();
601
- if (this.attributeMutationObserver) {
602
- this.attributeMutationObserver.disconnect();
603
- }
604
- for (let sub of this.allSubs) {
605
- sub.remove();
606
- this.allSubs.delete(sub);
607
- }
608
- this.#localCtx = null;
609
- for (let proc of this.templateProcessors) {
610
- this.templateProcessors.delete(proc);
611
- }
612
- }, 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();
613
637
  }
614
638
 
615
639
  /**