@jqhtml/core 2.3.64 → 2.3.68

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 (40) hide show
  1. package/README.md +1 -1
  2. package/dist/component-cache.d.ts +18 -0
  3. package/dist/component-cache.d.ts.map +1 -1
  4. package/dist/component-events.d.ts +11 -6
  5. package/dist/component-events.d.ts.map +1 -1
  6. package/dist/component-name.d.ts +7 -0
  7. package/dist/component-name.d.ts.map +1 -1
  8. package/dist/component-queue.d.ts +23 -12
  9. package/dist/component-queue.d.ts.map +1 -1
  10. package/dist/component.d.ts +48 -0
  11. package/dist/component.d.ts.map +1 -1
  12. package/dist/data-proxy.d.ts +5 -2
  13. package/dist/data-proxy.d.ts.map +1 -1
  14. package/dist/debug-overlay/index.d.ts +35 -0
  15. package/dist/debug-overlay/index.d.ts.map +1 -0
  16. package/dist/escape.d.ts +13 -0
  17. package/dist/escape.d.ts.map +1 -0
  18. package/dist/index.cjs +1853 -1022
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.ts +18 -4
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +1849 -1022
  23. package/dist/index.js.map +1 -1
  24. package/dist/instruction-processor.d.ts.map +1 -1
  25. package/dist/jqhtml-core.esm.js +1850 -1023
  26. package/dist/jqhtml-core.esm.js.map +1 -1
  27. package/dist/jquery-plugin.d.ts.map +1 -1
  28. package/dist/lifecycle-manager.d.ts +0 -4
  29. package/dist/lifecycle-manager.d.ts.map +1 -1
  30. package/dist/load-coordinator.d.ts +18 -9
  31. package/dist/load-coordinator.d.ts.map +1 -1
  32. package/dist/local-storage.d.ts +41 -8
  33. package/dist/local-storage.d.ts.map +1 -1
  34. package/dist/preload-data.d.ts +8 -0
  35. package/dist/preload-data.d.ts.map +1 -1
  36. package/dist/value-printers.d.ts +47 -0
  37. package/dist/value-printers.d.ts.map +1 -0
  38. package/package.json +2 -1
  39. package/dist/template-renderer.d.ts +0 -22
  40. package/dist/template-renderer.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -1,3 +1,194 @@
1
+ /**
2
+ * JQHTML Debug Module
3
+ *
4
+ * Provides comprehensive debugging capabilities for JQHTML components
5
+ */
6
+ // Global debug state
7
+ let performanceMetrics = new Map();
8
+ /**
9
+ * Development warning helper
10
+ * Warnings are suppressed in production builds or when JQHTML_SUPPRESS_WARNINGS is set
11
+ */
12
+ function devWarn(message) {
13
+ // Check if warnings are suppressed
14
+ if (typeof window !== 'undefined' && window.JQHTML_SUPPRESS_WARNINGS) {
15
+ return;
16
+ }
17
+ // Check if in production mode
18
+ if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'production') {
19
+ return;
20
+ }
21
+ console.warn(`[JQHTML Dev Warning] ${message}`);
22
+ }
23
+ // Get global jqhtml object
24
+ function getJqhtml() {
25
+ if (typeof window !== 'undefined' && window.jqhtml) {
26
+ return window.jqhtml;
27
+ }
28
+ // Fallback: try to get from global if available
29
+ if (typeof globalThis !== 'undefined' && globalThis.jqhtml) {
30
+ return globalThis.jqhtml;
31
+ }
32
+ throw new Error('FATAL: window.jqhtml is not defined. The JQHTML runtime must be loaded before using debug features. ' +
33
+ 'Import and initialize @jqhtml/core before attempting to use debug functionality.');
34
+ }
35
+ // Visual flash effect
36
+ function flashComponent(component, eventType) {
37
+ const jqhtml = getJqhtml();
38
+ if (!jqhtml?.debug?.flashComponents)
39
+ return;
40
+ const duration = jqhtml.debug.flashDuration || 500;
41
+ const colors = jqhtml.debug.flashColors || {};
42
+ const color = colors[eventType] || (eventType === 'create' ? '#3498db' :
43
+ eventType === 'render' ? '#27ae60' :
44
+ '#9b59b6');
45
+ // Store original border
46
+ const originalBorder = component.$.css('border');
47
+ // Apply flash border
48
+ component.$.css({
49
+ 'border': `2px solid ${color}`,
50
+ 'transition': `border ${duration}ms ease-out`
51
+ });
52
+ // Remove after duration
53
+ setTimeout(() => {
54
+ component.$.css('border', originalBorder || '');
55
+ }, duration);
56
+ }
57
+ // Log lifecycle event
58
+ function logLifecycle(component, phase, status) {
59
+ const jqhtml = getJqhtml();
60
+ if (!jqhtml?.debug)
61
+ return;
62
+ const shouldLog = jqhtml.debug.logFullLifecycle ||
63
+ (jqhtml.debug.logCreationReady && (phase === 'create' || phase === 'ready'));
64
+ if (!shouldLog)
65
+ return;
66
+ const componentName = component.constructor.name;
67
+ const timestamp = new Date().toISOString();
68
+ const prefix = `[JQHTML ${timestamp}]`;
69
+ if (status === 'start') {
70
+ console.log(`${prefix} ${componentName}#${component._cid} → ${phase} starting...`);
71
+ // Start performance tracking
72
+ if (jqhtml.debug.profilePerformance) {
73
+ performanceMetrics.set(`${component._cid}_${phase}`, Date.now());
74
+ }
75
+ }
76
+ else {
77
+ let message = `${prefix} ${componentName}#${component._cid} ✓ ${phase} complete`;
78
+ // Add performance data
79
+ if (jqhtml.debug.profilePerformance) {
80
+ const startTime = performanceMetrics.get(`${component._cid}_${phase}`);
81
+ if (startTime) {
82
+ const duration = Date.now() - startTime;
83
+ message += ` (${duration}ms)`;
84
+ // Highlight slow renders
85
+ if (phase === 'render' && jqhtml.debug.highlightSlowRenders &&
86
+ duration > jqhtml.debug.highlightSlowRenders) {
87
+ console.warn(`${prefix} SLOW RENDER: ${componentName}#${component._cid} took ${duration}ms`);
88
+ component.$.css('outline', '2px dashed red');
89
+ }
90
+ }
91
+ }
92
+ console.log(message);
93
+ // Visual feedback
94
+ if (jqhtml.debug.flashComponents && (phase === 'create' || phase === 'render' || phase === 'ready')) {
95
+ flashComponent(component, phase);
96
+ }
97
+ }
98
+ // Update component tree if enabled
99
+ if (jqhtml.debug.showComponentTree) {
100
+ updateComponentTree();
101
+ }
102
+ }
103
+ // Apply delays based on lifecycle phase
104
+ function applyDebugDelay(phase) {
105
+ const jqhtml = getJqhtml();
106
+ if (!jqhtml?.debug)
107
+ return;
108
+ let delayMs = 0;
109
+ switch (phase) {
110
+ case 'component':
111
+ delayMs = jqhtml.debug.delayAfterComponent || 0;
112
+ break;
113
+ case 'render':
114
+ delayMs = jqhtml.debug.delayAfterRender || 0;
115
+ break;
116
+ case 'rerender':
117
+ delayMs = jqhtml.debug.delayAfterRerender || 0;
118
+ break;
119
+ }
120
+ if (delayMs > 0) {
121
+ console.log(`[JQHTML Debug] Applying ${delayMs}ms delay after ${phase}`);
122
+ }
123
+ }
124
+ // Log instruction processing
125
+ function logInstruction(type, data) {
126
+ const jqhtml = getJqhtml();
127
+ if (!jqhtml?.debug?.logInstructionProcessing)
128
+ return;
129
+ console.log(`[JQHTML Instruction] ${type}:`, data);
130
+ }
131
+ // Log data changes
132
+ function logDataChange(component, property, oldValue, newValue) {
133
+ const jqhtml = getJqhtml();
134
+ if (!jqhtml?.debug?.traceDataFlow)
135
+ return;
136
+ console.log(`[JQHTML Data] ${component.constructor.name}#${component._cid}.data.${property}:`, { old: oldValue, new: newValue });
137
+ }
138
+ // Update component tree visualization
139
+ function updateComponentTree() {
140
+ // This would update a debug panel if implemented
141
+ // For now, just log the tree structure periodically
142
+ console.log('[JQHTML Tree] Component hierarchy updated');
143
+ }
144
+ // Router dispatch logging
145
+ function logDispatch(url, route, params, verbose = false) {
146
+ const jqhtml = getJqhtml();
147
+ if (!jqhtml?.debug)
148
+ return;
149
+ const shouldLog = jqhtml.debug.logDispatch || jqhtml.debug.logDispatchVerbose;
150
+ if (!shouldLog)
151
+ return;
152
+ const isVerbose = jqhtml.debug.logDispatchVerbose || verbose;
153
+ if (isVerbose) {
154
+ console.group(`[JQHTML Router] Dispatching: ${url}`);
155
+ console.log('Matched route:', route);
156
+ console.log('Extracted params:', params);
157
+ console.log('Route component:', route.component);
158
+ console.log('Route layout:', route.layout);
159
+ console.log('Route meta:', route.meta);
160
+ console.groupEnd();
161
+ }
162
+ else {
163
+ console.log(`[JQHTML Router] ${url} → ${route.component} (params: ${JSON.stringify(params)})`);
164
+ }
165
+ }
166
+ // Check if sequential processing is enabled
167
+ function isSequentialProcessing() {
168
+ const jqhtml = getJqhtml();
169
+ return jqhtml?.debug?.sequentialProcessing || false;
170
+ }
171
+ // Error handling with break on error
172
+ function handleComponentError(component, phase, error) {
173
+ const jqhtml = getJqhtml();
174
+ console.error(`[JQHTML Error] ${component.constructor.name}#${component._cid} failed in ${phase}:`, error);
175
+ if (jqhtml?.debug?.breakOnError) {
176
+ debugger; // This will pause execution in dev tools
177
+ }
178
+ }
179
+ // Additional debug suggestions that could be implemented:
180
+ //
181
+ // 1. Component Inspector - Click on any component to see its data/args/state
182
+ // 2. Time Travel Debugging - Record state changes and replay them
183
+ // 3. Network Request Tracking - Log all AJAX calls made during load()
184
+ // 4. Memory Leak Detection - Track component creation/destruction
185
+ // 5. Template Compilation Debugging - Show compiled template functions
186
+ // 6. Event Flow Visualization - Show event bubbling through components
187
+ // 7. Dependency Graph - Show which components depend on which data
188
+ // 8. Hot Reload Support - Reload components without losing state
189
+ // 9. Performance Budgets - Warn when components exceed size/time limits
190
+ // 10. Accessibility Auditing - Check for missing ARIA attributes
191
+
1
192
  /**
2
193
  * JQHTML v2 Lifecycle Manager
3
194
  *
@@ -46,8 +237,9 @@ class LifecycleManager {
46
237
  // Check if stopped during create
47
238
  if (component._stopped)
48
239
  return;
49
- // Trigger create event
50
- component.trigger('create');
240
+ // NOTE: no trigger('create') here. component.create() already fires it exactly
241
+ // once - its `_ready_state >= 1` guard makes a second create() a no-op, so this
242
+ // duplicate trigger only ever double-fired the event for subscribers.
51
243
  // Check for lifecycle truncation flags
52
244
  const load_only = component._load_only;
53
245
  const load_render_only = component._load_render_only;
@@ -173,8 +365,30 @@ class LifecycleManager {
173
365
  return;
174
366
  }
175
367
  catch (error) {
176
- console.error(`Error booting component ${component.component_name()}:`, error);
177
- throw error;
368
+ // A boot that throws must leave a STOPPED component behind, not a half-booted
369
+ // one. The component never reaches 'ready', so an ancestor parked in
370
+ // _wait_for_children_ready() can only be released by the child's 'stop' event;
371
+ // nothing else stops it, so the whole subtree above it would hang forever.
372
+ //
373
+ // And the throw must stop here: _boot() is called unawaited by
374
+ // instruction-processor.initialize_component() and by the jQuery plugin, so a
375
+ // rethrow surfaces as an unhandled promise rejection instead of an error report.
376
+ // The error object stays a console.error argument so callers (and tests) that
377
+ // grep the console for the thrown message still see it.
378
+ try {
379
+ handleComponentError(component, 'boot', error);
380
+ }
381
+ catch {
382
+ // handleComponentError needs the global jqhtml object and throws without it.
383
+ // Never lose the original error to a failure in the reporting path.
384
+ console.error(`Error booting component ${component.component_name()}:`, error);
385
+ }
386
+ try {
387
+ component._stop();
388
+ }
389
+ catch (stop_error) {
390
+ console.error(`[JQHTML] on_stop() threw while unwinding a failed boot:`, stop_error);
391
+ }
178
392
  }
179
393
  }
180
394
  /**
@@ -183,20 +397,6 @@ class LifecycleManager {
183
397
  unregister_component(component) {
184
398
  this.active_components.delete(component);
185
399
  }
186
- /**
187
- * Wait for all active components to reach ready state
188
- */
189
- async wait_for_ready() {
190
- const ready_promises = [];
191
- for (const component of this.active_components) {
192
- if (component._ready_state < 4) {
193
- ready_promises.push(new Promise((resolve) => {
194
- component.on('ready', () => resolve());
195
- }));
196
- }
197
- }
198
- await Promise.all(ready_promises);
199
- }
200
400
  }
201
401
 
202
402
  /**
@@ -213,6 +413,23 @@ const COMPONENT_NAME_RULE = 'must start with a capital letter, optionally preced
213
413
  function is_component_name(name) {
214
414
  return COMPONENT_NAME_PATTERN.test(name);
215
415
  }
416
+ /**
417
+ * The render-time check behind <{expression}>: the expression must evaluate
418
+ * to a component name string that a literal tag would accept - no more, no
419
+ * less. A valid name that names nothing renders the ordinary placeholder
420
+ * component, exactly as an undefined literal tag does.
421
+ */
422
+ function dynamic_component_name(value) {
423
+ if (typeof value !== 'string' || value === '') {
424
+ const shown = value === '' ? 'an empty string' : typeof value === 'string' ? `'${value}'` : `${value === null ? 'null' : typeof value}`;
425
+ throw new Error(`[JQHTML] Dynamic component tag <{...}> evaluated to ${shown}; expected a non-empty component name string`);
426
+ }
427
+ if (!is_component_name(value)) {
428
+ throw new Error(`[JQHTML] Dynamic component tag <{...}> evaluated to '${value}', which is not a valid component name: ` +
429
+ `a component name ${COMPONENT_NAME_RULE}, then letters, digits and underscores`);
430
+ }
431
+ return value;
432
+ }
216
433
 
217
434
  /**
218
435
  * JQHTML v2 Component Registry
@@ -642,30 +859,32 @@ function process_instructions(instructions, target, context, slots) {
642
859
  // Set innerHTML once - this is the performance win
643
860
  // Use native innerHTML for better performance
644
861
  target[0].innerHTML = html.join('');
645
- // Second pass: initialize special attributes and events
646
- for (const [tid, tagData] of Object.entries(tagElements)) {
647
- // Use native querySelector for better performance
648
- const el = target[0].querySelector(`[data-tid="${tid}"]`);
649
- if (el) {
650
- const element = $(el);
651
- el.removeAttribute('data-tid');
862
+ // Second pass: initialize special attributes and events.
863
+ // One querySelectorAll over the freshly injected subtree, in document
864
+ // order, rather than one querySelector per tracked element: a scan per
865
+ // element made this pass quadratic in the size of the template. Child
866
+ // components have not rendered yet (their elements are empty), so every
867
+ // data-tid here belongs to this level.
868
+ const root = target[0];
869
+ for (const el of Array.from(root.querySelectorAll('[data-tid]'))) {
870
+ const tagData = tagElements[el.getAttribute('data-tid')];
871
+ el.removeAttribute('data-tid');
872
+ if (tagData) {
652
873
  // Bind to the component whose template wrote this element, which for
653
874
  // spliced content is not the component being rendered.
654
- apply_attributes(element, tagData.attrs, tagData.context);
875
+ apply_attributes($(el), tagData.attrs, tagData.context);
655
876
  }
656
877
  }
657
878
  // Third pass: initialize and boot components in parallel
658
879
  // Like v1, all sibling components at this level boot simultaneously
659
880
  // DO NOT await - let children boot in background while parent continues
660
- for (const [cid, compData] of Object.entries(components)) {
661
- // Use native querySelector for better performance
662
- const el = target[0].querySelector(`[data-cid="${cid}"]`);
663
- if (el) {
664
- const element = $(el);
665
- el.removeAttribute('data-cid');
881
+ for (const el of Array.from(root.querySelectorAll('[data-cid]'))) {
882
+ const compData = components[el.getAttribute('data-cid')];
883
+ el.removeAttribute('data-cid');
884
+ if (compData) {
666
885
  // Boot this component (which will render and boot its children recursively)
667
886
  // Fire and forget - don't wait for boot to complete
668
- initialize_component(element, compData);
887
+ initialize_component($(el), compData);
669
888
  }
670
889
  }
671
890
  }
@@ -730,21 +949,13 @@ function process_tag_to_html(instruction, html, tagElements, components, context
730
949
  if (!key.startsWith('$') && !key.startsWith('on') && !key.startsWith('@') &&
731
950
  !key.startsWith('data-bind-') && !key.startsWith('data-__-on-') &&
732
951
  (typeof value === 'string' || typeof value === 'number')) {
733
- if (key === 'id' && tid) {
734
- // Special handling for id attribute - scope to parent component's _cid
735
- // This is for regular id="foo" attributes that need scoping (rare case)
736
- // Most scoping happens via $sid attribute which becomes data-sid
737
- // Don't double-scope if already scoped (contains :)
738
- if (typeof value === 'string' && value.includes(':')) {
739
- html.push(` id="${value}"`);
740
- }
741
- else {
742
- html.push(` id="${value}:${context._cid}"`);
743
- }
744
- }
745
- else {
746
- html.push(` ${key}="${value}"`);
747
- }
952
+ // A hand-written `id` is emitted exactly as written - including on a tracked
953
+ // element. It used to be rewritten to `<value>:<cid>` whenever the element
954
+ // happened to carry some OTHER tracked attribute, so `<label id="x" @click=…>`
955
+ // and `<label id="x">` disagreed. Per-instance ids are what $sid is for, and
956
+ // the compiler emits those already scoped (codegen.ts), so they arrive here as
957
+ // ordinary values and pass straight through.
958
+ html.push(` ${key}="${escape_attribute(value)}"`);
748
959
  }
749
960
  }
750
961
  // Close opening tag
@@ -755,6 +966,16 @@ function process_tag_to_html(instruction, html, tagElements, components, context
755
966
  html.push('>');
756
967
  }
757
968
  }
969
+ /**
970
+ * A double quote inside an attribute value would end the attribute in the
971
+ * HTML string this pass builds; an interpolated value can never legitimately
972
+ * do that, so it is encoded. Nothing else is touched - the value is otherwise
973
+ * emitted exactly as the template produced it.
974
+ */
975
+ function escape_attribute(value) {
976
+ const s = typeof value === 'string' ? value : String(value);
977
+ return s.indexOf('"') === -1 ? s : s.replace(/"/g, '&quot;');
978
+ }
758
979
  /**
759
980
  * Process a component instruction to HTML
760
981
  */
@@ -1111,13 +1332,10 @@ async function initialize_component(element, compData) {
1111
1332
  if (slots) {
1112
1333
  options._slots = slots;
1113
1334
  }
1114
- // Always pass _component_name when component name differs from class name
1115
- // This happens when:
1116
- // 1. No class registered for component (uses Jqhtml_Component)
1117
- // 2. Class inherited from parent via extends chain (uses parent class but child template)
1118
- if (ComponentClass.name !== name) {
1119
- options._component_name = name;
1120
- }
1335
+ // Always pass the invocation name: it is what component_name() reports, it
1336
+ // selects the template when the class is inherited via an extends chain or
1337
+ // is the bare Jqhtml_Component, and it is the class the element carries.
1338
+ options._component_name = name;
1121
1339
  // Pass lifecycle truncation flags via options (not DOM attributes, since _ prefix is filtered).
1122
1340
  // Accept both the plain key (cascaded/programmatic) and the '$'-prefixed key (template-authored).
1123
1341
  if (props._load_only === true || props['$_load_only'] === true) {
@@ -1133,210 +1351,19 @@ async function initialize_component(element, compData) {
1133
1351
  // Boot the component immediately - this runs its full lifecycle
1134
1352
  await instance._boot();
1135
1353
  }
1136
- /**
1137
- * Utility to extract slots from instructions
1138
- */
1139
- function extract_slots(instructions) {
1140
- const slots = {};
1141
- for (const instruction of instructions) {
1142
- if (typeof instruction === 'object' && 'slot' in instruction) {
1143
- const [name] = instruction.slot;
1144
- slots[name] = instruction;
1145
- }
1146
- }
1147
- return slots;
1148
- }
1149
-
1150
- /**
1151
- * JQHTML Debug Module
1152
- *
1153
- * Provides comprehensive debugging capabilities for JQHTML components
1154
- */
1155
- // Global debug state
1156
- let performanceMetrics = new Map();
1157
- /**
1158
- * Development warning helper
1159
- * Warnings are suppressed in production builds or when JQHTML_SUPPRESS_WARNINGS is set
1160
- */
1161
- function devWarn(message) {
1162
- // Check if warnings are suppressed
1163
- if (typeof window !== 'undefined' && window.JQHTML_SUPPRESS_WARNINGS) {
1164
- return;
1165
- }
1166
- // Check if in production mode
1167
- if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'production') {
1168
- return;
1169
- }
1170
- console.warn(`[JQHTML Dev Warning] ${message}`);
1171
- }
1172
- // Get global jqhtml object
1173
- function getJqhtml() {
1174
- if (typeof window !== 'undefined' && window.jqhtml) {
1175
- return window.jqhtml;
1176
- }
1177
- // Fallback: try to get from global if available
1178
- if (typeof globalThis !== 'undefined' && globalThis.jqhtml) {
1179
- return globalThis.jqhtml;
1180
- }
1181
- throw new Error('FATAL: window.jqhtml is not defined. The JQHTML runtime must be loaded before using debug features. ' +
1182
- 'Import and initialize @jqhtml/core before attempting to use debug functionality.');
1183
- }
1184
- // Visual flash effect
1185
- function flashComponent(component, eventType) {
1186
- const jqhtml = getJqhtml();
1187
- if (!jqhtml?.debug?.flashComponents)
1188
- return;
1189
- const duration = jqhtml.debug.flashDuration || 500;
1190
- const colors = jqhtml.debug.flashColors || {};
1191
- const color = colors[eventType] || (eventType === 'create' ? '#3498db' :
1192
- eventType === 'render' ? '#27ae60' :
1193
- '#9b59b6');
1194
- // Store original border
1195
- const originalBorder = component.$.css('border');
1196
- // Apply flash border
1197
- component.$.css({
1198
- 'border': `2px solid ${color}`,
1199
- 'transition': `border ${duration}ms ease-out`
1200
- });
1201
- // Remove after duration
1202
- setTimeout(() => {
1203
- component.$.css('border', originalBorder || '');
1204
- }, duration);
1205
- }
1206
- // Log lifecycle event
1207
- function logLifecycle(component, phase, status) {
1208
- const jqhtml = getJqhtml();
1209
- if (!jqhtml?.debug)
1210
- return;
1211
- const shouldLog = jqhtml.debug.logFullLifecycle ||
1212
- (jqhtml.debug.logCreationReady && (phase === 'create' || phase === 'ready'));
1213
- if (!shouldLog)
1214
- return;
1215
- const componentName = component.constructor.name;
1216
- const timestamp = new Date().toISOString();
1217
- const prefix = `[JQHTML ${timestamp}]`;
1218
- if (status === 'start') {
1219
- console.log(`${prefix} ${componentName}#${component._cid} → ${phase} starting...`);
1220
- // Start performance tracking
1221
- if (jqhtml.debug.profilePerformance) {
1222
- performanceMetrics.set(`${component._cid}_${phase}`, Date.now());
1223
- }
1224
- }
1225
- else {
1226
- let message = `${prefix} ${componentName}#${component._cid} ✓ ${phase} complete`;
1227
- // Add performance data
1228
- if (jqhtml.debug.profilePerformance) {
1229
- const startTime = performanceMetrics.get(`${component._cid}_${phase}`);
1230
- if (startTime) {
1231
- const duration = Date.now() - startTime;
1232
- message += ` (${duration}ms)`;
1233
- // Highlight slow renders
1234
- if (phase === 'render' && jqhtml.debug.highlightSlowRenders &&
1235
- duration > jqhtml.debug.highlightSlowRenders) {
1236
- console.warn(`${prefix} SLOW RENDER: ${componentName}#${component._cid} took ${duration}ms`);
1237
- component.$.css('outline', '2px dashed red');
1238
- }
1239
- }
1240
- }
1241
- console.log(message);
1242
- // Visual feedback
1243
- if (jqhtml.debug.flashComponents && (phase === 'create' || phase === 'render' || phase === 'ready')) {
1244
- flashComponent(component, phase);
1245
- }
1246
- }
1247
- // Update component tree if enabled
1248
- if (jqhtml.debug.showComponentTree) {
1249
- updateComponentTree();
1250
- }
1251
- }
1252
- // Apply delays based on lifecycle phase
1253
- function applyDebugDelay(phase) {
1254
- const jqhtml = getJqhtml();
1255
- if (!jqhtml?.debug)
1256
- return;
1257
- let delayMs = 0;
1258
- switch (phase) {
1259
- case 'component':
1260
- delayMs = jqhtml.debug.delayAfterComponent || 0;
1261
- break;
1262
- case 'render':
1263
- delayMs = jqhtml.debug.delayAfterRender || 0;
1264
- break;
1265
- case 'rerender':
1266
- delayMs = jqhtml.debug.delayAfterRerender || 0;
1267
- break;
1268
- }
1269
- if (delayMs > 0) {
1270
- console.log(`[JQHTML Debug] Applying ${delayMs}ms delay after ${phase}`);
1271
- }
1272
- }
1273
- // Log instruction processing
1274
- function logInstruction(type, data) {
1275
- const jqhtml = getJqhtml();
1276
- if (!jqhtml?.debug?.logInstructionProcessing)
1277
- return;
1278
- console.log(`[JQHTML Instruction] ${type}:`, data);
1279
- }
1280
- // Log data changes
1281
- function logDataChange(component, property, oldValue, newValue) {
1282
- const jqhtml = getJqhtml();
1283
- if (!jqhtml?.debug?.traceDataFlow)
1284
- return;
1285
- console.log(`[JQHTML Data] ${component.constructor.name}#${component._cid}.data.${property}:`, { old: oldValue, new: newValue });
1286
- }
1287
- // Update component tree visualization
1288
- function updateComponentTree() {
1289
- // This would update a debug panel if implemented
1290
- // For now, just log the tree structure periodically
1291
- console.log('[JQHTML Tree] Component hierarchy updated');
1292
- }
1293
- // Router dispatch logging
1294
- function logDispatch(url, route, params, verbose = false) {
1295
- const jqhtml = getJqhtml();
1296
- if (!jqhtml?.debug)
1297
- return;
1298
- const shouldLog = jqhtml.debug.logDispatch || jqhtml.debug.logDispatchVerbose;
1299
- if (!shouldLog)
1300
- return;
1301
- const isVerbose = jqhtml.debug.logDispatchVerbose || verbose;
1302
- if (isVerbose) {
1303
- console.group(`[JQHTML Router] Dispatching: ${url}`);
1304
- console.log('Matched route:', route);
1305
- console.log('Extracted params:', params);
1306
- console.log('Route component:', route.component);
1307
- console.log('Route layout:', route.layout);
1308
- console.log('Route meta:', route.meta);
1309
- console.groupEnd();
1310
- }
1311
- else {
1312
- console.log(`[JQHTML Router] ${url} → ${route.component} (params: ${JSON.stringify(params)})`);
1313
- }
1314
- }
1315
- // Check if sequential processing is enabled
1316
- function isSequentialProcessing() {
1317
- const jqhtml = getJqhtml();
1318
- return jqhtml?.debug?.sequentialProcessing || false;
1319
- }
1320
- // Error handling with break on error
1321
- function handleComponentError(component, phase, error) {
1322
- const jqhtml = getJqhtml();
1323
- console.error(`[JQHTML Error] ${component.constructor.name}#${component._cid} failed in ${phase}:`, error);
1324
- if (jqhtml?.debug?.breakOnError) {
1325
- debugger; // This will pause execution in dev tools
1354
+ /**
1355
+ * Utility to extract slots from instructions
1356
+ */
1357
+ function extract_slots(instructions) {
1358
+ const slots = {};
1359
+ for (const instruction of instructions) {
1360
+ if (typeof instruction === 'object' && 'slot' in instruction) {
1361
+ const [name] = instruction.slot;
1362
+ slots[name] = instruction;
1363
+ }
1326
1364
  }
1365
+ return slots;
1327
1366
  }
1328
- // Additional debug suggestions that could be implemented:
1329
- //
1330
- // 1. Component Inspector - Click on any component to see its data/args/state
1331
- // 2. Time Travel Debugging - Record state changes and replay them
1332
- // 3. Network Request Tracking - Log all AJAX calls made during load()
1333
- // 4. Memory Leak Detection - Track component creation/destruction
1334
- // 5. Template Compilation Debugging - Show compiled template functions
1335
- // 6. Event Flow Visualization - Show event bubbling through components
1336
- // 7. Dependency Graph - Show which components depend on which data
1337
- // 8. Hot Reload Support - Reload components without losing state
1338
- // 9. Performance Budgets - Warn when components exceed size/time limits
1339
- // 10. Accessibility Auditing - Check for missing ARIA attributes
1340
1367
 
1341
1368
  /**
1342
1369
  * JQHTML Cache Key Serializer
@@ -1605,15 +1632,12 @@ class Load_Coordinator {
1605
1632
  /**
1606
1633
  * Check if a component should execute on_load() or wait for existing request
1607
1634
  * Returns true if component should execute (is leader), false if should wait (is follower)
1635
+ *
1636
+ * @param key - The dedup key the caller captured for this load. Every coordinator
1637
+ * method takes it, because args may legally change during on_load()
1638
+ * and a recomputed key would address a different (or no) entry.
1608
1639
  */
1609
- static should_execute_on_load(component) {
1610
- const { key } = this.generate_invocation_key(component.component_name(), component.args);
1611
- // No identity means no coordination. Without this, every un-keyable component
1612
- // would share the single `null` registry entry and adopt an unrelated
1613
- // component's data - the worst failure this system can produce.
1614
- if (key === null) {
1615
- return true;
1616
- }
1640
+ static should_execute_on_load(component, key) {
1617
1641
  const entry = this._registry.get(key);
1618
1642
  if (!entry) {
1619
1643
  // No existing request - this component becomes the leader
@@ -1632,26 +1656,27 @@ class Load_Coordinator {
1632
1656
  * Register a leader component that will execute on_load()
1633
1657
  * Creates coordination entry and returns a function to call when data is ready
1634
1658
  *
1659
+ * @param key - The dedup key captured by the caller (see should_execute_on_load)
1635
1660
  * @returns A function that accepts the final data and completes coordination
1636
1661
  */
1637
- static register_leader(component, on_load_promise) {
1638
- const { key } = this.generate_invocation_key(component.component_name(), component.args);
1639
- // Un-keyable component: run alone, register nothing. See should_execute_on_load().
1640
- if (key === null) {
1641
- return () => { };
1642
- }
1643
- // Create a promise that we control - it resolves when complete_coordination is called
1662
+ static register_leader(component, key) {
1663
+ // Create a promise that we control - it settles when coordination completes or fails
1644
1664
  let resolve_promise;
1645
- const coordination_promise = new Promise((resolve) => {
1665
+ let reject_promise;
1666
+ const coordination_promise = new Promise((resolve, reject) => {
1646
1667
  resolve_promise = resolve;
1668
+ reject_promise = reject;
1647
1669
  });
1670
+ // A leader with no followers still has to be able to reject this promise on
1671
+ // error; without a handler that rejection surfaces as an unhandled rejection.
1672
+ coordination_promise.catch(() => { });
1648
1673
  const entry = {
1649
1674
  status: 'loading',
1650
- promise: coordination_promise, // Followers await THIS promise, not on_load_promise
1675
+ promise: coordination_promise, // Followers await THIS promise, not on_load's
1651
1676
  resolve_promise,
1677
+ reject_promise,
1652
1678
  leader_component: component,
1653
1679
  leader_data: null,
1654
- leader_error: null,
1655
1680
  waiting: []
1656
1681
  };
1657
1682
  this._registry.set(key, entry);
@@ -1660,10 +1685,9 @@ class Load_Coordinator {
1660
1685
  }
1661
1686
  /**
1662
1687
  * Get the coordination promise for a follower component
1663
- * Returns a promise that resolves when the leader completes
1688
+ * Returns a promise that resolves when the leader completes, or rejects if it failed
1664
1689
  */
1665
- static get_coordination_promise(component) {
1666
- const { key } = this.generate_invocation_key(component.component_name(), component.args);
1690
+ static get_coordination_promise(key) {
1667
1691
  const entry = this._registry.get(key);
1668
1692
  if (!entry || entry.status !== 'loading') {
1669
1693
  return null;
@@ -1675,7 +1699,7 @@ class Load_Coordinator {
1675
1699
  * Stores leader's data, marks entry as completed, and resolves the promise.
1676
1700
  * Followers retrieve the data themselves via get_leader_data().
1677
1701
  *
1678
- * @param key - The coordination key
1702
+ * @param key - The coordination key captured at registration
1679
1703
  * @param leader - The leader component
1680
1704
  * @param final_data - The final data after on_load and normalization
1681
1705
  * @private
@@ -1685,14 +1709,14 @@ class Load_Coordinator {
1685
1709
  if (!entry) {
1686
1710
  return;
1687
1711
  }
1688
- // Store the final data (already normalized by _apply_load_result)
1689
- // Deep clone to avoid sharing proxy objects between components
1712
+ // Stored as TEXT so each follower parses its own object graph - sharing one
1713
+ // decoded object would let one component's mutation reach every other.
1690
1714
  try {
1691
- entry.leader_data = JSON.parse(JSON.stringify(final_data));
1715
+ entry.leader_data = JSON.stringify(final_data);
1692
1716
  }
1693
1717
  catch (error) {
1694
- // If data can't be serialized, use direct reference (may have issues)
1695
- entry.leader_data = final_data;
1718
+ // Unserializable data cannot be shared; followers load independently.
1719
+ entry.leader_data = null;
1696
1720
  }
1697
1721
  entry.status = 'completed';
1698
1722
  if (window.jqhtml?.debug?.verbose) {
@@ -1700,22 +1724,22 @@ class Load_Coordinator {
1700
1724
  }
1701
1725
  // Resolve the promise - followers waiting on it will now wake up
1702
1726
  entry.resolve_promise();
1703
- // Note: We do NOT delete the entry here anymore.
1704
- // Followers need to retrieve the data after the promise resolves.
1705
- // Entry will be cleaned up when last follower retrieves data.
1727
+ // Nobody is waiting, so nothing will ever come back to collect the data.
1728
+ // Without this the registry grows once per distinct name+args, forever.
1729
+ if (entry.waiting.length === 0) {
1730
+ this._registry.delete(key);
1731
+ }
1706
1732
  }
1707
1733
  /**
1708
1734
  * Get leader's data for a follower component
1709
1735
  * Called by follower after coordination promise resolves
1710
- * Returns the data and cleans up if this is the last follower
1736
+ * Returns a freshly parsed copy and cleans up if this is the last follower
1737
+ *
1738
+ * @param key - The dedup key captured by the follower before it began waiting
1711
1739
  */
1712
- static get_leader_data(component) {
1713
- const { key } = this.generate_invocation_key(component.component_name(), component.args);
1714
- if (!key) {
1715
- return null;
1716
- }
1740
+ static get_leader_data(component, key) {
1717
1741
  const entry = this._registry.get(key);
1718
- if (!entry || entry.status !== 'completed') {
1742
+ if (!entry || entry.status !== 'completed' || entry.leader_data === null) {
1719
1743
  return null;
1720
1744
  }
1721
1745
  // Remove this follower from the waiting list
@@ -1723,6 +1747,8 @@ class Load_Coordinator {
1723
1747
  if (follower_index !== -1) {
1724
1748
  entry.waiting.splice(follower_index, 1);
1725
1749
  }
1750
+ // One parse per follower: each gets its OWN object, never a shared reference.
1751
+ const data = JSON.parse(entry.leader_data);
1726
1752
  if (window.jqhtml?.debug?.verbose) {
1727
1753
  console.log(`[Load Coordinator] Follower ${component._cid} retrieving data from leader ${entry.leader_component._cid}`, { key, remaining_followers: entry.waiting.length });
1728
1754
  }
@@ -1733,29 +1759,25 @@ class Load_Coordinator {
1733
1759
  console.log(`[Load Coordinator] Coordination complete for key: ${key}`, { registry_size: this._registry.size });
1734
1760
  }
1735
1761
  }
1736
- return entry.leader_data;
1762
+ return data;
1737
1763
  }
1738
1764
  /**
1739
1765
  * Handle leader on_load() error
1740
- * Propagates error to all followers and cleans up entry
1766
+ * Rejects every waiting follower and clears the entry so the next component retries
1767
+ *
1768
+ * @param key - The dedup key captured at registration
1741
1769
  */
1742
- static handle_leader_error(component, error) {
1743
- const { key } = this.generate_invocation_key(component.component_name(), component.args);
1770
+ static handle_leader_error(key, error) {
1744
1771
  const entry = this._registry.get(key);
1745
1772
  if (!entry) {
1746
1773
  return;
1747
1774
  }
1748
- entry.leader_error = error;
1749
1775
  entry.status = 'failed';
1750
- console.error(`[Load Coordinator] Leader ${component._cid} on_load() failed for key: ${key}`, error);
1751
- // Propagate error to all followers
1752
- // Note: Followers will handle errors the same way as if their own on_load() failed
1753
- // This is transparent to the developer
1754
- for (const follower of entry.waiting) {
1755
- console.error(`[Load Coordinator] Follower ${follower._cid} failed due to leader error`, error);
1756
- // The follower's lifecycle will handle the error naturally
1757
- // as the promise rejection will propagate
1758
- }
1776
+ console.error(`[Load Coordinator] Leader ${entry.leader_component._cid} on_load() failed for key: ${key}`, error);
1777
+ // Reject FIRST: followers are parked on this promise and their catch in _load()
1778
+ // propagates the failure exactly as if their own on_load() had thrown. Deleting
1779
+ // without rejecting left them awaiting a promise nobody could ever settle.
1780
+ entry.reject_promise(error);
1759
1781
  // Clear coordination entry so future requests can retry
1760
1782
  this._registry.delete(key);
1761
1783
  if (window.jqhtml?.debug?.verbose) {
@@ -1854,6 +1876,31 @@ Load_Coordinator._registry = new Map();
1854
1876
  * - Transient UI state (convenience, not required)
1855
1877
  *
1856
1878
  * @internal This class is not exposed in the public API
1879
+ *
1880
+ * ---------------------------------------------------------------------------
1881
+ * REPORTING WHAT WAS DROPPED
1882
+ *
1883
+ * `this.data` is always the serialized copy this file produces - in EVERY cache
1884
+ * mode, including 'none' (see component.ts `_apply_load_result`). Whatever the
1885
+ * serializer cannot express is therefore not merely missing from the cache, it
1886
+ * is missing from `this.data`, and an author needs to be told once rather than
1887
+ * discover it on the next cache hit.
1888
+ *
1889
+ * Two small optional parameters carry that:
1890
+ *
1891
+ * process_for_serialization(value, verbose, seen, path, collector?)
1892
+ * `collector(path, kind)` is invoked for every value that is dropped or
1893
+ * degraded. `path` is a dotted/bracketed path from the root the caller
1894
+ * named; `kind` is one of Strip_Kind. Paths are only BUILT when a
1895
+ * collector is present, so the no-collector path costs nothing.
1896
+ *
1897
+ * Jqhtml_Local_Storage.normalize_for_cache(value, component_name?)
1898
+ * With a component name, and only in development mode, each dropped path
1899
+ * prints exactly ONE console.warn for the life of the page (keyed
1900
+ * `${component_name}:${path}`, the same once-only shape as
1901
+ * warn_uncacheable_args in component-cache.ts). Production converts
1902
+ * silently. Neither ever throws.
1903
+ * ---------------------------------------------------------------------------
1857
1904
  */
1858
1905
  // ============================================================================
1859
1906
  // Class Registry for Serialization
@@ -1862,7 +1909,7 @@ Load_Coordinator._registry = new Map();
1862
1909
  const class_registry = Object.create(null);
1863
1910
  // Markers for serialized class instances (unique to avoid collisions with user data)
1864
1911
  // Replaced at build time by rollup (see rollup.config.js).
1865
- const CORE_VERSION = '2.3.64';
1912
+ const CORE_VERSION = '2.3.68';
1866
1913
  const CLASS_MARKER = '__jqhtml_class__';
1867
1914
  const PROPS_MARKER = '__jqhtml_props__';
1868
1915
  /**
@@ -1878,21 +1925,20 @@ function register_cache_class(klass) {
1878
1925
  }
1879
1926
  class_registry[klass.name] = klass;
1880
1927
  }
1881
- // ============================================================================
1882
- // Serialization (Object → String)
1883
- // ============================================================================
1884
1928
  /**
1885
1929
  * Serialize a value to JSON string, handling ES6 class instances recursively.
1886
1930
  * Returns null if serialization fails for any reason.
1887
1931
  *
1888
1932
  * @param value - The value to serialize
1889
1933
  * @param verbose - Whether to log warnings
1934
+ * @param path - Root path used when reporting drops (only used with a collector)
1935
+ * @param collector - Optional reporter, see the file header
1890
1936
  * @returns Serialized JSON string, or null if serialization failed
1891
1937
  */
1892
- function serialize_value(value, verbose) {
1938
+ function serialize_value(value, verbose, path = '', collector) {
1893
1939
  try {
1894
1940
  const seen = new WeakSet();
1895
- const processed = process_for_serialization(value, verbose, seen);
1941
+ const processed = process_for_serialization(value, verbose, seen, path, collector);
1896
1942
  if (processed === undefined) {
1897
1943
  // Serialization failed - undefined signals failure
1898
1944
  return null;
@@ -1908,14 +1954,23 @@ function serialize_value(value, verbose) {
1908
1954
  }
1909
1955
  /**
1910
1956
  * Recursively process a value for serialization.
1911
- * Returns undefined if serialization should fail (unserializable value encountered).
1957
+ *
1958
+ * Values the serializer cannot express are DROPPED, never passed through: the
1959
+ * result of this function is what becomes `this.data`, so letting a function or
1960
+ * a DOM node survive here would make `this.data` differ from what the cache can
1961
+ * ever return. A dropped property is omitted from an object and becomes `null`
1962
+ * in an array - JSON's own semantics for the same situation.
1963
+ *
1964
+ * Returns undefined for a value that has to be dropped.
1912
1965
  *
1913
1966
  * @param value - The value to process
1914
1967
  * @param verbose - Whether to log warnings
1915
1968
  * @param seen - WeakSet to detect circular references
1916
- * @returns Processed value ready for JSON.stringify, or undefined if failed
1969
+ * @param path - Dotted path of this value (only built when a collector is present)
1970
+ * @param collector - Optional reporter for dropped/degraded values
1971
+ * @returns Processed value ready for JSON.stringify, or undefined if dropped
1917
1972
  */
1918
- function process_for_serialization(value, verbose, seen) {
1973
+ function process_for_serialization(value, verbose, seen, path = '', collector) {
1919
1974
  // Handle null and undefined
1920
1975
  if (value === null) {
1921
1976
  return null;
@@ -1930,12 +1985,44 @@ function process_for_serialization(value, verbose, seen) {
1930
1985
  return value;
1931
1986
  }
1932
1987
  // bigint, symbol, function cannot be serialized
1988
+ if (typeof value === 'function') {
1989
+ collector?.(path, 'function');
1990
+ }
1991
+ else if (typeof value === 'symbol') {
1992
+ collector?.(path, 'symbol');
1993
+ }
1994
+ else if (typeof value === 'bigint') {
1995
+ collector?.(path, 'bigint');
1996
+ }
1933
1997
  if (verbose) {
1934
1998
  console.warn(`[JQHTML Cache] Cannot serialize ${typeof value} - value will be omitted`);
1935
1999
  }
1936
2000
  // Return undefined to omit this value (not fail entire serialization)
1937
2001
  return undefined;
1938
2002
  }
2003
+ // Live objects that only LOOK like data. Each is checked before anything
2004
+ // treats it as a bag of properties, because walking one produces a
2005
+ // meaningless husk (a jQuery object becomes {0: ..., length: 1}) instead of
2006
+ // the drop the author needs to hear about.
2007
+ if (typeof value.nodeType === 'number') {
2008
+ collector?.(path, 'dom-node');
2009
+ return undefined;
2010
+ }
2011
+ if (value.jquery) {
2012
+ collector?.(path, 'jquery');
2013
+ return undefined;
2014
+ }
2015
+ // Duck-typed on purpose: importing Jqhtml_Component here would be a cycle
2016
+ // (component.ts imports this file). _cid + component_name() is the pair no
2017
+ // plain data object carries.
2018
+ if (value._cid !== undefined && typeof value.component_name === 'function') {
2019
+ collector?.(path, 'component');
2020
+ return undefined;
2021
+ }
2022
+ if (typeof value.then === 'function') {
2023
+ collector?.(path, 'promise');
2024
+ return undefined;
2025
+ }
1939
2026
  // Handle circular references.
1940
2027
  // `seen` tracks only the current ancestor path (the DFS stack): an object is
1941
2028
  // added on the way down and removed on the way back up (see finally below).
@@ -1944,10 +2031,11 @@ function process_for_serialization(value, verbose, seen) {
1944
2031
  // JSON round-trip semantics do not preserve identity anyway, so emitting a
1945
2032
  // copy per reference is correct; silently omitting the property is not.
1946
2033
  if (seen.has(value)) {
2034
+ collector?.(path, 'circular');
1947
2035
  if (verbose) {
1948
- console.warn('[JQHTML Cache] Circular reference detected - cannot serialize');
2036
+ console.warn('[JQHTML Cache] Circular reference detected - cutting the cycle');
1949
2037
  }
1950
- return undefined; // Fail entire serialization
2038
+ return undefined; // Cut the cycle here; the rest of the tree still serializes
1951
2039
  }
1952
2040
  seen.add(value);
1953
2041
  try {
@@ -1956,7 +2044,7 @@ function process_for_serialization(value, verbose, seen) {
1956
2044
  const result = [];
1957
2045
  for (let i = 0; i < value.length; i++) {
1958
2046
  const item = value[i];
1959
- const processed = process_for_serialization(item, verbose, seen);
2047
+ const processed = process_for_serialization(item, verbose, seen, collector ? `${path}[${i}]` : '', collector);
1960
2048
  // For arrays, we keep undefined as null to preserve indices
1961
2049
  result.push(processed === undefined ? null : processed);
1962
2050
  }
@@ -1973,8 +2061,9 @@ function process_for_serialization(value, verbose, seen) {
1973
2061
  if (value instanceof Map) {
1974
2062
  const entries = [];
1975
2063
  for (const [k, v] of value) {
1976
- const processedKey = process_for_serialization(k, verbose, seen);
1977
- const processedValue = process_for_serialization(v, verbose, seen);
2064
+ const entry_path = collector ? `${path}.get(${String(k)})` : '';
2065
+ const processedKey = process_for_serialization(k, verbose, seen, entry_path, collector);
2066
+ const processedValue = process_for_serialization(v, verbose, seen, entry_path, collector);
1978
2067
  entries.push([processedKey, processedValue]);
1979
2068
  }
1980
2069
  return {
@@ -1985,8 +2074,9 @@ function process_for_serialization(value, verbose, seen) {
1985
2074
  // Handle Set objects
1986
2075
  if (value instanceof Set) {
1987
2076
  const items = [];
2077
+ let index = 0;
1988
2078
  for (const item of value) {
1989
- items.push(process_for_serialization(item, verbose, seen));
2079
+ items.push(process_for_serialization(item, verbose, seen, collector ? `${path}[Set ${index++}]` : '', collector));
1990
2080
  }
1991
2081
  return {
1992
2082
  [CLASS_MARKER]: 'Set',
@@ -1997,58 +2087,115 @@ function process_for_serialization(value, verbose, seen) {
1997
2087
  const ctor = value.constructor;
1998
2088
  // Handle registered class instances
1999
2089
  if (ctor && ctor.name && class_registry[ctor.name]) {
2000
- const props = {};
2001
- // Extract own enumerable properties (bypass any toJSON method)
2002
- for (const key of Object.keys(value)) {
2003
- const propValue = value[key];
2004
- const processed = process_for_serialization(propValue, verbose, seen);
2005
- // Only include if not undefined (failed serialization)
2006
- if (processed !== undefined || propValue === undefined) {
2007
- props[key] = processed;
2008
- }
2009
- }
2010
2090
  return {
2011
2091
  [CLASS_MARKER]: ctor.name,
2012
- [PROPS_MARKER]: props
2092
+ [PROPS_MARKER]: process_own_properties(value, verbose, seen, path, collector)
2013
2093
  };
2014
2094
  }
2015
2095
  // Handle plain objects (constructor is Object or no constructor)
2016
2096
  if (ctor === Object || ctor === undefined || ctor === null) {
2017
- const result = {};
2018
- for (const key of Object.keys(value)) {
2019
- const propValue = value[key];
2020
- const processed = process_for_serialization(propValue, verbose, seen);
2021
- // Only include if not undefined (unless original was undefined)
2022
- if (processed !== undefined || propValue === undefined) {
2023
- result[key] = processed;
2024
- }
2025
- }
2026
- return result;
2097
+ return process_own_properties(value, verbose, seen, path, collector);
2027
2098
  }
2028
- // Unregistered class instance - convert to plain object for hot/cold parity
2029
- // This ensures developers catch missing class registrations during development
2030
- // (methods will be lost, only properties preserved)
2099
+ // Unregistered class instance - convert to plain object for hot/cold parity.
2100
+ // Properties are preserved, prototype methods are lost, exactly as a cache
2101
+ // hit would produce, so the loss shows up on the first load rather than on
2102
+ // the next page view.
2103
+ collector?.(path, 'unregistered-class', ctor.name);
2031
2104
  if (verbose) {
2032
2105
  console.warn(`[JQHTML Cache] Converting unregistered class "${ctor.name}" to plain object. ` +
2033
2106
  `Methods will be lost. Call jqhtml.register_cache_class(${ctor.name}) to preserve the class.`);
2034
2107
  }
2035
- // Convert to plain object - properties are preserved, prototype methods are lost
2036
- const result = {};
2037
- for (const key of Object.keys(value)) {
2038
- const propValue = value[key];
2039
- const processed = process_for_serialization(propValue, verbose, seen);
2040
- // Only include if not undefined (unless original was undefined)
2041
- if (processed !== undefined || propValue === undefined) {
2042
- result[key] = processed;
2043
- }
2044
- }
2045
- return result;
2108
+ return process_own_properties(value, verbose, seen, path, collector);
2046
2109
  }
2047
2110
  finally {
2048
2111
  // Pop this object off the ancestor path now that its subtree is done.
2049
2112
  seen.delete(value);
2050
2113
  }
2051
2114
  }
2115
+ /**
2116
+ * Walk an object's own enumerable properties (bypassing any toJSON) into a plain
2117
+ * object. Shared by plain objects, registered class instances and degraded
2118
+ * unregistered instances - all three keep exactly the same property semantics.
2119
+ */
2120
+ function process_own_properties(value, verbose, seen, path, collector) {
2121
+ const result = {};
2122
+ for (const key of Object.keys(value)) {
2123
+ const propValue = value[key];
2124
+ const processed = process_for_serialization(propValue, verbose, seen, collector ? `${path}.${key}` : '', collector);
2125
+ // Only include if not undefined (unless original was undefined)
2126
+ if (processed !== undefined || propValue === undefined) {
2127
+ result[key] = processed;
2128
+ }
2129
+ }
2130
+ return result;
2131
+ }
2132
+ // ============================================================================
2133
+ // Development warnings for dropped values
2134
+ // ============================================================================
2135
+ // One warning per component + path, for the life of the page. A list of 50 rows
2136
+ // each carrying an $on_select callback must print ONE warning, not 50, and must
2137
+ // not print it again on the next reload() or on the next instance of the same
2138
+ // component. Same shape as _warned_uncacheable in component-cache.ts.
2139
+ const _warned_stripped = new Set();
2140
+ /**
2141
+ * What was lost, and where the value actually belongs. Every message names a
2142
+ * destination, because "it was dropped" without "put it here instead" is not
2143
+ * actionable.
2144
+ */
2145
+ function strip_advice(kind, detail) {
2146
+ switch (kind) {
2147
+ case 'function':
2148
+ return 'a function cannot be serialized. Callbacks are configuration, not loaded data - ' +
2149
+ 'pass it in this.args (from the parent template) and keep only ids in this.data.';
2150
+ case 'promise':
2151
+ return 'a promise cannot be serialized. Await it inside on_load() and store the RESULT, ' +
2152
+ 'or hold the pending promise in this.state.';
2153
+ case 'dom-node':
2154
+ return 'a DOM node cannot be serialized. Elements, timers, files and sockets belong in this.state.';
2155
+ case 'jquery':
2156
+ return 'a jQuery object cannot be serialized. Elements, timers, files and sockets belong in this.state.';
2157
+ case 'component':
2158
+ return 'a Jqhtml_Component cannot be serialized. Keep component references in this.state ' +
2159
+ 'and address children with this.sid().';
2160
+ case 'symbol':
2161
+ return 'a symbol cannot be serialized. Use a string, or keep it in this.state.';
2162
+ case 'bigint':
2163
+ return 'a bigint cannot be serialized. Convert it to a string in on_load(), or keep it in this.state.';
2164
+ case 'circular':
2165
+ return 'it points back to one of its own ancestors, and the cycle was cut. Store the graph ' +
2166
+ 'flat (ids instead of back-references) in this.data, or keep the linked form in this.state.';
2167
+ case 'unregistered-class':
2168
+ return `it is an instance of the unregistered class "${detail}", so it was degraded to a plain ` +
2169
+ `object and its methods are gone. Call jqhtml.register_cache_class(${detail}) at startup ` +
2170
+ `to get real instances back.`;
2171
+ }
2172
+ }
2173
+ /**
2174
+ * Build the collector normalize_for_cache() hands to the serializer, or
2175
+ * `undefined` when nobody is listening - production, or a caller that named no
2176
+ * component. Returning undefined (rather than a no-op function) is what keeps
2177
+ * the serializer from building path strings at all on the hot path.
2178
+ */
2179
+ function make_strip_collector(component_name) {
2180
+ if (!component_name)
2181
+ return undefined;
2182
+ if (get_config().mode !== 'development')
2183
+ return undefined;
2184
+ return (path, kind, detail) => {
2185
+ try {
2186
+ const dedupe_key = `${component_name}:${path}`;
2187
+ if (_warned_stripped.has(dedupe_key))
2188
+ return;
2189
+ _warned_stripped.add(dedupe_key);
2190
+ console.warn(`[JQHTML] <${component_name}> dropped ${path} from this.data: ${strip_advice(kind, detail)}\n` +
2191
+ ` this.data is always the serialized copy jqhtml stores in and restores from cache, ` +
2192
+ `so only serializable values survive on_load() - in every cache mode.`, { component: component_name, path, kind });
2193
+ }
2194
+ catch {
2195
+ // A warning must never be able to break a load.
2196
+ }
2197
+ };
2198
+ }
2052
2199
  // ============================================================================
2053
2200
  // Deserialization (String → Object)
2054
2201
  // ============================================================================
@@ -2392,36 +2539,36 @@ class Jqhtml_Local_Storage {
2392
2539
  /**
2393
2540
  * Perform a serialize/deserialize round-trip on a value.
2394
2541
  *
2395
- * This ensures "hot" data (fresh from on_load) behaves identically to "cold" data
2396
- * (restored from cache). Unregistered class instances will be converted to plain
2397
- * objects, exactly as they would be if restored from cache.
2398
- *
2399
- * Use this to normalize data after on_load() so developers catch missing class
2400
- * registrations immediately rather than only after a page reload.
2542
+ * The result is ALWAYS jqhtml's own copy: nothing of the caller's object graph
2543
+ * is aliased through, and a value the serializer cannot express is dropped
2544
+ * rather than smuggled out. That is what makes `this.data` identical whether it
2545
+ * came from on_load() or from a cache hit - the old "on failure return the
2546
+ * original" branch broke exactly that promise, and only on the hard cases.
2401
2547
  *
2402
2548
  * @param {any} value - The value to normalize
2403
- * @returns {any} The value after serialize/deserialize round-trip, or original if serialization fails
2549
+ * @param {string} [component_name] - Names the component in development warnings.
2550
+ * Omit to convert silently (the unit tests and non-component callers).
2551
+ * @returns {any} The round-tripped value. Never the original object.
2404
2552
  */
2405
- static normalize_for_cache(value) {
2553
+ static normalize_for_cache(value, component_name) {
2406
2554
  const verbose = this._is_verbose();
2555
+ const collector = make_strip_collector(component_name);
2407
2556
  // Serialize to JSON string
2408
- const serialized = serialize_value(value, verbose);
2557
+ const serialized = serialize_value(value, verbose, 'this.data', collector);
2409
2558
  if (serialized === null) {
2410
- // Serialization failed completely - return original
2411
- // (This happens with circular references or other fatal issues)
2412
- if (verbose) {
2413
- console.warn('[JQHTML Cache] normalize_for_cache: Serialization failed, returning original value');
2414
- }
2415
- return value;
2559
+ // The value as a WHOLE could not be expressed (it was itself a function,
2560
+ // a promise, a DOM node...). The round trip of such a value is nothing;
2561
+ // returning the original would put an uncacheable object into this.data.
2562
+ return {};
2416
2563
  }
2417
2564
  // Deserialize back to object
2418
2565
  const deserialized = deserialize_value(serialized, verbose);
2419
- if (deserialized === null) {
2420
- // Deserialization failed - return original
2421
- if (verbose) {
2422
- console.warn('[JQHTML Cache] normalize_for_cache: Deserialization failed, returning original value');
2423
- }
2424
- return value;
2566
+ // `null` from deserialize_value() is ambiguous: it means "failed", but a value
2567
+ // that legitimately serialized to the text `null` also comes back as null. The
2568
+ // serialized text disambiguates.
2569
+ if (deserialized === null && serialized !== 'null') {
2570
+ // Only reachable when a registered class constructor blew up on restore.
2571
+ return {};
2425
2572
  }
2426
2573
  return deserialized;
2427
2574
  }
@@ -2444,7 +2591,10 @@ class Jqhtml_Local_Storage {
2444
2591
  console.warn('[JQHTML Local Storage] Quota exceeded, clearing JQHTML keys and retrying');
2445
2592
  // Clear only JQHTML keys and retry once
2446
2593
  this._clear_jqhtml_keys();
2447
- localStorage.setItem('_jqhtml_cache_key', this._cache_key);
2594
+ // Re-stamp the SCOPE MARKER, not the raw developer key: _validate_scope()
2595
+ // compares against `${CORE_VERSION}::${key}`, so writing the bare key here
2596
+ // made the very next write look like a scope change and wipe the cache again.
2597
+ localStorage.setItem('_jqhtml_cache_key', this._scope_marker);
2448
2598
  try {
2449
2599
  localStorage.setItem(scoped_key, serialized);
2450
2600
  }
@@ -2485,17 +2635,22 @@ Jqhtml_Local_Storage._initialized = false;
2485
2635
  * Extracted from component.ts - handles lifecycle event registration,
2486
2636
  * triggering, and state tracking.
2487
2637
  *
2488
- * Events have "sticky" semantics for lifecycle events: if an event has already
2489
- * occurred, new .on() handlers fire immediately with the stored data.
2638
+ * EVERY event is "sticky", not just the lifecycle ones: trigger() records the event
2639
+ * name and its payload, and a handler registered afterwards fires immediately with that
2640
+ * last payload. This is deliberate and applies to custom events too - a subscriber that
2641
+ * arrives after `trigger('row_selected', row)` still learns which row is selected,
2642
+ * which is what makes late-attaching UI work without a separate "current state" read.
2490
2643
  */
2491
2644
  /**
2492
2645
  * Register a callback for an event.
2493
2646
  *
2494
- * Lifecycle events (create, render, load, loaded, ready) are "sticky":
2495
- * If a lifecycle event has already occurred, the callback fires immediately
2496
- * AND registers for future occurrences.
2647
+ * All events are "sticky", lifecycle (create, render, load, loaded, ready, stop) and
2648
+ * custom alike: if the event has already been triggered, the callback fires immediately
2649
+ * with the payload of that last trigger AND registers for future occurrences.
2497
2650
  *
2498
- * Custom events only fire when explicitly triggered via trigger().
2651
+ * invalidate(event_name) drops the stored marker when a component wants later
2652
+ * subscribers to wait for the next real occurrence instead (reload() does this for
2653
+ * 'ready').
2499
2654
  *
2500
2655
  * @param component - The component instance
2501
2656
  * @param event_name - Name of the event
@@ -2627,6 +2782,20 @@ function event_invalidate(component, event_name) {
2627
2782
  * - Data freeze/unfreeze enforcement via Proxy
2628
2783
  * - Detached on_load() execution with restricted access
2629
2784
  */
2785
+ /**
2786
+ * JSON for an error message. The value being rejected is arbitrary author data and may
2787
+ * be cyclic or otherwise unserializable - the diagnostic must never throw over the
2788
+ * error it is trying to report.
2789
+ */
2790
+ function safe_json(value) {
2791
+ try {
2792
+ const text = JSON.stringify(value);
2793
+ return text === undefined ? String(value) : text;
2794
+ }
2795
+ catch {
2796
+ return String(value);
2797
+ }
2798
+ }
2630
2799
  /**
2631
2800
  * Set up the `this.data` property on a component using Object.defineProperty
2632
2801
  * with a Proxy that enforces freeze/unfreeze semantics.
@@ -2640,9 +2809,78 @@ function event_invalidate(component, event_name) {
2640
2809
  */
2641
2810
  function setup_data_property(component) {
2642
2811
  let _data = {};
2812
+ // Wrapper memo for the deep-freeze proxies. Keyed by the RAW target object, so a
2813
+ // value read twice returns the same wrapper and `this.data.items === this.data.items`
2814
+ // holds - identity comparisons and `Set`/`Map` membership on nested data keep working.
2815
+ // WeakMap: a wrapper dies with the object it wraps.
2816
+ const frozen_wrappers = new WeakMap();
2817
+ // Only plain objects and arrays are wrapped. Anything with a real prototype
2818
+ // (Date, Map, Set, and classes restored by register_cache_class()) carries internal
2819
+ // slots that a Proxy receiver cannot satisfy: `this.data.created.getTime()` would
2820
+ // call the method with the proxy as `this` and throw. Those values pass through raw -
2821
+ // a shallow hole we accept, because breaking Date/Map/Set reads would be worse than
2822
+ // missing a rare mutation of one.
2823
+ const is_wrappable = (value) => {
2824
+ if (value === null || typeof value !== 'object')
2825
+ return false;
2826
+ if (Array.isArray(value))
2827
+ return true;
2828
+ const proto = Object.getPrototypeOf(value);
2829
+ return proto === Object.prototype || proto === null;
2830
+ };
2831
+ // Dotted path for error messages: array indices read as [0], keys as .name
2832
+ const join_path = (path, target, prop) => Array.isArray(target) ? `${path}[${String(prop)}]` : `${path}.${String(prop)}`;
2833
+ const frozen_violation = (path, verb, value) => {
2834
+ const value_text = verb === 'modify' ? ` = ${safe_json(value)}` : '';
2835
+ console.error(`[JQHTML] ERROR: Component "${component.component_name()}" attempted to ${verb} ${path} outside of on_create() or on_load().\n\n` +
2836
+ `RESTRICTION: this.data can ONLY be modified in:\n` +
2837
+ ` - on_create() (set initial defaults, synchronous only)\n` +
2838
+ ` - on_load() (fetch data from APIs, can be async)\n\n` +
2839
+ `NESTED VALUES COUNT: the freeze is DEEP. Mutating an object or array inside\n` +
2840
+ `this.data (push, splice, assigning a property, delete) is modifying this.data.\n\n` +
2841
+ `WHY: this.data represents loaded state. Modifying it outside these methods bypasses the framework's render cycle.\n\n` +
2842
+ `FIX:\n` +
2843
+ ` ❌ In on_ready(): ${path}${value_text};\n` +
2844
+ ` ✅ In on_load(): fetch the value, so the framework can re-render\n` +
2845
+ ` ✅ For component-local bookkeeping: this.state (unrestricted, never cached)`);
2846
+ throw new Error(`[JQHTML] Cannot ${verb} ${path} outside of on_create() or on_load(). ` +
2847
+ `this.data is frozen after on_create() and unfrozen only during on_load(). ` +
2848
+ `The freeze is deep - nested objects and arrays are frozen too.`);
2849
+ };
2850
+ // Read-only view of a nested value. Handed out ONLY while __data_frozen is true
2851
+ // (the top-level get trap checks), so the traps here never need to re-check: a
2852
+ // wrapper the author kept a reference to stays read-only for its whole life.
2853
+ const create_frozen_wrapper = (obj, path) => {
2854
+ const existing = frozen_wrappers.get(obj);
2855
+ if (existing)
2856
+ return existing;
2857
+ const wrapper = new Proxy(obj, {
2858
+ get: (target, prop) => {
2859
+ const value = target[prop];
2860
+ // Functions are returned raw: array methods are invoked with the wrapper as
2861
+ // `this`, so push/splice still land in this trap's set/deleteProperty.
2862
+ return is_wrappable(value) ? create_frozen_wrapper(value, join_path(path, target, prop)) : value;
2863
+ },
2864
+ set: (target, prop, value) => frozen_violation(join_path(path, target, prop), 'modify', value),
2865
+ deleteProperty: (target, prop) => frozen_violation(join_path(path, target, prop), 'delete')
2866
+ });
2867
+ frozen_wrappers.set(obj, wrapper);
2868
+ return wrapper;
2869
+ };
2643
2870
  // Helper to create frozen proxy for data object
2644
2871
  const create_proxy = (obj) => {
2645
2872
  return new Proxy(obj, {
2873
+ get: (target, prop) => {
2874
+ const value = target[prop];
2875
+ // Deep freeze: while frozen, every nested object/array is read through a
2876
+ // read-only wrapper, so this.data.items.push(x) throws instead of silently
2877
+ // mutating. Unfrozen (on_create, on_load's detached run, _apply_load_result)
2878
+ // reads return the raw value, because those phases may legally mutate it.
2879
+ if (component.__data_frozen && is_wrappable(value)) {
2880
+ return create_frozen_wrapper(value, `this.data.${String(prop)}`);
2881
+ }
2882
+ return value;
2883
+ },
2646
2884
  set: (target, prop, value) => {
2647
2885
  if (component.__data_frozen) {
2648
2886
  console.error(`[JQHTML] ERROR: Component "${component.component_name()}" attempted to modify this.data.${String(prop)} outside of on_create() or on_load().\n\n` +
@@ -2712,10 +2950,13 @@ function setup_data_property(component) {
2712
2950
  * All other property access (this.$, this.$sid, etc.) throws errors.
2713
2951
  *
2714
2952
  * @param component - The component instance
2715
- * @param use_load_coordinator - Whether to use Load_Coordinator for deduplication
2953
+ * @param dedup_key - The dedup key captured by the caller, or null to run uncoordinated.
2954
+ * The key is passed in rather than recomputed because args may legally
2955
+ * change while on_load() runs, and a recomputed key would address a
2956
+ * different entry than the one this leader registered.
2716
2957
  * @returns The resulting data and optional coordination completion function
2717
2958
  */
2718
- async function execute_on_load_detached(component, use_load_coordinator = false) {
2959
+ async function execute_on_load_detached(component, dedup_key = null) {
2719
2960
  // Clone this.data from the snapshot captured after on_create()
2720
2961
  const data_clone = component.__initial_data_snapshot
2721
2962
  ? JSON.parse(JSON.stringify(component.__initial_data_snapshot))
@@ -2723,14 +2964,23 @@ async function execute_on_load_detached(component, use_load_coordinator = false)
2723
2964
  // Create a read-only proxy for args that blocks all modifications
2724
2965
  // Can't use JSON clone because args may contain functions (_slots, callbacks)
2725
2966
  const component_name = component.component_name();
2967
+ // Wrapper memo for this one on_load() run. Without it every nested read built a
2968
+ // fresh Proxy, so `this.args.filter !== this.args.filter` for an object arg and
2969
+ // identity comparisons inside on_load() silently failed. Lives only for the duration
2970
+ // of this call - args may legally be replaced between loads.
2971
+ const readonly_wrappers = new WeakMap();
2726
2972
  const create_readonly_proxy = (obj, path = 'this.args') => {
2727
2973
  if (obj === null || typeof obj !== 'object')
2728
2974
  return obj;
2729
- return new Proxy(obj, {
2975
+ const existing = readonly_wrappers.get(obj);
2976
+ if (existing)
2977
+ return existing;
2978
+ const proxy = new Proxy(obj, {
2730
2979
  get(target, prop) {
2731
2980
  const value = target[prop];
2732
- // Recursively wrap nested objects (but not functions)
2733
- if (value !== null && typeof value === 'object' && typeof value !== 'function') {
2981
+ // Recursively wrap nested objects. Functions are returned raw - `typeof value`
2982
+ // is already 'object' here, so a function never reaches this branch.
2983
+ if (value !== null && typeof value === 'object') {
2734
2984
  return create_readonly_proxy(value, `${path}.${String(prop)}`);
2735
2985
  }
2736
2986
  return value;
@@ -2752,6 +3002,8 @@ async function execute_on_load_detached(component, use_load_coordinator = false)
2752
3002
  `this.args is read-only in on_load().`);
2753
3003
  }
2754
3004
  });
3005
+ readonly_wrappers.set(obj, proxy);
3006
+ return proxy;
2755
3007
  };
2756
3008
  // Create a detached context object that on_load will operate on
2757
3009
  const detached_context = {
@@ -2811,27 +3063,22 @@ async function execute_on_load_detached(component, use_load_coordinator = false)
2811
3063
  `Only this.data can be modified in on_load().`);
2812
3064
  }
2813
3065
  });
2814
- // Create promise for this on_load() call
2815
- const on_load_promise = (async () => {
2816
- try {
2817
- await component._call_lifecycle('on_load', restricted_this);
2818
- }
2819
- catch (error) {
2820
- if (use_load_coordinator) {
2821
- // Handle error and notify coordinator
2822
- Load_Coordinator.handle_leader_error(component, error);
2823
- }
2824
- throw error;
2825
- }
2826
- })();
2827
- // If using Load_Coordinator, register as leader
2828
- // Note: We store the completion function but DON'T call it here
2829
- // It will be called by _load() after _apply_load_result() updates this.data
3066
+ // Register as leader BEFORE on_load() runs, so the error path always finds the entry
3067
+ // it has to reject. The completion function is stored, not called here: _load() calls
3068
+ // it after _apply_load_result() has updated this.data.
2830
3069
  let complete_coordination = null;
2831
- if (use_load_coordinator) {
2832
- complete_coordination = Load_Coordinator.register_leader(component, on_load_promise);
3070
+ if (dedup_key !== null) {
3071
+ complete_coordination = Load_Coordinator.register_leader(component, dedup_key);
3072
+ }
3073
+ try {
3074
+ await component._call_lifecycle('on_load', restricted_this);
3075
+ }
3076
+ catch (error) {
3077
+ if (dedup_key !== null) {
3078
+ Load_Coordinator.handle_leader_error(dedup_key, error);
3079
+ }
3080
+ throw error;
2833
3081
  }
2834
- await on_load_promise;
2835
3082
  // Note: We don't validate args changes here because external code (like parent
2836
3083
  // components calling reload()) is allowed to modify component.args during on_load().
2837
3084
  // The read-only proxy only prevents code INSIDE on_load() from modifying args.
@@ -2933,6 +3180,21 @@ function warn_uncacheable_component(component, uncacheable_property, uncacheable
2933
3180
  all_args: component.args ? Object.keys(component.args) : [],
2934
3181
  });
2935
3182
  }
3183
+ /**
3184
+ * Read an HTML-cache entry, rejecting anything that is not a well-formed snapshot.
3185
+ * Entries written by an older core are bare strings; they are treated as a miss (and
3186
+ * are cleared wholesale by the CORE_VERSION scope marker on the next version bump).
3187
+ */
3188
+ function read_html_snapshot(html_cache_key) {
3189
+ const entry = Jqhtml_Local_Storage.get(html_cache_key);
3190
+ if (entry !== null &&
3191
+ typeof entry === 'object' &&
3192
+ typeof entry.cid === 'string' &&
3193
+ typeof entry.html === 'string') {
3194
+ return entry;
3195
+ }
3196
+ return null;
3197
+ }
2936
3198
  /**
2937
3199
  * Read cache during create() phase.
2938
3200
  * Sets component._cache_key, _cached_html, _use_cached_data_hit as side effects.
@@ -2964,11 +3226,11 @@ function read_cache_in_create(component) {
2964
3226
  if (cache_mode === 'html') {
2965
3227
  // HTML cache mode - check for cached HTML to inject on first render
2966
3228
  const html_cache_key = `${cache_key}::html`;
2967
- const cached_html = Jqhtml_Local_Storage.get(html_cache_key);
2968
- if (cached_html !== null && typeof cached_html === 'string') {
3229
+ const cached_html = read_html_snapshot(html_cache_key);
3230
+ if (cached_html !== null) {
2969
3231
  component._cached_html = cached_html;
2970
3232
  if (window.jqhtml?.debug?.verbose) {
2971
- console.log(`[Cache html] Component ${component._cid} (${component.component_name()}) found cached HTML`, { cache_key: html_cache_key, html_length: cached_html.length });
3233
+ console.log(`[Cache html] Component ${component._cid} (${component.component_name()}) found cached HTML`, { cache_key: html_cache_key, html_length: cached_html.html.length, snapshot_cid: cached_html.cid });
2972
3234
  }
2973
3235
  }
2974
3236
  else {
@@ -3025,10 +3287,10 @@ function check_cache_on_reload(component) {
3025
3287
  if (cache_mode === 'html') {
3026
3288
  // HTML cache mode - check for cached HTML
3027
3289
  const html_cache_key = `${cache_key}::html`;
3028
- const cached_html = Jqhtml_Local_Storage.get(html_cache_key);
3029
- if (cached_html !== null && typeof cached_html === 'string') {
3290
+ const cached_html = read_html_snapshot(html_cache_key);
3291
+ if (cached_html !== null) {
3030
3292
  if (window.jqhtml?.debug?.verbose) {
3031
- console.log(`[Cache html] reload() - Component ${component._cid} (${component.component_name()}) found cached HTML (args changed)`, { cache_key: html_cache_key, html_length: cached_html.length });
3293
+ console.log(`[Cache html] reload() - Component ${component._cid} (${component.component_name()}) found cached HTML (args changed)`, { cache_key: html_cache_key, html_length: cached_html.html.length, snapshot_cid: cached_html.cid });
3032
3294
  }
3033
3295
  component._cached_html = cached_html;
3034
3296
  // Call _render() directly (not render()) since _reload() manages the full lifecycle
@@ -3069,7 +3331,11 @@ function write_html_cache_snapshot(component) {
3069
3331
  component._should_cache_html_after_ready = false;
3070
3332
  const html = component.$.html();
3071
3333
  const html_cache_key = `${component._cache_key}::html`;
3072
- Jqhtml_Local_Storage.set(html_cache_key, html);
3334
+ // Store the cid this markup was rendered under alongside it: every scoped id inside
3335
+ // reads "<name>:<cid>", and a reader cannot tell the snapshotting component's own
3336
+ // elements from its children's without knowing which cid was the owner's.
3337
+ // See Jqhtml_Component._rescope_cached_html().
3338
+ Jqhtml_Local_Storage.set(html_cache_key, { cid: component._cid, html });
3073
3339
  if (window.jqhtml?.debug?.verbose) {
3074
3340
  console.log(`[Cache html] Component ${component._cid} (${component.component_name()}) cached HTML after children on_render complete`, { cache_key: html_cache_key, html_length: html.length });
3075
3341
  }
@@ -3109,16 +3375,158 @@ function write_cache_on_loaded(component, data_changed) {
3109
3375
  }
3110
3376
  }
3111
3377
 
3378
+ /**
3379
+ * HTML escaping for interpolated text.
3380
+ *
3381
+ * Output matches what `div.textContent = s; div.innerHTML` produced before -
3382
+ * a text node serialises only &, < and > as entities, and null/undefined as
3383
+ * "" - but without touching the DOM. Interpolation runs for every value of
3384
+ * every render, and a createElement per value was the most expensive thing a
3385
+ * text-heavy template did.
3386
+ */
3387
+ const NEEDS_ESCAPE = /[&<>]/;
3388
+ const ESCAPE_ALL = /[&<>]/g;
3389
+ const ENTITY = { '&': '&amp;', '<': '&lt;', '>': '&gt;' };
3390
+ const to_entity = (c) => ENTITY[c];
3391
+ function escape_html(value) {
3392
+ if (value === null || value === undefined)
3393
+ return '';
3394
+ const s = typeof value === 'string' ? value : String(value);
3395
+ return NEEDS_ESCAPE.test(s) ? s.replace(ESCAPE_ALL, to_entity) : s;
3396
+ }
3397
+ /** Escaped, then newlines become <br /> - the <%br= %> construct. */
3398
+ function escape_html_nl2br(value) {
3399
+ return escape_html(value).replace(/\n/g, '<br />');
3400
+ }
3401
+
3402
+ /**
3403
+ * Value printers: how <%= %> renders an OBJECT.
3404
+ *
3405
+ * Primitives never come here - the generated template code routes only
3406
+ * non-null, non-array objects to print_object(), so a hundred-row list of
3407
+ * strings costs exactly what it did before. An object reaching an
3408
+ * interpolation is walked through the printer chain in registration order;
3409
+ * the first printer to return anything but undefined handles it. A printer
3410
+ * returns a string (escaped or not according to the construct, exactly as a
3411
+ * string literal at that site) or a component descriptor:
3412
+ *
3413
+ * { component: { name: 'Rich_Text_Display', args: { value }, attrs: { class: 'x' } } }
3414
+ *
3415
+ * which jqhtml mounts as if the template had written the tag - live in the
3416
+ * browser, server-rendered under SSR - with no environment awareness on the
3417
+ * printer's side. A descriptor carries no content.
3418
+ *
3419
+ * Attribute position (<div title="<%= v %>">) compiles through a different
3420
+ * path and never consults printers.
3421
+ */
3422
+ const printers = [];
3423
+ /**
3424
+ * Register a printer at the end of the chain. Printers run in registration
3425
+ * order; return undefined to decline, a string, or a component descriptor.
3426
+ */
3427
+ function add_object_printer(printer) {
3428
+ if (typeof printer !== 'function') {
3429
+ throw new Error('[JQHTML] add_object_printer() expects a function (value) => undefined | string | descriptor');
3430
+ }
3431
+ printers.push(printer);
3432
+ }
3433
+ /** The registered printers, in order. Read-only view for diagnostics. */
3434
+ function get_object_printers() {
3435
+ return printers;
3436
+ }
3437
+ /**
3438
+ * Render an object at an interpolation site. Called by compiled templates for
3439
+ * every non-null, non-array object reaching <%= %>, <%!= %> or <%br= %>.
3440
+ * Throws when nothing handles the value or a printer returns garbage.
3441
+ */
3442
+ function print_object(value, mode) {
3443
+ if (value === null || typeof value !== 'object') {
3444
+ throw new TypeError(`[JQHTML] print_object() is the object branch of interpolation; got ${typeof value}`);
3445
+ }
3446
+ for (let i = 0; i < printers.length; i++) {
3447
+ const result = printers[i](value);
3448
+ if (result === undefined)
3449
+ continue;
3450
+ if (typeof result === 'string')
3451
+ return print_string(result, mode);
3452
+ if (is_descriptor(result))
3453
+ return descriptor_to_instruction(result, i);
3454
+ throw new Error(`[JQHTML] Object printer #${i + 1} of ${printers.length} returned ${describe(result)}; ` +
3455
+ `a printer must return undefined (decline), a string, or a { component: { name, args, attrs } } descriptor`);
3456
+ }
3457
+ throw new Error(`[JQHTML] Cannot interpolate a ${constructor_name(value)} object: ` +
3458
+ (printers.length
3459
+ ? `none of the ${printers.length} registered object printer(s) handled it. `
3460
+ : `no object printers are registered. `) +
3461
+ `Register one with jqhtml.add_object_printer(fn), or interpolate a primitive.`);
3462
+ }
3463
+ function print_string(text, mode) {
3464
+ if (mode === 'escape')
3465
+ return escape_html(text);
3466
+ if (mode === 'nl2br')
3467
+ return escape_html_nl2br(text);
3468
+ return text;
3469
+ }
3470
+ function is_descriptor(value) {
3471
+ return !!value && typeof value === 'object' && !Array.isArray(value) &&
3472
+ !!value.component && typeof value.component === 'object' && !Array.isArray(value.component);
3473
+ }
3474
+ function descriptor_to_instruction(descriptor, index) {
3475
+ const { name, args, attrs } = descriptor.component;
3476
+ const where = `Object printer #${index + 1}`;
3477
+ if (typeof name !== 'string' || !is_component_name(name)) {
3478
+ throw new Error(`[JQHTML] ${where} returned a descriptor whose component name ${describe(name)} is invalid: ` +
3479
+ `a component name ${COMPONENT_NAME_RULE}, then letters, digits and underscores`);
3480
+ }
3481
+ const props = {};
3482
+ if (attrs !== undefined) {
3483
+ if (!is_plain_object(attrs))
3484
+ throw new Error(`[JQHTML] ${where}: descriptor attrs must be a plain object`);
3485
+ for (const [key, value] of Object.entries(attrs)) {
3486
+ if (key.startsWith('$'))
3487
+ throw new Error(`[JQHTML] ${where}: descriptor attrs key '${key}' - component arguments go in args, without the $ sigil`);
3488
+ props[key] = value;
3489
+ }
3490
+ }
3491
+ if (args !== undefined) {
3492
+ if (!is_plain_object(args))
3493
+ throw new Error(`[JQHTML] ${where}: descriptor args must be a plain object`);
3494
+ for (const [key, value] of Object.entries(args)) {
3495
+ if (key.startsWith('$'))
3496
+ throw new Error(`[JQHTML] ${where}: descriptor args key '${key}' - the $ sigil is template syntax, not part of the argument name`);
3497
+ props[`$${key}`] = value;
3498
+ }
3499
+ }
3500
+ return { comp: [name, props] };
3501
+ }
3502
+ function is_plain_object(value) {
3503
+ return !!value && typeof value === 'object' && !Array.isArray(value);
3504
+ }
3505
+ function constructor_name(value) {
3506
+ const ctor = value.constructor;
3507
+ return ctor && ctor.name ? ctor.name : 'Object';
3508
+ }
3509
+ function describe(value) {
3510
+ if (value === null)
3511
+ return 'null';
3512
+ if (typeof value === 'string')
3513
+ return `'${value}'`;
3514
+ if (typeof value === 'object')
3515
+ return Array.isArray(value) ? 'an array' : `a ${constructor_name(value)} object without a valid component property`;
3516
+ return `${typeof value} ${String(value)}`;
3517
+ }
3518
+
3112
3519
  /**
3113
3520
  * JQHTML Component Lifecycle Queue
3114
3521
  *
3115
- * Serializes lifecycle operations (render, reload, refresh) per component.
3522
+ * Serializes lifecycle operations (render, reload, refresh, load) per component.
3116
3523
  * Replaces _create_debounced_function with a proper queue that:
3117
3524
  *
3118
3525
  * - At most one operation runs at a time per component
3119
- * - At most one operation is pending (waiting for the current to finish)
3120
- * - Same-type pending operations collapse (fan-in: all callers share one execution)
3121
- * - Different-type pending operations: new replaces old (old callers get the new result)
3526
+ * - At most one PENDING entry per type; different types queue behind each other FIFO
3527
+ * - Same-type pending operations collapse: the newest executor wins, and every
3528
+ * collapsed caller is settled with the value of the executor that actually ran
3529
+ * - A caller is settled BEFORE the next pending entry starts
3122
3530
  *
3123
3531
  * Boot bypasses this queue entirely - it runs the lifecycle directly.
3124
3532
  */
@@ -3126,92 +3534,106 @@ class Component_Queue {
3126
3534
  constructor() {
3127
3535
  /** Currently executing operation */
3128
3536
  this._current = null;
3129
- /** Next operation waiting to execute after current completes */
3130
- this._pending = null;
3537
+ /**
3538
+ * Operations waiting to run after the current one, in FIFO order.
3539
+ * At most one entry per type: a second reload() while a reload is pending
3540
+ * collapses into it, but a render() queued over a pending reload() is its
3541
+ * own entry and both run. Replacing the older entry (the previous behaviour)
3542
+ * dropped that operation entirely while still resolving its callers as if it
3543
+ * had run.
3544
+ */
3545
+ this._pending = [];
3131
3546
  }
3132
3547
  /**
3133
3548
  * Enqueue a lifecycle operation.
3134
3549
  *
3135
3550
  * Behavior:
3136
3551
  * - Nothing running → execute immediately
3137
- * - Something running, no pending → create pending entry
3138
- * - Something running, same type pending → collapse (share pending promise)
3139
- * - Something running, different type pending → replace pending (all callers get new result)
3552
+ * - Something running, no pending entry of this type → queue one (FIFO)
3553
+ * - Something running, same type pending → collapse: keep every caller, but
3554
+ * swap in the newest executor ("only the most recent call executes")
3555
+ *
3556
+ * Every caller collapsed onto one entry receives the value that entry's
3557
+ * executor returned - or its error, if it threw.
3140
3558
  *
3141
3559
  * @param type - Operation type ('render', 'reload', 'refresh', 'load')
3142
3560
  * @param executor - The async function to execute
3143
- * @returns Promise that resolves when the operation completes
3561
+ * @returns Promise that settles with the result of the execution that ran
3144
3562
  */
3145
3563
  enqueue(type, executor) {
3146
- // If nothing running, execute immediately
3564
+ // If nothing running, execute immediately.
3565
+ // The Promise executor runs synchronously, so the operation's synchronous
3566
+ // prologue (_render(), the ready invalidation) still happens in the calling
3567
+ // tick, as it did before the queue existed.
3147
3568
  if (!this._current) {
3148
- return this._execute(type, executor);
3149
- }
3150
- // Something is running — add to pending
3151
- if (this._pending) {
3152
- if (this._pending.type === type) {
3153
- // Same type pending → collapse (fan-in)
3154
- // All callers share the same future execution
3155
- return new Promise((resolve, reject) => {
3156
- this._pending.resolvers.push(resolve);
3157
- this._pending.rejecters.push(reject);
3158
- });
3159
- }
3160
- else {
3161
- // Different type pending → replace
3162
- // Old pending callers join the new operation
3163
- // (their operation was superseded by a different type)
3164
- const old_resolvers = this._pending.resolvers;
3165
- const old_rejecters = this._pending.rejecters;
3166
- return new Promise((resolve, reject) => {
3167
- this._pending = {
3168
- type,
3169
- executor,
3170
- resolvers: [...old_resolvers, resolve],
3171
- rejecters: [...old_rejecters, reject]
3172
- };
3173
- });
3174
- }
3569
+ return new Promise((resolve, reject) => {
3570
+ this._run({ type, executor, resolvers: [resolve], rejecters: [reject] });
3571
+ });
3175
3572
  }
3176
- // No pending entry yet — create one
3573
+ const existing = this._pending.find(entry => entry.type === type);
3574
+ if (existing) {
3575
+ // Same type already pending → collapse (fan-in).
3576
+ // The newest executor replaces the pending one: the documented rule is
3577
+ // "only the most recent call executes", and the older closure may carry
3578
+ // stale arguments. Keeping the OLD executor made two rapid `await load()`
3579
+ // calls resolve the second one `false` without ever running on_load().
3580
+ existing.executor = executor;
3581
+ return new Promise((resolve, reject) => {
3582
+ existing.resolvers.push(resolve);
3583
+ existing.rejecters.push(reject);
3584
+ });
3585
+ }
3586
+ // No pending entry of this type yet — queue one behind whatever is already waiting.
3177
3587
  return new Promise((resolve, reject) => {
3178
- this._pending = {
3179
- type,
3180
- executor,
3181
- resolvers: [resolve],
3182
- rejecters: [reject]
3183
- };
3588
+ this._pending.push({ type, executor, resolvers: [resolve], rejecters: [reject] });
3184
3589
  });
3185
3590
  }
3186
3591
  /**
3187
- * Execute an operation and handle pending queue after completion.
3592
+ * Run one entry, settle its callers, then start the next pending entry.
3188
3593
  * @private
3189
3594
  */
3190
- _execute(type, executor) {
3595
+ _run(entry) {
3596
+ // Mark busy BEFORE invoking the executor: the executor's synchronous prologue
3597
+ // can call back into enqueue(), and that call must queue rather than start a
3598
+ // second concurrent operation.
3599
+ this._current = { type: entry.type };
3191
3600
  const promise = (async () => {
3192
3601
  try {
3193
- await executor();
3602
+ const value = await entry.executor();
3603
+ // Settle this entry's callers FIRST, while the queue still reads as busy.
3604
+ for (const resolve of entry.resolvers)
3605
+ resolve(value);
3194
3606
  }
3195
- finally {
3196
- this._current = null;
3197
- // Run pending if exists
3198
- if (this._pending) {
3199
- const pending = this._pending;
3200
- this._pending = null;
3201
- try {
3202
- await this._execute(pending.type, pending.executor);
3203
- for (const resolve of pending.resolvers)
3204
- resolve();
3205
- }
3206
- catch (err) {
3207
- for (const reject of pending.rejecters)
3208
- reject(err);
3209
- }
3210
- }
3607
+ catch (error) {
3608
+ // A throwing executor rejects only its own callers; the queue continues.
3609
+ for (const reject of entry.rejecters)
3610
+ reject(error);
3211
3611
  }
3212
3612
  })();
3213
- this._current = { type, promise };
3214
- return promise;
3613
+ // The drain is deliberately OUTSIDE the awaited chain above: chaining it
3614
+ // inside made `await c.render()` also wait for a reload that was queued
3615
+ // after it.
3616
+ promise.then(() => {
3617
+ if (this._pending.length === 0) {
3618
+ // Nothing queued: release immediately, so the very common
3619
+ // `await c.reload(); c.render();` still starts the render in that tick.
3620
+ this._current = null;
3621
+ return;
3622
+ }
3623
+ // A queued entry must not start until every caller of the operation that
3624
+ // just finished has actually resumed. Those callers sit behind an unknown
3625
+ // number of microtask hops - an `async` public method adds two just by
3626
+ // returning the queue's promise - so draining on a microtask would start
3627
+ // the next on_load() before the previous caller's `await` came back. A
3628
+ // macrotask is the only boundary that is after all of them. _current stays
3629
+ // set until then, so nothing can start concurrently in the meantime.
3630
+ setTimeout(() => {
3631
+ this._current = null;
3632
+ const next = this._pending.shift();
3633
+ if (next)
3634
+ this._run(next);
3635
+ }, 0);
3636
+ });
3215
3637
  }
3216
3638
  /**
3217
3639
  * Check if any operation is currently running.
@@ -3223,7 +3645,7 @@ class Component_Queue {
3223
3645
  * Check if there's a pending operation waiting.
3224
3646
  */
3225
3647
  get has_pending() {
3226
- return this._pending !== null;
3648
+ return this._pending.length > 0;
3227
3649
  }
3228
3650
  }
3229
3651
 
@@ -3274,11 +3696,16 @@ function capture_component_data(component_name, args, data, cache_key) {
3274
3696
  try {
3275
3697
  const cloned_args = JSON.parse(JSON.stringify(args));
3276
3698
  const cloned_data = JSON.parse(JSON.stringify(data));
3277
- _capture_buffer.push({
3699
+ const entry = {
3278
3700
  component: component_name,
3279
3701
  args: cloned_args,
3280
3702
  data: cloned_data,
3281
- });
3703
+ };
3704
+ // Carry the key forward so the client matches on the SAME identity the server
3705
+ // used, rather than re-deriving one from args and hoping the shapes agree.
3706
+ if (cache_key !== null)
3707
+ entry.key = cache_key;
3708
+ _capture_buffer.push(entry);
3282
3709
  }
3283
3710
  catch (error) {
3284
3711
  // Non-serializable data — skip capture for this component
@@ -3324,10 +3751,15 @@ function set_preload_data(entries) {
3324
3751
  return;
3325
3752
  _preload_cache.clear();
3326
3753
  for (const entry of entries) {
3327
- // Generate key using the same algorithm as Load Coordinator
3328
- const result = Load_Coordinator.generate_invocation_key(entry.component, entry.args);
3329
- if (result.key !== null) {
3330
- _preload_cache.set(result.key, entry.data);
3754
+ // The captured key wins. Falling back to args means matching what
3755
+ // generate_cache_key() computes for a component with no cache_id(), which
3756
+ // INCLUDES content serialization - without it an object arg keyed to null
3757
+ // here and the entry was dropped, so preload never applied to it.
3758
+ const key = entry.key !== undefined
3759
+ ? entry.key
3760
+ : Load_Coordinator.generate_invocation_key(entry.component, entry.args, { allow_content_serialization: true }).key;
3761
+ if (key !== null) {
3762
+ _preload_cache.set(key, entry.data);
3331
3763
  }
3332
3764
  }
3333
3765
  }
@@ -3440,9 +3872,69 @@ function init_viewport_resize(jQuery) {
3440
3872
  * - Scoped IDs using _cid pattern
3441
3873
  * - Event emission and CSS class hierarchy
3442
3874
  */
3875
+ /**
3876
+ * The `jqhtml` argument every compiled render function receives: the same
3877
+ * escaping the runtime exports, the object-printer entry point, and the
3878
+ * dynamic tag name check. One shared object, not one per render.
3879
+ */
3880
+ const render_utilities = {
3881
+ escape_html,
3882
+ escape_html_nl2br,
3883
+ print_object,
3884
+ dynamic_component_name,
3885
+ };
3443
3886
  // WeakMap storage for protected lifecycle method implementations (Option 2)
3444
3887
  // See docs/internal/lifecycle-method-protection.md for design details
3445
3888
  const lifecycle_impls = new WeakMap();
3889
+ /**
3890
+ * Resolve the template a template inherits FROM, in the one order CLAUDE.md
3891
+ * documents ("Template Inheritance Resolution"): the explicit `extends=""`
3892
+ * attribute first, then the JS class prototype chain.
3893
+ *
3894
+ * This is the single implementation. Both slot-only rendering (which invokes the
3895
+ * parent template with the child's slots) and default-attribute collection walk
3896
+ * it, so a `<Define>`'s class/attrs can never resolve through a different chain
3897
+ * than its markup does.
3898
+ *
3899
+ * @param template_def The template whose parent is wanted
3900
+ * @param ctor The component class to walk the prototype chain of (null skips it)
3901
+ * @returns The parent template and the name it was found under, or null
3902
+ */
3903
+ function resolve_parent_template(template_def, ctor) {
3904
+ const verbose = window.jqhtml?.debug?.verbose;
3905
+ // 1. Explicit extends="" wins - the author said exactly which template to use.
3906
+ if (template_def?.extends) {
3907
+ const parent = get_template(template_def.extends);
3908
+ // get_template() never returns null: a miss yields DEFAULT_TEMPLATE, whose
3909
+ // name is 'Jqhtml_Component'. That is "not found", not a parent.
3910
+ if (parent && parent.name !== 'Jqhtml_Component') {
3911
+ if (verbose)
3912
+ console.log(`[JQHTML] resolve_parent_template: explicit extends -> ${template_def.extends}`);
3913
+ return { template: parent, name: template_def.extends };
3914
+ }
3915
+ if (verbose)
3916
+ console.log(`[JQHTML] resolve_parent_template: extends="${template_def.extends}" has no template`);
3917
+ }
3918
+ // 2. Otherwise walk the JS prototype chain for the nearest ancestor with a template.
3919
+ // Stop at the framework base, at Object, and at Function.prototype (name === ''),
3920
+ // which is what getPrototypeOf() hands back once the class chain is exhausted.
3921
+ let current_class = ctor ? Object.getPrototypeOf(ctor) : null;
3922
+ while (typeof current_class === 'function' && current_class.name &&
3923
+ current_class.name !== 'Object' && current_class.name !== 'Jqhtml_Component') {
3924
+ const class_name = current_class.name;
3925
+ // Internal base classes are aliases of Jqhtml_Component, never a parent template.
3926
+ if (class_name !== '_Jqhtml_Component' && class_name !== '_Base_Jqhtml_Component') {
3927
+ const class_template = get_template(class_name);
3928
+ if (class_template && class_template.name !== 'Jqhtml_Component' && class_template !== template_def) {
3929
+ if (verbose)
3930
+ console.log(`[JQHTML] resolve_parent_template: prototype chain -> ${class_name}`);
3931
+ return { template: class_template, name: class_name };
3932
+ }
3933
+ }
3934
+ current_class = Object.getPrototypeOf(current_class);
3935
+ }
3936
+ return null;
3937
+ }
3446
3938
  class Jqhtml_Component {
3447
3939
  constructor(element, args = {}) {
3448
3940
  this._ready_state = 0; // 0=created, 1=init, 2=loaded, 3=rendered, 4=ready
@@ -3467,7 +3959,10 @@ class Jqhtml_Component {
3467
3959
  // Cache mode properties
3468
3960
  this._cache_key = null; // Cache key for caching
3469
3961
  // 'html' mode caching
3470
- this._cached_html = null; // Cached HTML to inject on first render
3962
+ // The snapshot carries the cid it was taken under, not just markup: every scoped id
3963
+ // inside it reads "<name>:<cid>", so replaying it into a different instance requires
3964
+ // knowing which cid was the snapshotting component's own. See _rescope_cached_html().
3965
+ this._cached_html = null; // Cached HTML snapshot to inject on first render
3471
3966
  this._used_cached_html = false; // Flag if cached HTML was used (forces re-render after on_load)
3472
3967
  this._should_cache_html_after_ready = false; // Flag to cache HTML after on_ready lifecycle
3473
3968
  this._is_dynamic = false; // True if this.data changed during on_load() (used for HTML cache sync)
@@ -3542,6 +4037,14 @@ class Jqhtml_Component {
3542
4037
  // Merge in order: defineArgs (defaults from Define tag) < dataAttrs < args (invocation overrides)
3543
4038
  const defineArgs = template_for_args?.defineArgs || {};
3544
4039
  this.args = { ...defineArgs, ...dataAttrs, ...args };
4040
+ // The name this instance was invoked as. Every invocation path passes it
4041
+ // in args._component_name (template tag, $(el).component('Name'), boot
4042
+ // placeholder); a class handed directly to $(el).component(Class) has
4043
+ // only its own name to offer.
4044
+ const ctor = this.constructor;
4045
+ this._component_name = (typeof args._component_name === 'string' && args._component_name)
4046
+ || ctor.component_name
4047
+ || ctor.name;
3545
4048
  // Set lifecycle truncation flags from args
3546
4049
  if (this.args._load_only === true) {
3547
4050
  this._load_only = true;
@@ -3703,41 +4206,12 @@ class Jqhtml_Component {
3703
4206
  return child._render(null, options);
3704
4207
  }
3705
4208
  this._log_lifecycle('render', 'start');
3706
- // HTML CACHE MODE - If we have cached HTML, inject it directly and skip template rendering
3707
- if (this._cached_html !== null) {
3708
- if (window.jqhtml?.debug?.verbose) {
3709
- console.log(`[Cache html] Component ${this._cid} (${this.component_name()}) injecting cached HTML`, { html_length: this._cached_html.length });
3710
- }
3711
- // Inject cached HTML directly
3712
- this.$[0].innerHTML = this._cached_html;
3713
- // Mark that we used cached HTML (forces re-render after on_load)
3714
- this._used_cached_html = true;
3715
- // Clear cached HTML so next render uses template
3716
- this._cached_html = null;
3717
- // Mark first render complete
3718
- this._did_first_render = true;
3719
- this._log_lifecycle('render', 'complete (cached HTML)');
3720
- // Call on_render() after cache inject (unless suppressed by _load_render_only)
3721
- if (!options.skip_on_render) {
3722
- const cacheRenderResult = this._call_lifecycle_sync('on_render');
3723
- if (cacheRenderResult && typeof cacheRenderResult.then === 'function') {
3724
- console.warn(`[JQHTML] Component "${this.component_name()}" returned a Promise from on_render(). ` +
3725
- `on_render() must be synchronous code. Remove 'async' from the function declaration.`);
3726
- }
3727
- this._fire_viewport_resize();
3728
- }
3729
- // Emit lifecycle event
3730
- this.trigger('render');
3731
- // Store args/data snapshots for later comparison
3732
- try {
3733
- this._args_on_last_render = JSON.parse(JSON.stringify(this.args));
3734
- }
3735
- catch (error) {
3736
- this._args_on_last_render = null;
3737
- }
3738
- this._data_on_last_render = JSON.stringify(this.data);
3739
- return current_render_id;
3740
- }
4209
+ // --- Shared re-render prologue -------------------------------------------------
4210
+ // Everything below runs for BOTH the cached-HTML path and the template path. The
4211
+ // cached path used to return before it, so a cache-mode reload injected over a live
4212
+ // subtree without ever stopping the old children: their on_stop() never ran (timers
4213
+ // and listeners leaked) and they stayed in _dom_children as dead entries that every
4214
+ // later _wait_for_children_ready() walked.
3741
4215
  // Determine child-finding strategy: If component is off-DOM, children can't register
3742
4216
  // via _find_dom_parent() (no parent in DOM to find), so we'll need find() fallback later.
3743
4217
  // If attached to DOM, children register normally and we can use the fast _dom_children path.
@@ -3756,21 +4230,60 @@ class Jqhtml_Component {
3756
4230
  if (child && !child._stopped) {
3757
4231
  child._stop(); // Stop just the component, DOM will be cleared next
3758
4232
  }
3759
- });
3760
- // Clear the DOM
3761
- this.$[0].innerHTML = '';
3762
- }
3763
- else {
3764
- this._did_first_render = true;
4233
+ });
4234
+ // Clear the DOM
4235
+ this.$[0].innerHTML = '';
4236
+ }
4237
+ else {
4238
+ this._did_first_render = true;
4239
+ }
4240
+ // (No removeClass('_Component_Stopped') here: _render() returns above when
4241
+ // _stopped, and nothing ever clears _stopped, so a stopped component can never
4242
+ // reach this line. Clearing the class would only ever hide a real stopped state.)
4243
+ // Clear DOM children tracking - they're destroyed by innerHTML = '' anyway
4244
+ this._dom_children.clear();
4245
+ // --- End shared re-render prologue ---------------------------------------------
4246
+ // HTML CACHE MODE - If we have cached HTML, inject it directly and skip template rendering
4247
+ if (this._cached_html !== null) {
4248
+ if (window.jqhtml?.debug?.verbose) {
4249
+ console.log(`[Cache html] Component ${this._cid} (${this.component_name()}) injecting cached HTML`, { html_length: this._cached_html.html.length, snapshot_cid: this._cached_html.cid });
4250
+ }
4251
+ // Inject cached HTML directly, with every scoped id re-scoped to THIS instance.
4252
+ // The snapshot was taken from another component instance (or an earlier life of
4253
+ // this one), so its ids carry that instance's cids verbatim. Injecting them as-is
4254
+ // put duplicate ids in the document, and $sid() - which is getElementById first -
4255
+ // could hand this component the other instance's element.
4256
+ this.$[0].innerHTML = this._rescope_cached_html(this._cached_html);
4257
+ // Mark that we used cached HTML (forces re-render after on_load)
4258
+ this._used_cached_html = true;
4259
+ // Clear cached HTML so next render uses template
4260
+ this._cached_html = null;
4261
+ this._log_lifecycle('render', 'complete (cached HTML)');
4262
+ // Call on_render() after cache inject (unless suppressed by _load_render_only)
4263
+ if (!options.skip_on_render) {
4264
+ const cacheRenderResult = this._call_lifecycle_sync('on_render');
4265
+ if (cacheRenderResult && typeof cacheRenderResult.then === 'function') {
4266
+ console.warn(`[JQHTML] Component "${this.component_name()}" returned a Promise from on_render(). ` +
4267
+ `on_render() must be synchronous code. Remove 'async' from the function declaration.`);
4268
+ }
4269
+ this._fire_viewport_resize();
4270
+ }
4271
+ // Emit lifecycle event
4272
+ this.trigger('render');
4273
+ // Store args/data snapshots for later comparison
4274
+ try {
4275
+ this._args_on_last_render = JSON.parse(JSON.stringify(this.args));
4276
+ }
4277
+ catch (error) {
4278
+ this._args_on_last_render = null;
4279
+ }
4280
+ this._data_on_last_render = JSON.stringify(this.data);
4281
+ return current_render_id;
3765
4282
  }
3766
- // Remove _Component_Stopped class if present (allows re-render after stop)
3767
- this.$.removeClass('_Component_Stopped');
3768
4283
  // Capture data state before first render for comparison later
3769
4284
  if (this._data_before_render === null) {
3770
4285
  this._data_before_render = JSON.stringify(this.data);
3771
4286
  }
3772
- // Clear DOM children tracking - they're destroyed by innerHTML = '' anyway
3773
- this._dom_children.clear();
3774
4287
  // Get template and render it
3775
4288
  let template_def;
3776
4289
  // If we have a component name, try looking up by name first (for unregistered components)
@@ -3782,20 +4295,8 @@ class Jqhtml_Component {
3782
4295
  template_def = get_template_by_class(this.constructor);
3783
4296
  }
3784
4297
  if (template_def && template_def.render) {
3785
- // Create jqhtml utilities object
3786
- const jqhtml = {
3787
- escape_html: (str) => {
3788
- const div = document.createElement('div');
3789
- div.textContent = String(str);
3790
- return div.innerHTML;
3791
- },
3792
- escape_html_nl2br: (str) => {
3793
- const div = document.createElement('div');
3794
- div.textContent = String(str);
3795
- // Escape HTML first, then replace newlines with <br />
3796
- return div.innerHTML.replace(/\n/g, '<br />');
3797
- }
3798
- };
4298
+ // Utilities the compiled render function calls (see render_utilities)
4299
+ const jqhtml = render_utilities;
3799
4300
  // Execute template function
3800
4301
  // Commented out debug logging
3801
4302
  // console.log('[Component] About to call render, this:', this);
@@ -3834,69 +4335,48 @@ class Jqhtml_Component {
3834
4335
  // Check for template inheritance (slot-only OR explicit extends)
3835
4336
  // If instructions is {_slots: {...}}, find parent template and invoke it
3836
4337
  if (instructions && typeof instructions === 'object' && instructions._slots && !Array.isArray(instructions)) {
3837
- const componentName = template_def.name || this.args._component_name || this.constructor.name;
3838
- console.log(`[JQHTML] Slot-only template detected for ${componentName}`);
3839
- let parentTemplate = null;
3840
- let parentTemplateName = null;
3841
- // First check for explicit extends attribute in template metadata
3842
- if (template_def.extends) {
3843
- console.log(`[JQHTML] Using explicit extends: ${template_def.extends}`);
3844
- parentTemplate = get_template(template_def.extends);
3845
- parentTemplateName = template_def.extends;
3846
- }
3847
- // If no explicit extends, walk the prototype chain to find parent class with template
3848
- if (!parentTemplate) {
3849
- let currentClass = Object.getPrototypeOf(this.constructor);
3850
- while (currentClass && currentClass.name !== 'Object' && currentClass.name !== 'Jqhtml_Component') {
3851
- const className = currentClass.name;
3852
- console.log(`[JQHTML] Checking parent: ${className}`);
3853
- try {
3854
- const classTemplate = get_template(className);
3855
- if (classTemplate && classTemplate.name !== 'Jqhtml_Component') {
3856
- console.log(`[JQHTML] Found parent template: ${className}`);
3857
- parentTemplate = classTemplate;
3858
- parentTemplateName = className;
3859
- break;
3860
- }
3861
- }
3862
- catch (error) {
3863
- console.warn(`[JQHTML] Error finding parent template ${className}:`, error);
3864
- }
3865
- currentClass = Object.getPrototypeOf(currentClass);
3866
- }
4338
+ const component_name = template_def.name || this.args._component_name || this.constructor.name;
4339
+ const parent = resolve_parent_template(template_def, this.constructor);
4340
+ // A slot-only template is nothing but an override of a parent. With no parent
4341
+ // there is nothing to render, and rendering empty hides the mistake (usually a
4342
+ // missing register_template) behind a blank element. Fail loudly instead.
4343
+ if (!parent) {
4344
+ throw new Error(`[JQHTML] ${component_name}: slot-only template has no parent template. ` +
4345
+ `Add extends="Parent_Name" to <Define:${component_name}>, extend a class whose ` +
4346
+ `template is registered, or give the template markup of its own.`);
3867
4347
  }
3868
- // If we found a parent template, invoke it with child's slots
3869
- if (parentTemplate) {
3870
- try {
3871
- // Create a content function that invokes child slots
3872
- // When parent calls content('slotName'), it invokes the child's slot function
3873
- const childSlots = instructions._slots;
3874
- const contentFunction = (slotName, ...slotArgs) => {
3875
- if (childSlots[slotName] && typeof childSlots[slotName] === 'function') {
3876
- // Invoke the slot function with everything content() was given
3877
- const [slotInstructions, slotContext] = childSlots[slotName](...slotArgs);
3878
- // Return in render function format: [instructions, context]
3879
- // The template expression handler expects this format
3880
- return [slotInstructions, slotContext];
3881
- }
3882
- // Slot not found, return empty
3883
- return '';
3884
- };
3885
- // Invoke parent template with child's slots as content function
3886
- const [parentInstructions, parentContext] = parentTemplate.render.bind(this)(this.data, this.args, contentFunction, // Pass content function that invokes child slots
3887
- jqhtml);
3888
- console.log(`[JQHTML] Parent template invoked successfully`);
3889
- instructions = parentInstructions;
3890
- context = parentContext;
3891
- }
3892
- catch (error) {
3893
- console.warn(`[JQHTML] Error invoking parent template ${parentTemplateName}:`, error);
3894
- instructions = [];
4348
+ // Create a content function that invokes child slots
4349
+ // When parent calls content('slotName'), it invokes the child's slot function
4350
+ const childSlots = instructions._slots;
4351
+ const contentFunction = (slotName, ...slotArgs) => {
4352
+ if (childSlots[slotName] && typeof childSlots[slotName] === 'function') {
4353
+ // Invoke the slot function with everything content() was given
4354
+ const [slotInstructions, slotContext] = childSlots[slotName](...slotArgs);
4355
+ // Return in render function format: [instructions, context]
4356
+ // The template expression handler expects this format
4357
+ return [slotInstructions, slotContext];
3895
4358
  }
4359
+ // Slot not found, return empty
4360
+ return '';
4361
+ };
4362
+ // Invoke parent template with child's slots as content function.
4363
+ // A parent template that throws is a real defect in the parent's markup. It used
4364
+ // to be swallowed into an empty render plus a warning nobody reads; it is now
4365
+ // re-thrown, which routes it through the boot error path: logged, this component
4366
+ // stopped, its waiting ancestors released.
4367
+ try {
4368
+ const [parentInstructions, parentContext] = parent.template.render.bind(this)(this.data, this.args, contentFunction, // Pass content function that invokes child slots
4369
+ jqhtml);
4370
+ instructions = parentInstructions;
4371
+ context = parentContext;
3896
4372
  }
3897
- else {
3898
- console.warn(`[JQHTML] No parent template found for ${this.constructor.name}, rendering empty`);
3899
- instructions = [];
4373
+ catch (error) {
4374
+ // Rethrown, not swallowed - only re-labelled so the report names both ends
4375
+ // of the inheritance, which the raw template error does not.
4376
+ const wrapped = new Error(`[JQHTML] ${component_name}: parent template ${parent.name} threw while ` +
4377
+ `rendering slot-only child: ${error?.message ?? error}`);
4378
+ wrapped.cause = error; // ES2020 target: Error(message, {cause}) is not typed
4379
+ throw wrapped;
3900
4380
  }
3901
4381
  }
3902
4382
  // Process instructions to generate DOM. ['_content', ...] markers from
@@ -3917,10 +4397,33 @@ class Jqhtml_Component {
3917
4397
  }
3918
4398
  this._fire_viewport_resize();
3919
4399
  }
4400
+ // "Already rendered once" - read before the state below can move to 3.
4401
+ const isRerender = this._ready_state >= 3;
4402
+ // HTML CACHE MODE: Mark on_render complete after the post-on_load render.
4403
+ // This signals to parent components that this component's DOM is fully rendered
4404
+ // with fresh data and ready for HTML snapshot. It is set BEFORE trigger('render')
4405
+ // because _wait_for_children_on_render() waits on that very event and reads the
4406
+ // flag from its handler.
4407
+ if (this._ready_state >= 2) {
4408
+ this._on_render_complete = true;
4409
+ // State 3 = "rendered with loaded data, ready phase not finished yet".
4410
+ // Only meaningful once the load phase has happened (>= 2); before that the
4411
+ // component is still walking 0 -> 1 -> 2 and must not be pushed forward.
4412
+ // The ready phase (_ready(), render()'s executor, _reload()) restores 4.
4413
+ this._ready_state = 3;
4414
+ this._update_debug_attrs();
4415
+ }
4416
+ else if (!this.__has_custom_on_load) {
4417
+ // A component with no custom on_load() skips the load phase entirely, so it never
4418
+ // reaches _ready_state 2 and would never set the flag above - and its data cannot
4419
+ // change, so this first render IS its final, fresh render. Without this, an
4420
+ // html-cache parent waited forever in _wait_for_children_on_render() for a
4421
+ // template-only child and never snapshotted, rendered or fired 'ready'.
4422
+ this._on_render_complete = true;
4423
+ }
3920
4424
  // Emit lifecycle event
3921
4425
  this.trigger('render');
3922
4426
  // Apply debug delay after render
3923
- const isRerender = this._ready_state >= 3; // Already rendered once
3924
4427
  applyDebugDelay(isRerender ? 'rerender' : 'render');
3925
4428
  // Store args snapshot for reload() comparison (skip if non-serializable)
3926
4429
  try {
@@ -3932,12 +4435,6 @@ class Jqhtml_Component {
3932
4435
  }
3933
4436
  // Store data snapshot for refresh() comparison
3934
4437
  this._data_on_last_render = JSON.stringify(this.data);
3935
- // HTML CACHE MODE: Mark on_render complete after second render (post-on_load)
3936
- // This signals to parent components that this component's DOM is fully rendered
3937
- // with fresh data and ready for HTML snapshot
3938
- if (this._ready_state >= 2) {
3939
- this._on_render_complete = true;
3940
- }
3941
4438
  // Return the render ID so callers can check if this render is still current
3942
4439
  return current_render_id;
3943
4440
  }
@@ -3957,10 +4454,12 @@ class Jqhtml_Component {
3957
4454
  render(id = null) {
3958
4455
  if (this._stopped)
3959
4456
  return Promise.resolve();
3960
- // Invalidate ready event so new handlers wait for this render cycle to complete
3961
- // This prevents .on('ready') handlers from firing immediately based on previous lifecycle
3962
- this.invalidate('ready');
3963
- // If id provided, delegate to child component
4457
+ // If id provided, delegate to child component.
4458
+ // NOTE: this runs BEFORE invalidate('ready'). render(sid) does not start a
4459
+ // lifecycle on THIS component - it delegates to the redrawable child, which
4460
+ // invalidates and re-triggers its own 'ready'. Invalidating here would delete
4461
+ // this component's sticky ready marker with nothing left to re-trigger it, so
4462
+ // every later `await comp.ready()` would hang.
3964
4463
  if (id) {
3965
4464
  const $element = this.$sid(id);
3966
4465
  if ($element.length === 0) {
@@ -3975,14 +4474,23 @@ class Jqhtml_Component {
3975
4474
  }
3976
4475
  return child.render();
3977
4476
  }
4477
+ // Invalidate ready event so new handlers wait for this render cycle to complete
4478
+ // This prevents .on('ready') handlers from firing immediately based on previous lifecycle
4479
+ this.invalidate('ready');
3978
4480
  // Enqueue the full render lifecycle through the component queue
3979
4481
  // Return the queue promise so `await this.render()` resolves when the
3980
4482
  // full render lifecycle (DOM update, children ready, on_ready) completes
3981
4483
  return this._queue.enqueue('render', async () => {
4484
+ // The queued executor can start long after render() was called - re-check.
4485
+ if (this._stopped)
4486
+ return;
3982
4487
  // Execute render phase synchronously and capture render ID
3983
4488
  const render_id = this._render();
3984
4489
  // Wait for all child components to be ready
3985
4490
  await this._wait_for_children_ready();
4491
+ // Stopped while waiting for children: no hook, no event on a dead component.
4492
+ if (this._stopped)
4493
+ return;
3986
4494
  // Check if this render is still current before calling on_ready
3987
4495
  // If _render_count changed, another render happened and we should skip on_ready
3988
4496
  if (this._render_count !== render_id) {
@@ -3990,7 +4498,15 @@ class Jqhtml_Component {
3990
4498
  }
3991
4499
  // Call on_ready hook with authorization
3992
4500
  await this._call_lifecycle('on_ready');
4501
+ // on_ready() may itself have awaited long enough for a stop().
4502
+ if (this._stopped)
4503
+ return;
3993
4504
  this._fire_viewport_resize();
4505
+ // Back to the ready state: _render() dropped it to 3. Set BEFORE the trigger
4506
+ // so a handler that calls ready() during dispatch takes the already-ready
4507
+ // fast path instead of waiting for another trigger that will never come.
4508
+ this._ready_state = 4;
4509
+ this._update_debug_attrs();
3994
4510
  // Trigger ready event
3995
4511
  this.trigger('ready');
3996
4512
  });
@@ -4020,40 +4536,54 @@ class Jqhtml_Component {
4020
4536
  async load() {
4021
4537
  if (this._stopped)
4022
4538
  return false;
4023
- // Capture result through queue closure
4024
- let data_changed = false;
4025
- await this._queue.enqueue('load', async () => {
4539
+ // No custom on_load() means there is nothing to run and nothing can have changed.
4540
+ // Running the detached execution anyway seeded this.data with the empty detached
4541
+ // clone (create() takes no snapshot for these components), silently wiping whatever
4542
+ // on_create() had set.
4543
+ if (!this.__has_custom_on_load)
4544
+ return false;
4545
+ // The queue settles this caller with the value of the executor that actually
4546
+ // ran - including one that collapsed two rapid load() calls into one run - so
4547
+ // the result is returned from the executor, not read back out of a closure
4548
+ // variable that a discarded executor would have left at its initial value.
4549
+ return this._queue.enqueue('load', async () => {
4550
+ // The queued executor can start long after load() was called - re-check.
4551
+ if (this._stopped)
4552
+ return false;
4026
4553
  // Snapshot current data for change detection
4027
4554
  const data_before = JSON.stringify(this.data);
4028
4555
  // Execute on_load() on detached proxy (restores data to on_create snapshot)
4029
- const { data: result_data } = await this._execute_on_load_detached(false);
4030
- // Atomically update this.data: unfreeze → assign → normalize → refreeze
4556
+ const { data: result_data } = await this._execute_on_load_detached(null);
4557
+ // Stopped during on_load(): don't write data or cache for a dead component.
4558
+ if (this._stopped)
4559
+ return false;
4560
+ // Atomically update this.data: unfreeze → normalize → assign → refreeze.
4561
+ // The round trip runs in EVERY cache mode - see _apply_load_result().
4031
4562
  this.__data_frozen = false;
4032
- this.data = result_data;
4033
- const cache_mode = Jqhtml_Local_Storage.get_cache_mode();
4034
- if (cache_mode === 'data') {
4035
- const normalized = Jqhtml_Local_Storage.normalize_for_cache(this.data);
4036
- this.data = normalized;
4037
- }
4563
+ this.data = Jqhtml_Local_Storage.normalize_for_cache(result_data, this.component_name());
4038
4564
  this.__data_frozen = true;
4565
+ const cache_mode = Jqhtml_Local_Storage.get_cache_mode();
4039
4566
  // Detect if data changed
4040
4567
  const data_after = JSON.stringify(this.data);
4041
- data_changed = data_before !== data_after;
4568
+ const data_changed = data_before !== data_after;
4042
4569
  // Update cache with fresh data if changed
4043
4570
  if (data_changed) {
4044
- // Regenerate cache key (args may have changed since boot)
4045
- let cache_key = null;
4046
- if (typeof this.cache_id === 'function') {
4047
- try {
4048
- cache_key = `${this.component_name()}::${String(this.cache_id())}`;
4571
+ // ONE derivation, shared with the cache read in create() and with _load().
4572
+ // The copy that used to live here omitted content serialization, so an
4573
+ // object-arg component computed a null key and silently never wrote the
4574
+ // cache that create() would later read with the content-serialized key.
4575
+ // Recomputed rather than reused: args may have changed since boot.
4576
+ const { cache_key, uncacheable_property, uncacheable_reason } = generate_cache_key(this);
4577
+ if (cache_key === null) {
4578
+ // Leave the same record _load() leaves: the offending arg on the element,
4579
+ // and one dev warning. A silent catch here made a throwing cache_id()
4580
+ // undiagnosable - the component simply stopped being cached.
4581
+ if (uncacheable_property) {
4582
+ this.$.attr('data-nocache', uncacheable_reason ? `${uncacheable_property}:${uncacheable_reason}` : uncacheable_property);
4049
4583
  }
4050
- catch { /* cache_id() threw - skip caching */ }
4051
- }
4052
- else {
4053
- const result = Load_Coordinator.generate_invocation_key(this.component_name(), this.args);
4054
- cache_key = result.key;
4584
+ warn_uncacheable_component(this, uncacheable_property, uncacheable_reason);
4055
4585
  }
4056
- if (cache_key && cache_mode !== 'html') {
4586
+ else if (cache_mode !== 'html') {
4057
4587
  Jqhtml_Local_Storage.set(cache_key, this.data);
4058
4588
  }
4059
4589
  }
@@ -4061,10 +4591,13 @@ class Jqhtml_Component {
4061
4591
  // Suppressed by _load_only and _load_render_only flags (preloading mode)
4062
4592
  if (!this._load_only && !this._load_render_only) {
4063
4593
  await this._call_lifecycle('on_loaded');
4594
+ // on_loaded() may have awaited across a stop(); don't fire 'loaded' after it.
4595
+ if (this._stopped)
4596
+ return data_changed;
4064
4597
  this.trigger('loaded');
4065
4598
  }
4599
+ return data_changed;
4066
4600
  });
4067
- return data_changed;
4068
4601
  }
4069
4602
  /**
4070
4603
  * Create phase - Quick setup, prepare UI
@@ -4087,15 +4620,18 @@ class Jqhtml_Component {
4087
4620
  // OPTIMIZATION: Skip cache operations and snapshot if no custom on_load()
4088
4621
  // Components without on_load() don't fetch data, so nothing to cache or restore
4089
4622
  if (this.__has_custom_on_load) {
4623
+ // Snapshot this.data the moment on_create() returns, BEFORE any cache read.
4624
+ // on_load() restarts from this snapshot every time, and CLAUDE.md promises that
4625
+ // is the on_create() state. read_cache_in_create() REPLACES this.data on a warm
4626
+ // 'data' cache, so snapshotting after it made a warm boot restart on_load() from
4627
+ // cached data - `this.data.items.push(x)` doubled its rows on every reload.
4628
+ this.__initial_data_snapshot = JSON.parse(JSON.stringify(this.data));
4090
4629
  // CACHE CHECK - Read from cache based on cache mode ('data' or 'html')
4091
4630
  // Skip cache for detached elements — no point hydrating from cache when not in DOM
4092
4631
  // @see component-cache.ts for full implementation
4093
4632
  if (!this._is_detached) {
4094
4633
  read_cache_in_create(this);
4095
4634
  }
4096
- // Snapshot this.data after on_create() completes
4097
- // This will be restored before each on_load() execution to reset state
4098
- this.__initial_data_snapshot = JSON.parse(JSON.stringify(this.data));
4099
4635
  }
4100
4636
  // Freeze this.data after on_create() - only on_load() can modify it now
4101
4637
  this.__data_frozen = true;
@@ -4226,26 +4762,7 @@ class Jqhtml_Component {
4226
4762
  // follower never runs on_load() and adopts the leader's data with NO
4227
4763
  // revalidation, so a wrong key here is permanently wrong data. Redundant
4228
4764
  // concurrent requests are the cheaper failure.
4229
- let cache_key = null;
4230
- let uncacheable_property;
4231
- let uncacheable_reason;
4232
- if (typeof this.cache_id === 'function') {
4233
- try {
4234
- const custom_cache_id = this.cache_id();
4235
- cache_key = `${this.component_name()}::${String(custom_cache_id)}`;
4236
- }
4237
- catch (error) {
4238
- // cache_id() threw error - disable caching
4239
- uncacheable_property = 'cache_id()';
4240
- uncacheable_reason = 'cache-id-threw';
4241
- }
4242
- }
4243
- else {
4244
- const result = Load_Coordinator.generate_invocation_key(this.component_name(), this.args, { allow_content_serialization: true });
4245
- cache_key = result.key;
4246
- uncacheable_property = result.uncacheable_property;
4247
- uncacheable_reason = result.uncacheable_reason;
4248
- }
4765
+ const { cache_key, uncacheable_property, uncacheable_reason } = generate_cache_key(this);
4249
4766
  const dedup_key = Load_Coordinator.generate_invocation_key(this.component_name(), this.args).key;
4250
4767
  // SSR preload check: if preloaded data exists for this component+args, use it
4251
4768
  if (cache_key !== null && has_preload_data()) {
@@ -4276,24 +4793,26 @@ class Jqhtml_Component {
4276
4793
  if (window.jqhtml?.debug?.verbose) {
4277
4794
  console.log(`[Load Deduplication] Component ${this._cid} (${this.component_name()}) has no dedup key - loading independently`);
4278
4795
  }
4279
- const { data: result_data } = await this._execute_on_load_detached();
4796
+ const { data: result_data } = await this._execute_on_load_detached(null);
4280
4797
  await this._apply_load_result(result_data, data_before_load);
4281
4798
  return;
4282
4799
  }
4283
4800
  // Check if this component should execute on_load() or wait for existing request
4284
- const should_execute = Load_Coordinator.should_execute_on_load(this);
4801
+ const should_execute = Load_Coordinator.should_execute_on_load(this, dedup_key);
4285
4802
  if (!should_execute) {
4286
4803
  // This component is a follower - wait for leader to complete
4287
4804
  if (window.jqhtml?.debug?.verbose) {
4288
4805
  console.log(`[Load Deduplication] Component ${this._cid} (${this.component_name()}) is a follower, waiting for leader`, { args: this.args });
4289
4806
  }
4290
- const coordination_promise = Load_Coordinator.get_coordination_promise(this);
4807
+ // Every coordinator call uses the key captured ABOVE, before on_load() began.
4808
+ // Recomputing it here would miss the entry whenever args changed meanwhile.
4809
+ const coordination_promise = Load_Coordinator.get_coordination_promise(dedup_key);
4291
4810
  if (coordination_promise) {
4292
4811
  try {
4293
- // Wait for leader to complete
4812
+ // Wait for leader to complete (rejects if the leader's on_load() threw)
4294
4813
  await coordination_promise;
4295
4814
  // Retrieve leader's data from coordinator
4296
- const leader_data = Load_Coordinator.get_leader_data(this);
4815
+ const leader_data = Load_Coordinator.get_leader_data(this, dedup_key);
4297
4816
  if (leader_data !== null) {
4298
4817
  // Apply leader's data using the same method as leader
4299
4818
  // This properly handles freeze/unfreeze and normalization
@@ -4311,15 +4830,11 @@ class Jqhtml_Component {
4311
4830
  throw error;
4312
4831
  }
4313
4832
  }
4314
- // Fallback: if we couldn't get leader data, just mark as complete
4315
- this._ready_state = 2;
4316
- this._update_debug_attrs();
4317
- this._log_lifecycle('load', 'complete (follower)');
4318
- this.trigger('load');
4319
- if (!this._load_only && !this._load_render_only) {
4320
- await this._call_lifecycle('on_loaded');
4321
- this.trigger('loaded');
4322
- }
4833
+ // No leader data to adopt (the entry was already collected, or its data could
4834
+ // not be serialized). Load independently rather than firing load/loaded with the
4835
+ // untouched on_create() data.
4836
+ const { data: result_data } = await this._execute_on_load_detached(null);
4837
+ await this._apply_load_result(result_data, data_before_load);
4323
4838
  return;
4324
4839
  }
4325
4840
  // This component is a leader - execute on_load() on detached proxy
@@ -4327,7 +4842,7 @@ class Jqhtml_Component {
4327
4842
  console.log(`[Load Deduplication] Component ${this._cid} (${this.component_name()}) is the leader`, { args: this.args });
4328
4843
  }
4329
4844
  // Execute on_load on detached proxy with Load_Coordinator registration
4330
- const { data: result_data, complete_coordination } = await this._execute_on_load_detached(true);
4845
+ const { data: result_data, complete_coordination } = await this._execute_on_load_detached(dedup_key);
4331
4846
  // Apply result via sequential queue
4332
4847
  await this._apply_load_result(result_data, data_before_load);
4333
4848
  // Complete coordination AFTER this.data is updated
@@ -4341,8 +4856,8 @@ class Jqhtml_Component {
4341
4856
  * @see data-proxy.ts for full implementation
4342
4857
  * @private
4343
4858
  */
4344
- async _execute_on_load_detached(use_load_coordinator = false) {
4345
- return execute_on_load_detached(this, use_load_coordinator);
4859
+ async _execute_on_load_detached(dedup_key = null) {
4860
+ return execute_on_load_detached(this, dedup_key);
4346
4861
  }
4347
4862
  /**
4348
4863
  * Apply the result of on_load() to this.data via the sequential queue.
@@ -4365,21 +4880,22 @@ class Jqhtml_Component {
4365
4880
  await my_turn;
4366
4881
  try {
4367
4882
  // Now it's our turn to set this.data
4368
- // Unfreeze, set data, freeze
4883
+ // Every on_load() result is round-tripped through the cache serializer before it
4884
+ // becomes this.data - in EVERY cache mode, not just 'data'. Two consequences the
4885
+ // rest of the framework depends on:
4886
+ // - this.data is jqhtml's own copy. The author's object graph is never aliased,
4887
+ // so mutating what on_load() returned cannot reach a frozen this.data.
4888
+ // - this.data is BY CONSTRUCTION what the cache stores and what a cache hit
4889
+ // returns. Hot and cold are the same object shape in every mode, so turning
4890
+ // caching on can never change what a component sees.
4891
+ // Dates, Maps, Sets and register_cache_class() classes are reconstructed; anything
4892
+ // the serializer cannot express is dropped and warned about once (local-storage.ts).
4369
4893
  this.__data_frozen = false;
4370
- this.data = result_data;
4371
- // DATA MODE: Normalize this.data through serialize/deserialize round-trip
4372
- // This ensures "hot" data (fresh from on_load) behaves identically to "cold" data
4373
- const cache_mode = Jqhtml_Local_Storage.get_cache_mode();
4374
- if (cache_mode === 'data') {
4375
- const normalized = Jqhtml_Local_Storage.normalize_for_cache(this.data);
4376
- this.data = normalized;
4377
- if (window.jqhtml?.debug?.verbose) {
4378
- console.log(`[Cache data] Component ${this._cid} (${this.component_name()}) normalized this.data after on_load()`, { data: this.data });
4379
- }
4380
- }
4381
- // Freeze this.data
4894
+ this.data = Jqhtml_Local_Storage.normalize_for_cache(result_data, this.component_name());
4382
4895
  this.__data_frozen = true;
4896
+ if (window.jqhtml?.debug?.verbose) {
4897
+ console.log(`[Cache] Component ${this._cid} (${this.component_name()}) normalized this.data after on_load()`, { data: this.data });
4898
+ }
4383
4899
  // SSR data capture: record this component's data for preloading
4384
4900
  if (is_capture_enabled() && this._has_on_load()) {
4385
4901
  capture_component_data(this.component_name(), this.args, this.data, this._cache_key);
@@ -4465,9 +4981,11 @@ class Jqhtml_Component {
4465
4981
  callback();
4466
4982
  return Promise.resolve();
4467
4983
  }
4468
- // Return promise that resolves when ready event fires
4984
+ // Return promise that resolves when ready event fires.
4985
+ // once(), not on(): a promise can only settle once, so a permanent listener
4986
+ // just accumulates on the component - one per ready() call, forever.
4469
4987
  return new Promise((resolve) => {
4470
- this.on('ready', () => {
4988
+ this.once('ready', () => {
4471
4989
  if (callback)
4472
4990
  callback();
4473
4991
  resolve();
@@ -4525,9 +5043,18 @@ class Jqhtml_Component {
4525
5043
  if (child._ready_state >= 4) {
4526
5044
  continue;
4527
5045
  }
4528
- // Create promise that resolves when child reaches ready
5046
+ // A stopped child will never fire 'ready' again - waiting on it would wedge
5047
+ // this parent (and everything awaiting its ready()) forever.
5048
+ if (child._stopped) {
5049
+ continue;
5050
+ }
5051
+ // Create promise that resolves when child reaches ready.
5052
+ // once(), not on(): a permanent listener would be appended to the child on
5053
+ // every render/reload cycle of a polling parent and never removed.
5054
+ // Raced against 'stop' so a child stopped mid-wait releases the parent.
4529
5055
  const ready_promise = new Promise((resolve) => {
4530
- child.on('ready', () => resolve());
5056
+ child.once('ready', () => resolve());
5057
+ child.once('stop', () => resolve());
4531
5058
  });
4532
5059
  ready_promises.push(ready_promise);
4533
5060
  }
@@ -4553,22 +5080,42 @@ class Jqhtml_Component {
4553
5080
  // Create promises for each child that hasn't completed on_render yet
4554
5081
  const render_promises = [];
4555
5082
  for (const child of children) {
4556
- // If child already completed on_render post-on_load, skip
4557
- if (child._on_render_complete) {
5083
+ // If child already completed on_render post-on_load (or is dead), skip
5084
+ if (child._on_render_complete || child._stopped) {
4558
5085
  continue;
4559
5086
  }
4560
- // Create promise that resolves when child completes on_render
5087
+ // Event-driven, not polled: the child sets _on_render_complete just before it
5088
+ // fires 'render', and 'stop' ends the wait for a child that dies first.
5089
+ //
5090
+ // A plain once('render') would be wrong: events are sticky, and this child has
5091
+ // already rendered at least once (the pre-on_load render), so once() would fire
5092
+ // immediately off that stale marker and let the parent snapshot half-rendered DOM.
5093
+ // The handler therefore re-checks the flag and stays registered until it is set.
4561
5094
  const render_promise = new Promise((resolve) => {
4562
- // Poll for completion (simple approach - could use events for more efficiency)
4563
- const check = () => {
4564
- if (child._on_render_complete || child._stopped) {
4565
- resolve();
4566
- }
4567
- else {
4568
- setTimeout(check, 10);
5095
+ let settled = false;
5096
+ const on_child_event = () => {
5097
+ if (settled)
5098
+ return;
5099
+ if (!child._on_render_complete && !child._stopped)
5100
+ return; // pre-load render
5101
+ settled = true;
5102
+ // There is no off() in the event API; splice this handler out of both queues
5103
+ // the way once() does, so a long-lived child does not accumulate handlers
5104
+ // across repeated waits.
5105
+ for (const event_name of ['render', 'stop']) {
5106
+ const callbacks = child._lifecycle_callbacks.get(event_name);
5107
+ if (callbacks) {
5108
+ const idx = callbacks.indexOf(on_child_event);
5109
+ if (idx !== -1)
5110
+ callbacks.splice(idx, 1);
5111
+ }
4569
5112
  }
5113
+ resolve();
4570
5114
  };
4571
- check();
5115
+ // 'stop' first: registering 'render' can fire the handler synchronously (sticky),
5116
+ // and the handler must be able to deregister both queues when it does.
5117
+ child.on('stop', on_child_event);
5118
+ child.on('render', on_child_event);
4572
5119
  });
4573
5120
  render_promises.push(render_promise);
4574
5121
  }
@@ -4672,8 +5219,17 @@ class Jqhtml_Component {
4672
5219
  this.next_reload_force_refresh = null;
4673
5220
  this._render();
4674
5221
  await this._wait_for_children_ready();
5222
+ // Stopped while waiting for children: no hook, no event on a dead component.
5223
+ if (this._stopped)
5224
+ return;
4675
5225
  await this._call_lifecycle('on_ready');
5226
+ // on_ready() may itself have awaited long enough for a stop().
5227
+ if (this._stopped)
5228
+ return;
4676
5229
  this._fire_viewport_resize();
5230
+ // Restore the ready state (_render() dropped it to 3) before the trigger
5231
+ this._ready_state = 4;
5232
+ this._update_debug_attrs();
4677
5233
  this.trigger('ready');
4678
5234
  this._log_lifecycle('reload', 'complete (no on_load)');
4679
5235
  return;
@@ -4701,10 +5257,16 @@ class Jqhtml_Component {
4701
5257
  // STEP 2: Call on_load() on detached proxy
4702
5258
  // This uses the same detached execution as _load() - on_load runs isolated
4703
5259
  // and result is applied via sequential queue
4704
- const { data: result_data } = await this._execute_on_load_detached(false); // false = don't use Load_Coordinator
5260
+ const { data: result_data } = await this._execute_on_load_detached(null); // null = no coordination
5261
+ // Stopped during on_load(): don't write data or re-render a dead component.
5262
+ if (this._stopped)
5263
+ return;
4705
5264
  // Apply result via sequential queue
4706
5265
  // This handles normalization, caching, and setting _is_dynamic
4707
5266
  await this._apply_load_result(result_data, data_before_load);
5267
+ // The apply queue can yield; a stop() there must abort the render/ready tail.
5268
+ if (this._stopped)
5269
+ return;
4708
5270
  // Re-read data state after apply (for render decision below)
4709
5271
  const data_after_load = JSON.stringify(this.data);
4710
5272
  const data_changed = data_after_load !== data_before_load;
@@ -4713,6 +5275,15 @@ class Jqhtml_Component {
4713
5275
  const force_refresh = this.next_reload_force_refresh !== null ? this.next_reload_force_refresh : true;
4714
5276
  // Track if we need to render
4715
5277
  let should_render = false;
5278
+ // HTML CACHE MODE: a cache injection above replaced the subtree with inert markup -
5279
+ // a snapshot string, with no live child components in it. It must be re-rendered
5280
+ // from the template regardless of what the load decided, exactly as _should_rerender()
5281
+ // forces it at boot. Without this, a reload whose data came back unchanged left dead
5282
+ // HTML (stopped children, no instances) on screen.
5283
+ const used_cached_html = this._used_cached_html;
5284
+ if (used_cached_html) {
5285
+ this._used_cached_html = false;
5286
+ }
4716
5287
  if (force_refresh) {
4717
5288
  // reload(true) or reload() - always render if we haven't yet, OR data changed
4718
5289
  should_render = !rendered_from_cache || data_changed;
@@ -4733,6 +5304,11 @@ class Jqhtml_Component {
4733
5304
  }
4734
5305
  }
4735
5306
  // STEP 3: Perform second render if needed
5307
+ // The cache injection's inert markup is not optional to replace - this overrides both
5308
+ // the reload() and the refresh()/reload(false) decision above.
5309
+ if (used_cached_html) {
5310
+ should_render = true;
5311
+ }
4736
5312
  if (should_render) {
4737
5313
  this._render();
4738
5314
  }
@@ -4747,11 +5323,33 @@ class Jqhtml_Component {
4747
5323
  // STEP 3.5 & 4: Wait for children and call on_ready (only if we rendered)
4748
5324
  if (rendered_from_cache || should_render) {
4749
5325
  await this._wait_for_children_ready();
5326
+ // Stopped while waiting for children: no hook, no event on a dead component.
5327
+ if (this._stopped)
5328
+ return;
4750
5329
  await this._call_lifecycle('on_ready');
5330
+ // on_ready() may itself have awaited long enough for a stop().
5331
+ if (this._stopped)
5332
+ return;
4751
5333
  this._fire_viewport_resize();
5334
+ // Restore the ready state (the load phase dropped it to 2, _render() to 3)
5335
+ // before the trigger, so handlers see a ready component.
5336
+ this._ready_state = 4;
5337
+ this._update_debug_attrs();
4752
5338
  // Trigger ready event so parent callbacks fire on subsequent reloads
4753
5339
  this.trigger('ready');
4754
5340
  }
5341
+ else {
5342
+ // refresh()/reload(false) found unchanged data: no re-render, and on_ready()
5343
+ // is deliberately NOT called (documented behaviour). But the component IS
5344
+ // ready - and this cycle deleted the sticky 'ready' marker at the top of
5345
+ // _reload() and dropped _ready_state to 2 in the load phase. Without
5346
+ // restoring both, ready() never resolves again and a parent re-entering
5347
+ // _wait_for_children_ready() hangs on this child forever (the documented
5348
+ // polling pattern breaks after its first quiet refresh).
5349
+ this._ready_state = 4;
5350
+ this._update_debug_attrs();
5351
+ this.trigger('ready');
5352
+ }
4755
5353
  this._log_lifecycle('reload', 'complete');
4756
5354
  }
4757
5355
  /**
@@ -4776,26 +5374,28 @@ class Jqhtml_Component {
4776
5374
  this.__gate_resume = null;
4777
5375
  resume();
4778
5376
  }
4779
- // Early bailout: skip expensive cleanup if no handlers registered
4780
- // Only matters for aborting boot() lifecycle - minimal cleanup sufficient
4781
- const has_custom_stop = this.on_stop !== Jqhtml_Component.prototype.on_stop;
4782
- const has_stop_callbacks = this._on_registered('stop');
4783
- if (!has_custom_stop && !has_stop_callbacks) {
4784
- // Fast path: no cleanup logic defined, just mark as stopped
4785
- this._lifecycle_manager.unregister_component(this);
4786
- this._ready_state = 99;
4787
- return;
4788
- }
4789
- // Full cleanup path: component has custom stop logic
5377
+ // There is deliberately NO fast path for components without stop logic. The
5378
+ // marker class, the parent de-registration and the 'stop' event are not cleanup
5379
+ // the component asked for, they are how the rest of the framework learns this
5380
+ // component is dead: the class is the documented, observable stopped state; a
5381
+ // child left in _dom_parent._dom_children is a dead component every later
5382
+ // _wait_for_children_ready() and _get_dom_children() walks; and 'stop' is what
5383
+ // releases a parent (and boot's failure path) waiting on a child that will never
5384
+ // fire 'ready'. Skipping them for the common no-on_stop() child was what leaked
5385
+ // stopped children into the parent's registry.
4790
5386
  this._log_lifecycle('destroy', 'start');
4791
5387
  this.$.addClass('_Component_Stopped');
4792
5388
  // Unregister from lifecycle manager
4793
5389
  this._lifecycle_manager.unregister_component(this);
4794
- // Call user's on_stop() hook with authorization (sync)
4795
- const stopResult = this._call_lifecycle_sync('on_stop');
4796
- if (stopResult && typeof stopResult.then === 'function') {
4797
- console.warn(`[JQHTML] Component "${this.component_name()}" returned a Promise from on_stop(). ` +
4798
- `on_stop() must be synchronous code. Remove 'async' from the function declaration.`);
5390
+ // Call user's on_stop() hook with authorization (sync) - only when actually
5391
+ // overridden, since _call_lifecycle_sync() on the base no-op costs per child
5392
+ // on every re-render.
5393
+ if (this.on_stop !== Jqhtml_Component.prototype.on_stop) {
5394
+ const stopResult = this._call_lifecycle_sync('on_stop');
5395
+ if (stopResult && typeof stopResult.then === 'function') {
5396
+ console.warn(`[JQHTML] Component "${this.component_name()}" returned a Promise from on_stop(). ` +
5397
+ `on_stop() must be synchronous code. Remove 'async' from the function declaration.`);
5398
+ }
4799
5399
  }
4800
5400
  // Fire registered stop callbacks
4801
5401
  this.trigger('stop');
@@ -4880,8 +5480,15 @@ class Jqhtml_Component {
4880
5480
  /**
4881
5481
  * Get component name for debugging
4882
5482
  */
5483
+ /**
5484
+ * The name this component was invoked as - the tag written in the template
5485
+ * (<User_Card> -> 'User_Card'), the name given to $(el).component('User_Card'),
5486
+ * or the boot placeholder's data-component-init-name. For a template-only
5487
+ * component this is the template name, not 'Jqhtml_Component'. Falls back to
5488
+ * the class's static component_name, then its JS class name.
5489
+ */
4883
5490
  component_name() {
4884
- return this.constructor.name;
5491
+ return this._component_name;
4885
5492
  }
4886
5493
  /**
4887
5494
  * Register event callback - delegates to component-events.ts
@@ -5064,6 +5671,48 @@ class Jqhtml_Component {
5064
5671
  _generate_cid() {
5065
5672
  return uid();
5066
5673
  }
5674
+ /**
5675
+ * Re-scope every scoped id in an HTML-cache snapshot so it belongs to THIS instance.
5676
+ *
5677
+ * A snapshot is the inner HTML of some component instance, so it contains ids of the
5678
+ * form `<name>:<cid>`: the snapshotting component's own elements carry its cid, and
5679
+ * elements rendered by nested children carry each child's cid. Replayed verbatim into
5680
+ * a second instance those ids are duplicates of the originals, and $sid() resolves via
5681
+ * getElementById(), which returns whichever matching element is first in the document -
5682
+ * so one instance could read and write another instance's DOM.
5683
+ *
5684
+ * Mapping: the snapshot owner's cid becomes this._cid (so $sid() finds the elements
5685
+ * this component is about to treat as its own), and every other cid becomes a fresh
5686
+ * uid(), consistently within one injection. Two instances hydrated from one snapshot
5687
+ * therefore share no id at all.
5688
+ *
5689
+ * The ':' separator is written only by the compiler ($sid) and the instruction
5690
+ * processor (a scoped plain id), and cids are uid() output - [a-z][a-z0-9]* - so the
5691
+ * pattern is exact. A plain unscoped id has no ':' and is left alone.
5692
+ *
5693
+ * data-cid is the debug mirror of a component's own _cid (config.ts debug_attributes).
5694
+ * The snapshot's values are stale cids belonging to components that no longer exist,
5695
+ * so they go through the same mapping rather than being left to lie in DevTools.
5696
+ *
5697
+ * @private
5698
+ */
5699
+ _rescope_cached_html(snapshot) {
5700
+ const cid_map = new Map();
5701
+ cid_map.set(snapshot.cid, this._cid);
5702
+ const remap = (old_cid) => {
5703
+ let new_cid = cid_map.get(old_cid);
5704
+ if (new_cid === undefined) {
5705
+ new_cid = uid();
5706
+ cid_map.set(old_cid, new_cid);
5707
+ }
5708
+ return new_cid;
5709
+ };
5710
+ return snapshot.html
5711
+ // id="<name>:<cid>" - the name half may itself contain ':' (an author-written
5712
+ // id="a:b" is scoped as "a:b:cid"), so the cid is anchored at the end.
5713
+ .replace(/ id="([^"]*):([a-z][a-z0-9]*)"/g, (_match, name, old_cid) => ` id="${name}:${remap(old_cid)}"`)
5714
+ .replace(/ data-cid="([a-z][a-z0-9]*)"/g, (_match, old_cid) => ` data-cid="${remap(old_cid)}"`);
5715
+ }
5067
5716
  _apply_css_classes() {
5068
5717
  const hierarchy = this.constructor.get_class_hierarchy();
5069
5718
  // If component name differs from class name, add component name to hierarchy
@@ -5103,26 +5752,29 @@ class Jqhtml_Component {
5103
5752
  }
5104
5753
  if (!template)
5105
5754
  return;
5106
- // Walk the extends chain to collect all defaultAttributes from parent templates
5107
- // Apply from parent to child so child attributes take precedence
5755
+ // Walk the inheritance chain to collect defaultAttributes from parent templates,
5756
+ // applying parent first so the child's own attributes take precedence.
5757
+ //
5758
+ // This uses resolve_parent_template(), the same helper the slot-only render path
5759
+ // uses, so a <Define>'s class/attrs resolve through EXACTLY the chain its markup
5760
+ // does. It previously followed only `extends=`, so a slot-only JS subclass
5761
+ // (class Users_Grid extends Grid_Abstract) inherited the parent's template but
5762
+ // none of the parent <Define>'s class="" or attributes.
5108
5763
  const templateChain = [];
5109
5764
  let currentTemplate = template;
5110
- // Build chain from child to parent
5111
- while (currentTemplate) {
5765
+ let currentClass = this.constructor;
5766
+ const seen = new Set();
5767
+ while (currentTemplate && !seen.has(currentTemplate)) {
5768
+ seen.add(currentTemplate);
5112
5769
  templateChain.unshift(currentTemplate); // Add to front so parent comes first
5113
- // Check if this template extends another
5114
- if (currentTemplate.extends) {
5115
- try {
5116
- currentTemplate = get_template(currentTemplate.extends);
5117
- }
5118
- catch (error) {
5119
- // Parent template not found, stop chain
5120
- break;
5121
- }
5122
- }
5123
- else {
5770
+ const parent = resolve_parent_template(currentTemplate, currentClass);
5771
+ if (!parent)
5124
5772
  break;
5125
- }
5773
+ currentTemplate = parent.template;
5774
+ // Advance the prototype walk too: the next parent must be resolved relative to
5775
+ // the class we just landed on, not the original one. A template-only parent has
5776
+ // no class, which is correct - its own chain can only be an explicit extends=.
5777
+ currentClass = get_component_class(parent.name) || null;
5126
5778
  }
5127
5779
  // Apply defaultAttributes from each template in the chain (parent first, child last)
5128
5780
  for (const tmpl of templateChain) {
@@ -5199,8 +5851,10 @@ class Jqhtml_Component {
5199
5851
  }
5200
5852
  }
5201
5853
  else {
5202
- // Regular attributes - apply directly if not already set
5203
- if (!this.$.attr(key)) {
5854
+ // Regular attributes - apply directly if not already set.
5855
+ // === undefined, not falsy: tabindex="0" and an empty-string attribute
5856
+ // written at the invocation are SET, and a Define default must not win.
5857
+ if (this.$.attr(key) === undefined) {
5204
5858
  this.$.attr(key, value);
5205
5859
  }
5206
5860
  }
@@ -5292,278 +5946,416 @@ Jqhtml_Component.__jqhtml_component = true; // Marker for unified register() det
5292
5946
  // A bare component name, as accepted by closest() in place of a class selector
5293
5947
  Jqhtml_Component.COMPONENT_NAME_PATTERN = COMPONENT_NAME_PATTERN;
5294
5948
 
5949
+ var light_css = "html[data-jqhtml-debug] .jqhtml-debug-hit {\n outline: 2px solid #e5322d;\n outline-offset: -2px;\n}\n\nhtml[data-jqhtml-debug] .jqhtml-debug-hit.jqhtml-debug-depth-0 {\n outline-color: #e5322d;\n}\n\nhtml[data-jqhtml-debug] .jqhtml-debug-hit.jqhtml-debug-depth-1 {\n outline-color: #2f6fe4;\n}\n\nhtml[data-jqhtml-debug] .jqhtml-debug-hit.jqhtml-debug-depth-2 {\n outline-color: #1f9d55;\n}\n\nhtml[data-jqhtml-debug] .jqhtml-debug-hit.jqhtml-debug-depth-3 {\n outline-color: #d97706;\n}\n\nhtml[data-jqhtml-debug] .jqhtml-debug-hit.jqhtml-debug-depth-4 {\n outline-color: #7c3aed;\n}\n\nhtml[data-jqhtml-debug] .jqhtml-debug-hit.jqhtml-debug-depth-5 {\n outline-color: #0e7490;\n}";
5950
+
5951
+ var shadow_css = ":host {\n all: initial;\n display: block;\n position: fixed;\n box-sizing: border-box;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n z-index: 2147483647;\n pointer-events: none;\n font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, \"Liberation Mono\", monospace;\n font-size: 12px;\n font-weight: normal;\n font-style: normal;\n font-variant: normal;\n line-height: 1.4;\n color: #1c1c1c;\n text-align: left;\n text-transform: none;\n text-indent: 0;\n text-shadow: none;\n letter-spacing: normal;\n word-spacing: normal;\n white-space: normal;\n word-break: normal;\n overflow-wrap: anywhere;\n hyphens: none;\n tab-size: 4;\n direction: ltr;\n visibility: visible;\n cursor: default;\n list-style: none;\n quotes: none;\n}\n\n.jqhtml-debug-layer {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n overflow: hidden;\n pointer-events: none;\n}\n\n.jqhtml-debug-label {\n position: absolute;\n box-sizing: border-box;\n display: block;\n padding: 1px 5px;\n min-height: 18px;\n color: #ffffff;\n background: #e5322d;\n border-radius: 0 0 3px 0;\n font-size: 11px;\n line-height: 16px;\n white-space: normal;\n overflow-wrap: anywhere;\n overflow: hidden;\n pointer-events: none;\n}\n\n.jqhtml-debug-label.jqhtml-debug-depth-0 {\n background: #e5322d;\n}\n\n.jqhtml-debug-label.jqhtml-debug-depth-1 {\n background: #2f6fe4;\n}\n\n.jqhtml-debug-label.jqhtml-debug-depth-2 {\n background: #1f9d55;\n}\n\n.jqhtml-debug-label.jqhtml-debug-depth-3 {\n background: #d97706;\n}\n\n.jqhtml-debug-label.jqhtml-debug-depth-4 {\n background: #7c3aed;\n}\n\n.jqhtml-debug-label.jqhtml-debug-depth-5 {\n background: #0e7490;\n}\n\n.jqhtml-debug-label-name {\n font-weight: bold;\n}\n\n.jqhtml-debug-label-args {\n opacity: 0.9;\n margin-left: 6px;\n}\n\n.jqhtml-debug-modal {\n display: none;\n position: absolute;\n box-sizing: border-box;\n top: 24px;\n right: 24px;\n width: 520px;\n max-width: calc(100% - 48px);\n max-height: calc(100% - 48px);\n overflow: auto;\n padding: 0 0 12px 0;\n background: #ffffff;\n color: #1c1c1c;\n border: 1px solid #d0d0d0;\n border-radius: 6px;\n box-shadow: 0 8px 32px rgba(0, 0, 0, 0.25);\n pointer-events: auto;\n}\n\n.jqhtml-debug-modal.jqhtml-debug-modal-open {\n display: block;\n}\n\n.jqhtml-debug-title {\n display: flex;\n align-items: center;\n gap: 8px;\n position: sticky;\n top: 0;\n padding: 8px 12px;\n background: #1c1c1c;\n color: #ffffff;\n font-weight: bold;\n}\n\n.jqhtml-debug-title-name {\n flex: 1 1 auto;\n font-size: 13px;\n}\n\n.jqhtml-debug-button {\n all: unset;\n display: inline-block;\n box-sizing: border-box;\n padding: 2px 8px;\n border: 1px solid rgba(255, 255, 255, 0.6);\n border-radius: 3px;\n color: #ffffff;\n font-size: 11px;\n line-height: 16px;\n cursor: pointer;\n user-select: none;\n}\n\n.jqhtml-debug-button:hover {\n background: rgba(255, 255, 255, 0.15);\n}\n\n.jqhtml-debug-section {\n padding: 8px 12px 0 12px;\n}\n\n.jqhtml-debug-h {\n margin: 4px 0;\n color: #666666;\n font-size: 11px;\n text-transform: uppercase;\n letter-spacing: 0.06em;\n}\n\n.jqhtml-debug-table {\n display: grid;\n grid-template-columns: max-content max-content 1fr;\n column-gap: 12px;\n row-gap: 2px;\n align-items: baseline;\n}\n\n.jqhtml-debug-key {\n color: #005cc5;\n white-space: nowrap;\n}\n\n.jqhtml-debug-type {\n color: #666666;\n font-size: 11px;\n white-space: nowrap;\n}\n\n.jqhtml-debug-value {\n white-space: pre-wrap;\n overflow-wrap: anywhere;\n}\n\n.jqhtml-debug-empty {\n color: #666666;\n font-style: italic;\n}\n\n.jqhtml-debug-list {\n display: block;\n margin: 0;\n padding: 0;\n}\n\n.jqhtml-debug-link {\n display: block;\n padding: 2px 4px;\n margin: 0 -4px;\n border-radius: 3px;\n cursor: pointer;\n}\n\n.jqhtml-debug-link:hover {\n background: #eef3ff;\n}\n\n.jqhtml-debug-link-cid {\n color: #666666;\n margin-left: 6px;\n}\n\n.jqhtml-debug-note {\n margin-top: 4px;\n color: #92400e;\n font-size: 11px;\n}";
5952
+
5295
5953
  /**
5296
- * JQHTML v2 Template Renderer
5297
- *
5298
- * Connects compiled templates to components
5299
- * Processes instruction arrays and handles bindings
5300
- */
5301
- /**
5302
- * Process slot-only template inheritance
5954
+ * Component debug overlay.
5303
5955
  *
5304
- * When a component's template returns {_slots: {...}}, walk the prototype
5305
- * chain to find a parent template and invoke it with the child's slots as content.
5956
+ * `jqhtml.debug_overlay.enable()` turns the page into an inspector: hovering
5957
+ * any element outlines the component under the pointer and every component
5958
+ * above it, each with a small tab naming the component and its simple args;
5959
+ * clicking opens a modal describing the innermost component (identity, args,
5960
+ * data, state, ancestry, instantiator) instead of firing the click. Alt+click
5961
+ * passes through. `disable()` puts everything back.
5306
5962
  *
5307
- * @param component The component instance
5308
- * @param childSlots The slots object from the child template
5309
- * @returns [instructions, context] tuple or null if no parent found
5963
+ * Non-invasiveness, the design goal (details in ./CLAUDE.md):
5964
+ * - The overlay's own UI lives in a shadow root on a host element appended to
5965
+ * <body>, styled by shadow.scss. Page CSS cannot select into it and :host
5966
+ * cuts inheritance, so its look is fixed whatever the page does.
5967
+ * - The only thing added to application elements is a pair of classes,
5968
+ * .jqhtml-debug-hit / .jqhtml-debug-depth-N, which light.scss paints as an
5969
+ * inset outline (no layout effect) and only while <html data-jqhtml-debug>.
5970
+ * - Listeners are attached on enable and removed on disable. The stylesheets
5971
+ * and the (detached) host stay once installed: inert, and cheap to re-enable.
5972
+ * - Nothing is registered per component, so components created after enable
5973
+ * are covered automatically.
5310
5974
  */
5311
- async function process_slot_inheritance(component, childSlots) {
5312
- // Walk the prototype chain to find parent class with template
5313
- let currentClass = Object.getPrototypeOf(component.constructor);
5314
- console.log(`[JQHTML] Walking prototype chain for ${component.constructor.name}`);
5315
- while (currentClass && currentClass !== Jqhtml_Component && currentClass.name !== 'Object') {
5316
- const className = currentClass.name;
5317
- console.log(`[JQHTML] Checking parent class: ${className}`);
5318
- // Skip internal framework classes
5319
- if (className === '_Jqhtml_Component' || className === '_Base_Jqhtml_Component') {
5320
- currentClass = Object.getPrototypeOf(currentClass);
5321
- continue;
5322
- }
5323
- // Try to find template for this parent class
5324
- try {
5325
- const parentTemplate = get_template(className);
5326
- console.log(`[JQHTML] Template found for ${className}:`, parentTemplate ? parentTemplate.name : 'null');
5327
- // Check if we got the default template (means no real template found)
5328
- if (parentTemplate && parentTemplate.name !== 'Jqhtml_Component') {
5329
- console.log(`[JQHTML] Invoking parent template ${className}`);
5330
- // Found a real parent template - invoke it with child's slots as content
5331
- const [parentInstructions, parentContext] = parentTemplate.render.call(component, component.data, component.args, childSlots // Pass child slots as content parameter
5332
- );
5333
- // Check if parent also returns slots (recursive inheritance)
5334
- if (parentInstructions && typeof parentInstructions === 'object' && parentInstructions._slots) {
5335
- // Parent also has slot-only template - recurse
5336
- console.log(`[JQHTML] Parent also slot-only, recursing`);
5337
- return await process_slot_inheritance(component, parentInstructions._slots);
5338
- }
5339
- // Parent returned HTML - we're done
5340
- console.log(`[JQHTML] Parent returned instructions, inheritance complete`);
5341
- return [parentInstructions, parentContext];
5342
- }
5343
- }
5344
- catch (error) {
5345
- console.warn(`[JQHTML] Error looking up parent template for ${className}:`, error);
5346
- }
5347
- // Move to next parent
5348
- currentClass = Object.getPrototypeOf(currentClass);
5975
+ const PREFIX = 'jqhtml-debug-';
5976
+ const ROOT_ATTR = 'data-jqhtml-debug'; // on <html> while enabled - gates light.scss
5977
+ const HOST_ATTR = 'data-jqhtml-debug-root'; // the shadow host
5978
+ const LIGHT_STYLE_ID = 'jqhtml-debug-light-styles';
5979
+ const HIT_CLASS = `${PREFIX}hit`;
5980
+ const DEPTH_CLASS = `${PREFIX}depth-`;
5981
+ const DEPTH_COLORS = 6; // keep in step with $depth-colors in _tokens.scss
5982
+ const LABEL_HEIGHT = 18;
5983
+ const READY_STATES = ['created', 'init', 'loaded', 'rendered', 'ready'];
5984
+ const state = {
5985
+ enabled: false,
5986
+ host: null,
5987
+ shadow: null,
5988
+ layer: null,
5989
+ modal: null,
5990
+ chain: [],
5991
+ hit_elements: [],
5992
+ modal_component: null,
5993
+ };
5994
+ // ---------------------------------------------------------------------------
5995
+ // Public API
5996
+ // ---------------------------------------------------------------------------
5997
+ const debug_overlay = {
5998
+ /** Turn the overlay on. Returns false where there is no DOM (SSR). */
5999
+ enable() {
6000
+ if (typeof document === 'undefined' || !document.documentElement)
6001
+ return false;
6002
+ if (state.enabled)
6003
+ return true;
6004
+ install();
6005
+ if (!state.host.isConnected)
6006
+ (document.body || document.documentElement).appendChild(state.host);
6007
+ document.documentElement.setAttribute(ROOT_ATTR, '');
6008
+ document.addEventListener('mouseover', on_mouseover, true);
6009
+ document.addEventListener('mouseout', on_mouseout, true);
6010
+ document.addEventListener('click', on_click, true);
6011
+ document.addEventListener('keydown', on_keydown, true);
6012
+ document.addEventListener('scroll', on_reposition, true);
6013
+ window.addEventListener('resize', on_reposition);
6014
+ state.enabled = true;
6015
+ return true;
6016
+ },
6017
+ /** Turn the overlay off. Styles stay installed but match nothing. */
6018
+ disable() {
6019
+ if (!state.enabled)
6020
+ return;
6021
+ document.removeEventListener('mouseover', on_mouseover, true);
6022
+ document.removeEventListener('mouseout', on_mouseout, true);
6023
+ document.removeEventListener('click', on_click, true);
6024
+ document.removeEventListener('keydown', on_keydown, true);
6025
+ document.removeEventListener('scroll', on_reposition, true);
6026
+ window.removeEventListener('resize', on_reposition);
6027
+ clear_hover();
6028
+ close_modal();
6029
+ document.documentElement.removeAttribute(ROOT_ATTR);
6030
+ if (state.host && state.host.isConnected)
6031
+ state.host.remove();
6032
+ state.enabled = false;
6033
+ },
6034
+ is_enabled() {
6035
+ return state.enabled;
6036
+ },
6037
+ /**
6038
+ * Open the modal for a component, an element inside one, or a jQuery
6039
+ * object, without needing a click. Handy from the console and from tests.
6040
+ */
6041
+ inspect(target) {
6042
+ if (!state.enabled)
6043
+ return false;
6044
+ const component = target instanceof Jqhtml_Component
6045
+ ? target
6046
+ : chain_for(target && target.jquery ? target[0] : target)[0];
6047
+ if (!component)
6048
+ return false;
6049
+ open_modal(component);
6050
+ return true;
6051
+ },
6052
+ };
6053
+ // ---------------------------------------------------------------------------
6054
+ // Installation (once)
6055
+ // ---------------------------------------------------------------------------
6056
+ function install() {
6057
+ if (state.host)
6058
+ return;
6059
+ if (!document.getElementById(LIGHT_STYLE_ID)) {
6060
+ const style = document.createElement('style');
6061
+ style.id = LIGHT_STYLE_ID;
6062
+ style.textContent = light_css;
6063
+ document.head.appendChild(style);
6064
+ }
6065
+ const host = document.createElement('div');
6066
+ host.setAttribute(HOST_ATTR, '');
6067
+ const shadow = host.attachShadow({ mode: 'open' });
6068
+ const style = document.createElement('style');
6069
+ style.textContent = shadow_css;
6070
+ shadow.appendChild(style);
6071
+ const layer = el('div', 'layer');
6072
+ shadow.appendChild(layer);
6073
+ const modal = el('div', 'modal');
6074
+ shadow.appendChild(modal);
6075
+ state.host = host;
6076
+ state.shadow = shadow;
6077
+ state.layer = layer;
6078
+ state.modal = modal;
6079
+ }
6080
+ // ---------------------------------------------------------------------------
6081
+ // Component chain
6082
+ // ---------------------------------------------------------------------------
6083
+ /** Components from the one containing `node` outward to the root. */
6084
+ function chain_for(node) {
6085
+ const chain = [];
6086
+ let element = node instanceof Element ? node : (node && node.parentElement) || null;
6087
+ while (element) {
6088
+ const owner = element.closest('.Component');
6089
+ if (!owner)
6090
+ break;
6091
+ const component = $(owner).data('_component');
6092
+ if (component instanceof Jqhtml_Component && !component.$.hasClass('_Component_Stopped'))
6093
+ chain.push(component);
6094
+ element = owner.parentElement;
5349
6095
  }
5350
- // No parent template found
5351
- console.warn(`[JQHTML] No parent template found after walking chain`);
5352
- return null;
6096
+ return chain;
5353
6097
  }
5354
- /**
5355
- * Render a template for a component
5356
- * Templates are functions that return [instructions, context] tuples
5357
- */
5358
- async function render_template(component, template_fn) {
5359
- // Get template from registry if not provided
5360
- let render_fn = template_fn;
5361
- if (!render_fn) {
5362
- const template_def = get_template_by_class(component.constructor);
5363
- render_fn = template_def.render;
5364
- }
5365
- if (!render_fn) {
5366
- // No template, component should handle its own rendering
6098
+ function is_ours(event) {
6099
+ return !!state.host && event.composedPath().includes(state.host);
6100
+ }
6101
+ // ---------------------------------------------------------------------------
6102
+ // Hover
6103
+ // ---------------------------------------------------------------------------
6104
+ function on_mouseover(event) {
6105
+ if (is_ours(event))
5367
6106
  return;
5368
- }
5369
- // Clear existing content
5370
- component.$.empty();
5371
- // Execute template function
5372
- // Templates receive: (data, args, content)
5373
- // Provide a default empty content function if none provided
5374
- const defaultContent = () => '';
5375
- let [instructions, context] = render_fn.call(component, component.data, component.args, defaultContent // Default content function that returns empty string
5376
- );
5377
- // Check for slot-only template inheritance
5378
- // If instructions is {_slots: {...}}, this is a slot-only template
5379
- // We need to find the parent template and invoke it with these slots
5380
- if (instructions && typeof instructions === 'object' && instructions._slots) {
5381
- console.log(`[JQHTML] Slot-only template detected for ${component.constructor.name}, invoking inheritance`);
5382
- const result = await process_slot_inheritance(component, instructions._slots);
5383
- if (result) {
5384
- console.log(`[JQHTML] Parent template found, using parent instructions`);
5385
- instructions = result[0];
5386
- context = result[1];
5387
- }
5388
- else {
5389
- console.warn(`[JQHTML] No parent template found for ${component.constructor.name}, rendering empty`);
5390
- // No parent template found - return empty
5391
- instructions = [];
5392
- }
5393
- }
5394
- // Process instructions to generate DOM
5395
- await process_instructions(instructions, component.$, component);
5396
- // Process bindings after DOM is created
5397
- await process_bindings(component);
5398
- // Attach event handlers
5399
- await attach_event_handlers(component);
6107
+ const chain = chain_for(event.target);
6108
+ if (chain[0] === state.chain[0])
6109
+ return;
6110
+ set_hover(chain);
5400
6111
  }
5401
- /**
5402
- * Process data bindings (attributes created by :prop syntax)
5403
- */
5404
- async function process_bindings(component) {
5405
- // Find all elements with data-bind-* attributes
5406
- component.$.find('[data-bind-prop], [data-bind-value], [data-bind-text], [data-bind-html], [data-bind-class], [data-bind-style]').each((_, element) => {
5407
- const el = $(element);
5408
- const attrs = element.attributes;
5409
- for (let i = 0; i < attrs.length; i++) {
5410
- const attr = attrs[i];
5411
- if (attr.name.startsWith('data-bind-')) {
5412
- const binding_type = attr.name.substring(10); // Remove 'data-bind-'
5413
- const expression = attr.value;
5414
- try {
5415
- // Evaluate expression in component context
5416
- const value = evaluate_expression(expression, component);
5417
- // Apply binding based on type
5418
- switch (binding_type) {
5419
- case 'prop':
5420
- // Generic property binding
5421
- const prop_name = el.attr('data-bind-prop-name') || 'value';
5422
- el.prop(prop_name, value);
5423
- break;
5424
- case 'value':
5425
- el.val(value);
5426
- break;
5427
- case 'text':
5428
- el.text(value);
5429
- break;
5430
- case 'html':
5431
- el.html(value);
5432
- break;
5433
- case 'class':
5434
- if (typeof value === 'object') {
5435
- // Object syntax: {active: true, disabled: false}
5436
- Object.entries(value).forEach(([className, enabled]) => {
5437
- el.toggleClass(className, !!enabled);
5438
- });
5439
- }
5440
- else {
5441
- // String syntax
5442
- el.addClass(String(value));
5443
- }
5444
- break;
5445
- case 'style':
5446
- if (typeof value === 'object') {
5447
- el.css(value);
5448
- }
5449
- else {
5450
- el.attr('style', String(value));
5451
- }
5452
- break;
5453
- default:
5454
- // Custom binding - set as attribute
5455
- el.attr(binding_type, value);
5456
- }
5457
- }
5458
- catch (error) {
5459
- console.error(`Error evaluating binding "${expression}":`, error);
5460
- }
5461
- }
5462
- }
5463
- });
6112
+ function on_mouseout(event) {
6113
+ if (!event.relatedTarget)
6114
+ clear_hover(); // pointer left the document
5464
6115
  }
5465
- /**
5466
- * Attach event handlers (attributes created by @event syntax)
5467
- */
5468
- async function attach_event_handlers(component) {
5469
- // Find all elements with data-on-* attributes
5470
- component.$.find('[data-on-click], [data-on-change], [data-on-submit], [data-on-keyup], [data-on-keydown], [data-on-focus], [data-on-blur]').each((_, element) => {
5471
- const el = $(element);
5472
- const attrs = element.attributes;
5473
- for (let i = 0; i < attrs.length; i++) {
5474
- const attr = attrs[i];
5475
- if (attr.name.startsWith('data-on-')) {
5476
- const event_name = attr.name.substring(8); // Remove 'data-on-'
5477
- const handler_expr = attr.value;
5478
- // Remove the attribute to avoid re-processing
5479
- el.removeAttr(attr.name);
5480
- // Attach event handler
5481
- el.on(event_name, function (event) {
5482
- try {
5483
- // Create handler function in component context
5484
- const handler = evaluate_handler(handler_expr, component);
5485
- if (typeof handler === 'function') {
5486
- // Call with component as 'this' and pass event
5487
- handler.call(component, event);
5488
- }
5489
- else {
5490
- // Expression to execute
5491
- evaluate_expression(handler_expr, component, { $event: event });
5492
- }
5493
- }
5494
- catch (error) {
5495
- console.error(`Error in ${event_name} handler "${handler_expr}":`, error);
5496
- }
5497
- });
5498
- }
5499
- }
6116
+ function on_reposition() {
6117
+ if (state.chain.length)
6118
+ render_labels();
6119
+ }
6120
+ function set_hover(chain) {
6121
+ clear_hover();
6122
+ state.chain = chain;
6123
+ chain.forEach((component, depth) => {
6124
+ const element = component.$[0];
6125
+ element.classList.add(HIT_CLASS, DEPTH_CLASS + (depth % DEPTH_COLORS));
6126
+ state.hit_elements.push(element);
5500
6127
  });
6128
+ render_labels();
6129
+ }
6130
+ function clear_hover() {
6131
+ for (const element of state.hit_elements) {
6132
+ element.classList.remove(HIT_CLASS);
6133
+ for (let i = 0; i < DEPTH_COLORS; i++)
6134
+ element.classList.remove(DEPTH_CLASS + i);
6135
+ }
6136
+ state.hit_elements = [];
6137
+ state.chain = [];
6138
+ if (state.layer)
6139
+ state.layer.textContent = '';
5501
6140
  }
5502
6141
  /**
5503
- * Evaluate an expression in component context
6142
+ * One tab per component in the chain, pinned to the component's top-left
6143
+ * corner and no wider than the component. Outermost first so the innermost
6144
+ * paints on top; tabs that share a corner (a child filling its parent, the
6145
+ * usual case) stack downward instead of hiding each other.
5504
6146
  */
5505
- function evaluate_expression(expression, component, locals = {}) {
5506
- // Create evaluation context
5507
- const context = {
5508
- // Component properties
5509
- data: component.data,
5510
- args: component.args,
5511
- $: component.$,
5512
- // Component methods
5513
- $sid: component.$sid.bind(component),
5514
- // Locals (like $event)
5515
- ...locals
5516
- };
5517
- // Build function that evaluates in context
5518
- const keys = Object.keys(context);
5519
- const values = Object.values(context);
5520
- try {
5521
- // Use Function constructor for better performance than eval
5522
- const fn = new Function(...keys, `return (${expression})`);
5523
- return fn(...values);
6147
+ function render_labels() {
6148
+ const layer = state.layer;
6149
+ layer.textContent = '';
6150
+ const taken = new Map();
6151
+ for (let depth = state.chain.length - 1; depth >= 0; depth--) {
6152
+ const component = state.chain[depth];
6153
+ const rect = component.$[0].getBoundingClientRect();
6154
+ if (rect.width <= 0 || rect.height <= 0)
6155
+ continue;
6156
+ const left = Math.max(0, Math.round(rect.left));
6157
+ const top = Math.max(0, Math.round(rect.top));
6158
+ const key = `${left},${top}`;
6159
+ const stacked = taken.get(key) || 0;
6160
+ taken.set(key, stacked + 1);
6161
+ const label = el('div', `label ${PREFIX}depth-${depth % DEPTH_COLORS}`);
6162
+ label.style.left = `${left}px`;
6163
+ label.style.top = `${top + stacked * LABEL_HEIGHT}px`;
6164
+ label.style.maxWidth = `${Math.max(24, Math.round(rect.width))}px`;
6165
+ label.appendChild(el('span', 'label-name', component.component_name()));
6166
+ const args = simple_args(component);
6167
+ if (args)
6168
+ label.appendChild(el('span', 'label-args', args));
6169
+ layer.appendChild(label);
5524
6170
  }
5525
- catch (error) {
5526
- console.error(`Invalid expression: ${expression}`, error);
5527
- return undefined;
6171
+ }
6172
+ /** `$id=7 $title="Users"` - only strings, numbers and booleans, never internals. */
6173
+ function simple_args(component) {
6174
+ const parts = [];
6175
+ for (const [key, value] of Object.entries(component.args || {})) {
6176
+ if (key.startsWith('_'))
6177
+ continue;
6178
+ if (typeof value === 'string')
6179
+ parts.push(`$${key}=${JSON.stringify(truncate(value, 24))}`);
6180
+ else if (typeof value === 'number' || typeof value === 'boolean')
6181
+ parts.push(`$${key}=${value}`);
5528
6182
  }
6183
+ return parts.join(' ');
5529
6184
  }
5530
- /**
5531
- * Evaluate a handler expression (might be method name or inline code)
5532
- */
5533
- function evaluate_handler(expression, component) {
5534
- // Check if it's a method name on the component
5535
- if (expression in component && typeof component[expression] === 'function') {
5536
- return component[expression];
6185
+ // ---------------------------------------------------------------------------
6186
+ // Click -> modal
6187
+ // ---------------------------------------------------------------------------
6188
+ function on_click(event) {
6189
+ if (is_ours(event) || event.altKey)
6190
+ return;
6191
+ event.preventDefault();
6192
+ event.stopPropagation();
6193
+ event.stopImmediatePropagation();
6194
+ const chain = chain_for(event.target);
6195
+ if (!chain.length) {
6196
+ close_modal();
6197
+ return;
6198
+ }
6199
+ open_modal(chain[0]);
6200
+ }
6201
+ function on_keydown(event) {
6202
+ if (event.key === 'Escape' && state.modal_component) {
6203
+ close_modal();
6204
+ event.stopPropagation();
6205
+ }
6206
+ }
6207
+ function close_modal() {
6208
+ if (!state.modal)
6209
+ return;
6210
+ state.modal.classList.remove(`${PREFIX}modal-open`);
6211
+ state.modal.textContent = '';
6212
+ state.modal_component = null;
6213
+ }
6214
+ function open_modal(component) {
6215
+ const modal = state.modal;
6216
+ modal.textContent = '';
6217
+ state.modal_component = component;
6218
+ const chain = chain_for(component.$[0]);
6219
+ const ancestors = chain.slice(1);
6220
+ const element = component.$[0];
6221
+ // Title bar
6222
+ const title = el('div', 'title');
6223
+ title.appendChild(el('span', 'title-name', `<${component.component_name()}>`));
6224
+ const log = el('button', 'button', 'Log to console');
6225
+ log.addEventListener('click', () => {
6226
+ console.log(`[JQHTML debug] <${component.component_name()}>`, component, element);
6227
+ });
6228
+ title.appendChild(log);
6229
+ const close = el('button', 'button', 'Close');
6230
+ close.addEventListener('click', close_modal);
6231
+ title.appendChild(close);
6232
+ modal.appendChild(title);
6233
+ // Identity
6234
+ const ctor = component.constructor;
6235
+ const hierarchy = ctor.get_class_hierarchy ? ctor.get_class_hierarchy() : [ctor.name];
6236
+ const identity = table();
6237
+ row(identity, 'name', '', component.component_name());
6238
+ row(identity, 'class', '', hierarchy.join(' → '));
6239
+ row(identity, 'element', '', describe_element(element));
6240
+ row(identity, '_cid', '', String(component._cid));
6241
+ row(identity, 'lifecycle', '', READY_STATES[component._ready_state] || String(component._ready_state));
6242
+ const nocache = element.getAttribute('data-nocache');
6243
+ if (nocache)
6244
+ row(identity, 'cache', '', `declined: ${nocache}`);
6245
+ modal.appendChild(section('Identity', identity));
6246
+ // Args / data / state
6247
+ modal.appendChild(section('Args', object_table(component.args)));
6248
+ modal.appendChild(section('Data', object_table(component.data)));
6249
+ modal.appendChild(section('State', object_table(component.state)));
6250
+ // Ancestry
6251
+ const list = el('div', 'list');
6252
+ if (!ancestors.length)
6253
+ list.appendChild(el('div', 'empty', 'none - this is a root component'));
6254
+ for (const ancestor of ancestors) {
6255
+ const link = el('div', 'link');
6256
+ link.appendChild(el('span', 'link-name', `<${ancestor.component_name()}>`));
6257
+ link.appendChild(el('span', 'link-cid', String(ancestor._cid)));
6258
+ link.addEventListener('click', () => open_modal(ancestor));
6259
+ list.appendChild(link);
6260
+ }
6261
+ modal.appendChild(section('Ancestry (DOM, nearest first)', list));
6262
+ // Instantiator - the component whose template wrote this tag. Differs from
6263
+ // the DOM parent for markup written in a slot body or default content.
6264
+ const instantiator = component.instantiator ? component.instantiator() : null;
6265
+ const inst = el('div', 'list');
6266
+ if (instantiator) {
6267
+ const link = el('div', 'link');
6268
+ link.appendChild(el('span', 'link-name', `<${instantiator.component_name()}>`));
6269
+ link.appendChild(el('span', 'link-cid', String(instantiator._cid)));
6270
+ link.addEventListener('click', () => open_modal(instantiator));
6271
+ inst.appendChild(link);
6272
+ if (ancestors[0] && instantiator !== ancestors[0]) {
6273
+ inst.appendChild(el('div', 'note', 'Written in this component\'s template but rendered inside a different parent (slot or default content): handlers and $sid bind here.'));
6274
+ }
5537
6275
  }
5538
- // Otherwise treat as inline code
6276
+ else {
6277
+ inst.appendChild(el('div', 'empty', 'none - created directly'));
6278
+ }
6279
+ modal.appendChild(section('Instantiator', inst));
6280
+ modal.classList.add(`${PREFIX}modal-open`);
6281
+ }
6282
+ // ---------------------------------------------------------------------------
6283
+ // DOM helpers (shadow side)
6284
+ // ---------------------------------------------------------------------------
6285
+ function el(tag, classes, text) {
6286
+ const node = document.createElement(tag);
6287
+ node.className = classes.split(' ').map((c) => (c.startsWith(PREFIX) ? c : PREFIX + c)).join(' ');
6288
+ if (text !== undefined)
6289
+ node.textContent = text;
6290
+ return node;
6291
+ }
6292
+ function section(heading, body) {
6293
+ const wrap = el('div', 'section');
6294
+ wrap.appendChild(el('div', 'h', heading));
6295
+ wrap.appendChild(body);
6296
+ return wrap;
6297
+ }
6298
+ function table() {
6299
+ return el('div', 'table');
6300
+ }
6301
+ function row(t, key, type, value) {
6302
+ t.appendChild(el('span', 'key', key));
6303
+ t.appendChild(el('span', 'type', type));
6304
+ t.appendChild(el('span', 'value', value));
6305
+ }
6306
+ function object_table(source) {
6307
+ const entries = source && typeof source === 'object' ? Object.entries(source) : [];
6308
+ if (!entries.length)
6309
+ return el('div', 'empty', 'empty');
6310
+ const t = table();
6311
+ for (const [key, value] of entries)
6312
+ row(t, key, type_of(value), preview(value));
6313
+ return t;
6314
+ }
6315
+ function type_of(value) {
6316
+ if (value === null)
6317
+ return 'null';
6318
+ if (Array.isArray(value))
6319
+ return `array(${value.length})`;
6320
+ if (value instanceof Jqhtml_Component)
6321
+ return 'component';
6322
+ if (value && value.jquery)
6323
+ return `jQuery(${value.length})`;
6324
+ if (typeof value === 'object' && value instanceof Element)
6325
+ return 'element';
6326
+ return typeof value;
6327
+ }
6328
+ function preview(value) {
6329
+ if (value === undefined)
6330
+ return 'undefined';
6331
+ if (value === null)
6332
+ return 'null';
6333
+ if (typeof value === 'string')
6334
+ return JSON.stringify(truncate(value, 200));
6335
+ if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint')
6336
+ return String(value);
6337
+ if (typeof value === 'function')
6338
+ return `ƒ ${value.name || 'anonymous'}()`;
6339
+ if (value instanceof Jqhtml_Component)
6340
+ return `<${value.component_name()}> ${value._cid}`;
6341
+ if (value.jquery)
6342
+ return value.length ? describe_element(value[0]) : 'empty';
6343
+ if (value instanceof Element)
6344
+ return describe_element(value);
5539
6345
  try {
5540
- return new Function('$event', `
5541
- const { data, args, $, emit, $sid } = this;
5542
- ${expression}
5543
- `).bind(component);
6346
+ return truncate(JSON.stringify(value), 200);
5544
6347
  }
5545
- catch (error) {
5546
- console.error(`Invalid handler: ${expression}`, error);
5547
- return null;
6348
+ catch {
6349
+ return `{${Object.keys(value).join(', ')}}`;
5548
6350
  }
5549
6351
  }
5550
- /**
5551
- * Helper to escape HTML for safe output
5552
- */
5553
- function escape_html(str) {
5554
- const div = document.createElement('div');
5555
- div.textContent = str;
5556
- return div.innerHTML;
6352
+ function describe_element(element) {
6353
+ const id = element.id ? `#${element.id}` : '';
6354
+ const classes = element.classList.length ? `.${Array.from(element.classList).join('.')}` : '';
6355
+ return `${element.tagName.toLowerCase()}${id}${classes}`;
5557
6356
  }
5558
- /**
5559
- * Helper to escape HTML and convert newlines to <br /> tags
5560
- * Used by <%br= %> syntax for displaying user-entered text with line breaks
5561
- */
5562
- function escape_html_nl2br(str) {
5563
- const div = document.createElement('div');
5564
- div.textContent = str;
5565
- // Escape HTML first, then replace newlines with <br />
5566
- return div.innerHTML.replace(/\n/g, '<br />');
6357
+ function truncate(text, max) {
6358
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
5567
6359
  }
5568
6360
 
5569
6361
  /**
@@ -5723,13 +6515,12 @@ function init_jquery_plugin(jQuery) {
5723
6515
  const _jqhtml_original_jquery = jQuery;
5724
6516
  // Override jQuery constructor to handle component instances
5725
6517
  const JQueryWithComponentSupport = function (selector, context) {
5726
- // Check if selector is a JQHTML component instance
5727
- if (selector &&
5728
- typeof selector === 'object' &&
5729
- selector.$ &&
5730
- typeof selector.$sid === 'function' &&
5731
- typeof selector.id === 'function') {
5732
- // Return the component's jQuery element
6518
+ // Unwrap a component instance to its root element, so $(component) behaves
6519
+ // exactly like component.$ (addClass, find, [0] and every other jQuery method).
6520
+ // The check is an instanceof on the class itself: the previous duck-type tested
6521
+ // for an id() method, which Jqhtml_Component has never had, so this branch was
6522
+ // dead and $(component) wrapped the plain object instead.
6523
+ if (selector instanceof Jqhtml_Component) {
5733
6524
  return selector.$;
5734
6525
  }
5735
6526
  // Otherwise, call original jQuery constructor
@@ -5805,13 +6596,12 @@ function init_jquery_plugin(jQuery) {
5805
6596
  // Check if component already exists on this element
5806
6597
  const existingComponent = element.data('_component');
5807
6598
  if (existingComponent) {
5808
- // Stop existing component (with error handling to continue on failure)
5809
- try {
5810
- existingComponent.stop();
5811
- }
5812
- catch (error) {
5813
- console.warn('[JQHTML] Error stopping existing component during replacement:', error);
5814
- }
6599
+ // Stop the existing component. A throwing stop() is NOT swallowed: the caller
6600
+ // asked to replace a live component, and overwriting one whose on_stop() failed
6601
+ // would leave its timers, intervals and listeners running against DOM that is
6602
+ // about to be destroyed. Let the throw reach the caller with the old component
6603
+ // still in place, so the failure is visible and recoverable.
6604
+ existingComponent.stop();
5815
6605
  // Remove component classes (any class starting with a capital letter, or a
5816
6606
  // component name with the reserved underscore prefix - except BEM classes)
5817
6607
  const classes = element.attr('class');
@@ -5827,7 +6617,15 @@ function init_jquery_plugin(jQuery) {
5827
6617
  const capital_first = cls[0] === cls[0].toUpperCase() && cls[0] !== cls[0].toLowerCase();
5828
6618
  return !capital_first && !is_component_name(cls);
5829
6619
  });
5830
- element.attr('class', nonComponentClasses.join(' '));
6620
+ // Drop the attribute entirely when nothing survived the strip: attr('class', '')
6621
+ // leaves a `class=""` in the markup, which is noise in the DOM and in snapshot
6622
+ // comparisons for an element that now has no classes at all.
6623
+ if (nonComponentClasses.length > 0) {
6624
+ element.attr('class', nonComponentClasses.join(' '));
6625
+ }
6626
+ else {
6627
+ element.removeAttr('class');
6628
+ }
5831
6629
  }
5832
6630
  // Remove component data
5833
6631
  element.removeData('_component');
@@ -5854,8 +6652,11 @@ function init_jquery_plugin(jQuery) {
5854
6652
  }
5855
6653
  }
5856
6654
  else {
5857
- // Direct class reference
6655
+ // Direct class reference. The invocation name is the class's own; it is
6656
+ // recorded for component_name() but does not drive the template tag
6657
+ // check below, which is for named (template-backed) invocations.
5858
6658
  ComponentClass = componentOrName;
6659
+ args = { ...args, _component_name: componentOrName.component_name || componentOrName.name };
5859
6660
  }
5860
6661
  // Check if element tag matches expected tag from template
5861
6662
  let targetElement = element;
@@ -5865,18 +6666,35 @@ function init_jquery_plugin(jQuery) {
5865
6666
  const expectedTag = args._tag || template.tag || 'div';
5866
6667
  const currentTag = element.prop('tagName').toLowerCase();
5867
6668
  if (currentTag !== expectedTag.toLowerCase()) {
5868
- // Tag mismatch
5869
- if (args._inner_html) {
5870
- // Replace element with correct tag (only when using server-rendered content)
6669
+ // Tag mismatch. Replace whenever we can actually do it: the element must be in
6670
+ // a document (replaceWith() on a parentless element is a silent no-op that would
6671
+ // strand the component on a detached node) and must not be <body>.
6672
+ //
6673
+ // This used to require a truthy args._inner_html, i.e. server-rendered content.
6674
+ // boot.ts always sets _inner_html - but it empties the placeholder first, so a
6675
+ // placeholder with no server content carries '' and fell through to a warning,
6676
+ // hydrating into the wrong tag. Hydration of an empty placeholder still works:
6677
+ // the copied innerHTML is simply ''.
6678
+ const oldEl = element[0];
6679
+ const can_replace = currentTag !== 'body' && !!(oldEl && oldEl.parentNode);
6680
+ if (can_replace) {
5871
6681
  const newElement = jQuery(`<${expectedTag}></${expectedTag}>`);
5872
6682
  // Copy all attributes from old element to new element
5873
- const oldEl = element[0];
5874
6683
  if (oldEl && oldEl.attributes) {
5875
6684
  for (let i = 0; i < oldEl.attributes.length; i++) {
5876
6685
  const attr = oldEl.attributes[i];
5877
6686
  newElement.attr(attr.name, attr.value);
5878
6687
  }
5879
6688
  }
6689
+ // Carry the jQuery data store across. $-args and anything the caller stashed
6690
+ // with .data() live there, and they are read back off the element during
6691
+ // component construction - dropping them silently changed the component's args.
6692
+ const old_data = element.data();
6693
+ if (old_data) {
6694
+ for (const key of Object.keys(old_data)) {
6695
+ newElement.data(key, old_data[key]);
6696
+ }
6697
+ }
5880
6698
  // Copy innerHTML
5881
6699
  newElement.html(element.html());
5882
6700
  // Replace in DOM
@@ -6191,12 +7009,14 @@ function init(jQuery, config) {
6191
7009
  }
6192
7010
  }
6193
7011
  // Version - will be replaced during build with actual version from package.json
6194
- const version = '2.3.64';
7012
+ const version = '2.3.68';
6195
7013
  // Default export with all functionality
6196
7014
  const jqhtml = {
6197
7015
  // Core
6198
7016
  Jqhtml_Component,
6199
7017
  LifecycleManager,
7018
+ // Internal - exposed for debugging and for tests that inspect coordination state
7019
+ Load_Coordinator,
6200
7020
  // Registry
6201
7021
  register,
6202
7022
  register_component,
@@ -6212,7 +7032,6 @@ const jqhtml = {
6212
7032
  // Template system
6213
7033
  process_instructions,
6214
7034
  extract_slots,
6215
- render_template,
6216
7035
  escape_html,
6217
7036
  escape_html_nl2br,
6218
7037
  // Version property - internal
@@ -6222,6 +7041,14 @@ const jqhtml = {
6222
7041
  // Integration configuration - see config.ts
6223
7042
  configure,
6224
7043
  get_config,
7044
+ // Value printers: how <%= %> renders an object (see value-printers.ts).
7045
+ // print_object and dynamic_component_name are called by compiled templates.
7046
+ add_object_printer,
7047
+ print_object,
7048
+ dynamic_component_name,
7049
+ // Component debug overlay: hover outlines + click-to-inspect modal.
7050
+ // jqhtml.debug_overlay.enable() / .disable() / .is_enabled() / .inspect(x)
7051
+ debug_overlay,
6225
7052
  // Debug settings
6226
7053
  debug: {
6227
7054
  enabled: false,
@@ -6327,5 +7154,5 @@ if (typeof window !== 'undefined' && !window.jqhtml) {
6327
7154
  }
6328
7155
  }
6329
7156
 
6330
- export { COMPONENT_NAME_PATTERN, COMPONENT_NAME_RULE, Jqhtml_Component, LifecycleManager as Jqhtml_LifecycleManager, Jqhtml_Local_Storage, LifecycleManager, Load_Coordinator, applyDebugDelay, boot, clear_preload_data, configure, create_component, jqhtml as default, devWarn, escape_html, escape_html_nl2br, extract_slots, get_captured_data, get_component_class, get_component_names, get_config, get_registered_templates, get_template, get_template_by_class, handleComponentError, has_component, init, init_jquery_plugin, isSequentialProcessing, is_component_name, list_components, logDataChange, logDispatch, logInstruction, logLifecycle, process_instructions, register, register_cache_class, register_component, register_template, render_template, set_preload_data, start_data_capture, stop_data_capture, version };
7157
+ export { COMPONENT_NAME_PATTERN, COMPONENT_NAME_RULE, Jqhtml_Component, LifecycleManager as Jqhtml_LifecycleManager, Jqhtml_Local_Storage, LifecycleManager, Load_Coordinator, add_object_printer, applyDebugDelay, boot, clear_preload_data, configure, create_component, debug_overlay, jqhtml as default, devWarn, dynamic_component_name, escape_html, escape_html_nl2br, extract_slots, get_captured_data, get_component_class, get_component_names, get_config, get_object_printers, get_registered_templates, get_template, get_template_by_class, handleComponentError, has_component, init, init_jquery_plugin, isSequentialProcessing, is_component_name, list_components, logDataChange, logDispatch, logInstruction, logLifecycle, print_object, process_instructions, register, register_cache_class, register_component, register_template, set_preload_data, start_data_capture, stop_data_capture, version };
6331
7158
  //# sourceMappingURL=index.js.map