@jqhtml/core 2.3.35 → 2.3.50

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.
package/dist/index.cjs CHANGED
@@ -38,11 +38,9 @@ class LifecycleManager {
38
38
  * Boot a component - run its full lifecycle
39
39
  * Called when component is created
40
40
  *
41
- * Supports lifecycle skip flags:
42
- * - skip_render_and_ready: Skip first render/on_render and skip on_ready entirely.
43
- * Component reports ready after on_load completes.
44
- * - skip_ready: Skip on_ready only.
45
- * Component reports ready after on_render completes (after potential re-render from on_load).
41
+ * Supports lifecycle truncation flags:
42
+ * - _load_only: on_create + on_load only. No render, no children, no on_render, no on_loaded, no on_ready.
43
+ * - _load_render_only: on_create + render + on_load + re-render. No on_render, no on_loaded, no on_ready.
46
44
  */
47
45
  async boot_component(component) {
48
46
  this.active_components.add(component);
@@ -54,20 +52,25 @@ class LifecycleManager {
54
52
  return;
55
53
  // Trigger create event
56
54
  component.trigger('create');
57
- // Check for skip_render_and_ready flag
58
- const skip_render_and_ready = component._skip_render_and_ready;
59
- const skip_ready = component._skip_ready;
55
+ // Check for lifecycle truncation flags
56
+ const load_only = component._load_only;
57
+ const load_render_only = component._load_render_only;
58
+ const is_detached = component._is_detached;
60
59
  let render_id;
61
- if (skip_render_and_ready) {
62
- // Skip the first render/on_render before on_load
63
- // Still need to set render_id to 0 for tracking
60
+ if (load_only || is_detached) {
61
+ // _load_only or detached: skip initial render entirely
64
62
  render_id = 0;
65
63
  component._render_count = 0;
66
64
  }
65
+ else if (load_render_only) {
66
+ // _load_render_only: render to create children, but skip on_render()
67
+ render_id = component._render(null, { skip_on_render: true });
68
+ // Check if stopped during render
69
+ if (component._stopped)
70
+ return;
71
+ }
67
72
  else {
68
- // Render phase - SYNCHRONOUS, creates DOM and child components
69
- // Note: _render() now calls on_render() internally after DOM update
70
- // Capture render ID to detect if another render happens before ready
73
+ // Normal: render with on_render()
71
74
  render_id = component._render();
72
75
  // Check if stopped during render
73
76
  if (component._stopped)
@@ -76,30 +79,39 @@ class LifecycleManager {
76
79
  // Load phase - ASYNC, but only if on_load() is overridden
77
80
  // Skip entirely if component uses default stub to avoid unnecessary yield
78
81
  if (component._has_on_load()) {
82
+ // Load gates: await any promises registered via gate_load() during
83
+ // on_create() before the FIRST on_load(). Gates delay ONLY this load
84
+ // phase — create/render/on_render/cached-paint already happened above.
85
+ // Released early by reload()/refresh()/stop() while gated (see component).
86
+ // Returns null (no await) for the common no-gate case to keep timing
87
+ // identical for ungated components.
88
+ const gate_wait = component._await_load_gates();
89
+ if (gate_wait) {
90
+ await gate_wait;
91
+ // Check if stopped while awaiting gates
92
+ if (component._stopped)
93
+ return;
94
+ }
79
95
  await component._load();
80
96
  // Yield to microtask queue after on_load completes
81
97
  // This ensures async queue tasks always run before the on_load process completes,
82
98
  // even if on_load() itself completes instantly (deterministic behavior)
83
99
  await Promise.resolve();
84
100
  }
85
- // Trigger 'loaded' event - fires after on_load completes (or would have completed)
86
- // This happens before the render/on_render second step
87
- component.trigger('loaded');
88
101
  // Check if stopped during load
89
102
  if (component._stopped)
90
103
  return;
91
- // If skip_render_and_ready, mark component as ready now and return
92
- if (skip_render_and_ready) {
93
- // Set ready state and trigger event
104
+ // If _load_only, mark component as ready now and return
105
+ if (load_only) {
94
106
  component._ready_state = 4;
95
107
  component._update_debug_attrs();
96
- component._log_lifecycle('ready', 'complete (skip_render_and_ready)');
108
+ component._log_lifecycle('ready', 'complete (_load_only)');
97
109
  component.trigger('ready');
98
110
  return;
99
111
  }
100
- // If data changed during load, re-render
101
- // Note: _render() now calls on_render() internally after DOM update
102
- if (component._should_rerender()) {
112
+ // Detached elements always render here (initial render was skipped)
113
+ // Normal elements re-render only if data changed during on_load
114
+ if (is_detached || component._should_rerender()) {
103
115
  // Disable animations during re-render to prevent visual artifacts
104
116
  // from CSS transitions/animations firing on newly rendered elements
105
117
  const $el = component.$;
@@ -116,11 +128,25 @@ class LifecycleManager {
116
128
  }, 5);
117
129
  });
118
130
  }
119
- render_id = component._render();
131
+ // _load_render_only: re-render with skip_on_render to suppress DOM hooks
132
+ if (load_render_only) {
133
+ render_id = component._render(null, { skip_on_render: true });
134
+ }
135
+ else {
136
+ render_id = component._render();
137
+ }
120
138
  // Check if stopped during re-render
121
139
  if (component._stopped)
122
140
  return;
123
141
  }
142
+ // _load_render_only: skip waiting for children, on_ready — mark ready and return
143
+ if (load_render_only) {
144
+ component._ready_state = 4;
145
+ component._update_debug_attrs();
146
+ component._log_lifecycle('ready', 'complete (_load_render_only)');
147
+ component.trigger('ready');
148
+ return;
149
+ }
124
150
  // Fire 'rendered' event - component has completed its synchronous render chain
125
151
  // This happens once, after the final on_render (whether from first render or re-render after on_load)
126
152
  if (!component._has_rendered) {
@@ -144,15 +170,6 @@ class LifecycleManager {
144
170
  if (component._render_count !== render_id) {
145
171
  return; // Stale render, don't call ready
146
172
  }
147
- // If skip_ready, mark component as ready now without calling _ready()
148
- if (skip_ready) {
149
- // Set ready state and trigger event
150
- component._ready_state = 4;
151
- component._update_debug_attrs();
152
- component._log_lifecycle('ready', 'complete (skip_ready)');
153
- component.trigger('ready');
154
- return;
155
- }
156
173
  // Ready phase - waits for children, then calls on_ready()
157
174
  await component._ready();
158
175
  // Check if stopped during ready
@@ -658,20 +675,26 @@ function process_component_to_html(instruction, html, components, context) {
658
675
  // pass this behavior to all child components rendered in its template
659
676
  let props = originalProps;
660
677
  const parentArgs = context.args;
661
- // Check if we need to propagate any flags
662
- const propagate_use_cached_data = parentArgs?.use_cached_data === true && props.use_cached_data === undefined;
663
- const propagate_skip_render_and_ready = parentArgs?.skip_render_and_ready === true && props.skip_render_and_ready === undefined;
664
- const propagate_skip_ready = parentArgs?.skip_ready === true && props.skip_ready === undefined;
665
- if (propagate_use_cached_data || propagate_skip_render_and_ready || propagate_skip_ready) {
678
+ // Check if we need to propagate any flags.
679
+ // Template-authored flags arrive with the '$' still on the key ($_load_only=false
680
+ // compiles to props['$_load_only']) - honor both spellings so a child template can
681
+ // opt out of a cascading parent flag with an explicit false.
682
+ const own_use_cached_data = props.use_cached_data !== undefined ? props.use_cached_data : props['$use_cached_data'];
683
+ const own_load_only = props._load_only !== undefined ? props._load_only : props['$_load_only'];
684
+ const own_load_render_only = props._load_render_only !== undefined ? props._load_render_only : props['$_load_render_only'];
685
+ const propagate_use_cached_data = parentArgs?.use_cached_data === true && own_use_cached_data === undefined;
686
+ const propagate_load_only = parentArgs?._load_only === true && own_load_only === undefined;
687
+ const propagate_load_render_only = parentArgs?._load_render_only === true && own_load_render_only === undefined;
688
+ if (propagate_use_cached_data || propagate_load_only || propagate_load_render_only) {
666
689
  props = { ...originalProps };
667
690
  if (propagate_use_cached_data) {
668
691
  props.use_cached_data = true;
669
692
  }
670
- if (propagate_skip_render_and_ready) {
671
- props.skip_render_and_ready = true;
693
+ if (propagate_load_only) {
694
+ props._load_only = true;
672
695
  }
673
- if (propagate_skip_ready) {
674
- props.skip_ready = true;
696
+ if (propagate_load_render_only) {
697
+ props._load_render_only = true;
675
698
  }
676
699
  }
677
700
  // Determine if third parameter is a function (default content) or object (named slots)
@@ -987,6 +1010,14 @@ async function initialize_component(element, compData) {
987
1010
  if (ComponentClass.name !== name) {
988
1011
  options._component_name = name;
989
1012
  }
1013
+ // Pass lifecycle truncation flags via options (not DOM attributes, since _ prefix is filtered).
1014
+ // Accept both the plain key (cascaded/programmatic) and the '$'-prefixed key (template-authored).
1015
+ if (props._load_only === true || props['$_load_only'] === true) {
1016
+ options._load_only = true;
1017
+ }
1018
+ if (props._load_render_only === true || props['$_load_render_only'] === true) {
1019
+ options._load_render_only = true;
1020
+ }
990
1021
  // Create component instance - element first, then options
991
1022
  const instance = new ComponentClass(element, options);
992
1023
  // Set the instantiator (the component that rendered this one in their template)
@@ -1244,7 +1275,8 @@ class Load_Coordinator {
1244
1275
  continue; // Skip internal properties
1245
1276
  }
1246
1277
  // Skip framework properties that shouldn't affect cache identity
1247
- if (key === 'use_cached_data' || key === 'skip_render_and_ready' || key === 'skip_ready') {
1278
+ // Note: _load_only and _load_render_only are already filtered by the _ prefix check above
1279
+ if (key === 'use_cached_data') {
1248
1280
  continue;
1249
1281
  }
1250
1282
  const value = args[key];
@@ -1622,7 +1654,13 @@ function process_for_serialization(value, verbose, seen) {
1622
1654
  // Return undefined to omit this value (not fail entire serialization)
1623
1655
  return undefined;
1624
1656
  }
1625
- // Handle circular references
1657
+ // Handle circular references.
1658
+ // `seen` tracks only the current ancestor path (the DFS stack): an object is
1659
+ // added on the way down and removed on the way back up (see finally below).
1660
+ // This flags a genuine cycle (a back-edge to an ancestor) while allowing a
1661
+ // shared reference in a DAG to be serialized independently on each visit.
1662
+ // JSON round-trip semantics do not preserve identity anyway, so emitting a
1663
+ // copy per reference is correct; silently omitting the property is not.
1626
1664
  if (seen.has(value)) {
1627
1665
  if (verbose) {
1628
1666
  console.warn('[JQHTML Cache] Circular reference detected - cannot serialize');
@@ -1630,69 +1668,89 @@ function process_for_serialization(value, verbose, seen) {
1630
1668
  return undefined; // Fail entire serialization
1631
1669
  }
1632
1670
  seen.add(value);
1633
- // Handle arrays
1634
- if (Array.isArray(value)) {
1635
- const result = [];
1636
- for (let i = 0; i < value.length; i++) {
1637
- const item = value[i];
1638
- const processed = process_for_serialization(item, verbose, seen);
1639
- // For arrays, we keep undefined as null to preserve indices
1640
- result.push(processed === undefined ? null : processed);
1671
+ try {
1672
+ // Handle arrays
1673
+ if (Array.isArray(value)) {
1674
+ const result = [];
1675
+ for (let i = 0; i < value.length; i++) {
1676
+ const item = value[i];
1677
+ const processed = process_for_serialization(item, verbose, seen);
1678
+ // For arrays, we keep undefined as null to preserve indices
1679
+ result.push(processed === undefined ? null : processed);
1680
+ }
1681
+ return result;
1641
1682
  }
1642
- return result;
1643
- }
1644
- // Handle Date objects specially
1645
- if (value instanceof Date) {
1646
- return {
1647
- [CLASS_MARKER]: 'Date',
1648
- [PROPS_MARKER]: value.toISOString()
1649
- };
1650
- }
1651
- // Handle Map objects
1652
- if (value instanceof Map) {
1653
- const entries = [];
1654
- for (const [k, v] of value) {
1655
- const processedKey = process_for_serialization(k, verbose, seen);
1656
- const processedValue = process_for_serialization(v, verbose, seen);
1657
- entries.push([processedKey, processedValue]);
1658
- }
1659
- return {
1660
- [CLASS_MARKER]: 'Map',
1661
- [PROPS_MARKER]: entries
1662
- };
1663
- }
1664
- // Handle Set objects
1665
- if (value instanceof Set) {
1666
- const items = [];
1667
- for (const item of value) {
1668
- items.push(process_for_serialization(item, verbose, seen));
1683
+ // Handle Date objects specially
1684
+ if (value instanceof Date) {
1685
+ return {
1686
+ [CLASS_MARKER]: 'Date',
1687
+ [PROPS_MARKER]: value.toISOString()
1688
+ };
1669
1689
  }
1670
- return {
1671
- [CLASS_MARKER]: 'Set',
1672
- [PROPS_MARKER]: items
1673
- };
1674
- }
1675
- // Get the constructor
1676
- const ctor = value.constructor;
1677
- // Handle registered class instances
1678
- if (ctor && ctor.name && class_registry[ctor.name]) {
1679
- const props = {};
1680
- // Extract own enumerable properties (bypass any toJSON method)
1681
- for (const key of Object.keys(value)) {
1682
- const propValue = value[key];
1683
- const processed = process_for_serialization(propValue, verbose, seen);
1684
- // Only include if not undefined (failed serialization)
1685
- if (processed !== undefined || propValue === undefined) {
1686
- props[key] = processed;
1690
+ // Handle Map objects
1691
+ if (value instanceof Map) {
1692
+ const entries = [];
1693
+ for (const [k, v] of value) {
1694
+ const processedKey = process_for_serialization(k, verbose, seen);
1695
+ const processedValue = process_for_serialization(v, verbose, seen);
1696
+ entries.push([processedKey, processedValue]);
1697
+ }
1698
+ return {
1699
+ [CLASS_MARKER]: 'Map',
1700
+ [PROPS_MARKER]: entries
1701
+ };
1702
+ }
1703
+ // Handle Set objects
1704
+ if (value instanceof Set) {
1705
+ const items = [];
1706
+ for (const item of value) {
1707
+ items.push(process_for_serialization(item, verbose, seen));
1687
1708
  }
1709
+ return {
1710
+ [CLASS_MARKER]: 'Set',
1711
+ [PROPS_MARKER]: items
1712
+ };
1688
1713
  }
1689
- return {
1690
- [CLASS_MARKER]: ctor.name,
1691
- [PROPS_MARKER]: props
1692
- };
1693
- }
1694
- // Handle plain objects (constructor is Object or no constructor)
1695
- if (ctor === Object || ctor === undefined || ctor === null) {
1714
+ // Get the constructor
1715
+ const ctor = value.constructor;
1716
+ // Handle registered class instances
1717
+ if (ctor && ctor.name && class_registry[ctor.name]) {
1718
+ const props = {};
1719
+ // Extract own enumerable properties (bypass any toJSON method)
1720
+ for (const key of Object.keys(value)) {
1721
+ const propValue = value[key];
1722
+ const processed = process_for_serialization(propValue, verbose, seen);
1723
+ // Only include if not undefined (failed serialization)
1724
+ if (processed !== undefined || propValue === undefined) {
1725
+ props[key] = processed;
1726
+ }
1727
+ }
1728
+ return {
1729
+ [CLASS_MARKER]: ctor.name,
1730
+ [PROPS_MARKER]: props
1731
+ };
1732
+ }
1733
+ // Handle plain objects (constructor is Object or no constructor)
1734
+ if (ctor === Object || ctor === undefined || ctor === null) {
1735
+ const result = {};
1736
+ for (const key of Object.keys(value)) {
1737
+ const propValue = value[key];
1738
+ const processed = process_for_serialization(propValue, verbose, seen);
1739
+ // Only include if not undefined (unless original was undefined)
1740
+ if (processed !== undefined || propValue === undefined) {
1741
+ result[key] = processed;
1742
+ }
1743
+ }
1744
+ return result;
1745
+ }
1746
+ // Unregistered class instance - convert to plain object for hot/cold parity
1747
+ // This ensures developers catch missing class registrations during development
1748
+ // (methods will be lost, only properties preserved)
1749
+ if (verbose) {
1750
+ console.warn(`[JQHTML Cache] Converting unregistered class "${ctor.name}" to plain object. ` +
1751
+ `Methods will be lost. Call jqhtml.register_cache_class(${ctor.name}) to preserve the class.`);
1752
+ }
1753
+ // Convert to plain object - properties are preserved, prototype methods are lost
1696
1754
  const result = {};
1697
1755
  for (const key of Object.keys(value)) {
1698
1756
  const propValue = value[key];
@@ -1704,24 +1762,10 @@ function process_for_serialization(value, verbose, seen) {
1704
1762
  }
1705
1763
  return result;
1706
1764
  }
1707
- // Unregistered class instance - convert to plain object for hot/cold parity
1708
- // This ensures developers catch missing class registrations during development
1709
- // (methods will be lost, only properties preserved)
1710
- if (verbose) {
1711
- console.warn(`[JQHTML Cache] Converting unregistered class "${ctor.name}" to plain object. ` +
1712
- `Methods will be lost. Call jqhtml.register_cache_class(${ctor.name}) to preserve the class.`);
1713
- }
1714
- // Convert to plain object - properties are preserved, prototype methods are lost
1715
- const result = {};
1716
- for (const key of Object.keys(value)) {
1717
- const propValue = value[key];
1718
- const processed = process_for_serialization(propValue, verbose, seen);
1719
- // Only include if not undefined (unless original was undefined)
1720
- if (processed !== undefined || propValue === undefined) {
1721
- result[key] = processed;
1722
- }
1765
+ finally {
1766
+ // Pop this object off the ancestor path now that its subtree is done.
1767
+ seen.delete(value);
1723
1768
  }
1724
- return result;
1725
1769
  }
1726
1770
  // ============================================================================
1727
1771
  // Deserialization (String → Object)
@@ -2140,10 +2184,825 @@ class Jqhtml_Local_Storage {
2140
2184
  }
2141
2185
  }
2142
2186
  }
2143
- Jqhtml_Local_Storage._cache_key = null;
2144
- Jqhtml_Local_Storage._cache_mode = 'data';
2145
- Jqhtml_Local_Storage._storage_available = null;
2146
- Jqhtml_Local_Storage._initialized = false;
2187
+ Jqhtml_Local_Storage._cache_key = null;
2188
+ Jqhtml_Local_Storage._cache_mode = 'data';
2189
+ Jqhtml_Local_Storage._storage_available = null;
2190
+ Jqhtml_Local_Storage._initialized = false;
2191
+
2192
+ /**
2193
+ * JQHTML Component Event System
2194
+ *
2195
+ * Extracted from component.ts - handles lifecycle event registration,
2196
+ * triggering, and state tracking.
2197
+ *
2198
+ * Events have "sticky" semantics for lifecycle events: if an event has already
2199
+ * occurred, new .on() handlers fire immediately with the stored data.
2200
+ */
2201
+ /**
2202
+ * Register a callback for an event.
2203
+ *
2204
+ * Lifecycle events (create, render, load, loaded, ready) are "sticky":
2205
+ * If a lifecycle event has already occurred, the callback fires immediately
2206
+ * AND registers for future occurrences.
2207
+ *
2208
+ * Custom events only fire when explicitly triggered via trigger().
2209
+ *
2210
+ * @param component - The component instance
2211
+ * @param event_name - Name of the event
2212
+ * @param callback - Callback: (component, data?) => void
2213
+ */
2214
+ function event_on(component, event_name, callback) {
2215
+ // Initialize callback array for this event if needed
2216
+ if (!component._lifecycle_callbacks.has(event_name)) {
2217
+ component._lifecycle_callbacks.set(event_name, []);
2218
+ }
2219
+ // Add callback to queue
2220
+ component._lifecycle_callbacks.get(event_name).push(callback);
2221
+ // If this lifecycle event has already occurred, fire the callback immediately
2222
+ // with the stored data from when trigger() was called
2223
+ if (component._lifecycle_states.has(event_name)) {
2224
+ try {
2225
+ const stored_data = component._lifecycle_states.get(event_name);
2226
+ callback(component, stored_data);
2227
+ }
2228
+ catch (error) {
2229
+ console.error(`[JQHTML] Error in ${event_name} callback:`, error);
2230
+ }
2231
+ }
2232
+ return component;
2233
+ }
2234
+ /**
2235
+ * Register a callback that fires exactly once.
2236
+ *
2237
+ * - If the event already occurred (sticky), fires immediately and does NOT register.
2238
+ * - If the event has not occurred, registers and auto-deregisters after first fire.
2239
+ *
2240
+ * @param component - The component instance
2241
+ * @param event_name - Name of the event
2242
+ * @param callback - Callback: (component, data?) => void
2243
+ */
2244
+ function event_once(component, event_name, callback) {
2245
+ // If event already occurred, fire immediately and we're done
2246
+ if (component._lifecycle_states.has(event_name)) {
2247
+ try {
2248
+ const stored_data = component._lifecycle_states.get(event_name);
2249
+ callback(component, stored_data);
2250
+ }
2251
+ catch (error) {
2252
+ console.error(`[JQHTML] Error in ${event_name} once callback:`, error);
2253
+ }
2254
+ return component;
2255
+ }
2256
+ // Wrap callback to auto-deregister after first fire
2257
+ const wrapper = (comp, data) => {
2258
+ // Remove ourselves from the callback list
2259
+ const callbacks = component._lifecycle_callbacks.get(event_name);
2260
+ if (callbacks) {
2261
+ const idx = callbacks.indexOf(wrapper);
2262
+ if (idx !== -1)
2263
+ callbacks.splice(idx, 1);
2264
+ }
2265
+ callback(comp, data);
2266
+ };
2267
+ // Initialize callback array for this event if needed
2268
+ if (!component._lifecycle_callbacks.has(event_name)) {
2269
+ component._lifecycle_callbacks.set(event_name, []);
2270
+ }
2271
+ component._lifecycle_callbacks.get(event_name).push(wrapper);
2272
+ return component;
2273
+ }
2274
+ /**
2275
+ * Trigger an event - fires all registered callbacks.
2276
+ * Marks event as occurred so future .on() calls fire immediately.
2277
+ *
2278
+ * @param component - The component instance
2279
+ * @param event_name - Name of the event to trigger
2280
+ * @param data - Optional data to pass to callbacks as second parameter
2281
+ */
2282
+ function event_trigger(component, event_name, data) {
2283
+ // Mark this event as occurred and store the data for late subscribers
2284
+ component._lifecycle_states.set(event_name, data);
2285
+ // Fire all registered callbacks for this event
2286
+ const callbacks = component._lifecycle_callbacks.get(event_name);
2287
+ if (callbacks) {
2288
+ for (const callback of callbacks) {
2289
+ try {
2290
+ callback.bind(component)(component, data);
2291
+ }
2292
+ catch (error) {
2293
+ console.error(`[JQHTML] Error in ${event_name} callback:`, error);
2294
+ }
2295
+ }
2296
+ }
2297
+ }
2298
+ /**
2299
+ * Check if any callbacks are registered for a given event.
2300
+ *
2301
+ * @param component - The component instance
2302
+ * @param event_name - Name of the event to check
2303
+ */
2304
+ function event_on_registered(component, event_name) {
2305
+ const callbacks = component._lifecycle_callbacks.get(event_name);
2306
+ return !!(callbacks && callbacks.length > 0);
2307
+ }
2308
+ /**
2309
+ * Invalidate a lifecycle event - removes the "already occurred" marker.
2310
+ *
2311
+ * After invalidate() is called:
2312
+ * - New .on() handlers will NOT fire immediately
2313
+ * - The ready() promise will NOT resolve immediately
2314
+ * - Handlers wait for the next trigger() call
2315
+ *
2316
+ * Existing registered callbacks are NOT removed - they'll fire on next trigger().
2317
+ *
2318
+ * Use case: Call invalidate('ready') at the start of reload() or render()
2319
+ * so that any new .on('ready') handlers wait for the reload/render to complete.
2320
+ *
2321
+ * @param component - The component instance
2322
+ * @param event_name - Name of the event to invalidate
2323
+ */
2324
+ function event_invalidate(component, event_name) {
2325
+ component._lifecycle_states.delete(event_name);
2326
+ }
2327
+
2328
+ /**
2329
+ * JQHTML Data Proxy System
2330
+ *
2331
+ * Extracted from component.ts - handles:
2332
+ * - Data freeze/unfreeze enforcement via Proxy
2333
+ * - Detached on_load() execution with restricted access
2334
+ */
2335
+ /**
2336
+ * Set up the `this.data` property on a component using Object.defineProperty
2337
+ * with a Proxy that enforces freeze/unfreeze semantics.
2338
+ *
2339
+ * After setup:
2340
+ * - `this.data` reads/writes go through a Proxy
2341
+ * - When `component.__data_frozen === true`, writes throw errors
2342
+ * - When frozen is false, writes pass through normally
2343
+ *
2344
+ * @param component - The component instance to set up data on
2345
+ */
2346
+ function setup_data_property(component) {
2347
+ let _data = {};
2348
+ // Helper to create frozen proxy for data object
2349
+ const create_proxy = (obj) => {
2350
+ return new Proxy(obj, {
2351
+ set: (target, prop, value) => {
2352
+ if (component.__data_frozen) {
2353
+ console.error(`[JQHTML] ERROR: Component "${component.component_name()}" attempted to modify this.data.${String(prop)} outside of on_create() or on_load().\n\n` +
2354
+ `RESTRICTION: this.data can ONLY be modified in:\n` +
2355
+ ` - on_create() (set initial defaults, synchronous only)\n` +
2356
+ ` - on_load() (fetch data from APIs, can be async)\n\n` +
2357
+ `WHY: this.data represents loaded state. Modifying it outside these methods bypasses the framework's render cycle.\n\n` +
2358
+ `FIX: Modify this.data in on_create() (for defaults) or on_load() (for fetched data):\n` +
2359
+ ` ❌ In on_ready(): this.data.${String(prop)} = ${JSON.stringify(value)};\n` +
2360
+ ` ✅ In on_create(): this.data.${String(prop)} = ${JSON.stringify(value)}; // Set default\n` +
2361
+ ` ✅ In on_load(): this.data.${String(prop)} = ${JSON.stringify(value)}; // Fetch from API\n` +
2362
+ ` ✅ For component state: this.args.${String(prop)} = ${JSON.stringify(value)}; (accessible in on_load)`);
2363
+ throw new Error(`[JQHTML] Cannot modify this.data.${String(prop)} outside of on_create() or on_load(). ` +
2364
+ `this.data is frozen after on_create() and unfrozen only during on_load().`);
2365
+ }
2366
+ target[prop] = value;
2367
+ return true;
2368
+ },
2369
+ deleteProperty: (target, prop) => {
2370
+ if (component.__data_frozen) {
2371
+ console.error(`[JQHTML] ERROR: Component "${component.component_name()}" attempted to delete this.data.${String(prop)} outside of on_create() or on_load().\n\n` +
2372
+ `RESTRICTION: this.data can ONLY be modified in:\n` +
2373
+ ` - on_create() (set initial defaults, synchronous only)\n` +
2374
+ ` - on_load() (fetch data from APIs, can be async)\n\n` +
2375
+ `WHY: this.data represents loaded state. Modifying it outside these methods bypasses the framework's render cycle.`);
2376
+ throw new Error(`[JQHTML] Cannot delete this.data.${String(prop)} outside of on_create() or on_load(). ` +
2377
+ `this.data is frozen after on_create() and unfrozen only during on_load().`);
2378
+ }
2379
+ delete target[prop];
2380
+ return true;
2381
+ }
2382
+ });
2383
+ };
2384
+ // Create initial proxied data object
2385
+ _data = create_proxy({});
2386
+ Object.defineProperty(component, 'data', {
2387
+ get: () => _data,
2388
+ set: (value) => {
2389
+ if (component.__data_frozen) {
2390
+ console.error(`[JQHTML] ERROR: Component "${component.component_name()}" attempted to reassign this.data outside of on_create() or on_load().\n\n` +
2391
+ `RESTRICTION: this.data can ONLY be modified in:\n` +
2392
+ ` - on_create() (set initial defaults, synchronous only)\n` +
2393
+ ` - on_load() (fetch data from APIs, can be async)\n\n` +
2394
+ `WHY: this.data represents loaded state. Modifying it outside these methods bypasses the framework's render cycle.\n\n` +
2395
+ `FIX: Modify this.data in on_create() (for defaults) or on_load() (for fetched data):\n` +
2396
+ ` ❌ In on_ready(): this.data = {...};\n` +
2397
+ ` ✅ In on_create(): this.data.count = 0; // Set default\n` +
2398
+ ` ✅ In on_load(): this.data = await fetch(...); // Fetch from API\n` +
2399
+ ` ✅ For component state: this.args.count = 5; (accessible in on_load)`);
2400
+ throw new Error(`[JQHTML] Cannot reassign this.data outside of on_create() or on_load(). ` +
2401
+ `this.data is frozen after on_create() and unfrozen only during on_load().`);
2402
+ }
2403
+ // When setting, wrap the new value in a proxy too
2404
+ _data = create_proxy(value);
2405
+ },
2406
+ enumerable: true,
2407
+ configurable: false
2408
+ });
2409
+ }
2410
+ /**
2411
+ * Execute on_load() in a detached context with restricted access.
2412
+ *
2413
+ * Creates a sandboxed environment where on_load() can only access:
2414
+ * - this.args (read-only)
2415
+ * - this.data (read/write, cloned from __initial_data_snapshot)
2416
+ *
2417
+ * All other property access (this.$, this.$sid, etc.) throws errors.
2418
+ *
2419
+ * @param component - The component instance
2420
+ * @param use_load_coordinator - Whether to use Load_Coordinator for deduplication
2421
+ * @returns The resulting data and optional coordination completion function
2422
+ */
2423
+ async function execute_on_load_detached(component, use_load_coordinator = false) {
2424
+ // Clone this.data from the snapshot captured after on_create()
2425
+ const data_clone = component.__initial_data_snapshot
2426
+ ? JSON.parse(JSON.stringify(component.__initial_data_snapshot))
2427
+ : {};
2428
+ // Create a read-only proxy for args that blocks all modifications
2429
+ // Can't use JSON clone because args may contain functions (_slots, callbacks)
2430
+ const component_name = component.component_name();
2431
+ const create_readonly_proxy = (obj, path = 'this.args') => {
2432
+ if (obj === null || typeof obj !== 'object')
2433
+ return obj;
2434
+ return new Proxy(obj, {
2435
+ get(target, prop) {
2436
+ const value = target[prop];
2437
+ // Recursively wrap nested objects (but not functions)
2438
+ if (value !== null && typeof value === 'object' && typeof value !== 'function') {
2439
+ return create_readonly_proxy(value, `${path}.${String(prop)}`);
2440
+ }
2441
+ return value;
2442
+ },
2443
+ set(_target, prop, value) {
2444
+ console.error(`[JQHTML] ERROR: Component "${component_name}" attempted to modify ${path}.${String(prop)} during on_load().\n\n` +
2445
+ `RESTRICTION: this.args is READ-ONLY during on_load().\n\n` +
2446
+ `WHY: this.args configures what data to fetch. Modifying it during on_load() creates circular dependencies.\n\n` +
2447
+ `FIX: Modify this.args BEFORE on_load() runs (in on_create() or before calling reload()):\n` +
2448
+ ` ❌ Inside on_load(): ${path}.${String(prop)} = ${JSON.stringify(value)};\n` +
2449
+ ` ✅ In on_create(): this.args.${String(prop)} = defaultValue;`);
2450
+ throw new Error(`[JQHTML] Cannot modify ${path}.${String(prop)} during on_load(). ` +
2451
+ `this.args is read-only in on_load().`);
2452
+ },
2453
+ deleteProperty(_target, prop) {
2454
+ console.error(`[JQHTML] ERROR: Component "${component_name}" attempted to delete ${path}.${String(prop)} during on_load().\n\n` +
2455
+ `RESTRICTION: this.args is READ-ONLY during on_load().`);
2456
+ throw new Error(`[JQHTML] Cannot delete ${path}.${String(prop)} during on_load(). ` +
2457
+ `this.args is read-only in on_load().`);
2458
+ }
2459
+ });
2460
+ };
2461
+ // Create a detached context object that on_load will operate on
2462
+ const detached_context = {
2463
+ args: create_readonly_proxy(component.args), // Read-only proxy wrapping real args
2464
+ data: data_clone // Cloned data - modifications stay isolated
2465
+ };
2466
+ // Create restricted proxy that operates on the detached context
2467
+ const restricted_this = new Proxy(detached_context, {
2468
+ get(target, prop) {
2469
+ // Only allow access to args and data
2470
+ if (prop === 'args') {
2471
+ return target.args;
2472
+ }
2473
+ if (prop === 'data') {
2474
+ return target.data;
2475
+ }
2476
+ // Block everything else
2477
+ console.error(`[JQHTML] ERROR: Component "${component_name}" attempted to access this.${String(prop)} during on_load().\n\n` +
2478
+ `RESTRICTION: on_load() may ONLY access:\n` +
2479
+ ` - this.args (read-only)\n` +
2480
+ ` - this.data (read/write)\n\n` +
2481
+ `WHY: on_load() is for data fetching only. All other component functionality should happen in other lifecycle methods.\n\n` +
2482
+ `FIX:\n` +
2483
+ ` - DOM manipulation → use on_render() or on_ready()\n` +
2484
+ ` - Component methods → call them before/after on_load(), not inside it\n` +
2485
+ ` - Other properties → restructure code to only use this.args and this.data in on_load()`);
2486
+ throw new Error(`[JQHTML] Cannot access this.${String(prop)} during on_load(). ` +
2487
+ `on_load() may only access this.args and this.data.`);
2488
+ },
2489
+ set(target, prop, value) {
2490
+ // Only allow setting data
2491
+ if (prop === 'data') {
2492
+ target.data = value;
2493
+ return true;
2494
+ }
2495
+ // Block setting args
2496
+ if (prop === 'args') {
2497
+ console.error(`[JQHTML] ERROR: Component "${component_name}" attempted to modify this.args during on_load().\n\n` +
2498
+ `RESTRICTION: on_load() may ONLY modify:\n` +
2499
+ ` - this.data (read/write)\n\n` +
2500
+ `WHY: this.args is component state that on_load() depends on. Modifying it inside on_load() creates circular dependencies.\n\n` +
2501
+ `FIX: Modify this.args BEFORE calling on_load() (in on_create() or other lifecycle methods), not inside on_load():\n` +
2502
+ ` ❌ Inside on_load(): this.args.filter = 'new_value';\n` +
2503
+ ` ✅ In on_create(): this.args.filter = this.args.initial_filter || 'default';`);
2504
+ throw new Error(`[JQHTML] Cannot modify this.args during on_load(). ` +
2505
+ `Modify this.args in other lifecycle methods, not inside on_load().`);
2506
+ }
2507
+ // Block setting any other properties
2508
+ console.error(`[JQHTML] ERROR: Component "${component_name}" attempted to modify this.${String(prop)} during on_load().\n\n` +
2509
+ `RESTRICTION: on_load() may ONLY modify:\n` +
2510
+ ` - this.data (read/write)\n\n` +
2511
+ `WHY: on_load() is for data fetching only. Setting properties on the component instance should happen in other lifecycle methods.\n\n` +
2512
+ `FIX: Store your data in this.data instead:\n` +
2513
+ ` ❌ this.${String(prop)} = value;\n` +
2514
+ ` ✅ this.data.${String(prop)} = value;`);
2515
+ throw new Error(`[JQHTML] Cannot modify this.${String(prop)} during on_load(). ` +
2516
+ `Only this.data can be modified in on_load().`);
2517
+ }
2518
+ });
2519
+ // Create promise for this on_load() call
2520
+ const on_load_promise = (async () => {
2521
+ try {
2522
+ await component._call_lifecycle('on_load', restricted_this);
2523
+ }
2524
+ catch (error) {
2525
+ if (use_load_coordinator) {
2526
+ // Handle error and notify coordinator
2527
+ Load_Coordinator.handle_leader_error(component, error);
2528
+ }
2529
+ throw error;
2530
+ }
2531
+ })();
2532
+ // If using Load_Coordinator, register as leader
2533
+ // Note: We store the completion function but DON'T call it here
2534
+ // It will be called by _load() after _apply_load_result() updates this.data
2535
+ let complete_coordination = null;
2536
+ if (use_load_coordinator) {
2537
+ complete_coordination = Load_Coordinator.register_leader(component, on_load_promise);
2538
+ }
2539
+ await on_load_promise;
2540
+ // Note: We don't validate args changes here because external code (like parent
2541
+ // components calling reload()) is allowed to modify component.args during on_load().
2542
+ // The read-only proxy only prevents code INSIDE on_load() from modifying args.
2543
+ // Return the data from the detached context AND the completion function
2544
+ return {
2545
+ data: detached_context.data,
2546
+ complete_coordination
2547
+ };
2548
+ }
2549
+
2550
+ /**
2551
+ * JQHTML Component Cache Integration
2552
+ *
2553
+ * Extracted from component.ts - handles cache key generation,
2554
+ * cache reads during create(), cache checks during reload(),
2555
+ * and HTML cache snapshots during ready().
2556
+ *
2557
+ * Uses Jqhtml_Local_Storage as the underlying storage layer.
2558
+ */
2559
+ /**
2560
+ * Generate a cache key for a component using its name + args.
2561
+ * Supports custom cache_id() override.
2562
+ *
2563
+ * @param component - The component instance
2564
+ * @returns Cache key string or null if caching is disabled
2565
+ */
2566
+ function generate_cache_key(component) {
2567
+ if (typeof component.cache_id === 'function') {
2568
+ try {
2569
+ const custom_cache_id = component.cache_id();
2570
+ return { cache_key: `${component.component_name()}::${String(custom_cache_id)}` };
2571
+ }
2572
+ catch (error) {
2573
+ return { cache_key: null, uncacheable_property: 'cache_id()' };
2574
+ }
2575
+ }
2576
+ // Use standard args-based cache key generation
2577
+ const result = Load_Coordinator.generate_invocation_key(component.component_name(), component.args);
2578
+ return { cache_key: result.key, uncacheable_property: result.uncacheable_property };
2579
+ }
2580
+ /**
2581
+ * Read cache during create() phase.
2582
+ * Sets component._cache_key, _cached_html, _use_cached_data_hit as side effects.
2583
+ *
2584
+ * @param component - The component instance
2585
+ */
2586
+ function read_cache_in_create(component) {
2587
+ const { cache_key, uncacheable_property } = generate_cache_key(component);
2588
+ // If cache_key is null, caching disabled
2589
+ if (cache_key === null) {
2590
+ // Set data-nocache attribute for debugging
2591
+ if (uncacheable_property) {
2592
+ component.$.attr('data-nocache', uncacheable_property);
2593
+ }
2594
+ if (window.jqhtml?.debug?.verbose) {
2595
+ console.log(`[Cache] Component ${component._cid} (${component.component_name()}) has non-serializable args - caching disabled`, { uncacheable_property });
2596
+ }
2597
+ return;
2598
+ }
2599
+ // Store cache key for later use
2600
+ component._cache_key = cache_key;
2601
+ // Get cache mode
2602
+ const cache_mode = Jqhtml_Local_Storage.get_cache_mode();
2603
+ if (window.jqhtml?.debug?.verbose) {
2604
+ console.log(`[Cache ${cache_mode}] Component ${component._cid} (${component.component_name()}) checking cache in create()`, { cache_key, cache_mode, has_cache_key_set: Jqhtml_Local_Storage.has_cache_key() });
2605
+ }
2606
+ if (cache_mode === 'html') {
2607
+ // HTML cache mode - check for cached HTML to inject on first render
2608
+ const html_cache_key = `${cache_key}::html`;
2609
+ const cached_html = Jqhtml_Local_Storage.get(html_cache_key);
2610
+ if (cached_html !== null && typeof cached_html === 'string') {
2611
+ component._cached_html = cached_html;
2612
+ if (window.jqhtml?.debug?.verbose) {
2613
+ console.log(`[Cache html] Component ${component._cid} (${component.component_name()}) found cached HTML`, { cache_key: html_cache_key, html_length: cached_html.length });
2614
+ }
2615
+ }
2616
+ else {
2617
+ if (window.jqhtml?.debug?.verbose) {
2618
+ console.log(`[Cache html] Component ${component._cid} (${component.component_name()}) cache miss`, { cache_key: html_cache_key });
2619
+ }
2620
+ }
2621
+ // Warn if use_cached_data is set in html cache mode
2622
+ if (component.args.use_cached_data === true) {
2623
+ console.warn(`[JQHTML] Component "${component.component_name()}" has use_cached_data=true but cache mode is 'html'.\n` +
2624
+ `use_cached_data only applies to 'data' cache mode. In 'html' mode, the entire rendered HTML is cached.\n` +
2625
+ `The use_cached_data flag will be ignored.`);
2626
+ }
2627
+ }
2628
+ else {
2629
+ // Data cache mode (default) - check for cached data to hydrate this.data
2630
+ const cached_data = Jqhtml_Local_Storage.get(cache_key);
2631
+ if (cached_data !== null && typeof cached_data === 'object') {
2632
+ // Hydrate this.data with cached data
2633
+ component.data = cached_data;
2634
+ if (component.args.use_cached_data === true) {
2635
+ component._use_cached_data_hit = true;
2636
+ if (window.jqhtml?.debug?.verbose) {
2637
+ console.log(`[Cache data] Component ${component._cid} (${component.component_name()}) using cached data (use_cached_data=true, skipping on_load)`, { cache_key, data: cached_data });
2638
+ }
2639
+ }
2640
+ else {
2641
+ if (window.jqhtml?.debug?.verbose) {
2642
+ console.log(`[Cache data] Component ${component._cid} (${component.component_name()}) hydrated from cache`, { cache_key, data: cached_data });
2643
+ }
2644
+ }
2645
+ }
2646
+ else {
2647
+ if (window.jqhtml?.debug?.verbose) {
2648
+ console.log(`[Cache data] Component ${component._cid} (${component.component_name()}) cache miss`, { cache_key });
2649
+ }
2650
+ }
2651
+ }
2652
+ }
2653
+ /**
2654
+ * Check cache during reload() when args have changed.
2655
+ * If cache hit, hydrates data/html and triggers an immediate render.
2656
+ *
2657
+ * @param component - The component instance
2658
+ * @returns true if rendered from cache, false otherwise
2659
+ */
2660
+ function check_cache_on_reload(component) {
2661
+ const { cache_key } = generate_cache_key(component);
2662
+ if (cache_key === null) {
2663
+ return false;
2664
+ }
2665
+ const cache_mode = Jqhtml_Local_Storage.get_cache_mode();
2666
+ component._cache_key = cache_key;
2667
+ if (cache_mode === 'html') {
2668
+ // HTML cache mode - check for cached HTML
2669
+ const html_cache_key = `${cache_key}::html`;
2670
+ const cached_html = Jqhtml_Local_Storage.get(html_cache_key);
2671
+ if (cached_html !== null && typeof cached_html === 'string') {
2672
+ if (window.jqhtml?.debug?.verbose) {
2673
+ 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 });
2674
+ }
2675
+ component._cached_html = cached_html;
2676
+ // Call _render() directly (not render()) since _reload() manages the full lifecycle
2677
+ // Using render() would trigger a separate queue entry and interfere with _reload()'s flow
2678
+ component._render();
2679
+ return true;
2680
+ }
2681
+ }
2682
+ else {
2683
+ // Data cache mode (default) - check for cached data
2684
+ const cached_data = Jqhtml_Local_Storage.get(cache_key);
2685
+ if (cached_data !== null && typeof cached_data === 'object' && JSON.stringify(cached_data) !== '{}') {
2686
+ if (window.jqhtml?.debug?.verbose) {
2687
+ console.log(`[Cache data] reload() - Component ${component._cid} (${component.component_name()}) hydrated from cache (args changed)`, { cache_key, data: cached_data });
2688
+ }
2689
+ // Hydrate this.data with cached data
2690
+ component.__data_frozen = false;
2691
+ component.data = cached_data;
2692
+ component.__data_frozen = true;
2693
+ // Call _render() directly (not render()) since _reload() manages the full lifecycle
2694
+ component._render();
2695
+ return true;
2696
+ }
2697
+ }
2698
+ return false;
2699
+ }
2700
+ /**
2701
+ * Write HTML cache snapshot during ready() phase.
2702
+ * Only caches if the component is dynamic (data changed during on_load).
2703
+ *
2704
+ * @param component - The component instance
2705
+ */
2706
+ function write_html_cache_snapshot(component) {
2707
+ if (!component._should_cache_html_after_ready || !component._cache_key) {
2708
+ return;
2709
+ }
2710
+ if (component._is_dynamic) {
2711
+ component._should_cache_html_after_ready = false;
2712
+ const html = component.$.html();
2713
+ const html_cache_key = `${component._cache_key}::html`;
2714
+ Jqhtml_Local_Storage.set(html_cache_key, html);
2715
+ if (window.jqhtml?.debug?.verbose) {
2716
+ 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 });
2717
+ }
2718
+ }
2719
+ else {
2720
+ component._should_cache_html_after_ready = false;
2721
+ if (window.jqhtml?.debug?.verbose) {
2722
+ console.log(`[Cache html] Component ${component._cid} (${component.component_name()}) is static (no data change) - skipping HTML cache`);
2723
+ }
2724
+ }
2725
+ }
2726
+ /**
2727
+ * Write data/HTML to cache after on_load() completes.
2728
+ * Called from _apply_load_result().
2729
+ *
2730
+ * @param component - The component instance
2731
+ * @param data_changed - Whether this.data changed during on_load
2732
+ */
2733
+ function write_cache_on_loaded(component, data_changed) {
2734
+ if (!data_changed || !component._cache_key) {
2735
+ return;
2736
+ }
2737
+ const cache_mode = Jqhtml_Local_Storage.get_cache_mode();
2738
+ if (cache_mode === 'html') {
2739
+ // HTML cache mode - flag to cache HTML after children ready in _ready()
2740
+ component._should_cache_html_after_ready = true;
2741
+ if (window.jqhtml?.debug?.verbose) {
2742
+ console.log(`[Cache html] Component ${component._cid} (${component.component_name()}) will cache HTML after ready`, { cache_key: component._cache_key });
2743
+ }
2744
+ }
2745
+ else {
2746
+ // Data cache mode (default) - write this.data to cache
2747
+ Jqhtml_Local_Storage.set(component._cache_key, component.data);
2748
+ if (window.jqhtml?.debug?.verbose) {
2749
+ console.log(`[Cache data] Component ${component._cid} (${component.component_name()}) cached data after on_load()`, { cache_key: component._cache_key, data: component.data });
2750
+ }
2751
+ }
2752
+ }
2753
+
2754
+ /**
2755
+ * JQHTML Component Lifecycle Queue
2756
+ *
2757
+ * Serializes lifecycle operations (render, reload, refresh) per component.
2758
+ * Replaces _create_debounced_function with a proper queue that:
2759
+ *
2760
+ * - At most one operation runs at a time per component
2761
+ * - At most one operation is pending (waiting for the current to finish)
2762
+ * - Same-type pending operations collapse (fan-in: all callers share one execution)
2763
+ * - Different-type pending operations: new replaces old (old callers get the new result)
2764
+ *
2765
+ * Boot bypasses this queue entirely - it runs the lifecycle directly.
2766
+ */
2767
+ class Component_Queue {
2768
+ constructor() {
2769
+ /** Currently executing operation */
2770
+ this._current = null;
2771
+ /** Next operation waiting to execute after current completes */
2772
+ this._pending = null;
2773
+ }
2774
+ /**
2775
+ * Enqueue a lifecycle operation.
2776
+ *
2777
+ * Behavior:
2778
+ * - Nothing running → execute immediately
2779
+ * - Something running, no pending → create pending entry
2780
+ * - Something running, same type pending → collapse (share pending promise)
2781
+ * - Something running, different type pending → replace pending (all callers get new result)
2782
+ *
2783
+ * @param type - Operation type ('render', 'reload', 'refresh', 'load')
2784
+ * @param executor - The async function to execute
2785
+ * @returns Promise that resolves when the operation completes
2786
+ */
2787
+ enqueue(type, executor) {
2788
+ // If nothing running, execute immediately
2789
+ if (!this._current) {
2790
+ return this._execute(type, executor);
2791
+ }
2792
+ // Something is running — add to pending
2793
+ if (this._pending) {
2794
+ if (this._pending.type === type) {
2795
+ // Same type pending → collapse (fan-in)
2796
+ // All callers share the same future execution
2797
+ return new Promise((resolve, reject) => {
2798
+ this._pending.resolvers.push(resolve);
2799
+ this._pending.rejecters.push(reject);
2800
+ });
2801
+ }
2802
+ else {
2803
+ // Different type pending → replace
2804
+ // Old pending callers join the new operation
2805
+ // (their operation was superseded by a different type)
2806
+ const old_resolvers = this._pending.resolvers;
2807
+ const old_rejecters = this._pending.rejecters;
2808
+ return new Promise((resolve, reject) => {
2809
+ this._pending = {
2810
+ type,
2811
+ executor,
2812
+ resolvers: [...old_resolvers, resolve],
2813
+ rejecters: [...old_rejecters, reject]
2814
+ };
2815
+ });
2816
+ }
2817
+ }
2818
+ // No pending entry yet — create one
2819
+ return new Promise((resolve, reject) => {
2820
+ this._pending = {
2821
+ type,
2822
+ executor,
2823
+ resolvers: [resolve],
2824
+ rejecters: [reject]
2825
+ };
2826
+ });
2827
+ }
2828
+ /**
2829
+ * Execute an operation and handle pending queue after completion.
2830
+ * @private
2831
+ */
2832
+ _execute(type, executor) {
2833
+ const promise = (async () => {
2834
+ try {
2835
+ await executor();
2836
+ }
2837
+ finally {
2838
+ this._current = null;
2839
+ // Run pending if exists
2840
+ if (this._pending) {
2841
+ const pending = this._pending;
2842
+ this._pending = null;
2843
+ try {
2844
+ await this._execute(pending.type, pending.executor);
2845
+ for (const resolve of pending.resolvers)
2846
+ resolve();
2847
+ }
2848
+ catch (err) {
2849
+ for (const reject of pending.rejecters)
2850
+ reject(err);
2851
+ }
2852
+ }
2853
+ }
2854
+ })();
2855
+ this._current = { type, promise };
2856
+ return promise;
2857
+ }
2858
+ /**
2859
+ * Check if any operation is currently running.
2860
+ */
2861
+ get is_busy() {
2862
+ return this._current !== null;
2863
+ }
2864
+ /**
2865
+ * Check if there's a pending operation waiting.
2866
+ */
2867
+ get has_pending() {
2868
+ return this._pending !== null;
2869
+ }
2870
+ }
2871
+
2872
+ /**
2873
+ * JQHTML SSR Preload Data System
2874
+ *
2875
+ * Captures component data during SSR rendering and replays it on the client
2876
+ * to skip redundant on_load() calls during hydration.
2877
+ *
2878
+ * Server-side: start_data_capture() → render → get_captured_data()
2879
+ * Client-side: set_preload_data(entries) → components boot with preloaded data → clear_preload_data()
2880
+ */
2881
+ // --- Capture (Server Side) ---
2882
+ let _capture_enabled = false;
2883
+ let _capture_buffer = [];
2884
+ // Track captured keys to avoid duplicates from Load Coordinator followers
2885
+ let _captured_keys = new Set();
2886
+ /**
2887
+ * Enable data capture mode. After this call, every component that completes
2888
+ * on_load() has its final this.data recorded.
2889
+ *
2890
+ * Idempotent — calling twice is fine.
2891
+ */
2892
+ function start_data_capture() {
2893
+ _capture_enabled = true;
2894
+ _capture_buffer = [];
2895
+ _captured_keys.clear();
2896
+ }
2897
+ /**
2898
+ * Record a component's data after on_load() completes.
2899
+ * Called internally from _apply_load_result().
2900
+ *
2901
+ * @param component_name - Component name
2902
+ * @param args - Component args at time of on_load()
2903
+ * @param data - this.data after on_load() completed
2904
+ * @param cache_key - The cache key for deduplication (null = always capture)
2905
+ */
2906
+ function capture_component_data(component_name, args, data, cache_key) {
2907
+ if (!_capture_enabled)
2908
+ return;
2909
+ // Deduplicate: if Load Coordinator already captured this key, skip
2910
+ if (cache_key !== null) {
2911
+ if (_captured_keys.has(cache_key))
2912
+ return;
2913
+ _captured_keys.add(cache_key);
2914
+ }
2915
+ // Deep clone args and data to plain objects (no proxies, no class instances)
2916
+ try {
2917
+ const cloned_args = JSON.parse(JSON.stringify(args));
2918
+ const cloned_data = JSON.parse(JSON.stringify(data));
2919
+ _capture_buffer.push({
2920
+ component: component_name,
2921
+ args: cloned_args,
2922
+ data: cloned_data,
2923
+ });
2924
+ }
2925
+ catch (error) {
2926
+ // Non-serializable data — skip capture for this component
2927
+ if (typeof console !== 'undefined') {
2928
+ console.warn(`[JQHTML SSR Capture] Failed to serialize data for ${component_name}:`, error);
2929
+ }
2930
+ }
2931
+ }
2932
+ /**
2933
+ * Returns all captured component data and resets the capture buffer.
2934
+ * One-shot: calling clears the buffer.
2935
+ */
2936
+ function get_captured_data() {
2937
+ const result = _capture_buffer;
2938
+ _capture_buffer = [];
2939
+ _captured_keys.clear();
2940
+ return result;
2941
+ }
2942
+ /**
2943
+ * Check if data capture is currently enabled.
2944
+ */
2945
+ function is_capture_enabled() {
2946
+ return _capture_enabled;
2947
+ }
2948
+ /**
2949
+ * Stop data capture and clear all state.
2950
+ */
2951
+ function stop_data_capture() {
2952
+ _capture_enabled = false;
2953
+ _capture_buffer = [];
2954
+ _captured_keys.clear();
2955
+ }
2956
+ // --- Preload (Client Side) ---
2957
+ let _preload_cache = new Map();
2958
+ /**
2959
+ * Seed the preload cache with SSR-captured data.
2960
+ * Must be called before any component _load() runs.
2961
+ *
2962
+ * @param entries - Array of { component, args, data } entries from get_captured_data()
2963
+ */
2964
+ function set_preload_data(entries) {
2965
+ if (!entries || entries.length === 0)
2966
+ return;
2967
+ _preload_cache.clear();
2968
+ for (const entry of entries) {
2969
+ // Generate key using the same algorithm as Load Coordinator
2970
+ const result = Load_Coordinator.generate_invocation_key(entry.component, entry.args);
2971
+ if (result.key !== null) {
2972
+ _preload_cache.set(result.key, entry.data);
2973
+ }
2974
+ }
2975
+ }
2976
+ /**
2977
+ * Check if preloaded data exists for a given cache key.
2978
+ * If found, returns the data and removes the entry (one-shot).
2979
+ *
2980
+ * @param cache_key - The cache key (same format as Load Coordinator)
2981
+ * @returns The preloaded data, or null if no match
2982
+ */
2983
+ function consume_preload_data(cache_key) {
2984
+ if (_preload_cache.size === 0)
2985
+ return null;
2986
+ const data = _preload_cache.get(cache_key);
2987
+ if (data !== undefined) {
2988
+ _preload_cache.delete(cache_key);
2989
+ return data;
2990
+ }
2991
+ return null;
2992
+ }
2993
+ /**
2994
+ * Clear any remaining unconsumed preload entries.
2995
+ * Call after initial page hydration is complete.
2996
+ */
2997
+ function clear_preload_data() {
2998
+ _preload_cache.clear();
2999
+ }
3000
+ /**
3001
+ * Check if any preload data is available (for fast early exit in _load).
3002
+ */
3003
+ function has_preload_data() {
3004
+ return _preload_cache.size > 0;
3005
+ }
2147
3006
 
2148
3007
  /**
2149
3008
  * JQHTML v2 Component Base Class
@@ -2175,6 +3034,7 @@ class Jqhtml_Component {
2175
3034
  this._data_on_last_render = null; // Data snapshot from last render (for refresh() comparison)
2176
3035
  this.__initial_data_snapshot = null; // Snapshot of this.data after on_create() for restoration before on_load()
2177
3036
  this.__data_frozen = false; // Track if this.data is currently frozen
3037
+ this._queue = new Component_Queue(); // Lifecycle operation queue (render/reload/refresh)
2178
3038
  this.next_reload_force_refresh = null; // State machine for reload()/refresh() debounce precedence
2179
3039
  this.__lifecycle_authorized = false; // Flag for lifecycle method protection
2180
3040
  // Cache mode properties
@@ -2188,12 +3048,17 @@ class Jqhtml_Component {
2188
3048
  this._on_render_complete = false; // True after on_render() has been called post-on_load
2189
3049
  // use_cached_data feature - skip on_load() when cache hit occurs
2190
3050
  this._use_cached_data_hit = false; // True if use_cached_data=true AND cache was used
2191
- // skip_render_and_ready feature - skip first render/on_render and on_ready entirely
2192
- // Component reports ready after on_load completes
2193
- this._skip_render_and_ready = false;
2194
- // skip_ready feature - skip on_ready only
2195
- // Component reports ready after on_render completes
2196
- this._skip_ready = false;
3051
+ // _load_only: create + load only. No render, no children, no on_render, no on_loaded, no on_ready.
3052
+ this._load_only = false;
3053
+ // _load_render_only: create + render + load + re-render. No on_render, no on_loaded, no on_ready.
3054
+ this._load_render_only = false;
3055
+ // Detached optimization: true when element is not in the DOM at boot time.
3056
+ // Skips initial render and cache read — just on_load then render.
3057
+ // Override with _force_initial_render to keep normal double-render behavior.
3058
+ this._is_detached = false;
3059
+ // _force_initial_render: override detached optimization — render even when not in DOM.
3060
+ // Use when you need the loading spinner visible immediately after appending.
3061
+ this._force_initial_render = false;
2197
3062
  // rendered event - fires once after the synchronous render chain completes
2198
3063
  // (after on_load's re-render if applicable, or after first render if no on_load)
2199
3064
  this._has_rendered = false;
@@ -2204,6 +3069,11 @@ class Jqhtml_Component {
2204
3069
  // Set in constructor (prototype chain is established before constructor runs)
2205
3070
  // Used to skip expensive cache/load operations for static components
2206
3071
  this.__has_custom_on_load = false;
3072
+ // gate_load() — "load gates" registered during on_create() that must settle
3073
+ // before the component's FIRST on_load() runs. See gate_load() / _await_load_gates().
3074
+ this.__load_gates = []; // Pending gates (cleared once the first load begins)
3075
+ this.__first_load_started = false; // Latch: true once the first load phase begins (enforces one-shot + throw-after)
3076
+ this.__gate_resume = null; // Resolver to release an in-progress gate wait early (reload/refresh/stop)
2207
3077
  // Detect custom on_load() override immediately
2208
3078
  // Prototype chain is set up before constructor runs, so this.on_load
2209
3079
  // correctly resolves to child class override if one exists
@@ -2245,12 +3115,15 @@ class Jqhtml_Component {
2245
3115
  // Merge in order: defineArgs (defaults from Define tag) < dataAttrs < args (invocation overrides)
2246
3116
  const defineArgs = template_for_args?.defineArgs || {};
2247
3117
  this.args = { ...defineArgs, ...dataAttrs, ...args };
2248
- // Set lifecycle skip flags from args
2249
- if (this.args.skip_render_and_ready === true) {
2250
- this._skip_render_and_ready = true;
3118
+ // Set lifecycle truncation flags from args
3119
+ if (this.args._load_only === true) {
3120
+ this._load_only = true;
3121
+ }
3122
+ if (this.args._load_render_only === true) {
3123
+ this._load_render_only = true;
2251
3124
  }
2252
- if (this.args.skip_ready === true) {
2253
- this._skip_ready = true;
3125
+ if (this.args._force_initial_render === true) {
3126
+ this._force_initial_render = true;
2254
3127
  }
2255
3128
  // Attach component to element
2256
3129
  this.$.data('_component', this);
@@ -2261,68 +3134,8 @@ class Jqhtml_Component {
2261
3134
  // Find DOM parent component (for lifecycle coordination)
2262
3135
  this._find_dom_parent();
2263
3136
  // Setup data property with freeze enforcement using Proxy
2264
- let _data = {};
2265
- // Helper to create frozen proxy for data object
2266
- const createDataProxy = (obj) => {
2267
- return new Proxy(obj, {
2268
- set: (target, prop, value) => {
2269
- if (this.__data_frozen) {
2270
- console.error(`[JQHTML] ERROR: Component "${this.component_name()}" attempted to modify this.data.${String(prop)} outside of on_create() or on_load().\n\n` +
2271
- `RESTRICTION: this.data can ONLY be modified in:\n` +
2272
- ` - on_create() (set initial defaults, synchronous only)\n` +
2273
- ` - on_load() (fetch data from APIs, can be async)\n\n` +
2274
- `WHY: this.data represents loaded state. Modifying it outside these methods bypasses the framework's render cycle.\n\n` +
2275
- `FIX: Modify this.data in on_create() (for defaults) or on_load() (for fetched data):\n` +
2276
- ` ❌ In on_ready(): this.data.${String(prop)} = ${JSON.stringify(value)};\n` +
2277
- ` ✅ In on_create(): this.data.${String(prop)} = ${JSON.stringify(value)}; // Set default\n` +
2278
- ` ✅ In on_load(): this.data.${String(prop)} = ${JSON.stringify(value)}; // Fetch from API\n` +
2279
- ` ✅ For component state: this.args.${String(prop)} = ${JSON.stringify(value)}; (accessible in on_load)`);
2280
- throw new Error(`[JQHTML] Cannot modify this.data.${String(prop)} outside of on_create() or on_load(). ` +
2281
- `this.data is frozen after on_create() and unfrozen only during on_load().`);
2282
- }
2283
- target[prop] = value;
2284
- return true;
2285
- },
2286
- deleteProperty: (target, prop) => {
2287
- if (this.__data_frozen) {
2288
- console.error(`[JQHTML] ERROR: Component "${this.component_name()}" attempted to delete this.data.${String(prop)} outside of on_create() or on_load().\n\n` +
2289
- `RESTRICTION: this.data can ONLY be modified in:\n` +
2290
- ` - on_create() (set initial defaults, synchronous only)\n` +
2291
- ` - on_load() (fetch data from APIs, can be async)\n\n` +
2292
- `WHY: this.data represents loaded state. Modifying it outside these methods bypasses the framework's render cycle.`);
2293
- throw new Error(`[JQHTML] Cannot delete this.data.${String(prop)} outside of on_create() or on_load(). ` +
2294
- `this.data is frozen after on_create() and unfrozen only during on_load().`);
2295
- }
2296
- delete target[prop];
2297
- return true;
2298
- }
2299
- });
2300
- };
2301
- // Create initial proxied data object
2302
- _data = createDataProxy({});
2303
- Object.defineProperty(this, 'data', {
2304
- get: () => _data,
2305
- set: (value) => {
2306
- if (this.__data_frozen) {
2307
- console.error(`[JQHTML] ERROR: Component "${this.component_name()}" attempted to reassign this.data outside of on_create() or on_load().\n\n` +
2308
- `RESTRICTION: this.data can ONLY be modified in:\n` +
2309
- ` - on_create() (set initial defaults, synchronous only)\n` +
2310
- ` - on_load() (fetch data from APIs, can be async)\n\n` +
2311
- `WHY: this.data represents loaded state. Modifying it outside these methods bypasses the framework's render cycle.\n\n` +
2312
- `FIX: Modify this.data in on_create() (for defaults) or on_load() (for fetched data):\n` +
2313
- ` ❌ In on_ready(): this.data = {...};\n` +
2314
- ` ✅ In on_create(): this.data.count = 0; // Set default\n` +
2315
- ` ✅ In on_load(): this.data = await fetch(...); // Fetch from API\n` +
2316
- ` ✅ For component state: this.args.count = 5; (accessible in on_load)`);
2317
- throw new Error(`[JQHTML] Cannot reassign this.data outside of on_create() or on_load(). ` +
2318
- `this.data is frozen after on_create() and unfrozen only during on_load().`);
2319
- }
2320
- // When setting, wrap the new value in a proxy too
2321
- _data = createDataProxy(value);
2322
- },
2323
- enumerable: true,
2324
- configurable: false
2325
- });
3137
+ // @see data-proxy.ts for full implementation
3138
+ setup_data_property(this);
2326
3139
  // Initialize this.state as an empty object (convention for arbitrary component state)
2327
3140
  // No special meaning to framework - mutable anywhere, not cached, not frozen
2328
3141
  this.state = {};
@@ -2424,7 +3237,7 @@ class Jqhtml_Component {
2424
3237
  * @returns The current _render_count after incrementing (used to detect stale renders)
2425
3238
  * @private
2426
3239
  */
2427
- _render(id = null) {
3240
+ _render(id = null, options = {}) {
2428
3241
  // Increment render count to track this specific render
2429
3242
  this._render_count++;
2430
3243
  const current_render_id = this._render_count;
@@ -2445,7 +3258,7 @@ class Jqhtml_Component {
2445
3258
  `Element with $sid="${id}" exists but is not initialized as a component.\n` +
2446
3259
  `Add $redrawable attribute or make it a proper component.`);
2447
3260
  }
2448
- return child._render();
3261
+ return child._render(null, options);
2449
3262
  }
2450
3263
  this._log_lifecycle('render', 'start');
2451
3264
  // HTML CACHE MODE - If we have cached HTML, inject it directly and skip template rendering
@@ -2462,13 +3275,13 @@ class Jqhtml_Component {
2462
3275
  // Mark first render complete
2463
3276
  this._did_first_render = true;
2464
3277
  this._log_lifecycle('render', 'complete (cached HTML)');
2465
- // NEW ARCHITECTURE: Call on_render() even after cache inject
2466
- // This ensures consistent behavior - on_render() always runs after DOM update
2467
- // Note: this.data has defaults from on_create(), not fresh data yet
2468
- const cacheRenderResult = this._call_lifecycle_sync('on_render');
2469
- if (cacheRenderResult && typeof cacheRenderResult.then === 'function') {
2470
- console.warn(`[JQHTML] Component "${this.component_name()}" returned a Promise from on_render(). ` +
2471
- `on_render() must be synchronous code. Remove 'async' from the function declaration.`);
3278
+ // Call on_render() after cache inject (unless suppressed by _load_render_only)
3279
+ if (!options.skip_on_render) {
3280
+ const cacheRenderResult = this._call_lifecycle_sync('on_render');
3281
+ if (cacheRenderResult && typeof cacheRenderResult.then === 'function') {
3282
+ console.warn(`[JQHTML] Component "${this.component_name()}" returned a Promise from on_render(). ` +
3283
+ `on_render() must be synchronous code. Remove 'async' from the function declaration.`);
3284
+ }
2472
3285
  }
2473
3286
  // Emit lifecycle event
2474
3287
  this.trigger('render');
@@ -2653,18 +3466,13 @@ class Jqhtml_Component {
2653
3466
  // Don't update ready state here - let phases complete in order
2654
3467
  this._update_debug_attrs();
2655
3468
  this._log_lifecycle('render', 'complete');
2656
- // Call on_render() with authorization (sync) immediately after render completes
2657
- // This ensures event handlers are always re-attached after DOM updates
2658
- //
2659
- // NEW ARCHITECTURE: on_render() can now access this.data normally
2660
- // The HTML cache mode now properly synchronizes - on_render() runs after both:
2661
- // 1. Cache inject (with on_create() defaults)
2662
- // 2. Second render (with fresh data from on_load())
2663
- // Since on_render() always runs with appropriate data, no proxy restriction needed
2664
- const renderResult = this._call_lifecycle_sync('on_render');
2665
- if (renderResult && typeof renderResult.then === 'function') {
2666
- console.warn(`[JQHTML] Component "${this.component_name()}" returned a Promise from on_render(). ` +
2667
- `on_render() must be synchronous code. Remove 'async' from the function declaration.`);
3469
+ // Call on_render() after render completes (unless suppressed by _load_render_only)
3470
+ if (!options.skip_on_render) {
3471
+ const renderResult = this._call_lifecycle_sync('on_render');
3472
+ if (renderResult && typeof renderResult.then === 'function') {
3473
+ console.warn(`[JQHTML] Component "${this.component_name()}" returned a Promise from on_render(). ` +
3474
+ `on_render() must be synchronous code. Remove 'async' from the function declaration.`);
3475
+ }
2668
3476
  }
2669
3477
  // Emit lifecycle event
2670
3478
  this.trigger('render');
@@ -2694,18 +3502,18 @@ class Jqhtml_Component {
2694
3502
  * Public render method - re-renders component and completes lifecycle
2695
3503
  * This is what users should call when they want to update a component.
2696
3504
  *
2697
- * Lifecycle sequence:
3505
+ * Lifecycle sequence (serialized via component queue):
2698
3506
  * 1. _render() - Updates DOM synchronously, calls on_render(), fires 'render' event
2699
- * 2. Async continuation (fire and forget):
2700
- * - _wait_for_children_ready() - Waits for all children to reach ready state
2701
- * - on_ready() - Calls user's ready hook
2702
- * - trigger('ready') - Fires ready event
3507
+ * 2. _wait_for_children_ready() - Waits for all children to reach ready state
3508
+ * 3. on_ready() - Calls user's ready hook
3509
+ * 4. trigger('ready') - Fires ready event
2703
3510
  *
2704
- * Returns immediately after _render() completes - does NOT wait for children
3511
+ * Goes through the component queue to prevent concurrent lifecycle operations.
3512
+ * Returns a Promise that resolves when the full render lifecycle completes.
2705
3513
  */
2706
3514
  render(id = null) {
2707
3515
  if (this._stopped)
2708
- return;
3516
+ return Promise.resolve();
2709
3517
  // Invalidate ready event so new handlers wait for this render cycle to complete
2710
3518
  // This prevents .on('ready') handlers from firing immediately based on previous lifecycle
2711
3519
  this.invalidate('ready');
@@ -2724,10 +3532,12 @@ class Jqhtml_Component {
2724
3532
  }
2725
3533
  return child.render();
2726
3534
  }
2727
- // Execute render phase synchronously and capture render ID
2728
- const render_id = this._render();
2729
- // Fire off async lifecycle completion in background (don't await)
2730
- (async () => {
3535
+ // Enqueue the full render lifecycle through the component queue
3536
+ // Return the queue promise so `await this.render()` resolves when the
3537
+ // full render lifecycle (DOM update, children ready, on_ready) completes
3538
+ return this._queue.enqueue('render', async () => {
3539
+ // Execute render phase synchronously and capture render ID
3540
+ const render_id = this._render();
2731
3541
  // Wait for all child components to be ready
2732
3542
  await this._wait_for_children_ready();
2733
3543
  // Check if this render is still current before calling on_ready
@@ -2738,8 +3548,8 @@ class Jqhtml_Component {
2738
3548
  // Call on_ready hook with authorization
2739
3549
  await this._call_lifecycle('on_ready');
2740
3550
  // Trigger ready event
2741
- await this.trigger('ready');
2742
- })();
3551
+ this.trigger('ready');
3552
+ });
2743
3553
  }
2744
3554
  /**
2745
3555
  * Alias for render() - re-renders component with current data
@@ -2748,6 +3558,70 @@ class Jqhtml_Component {
2748
3558
  redraw(id = null) {
2749
3559
  return this.render(id);
2750
3560
  }
3561
+ /**
3562
+ * Re-fetch data by executing on_load() without triggering re-render or lifecycle.
3563
+ *
3564
+ * Runs on_load() on a detached proxy (same restrictions as during boot):
3565
+ * - this.data is restored to on_create() snapshot, then unfrozen for writing
3566
+ * - this.args is read-only
3567
+ * - All other properties (this.$, this.$sid, etc.) are blocked
3568
+ *
3569
+ * After on_load() completes, this.data is atomically updated and re-frozen.
3570
+ * The developer decides what to do next (e.g., call this.render()).
3571
+ *
3572
+ * Pattern: load() invokes on_load(), just as render() invokes on_render().
3573
+ *
3574
+ * @returns true if this.data changed, false if unchanged
3575
+ */
3576
+ async load() {
3577
+ if (this._stopped)
3578
+ return false;
3579
+ // Capture result through queue closure
3580
+ let data_changed = false;
3581
+ await this._queue.enqueue('load', async () => {
3582
+ // Snapshot current data for change detection
3583
+ const data_before = JSON.stringify(this.data);
3584
+ // Execute on_load() on detached proxy (restores data to on_create snapshot)
3585
+ const { data: result_data } = await this._execute_on_load_detached(false);
3586
+ // Atomically update this.data: unfreeze → assign → normalize → refreeze
3587
+ this.__data_frozen = false;
3588
+ this.data = result_data;
3589
+ const cache_mode = Jqhtml_Local_Storage.get_cache_mode();
3590
+ if (cache_mode === 'data') {
3591
+ const normalized = Jqhtml_Local_Storage.normalize_for_cache(this.data);
3592
+ this.data = normalized;
3593
+ }
3594
+ this.__data_frozen = true;
3595
+ // Detect if data changed
3596
+ const data_after = JSON.stringify(this.data);
3597
+ data_changed = data_before !== data_after;
3598
+ // Update cache with fresh data if changed
3599
+ if (data_changed) {
3600
+ // Regenerate cache key (args may have changed since boot)
3601
+ let cache_key = null;
3602
+ if (typeof this.cache_id === 'function') {
3603
+ try {
3604
+ cache_key = `${this.component_name()}::${String(this.cache_id())}`;
3605
+ }
3606
+ catch { /* cache_id() threw - skip caching */ }
3607
+ }
3608
+ else {
3609
+ const result = Load_Coordinator.generate_invocation_key(this.component_name(), this.args);
3610
+ cache_key = result.key;
3611
+ }
3612
+ if (cache_key && cache_mode !== 'html') {
3613
+ Jqhtml_Local_Storage.set(cache_key, this.data);
3614
+ }
3615
+ }
3616
+ // Call on_loaded() on the real component (this.data frozen, full access to this.$, this.state)
3617
+ // Suppressed by _load_only and _load_render_only flags (preloading mode)
3618
+ if (!this._load_only && !this._load_render_only) {
3619
+ await this._call_lifecycle('on_loaded');
3620
+ this.trigger('loaded');
3621
+ }
3622
+ });
3623
+ return data_changed;
3624
+ }
2751
3625
  /**
2752
3626
  * Create phase - Quick setup, prepare UI
2753
3627
  * SYNCHRONOUS - no awaits, no yields
@@ -2763,97 +3637,17 @@ class Jqhtml_Component {
2763
3637
  `on_create() must be synchronous code. Remove 'async' from the function declaration.`);
2764
3638
  // Don't await - on_create MUST be sync. The warning is enough.
2765
3639
  }
3640
+ // Detect detached elements — skip cache and initial render for elements not in DOM
3641
+ // _force_initial_render overrides this optimization
3642
+ this._is_detached = !this.$[0].isConnected && !this._force_initial_render;
2766
3643
  // OPTIMIZATION: Skip cache operations and snapshot if no custom on_load()
2767
3644
  // Components without on_load() don't fetch data, so nothing to cache or restore
2768
3645
  if (this.__has_custom_on_load) {
2769
3646
  // CACHE CHECK - Read from cache based on cache mode ('data' or 'html')
2770
- // This happens after on_create() but before render, allowing instant first render
2771
- // Check if component implements cache_id() for custom cache key
2772
- let cache_key = null;
2773
- let uncacheable_property;
2774
- if (typeof this.cache_id === 'function') {
2775
- try {
2776
- const custom_cache_id = this.cache_id();
2777
- cache_key = `${this.component_name()}::${String(custom_cache_id)}`;
2778
- }
2779
- catch (error) {
2780
- // cache_id() threw error - disable caching
2781
- uncacheable_property = 'cache_id()';
2782
- }
2783
- }
2784
- else {
2785
- // Use standard args-based cache key generation
2786
- const result = Load_Coordinator.generate_invocation_key(this.component_name(), this.args);
2787
- cache_key = result.key;
2788
- uncacheable_property = result.uncacheable_property;
2789
- }
2790
- // If cache_key is null, caching disabled
2791
- if (cache_key === null) {
2792
- // Set data-nocache attribute for debugging (shows which property prevented caching)
2793
- if (uncacheable_property) {
2794
- this.$.attr('data-nocache', uncacheable_property);
2795
- }
2796
- if (window.jqhtml?.debug?.verbose) {
2797
- console.log(`[Cache] Component ${this._cid} (${this.component_name()}) has non-serializable args - caching disabled`, { uncacheable_property });
2798
- }
2799
- // Don't return - continue to snapshot this.data for on_load restoration
2800
- }
2801
- else {
2802
- // Store cache key for later use
2803
- this._cache_key = cache_key;
2804
- // Get cache mode
2805
- const cache_mode = Jqhtml_Local_Storage.get_cache_mode();
2806
- if (window.jqhtml?.debug?.verbose) {
2807
- console.log(`[Cache ${cache_mode}] Component ${this._cid} (${this.component_name()}) checking cache in create()`, { cache_key, cache_mode, has_cache_key_set: Jqhtml_Local_Storage.has_cache_key() });
2808
- }
2809
- if (cache_mode === 'html') {
2810
- // HTML cache mode - check for cached HTML to inject on first render
2811
- const html_cache_key = `${cache_key}::html`;
2812
- const cached_html = Jqhtml_Local_Storage.get(html_cache_key);
2813
- if (cached_html !== null && typeof cached_html === 'string') {
2814
- // Store cached HTML for injection in _render()
2815
- this._cached_html = cached_html;
2816
- if (window.jqhtml?.debug?.verbose) {
2817
- console.log(`[Cache html] Component ${this._cid} (${this.component_name()}) found cached HTML`, { cache_key: html_cache_key, html_length: cached_html.length });
2818
- }
2819
- }
2820
- else {
2821
- if (window.jqhtml?.debug?.verbose) {
2822
- console.log(`[Cache html] Component ${this._cid} (${this.component_name()}) cache miss`, { cache_key: html_cache_key });
2823
- }
2824
- }
2825
- // Warn if use_cached_data is set in html cache mode - it has no effect
2826
- if (this.args.use_cached_data === true) {
2827
- console.warn(`[JQHTML] Component "${this.component_name()}" has use_cached_data=true but cache mode is 'html'.\n` +
2828
- `use_cached_data only applies to 'data' cache mode. In 'html' mode, the entire rendered HTML is cached.\n` +
2829
- `The use_cached_data flag will be ignored.`);
2830
- }
2831
- }
2832
- else {
2833
- // Data cache mode (default) - check for cached data to hydrate this.data
2834
- const cached_data = Jqhtml_Local_Storage.get(cache_key);
2835
- if (cached_data !== null && typeof cached_data === 'object') {
2836
- // Hydrate this.data with cached data
2837
- this.data = cached_data;
2838
- // If use_cached_data=true, skip on_load() entirely - use cached data as final data
2839
- if (this.args.use_cached_data === true) {
2840
- this._use_cached_data_hit = true;
2841
- if (window.jqhtml?.debug?.verbose) {
2842
- console.log(`[Cache data] Component ${this._cid} (${this.component_name()}) using cached data (use_cached_data=true, skipping on_load)`, { cache_key, data: cached_data });
2843
- }
2844
- }
2845
- else {
2846
- if (window.jqhtml?.debug?.verbose) {
2847
- console.log(`[Cache data] Component ${this._cid} (${this.component_name()}) hydrated from cache`, { cache_key, data: cached_data });
2848
- }
2849
- }
2850
- }
2851
- else {
2852
- if (window.jqhtml?.debug?.verbose) {
2853
- console.log(`[Cache data] Component ${this._cid} (${this.component_name()}) cache miss`, { cache_key });
2854
- }
2855
- }
2856
- }
3647
+ // Skip cache for detached elements — no point hydrating from cache when not in DOM
3648
+ // @see component-cache.ts for full implementation
3649
+ if (!this._is_detached) {
3650
+ read_cache_in_create(this);
2857
3651
  }
2858
3652
  // Snapshot this.data after on_create() completes
2859
3653
  // This will be restored before each on_load() execution to reset state
@@ -2867,6 +3661,90 @@ class Jqhtml_Component {
2867
3661
  // Emit lifecycle event
2868
3662
  this.trigger('create');
2869
3663
  }
3664
+ /**
3665
+ * Register a "load gate" — a promise that must settle before this component's
3666
+ * FIRST on_load() runs.
3667
+ *
3668
+ * Register gates during on_create(). Multiple calls accumulate; all gates are
3669
+ * awaited together (via Promise.allSettled) at the seam between create and the
3670
+ * first load. A REJECTED gate does NOT block or abort the load — it is an
3671
+ * ordering hint, not a data dependency, so loading proceeds after settlement
3672
+ * (rejections are logged through the debug channel).
3673
+ *
3674
+ * Gates are ONE-SHOT: they delay the first on_load() only. Once that load
3675
+ * begins the gate list is cleared, and reload()/refresh() never re-await gates.
3676
+ * Calling reload()/refresh() while a gate is still holding the first load
3677
+ * releases the wait immediately and resumes the lifecycle (a later gate
3678
+ * settlement then does nothing).
3679
+ *
3680
+ * Gates delay ONLY the on_load phase — never create(), the initial render,
3681
+ * on_render(), or the cached-content first paint (stale-while-revalidate is
3682
+ * preserved). Components with no custom on_load() ignore gates entirely.
3683
+ *
3684
+ * No-op during SSR (the server cannot await arbitrary client promises).
3685
+ *
3686
+ * jqhtml has no knowledge of WHAT is being awaited — the caller supplies the
3687
+ * promise, and policy such as timeouts is the caller's responsibility (bake it
3688
+ * into the promise you pass).
3689
+ *
3690
+ * @param promise The promise to await before the first on_load().
3691
+ * @throws If called after the component's first load has already started.
3692
+ */
3693
+ gate_load(promise) {
3694
+ if (this.__first_load_started) {
3695
+ throw new Error(`[JQHTML] gate_load() may only be called before the component's first load - ` +
3696
+ `register gates in on_create(). ` +
3697
+ `Component: ${this.component_name()} (_cid: ${this._cid})`);
3698
+ }
3699
+ this.__load_gates.push(promise);
3700
+ }
3701
+ /**
3702
+ * Await all registered load gates before the first on_load().
3703
+ *
3704
+ * Called exactly once, at the boot seam immediately before the load phase
3705
+ * (only for components with a custom on_load()). Latches "first load started"
3706
+ * so any later gate_load() throws and reload()/refresh() never re-await.
3707
+ *
3708
+ * Returns a promise to await when there are gates to wait on, or `null` when
3709
+ * there is nothing to wait for (no gates, or SSR). Returning `null` keeps the
3710
+ * common no-gate path free of an extra microtask hop, so it does not shift the
3711
+ * timing of ungated components.
3712
+ *
3713
+ * The returned promise resolves as soon as any of the following happens
3714
+ * (whichever is first — the rest become no-ops):
3715
+ * - all gates settle (Promise.allSettled),
3716
+ * - reload()/refresh() is called while gated (they resolve __gate_resume),
3717
+ * - the component is stopped (stop() resolves __gate_resume).
3718
+ *
3719
+ * @private
3720
+ */
3721
+ _await_load_gates() {
3722
+ // Latch (synchronous): from here on, gate_load() throws and this runs at
3723
+ // most once — set even when there are no gates so point 2 always holds.
3724
+ this.__first_load_started = true;
3725
+ const gates = this.__load_gates;
3726
+ this.__load_gates = [];
3727
+ // Nothing to gate, or SSR (cannot await arbitrary client promises) — proceed now.
3728
+ if (gates.length === 0 || is_capture_enabled())
3729
+ return null;
3730
+ // Promise.allSettled never rejects; rejected gates are logged (debug channel)
3731
+ // whenever they settle, independent of whether the wait was resumed early.
3732
+ const settled = Promise.allSettled(gates);
3733
+ settled.then((results) => {
3734
+ for (const result of results) {
3735
+ if (result.status === 'rejected' && window.jqhtml?.debug?.verbose) {
3736
+ console.log(`[JQHTML gate_load] Component ${this._cid} (${this.component_name()}) gate rejected (ignored, load proceeds)`, result.reason);
3737
+ }
3738
+ }
3739
+ });
3740
+ // Race gate settlement against an early-resume signal (reload/refresh/stop while gated).
3741
+ return new Promise((resolve) => {
3742
+ this.__gate_resume = resolve;
3743
+ settled.then(() => resolve());
3744
+ }).then(() => {
3745
+ this.__gate_resume = null;
3746
+ });
3747
+ }
2870
3748
  /**
2871
3749
  * Load phase - Fetch asynchronous data
2872
3750
  * Called bottom-up, fully parallel
@@ -2889,9 +3767,13 @@ class Jqhtml_Component {
2889
3767
  this._update_debug_attrs();
2890
3768
  this._log_lifecycle('load', 'complete (use_cached_data - skipped on_load)');
2891
3769
  this.trigger('load');
3770
+ if (!this._load_only && !this._load_render_only) {
3771
+ await this._call_lifecycle('on_loaded');
3772
+ this.trigger('loaded');
3773
+ }
2892
3774
  return;
2893
3775
  }
2894
- // Check if component implements cache_id() for custom cache key
3776
+ // Generate cache key (needed for both preload check and load deduplication)
2895
3777
  let cache_key = null;
2896
3778
  let uncacheable_property;
2897
3779
  if (typeof this.cache_id === 'function') {
@@ -2910,6 +3792,19 @@ class Jqhtml_Component {
2910
3792
  cache_key = result.key;
2911
3793
  uncacheable_property = result.uncacheable_property;
2912
3794
  }
3795
+ // SSR preload check: if preloaded data exists for this component+args, use it
3796
+ if (cache_key !== null && has_preload_data()) {
3797
+ const preloaded_data = consume_preload_data(cache_key);
3798
+ if (preloaded_data !== null) {
3799
+ this._cache_key = cache_key;
3800
+ if (window.jqhtml?.debug?.verbose) {
3801
+ console.log(`[SSR Preload] Component ${this._cid} (${this.component_name()}) using preloaded data`, { cache_key });
3802
+ }
3803
+ const data_before_load = JSON.stringify(this.data);
3804
+ await this._apply_load_result(preloaded_data, data_before_load);
3805
+ return;
3806
+ }
3807
+ }
2913
3808
  // Store cache key for later use
2914
3809
  this._cache_key = cache_key;
2915
3810
  // If cache_key is null, args are not serializable - skip load deduplication and caching
@@ -2965,6 +3860,10 @@ class Jqhtml_Component {
2965
3860
  this._update_debug_attrs();
2966
3861
  this._log_lifecycle('load', 'complete (follower)');
2967
3862
  this.trigger('load');
3863
+ if (!this._load_only && !this._load_render_only) {
3864
+ await this._call_lifecycle('on_loaded');
3865
+ this.trigger('loaded');
3866
+ }
2968
3867
  return;
2969
3868
  }
2970
3869
  // This component is a leader - execute on_load() on detached proxy
@@ -2983,143 +3882,11 @@ class Jqhtml_Component {
2983
3882
  }
2984
3883
  /**
2985
3884
  * Execute on_load() on a fully detached proxy.
2986
- *
2987
- * The proxy has:
2988
- * - A CLONE of this.data (from __initial_data_snapshot)
2989
- * - Read-only access to this.args
2990
- * - No access to anything else (this.$, this.sid, etc.)
2991
- *
2992
- * This ensures on_load runs completely isolated from the component instance.
2993
- *
2994
- * @param use_load_coordinator - If true, register with Load_Coordinator for deduplication
2995
- * @returns The resulting data from the proxy after on_load completes
3885
+ * @see data-proxy.ts for full implementation
2996
3886
  * @private
2997
3887
  */
2998
3888
  async _execute_on_load_detached(use_load_coordinator = false) {
2999
- // Clone this.data from the snapshot captured after on_create()
3000
- const data_clone = this.__initial_data_snapshot
3001
- ? JSON.parse(JSON.stringify(this.__initial_data_snapshot))
3002
- : {};
3003
- // Create a read-only proxy for args that blocks all modifications
3004
- // Can't use JSON clone because args may contain functions (_slots, callbacks)
3005
- const create_readonly_proxy = (obj, path = 'this.args') => {
3006
- if (obj === null || typeof obj !== 'object')
3007
- return obj;
3008
- return new Proxy(obj, {
3009
- get(target, prop) {
3010
- const value = target[prop];
3011
- // Recursively wrap nested objects (but not functions)
3012
- if (value !== null && typeof value === 'object' && typeof value !== 'function') {
3013
- return create_readonly_proxy(value, `${path}.${String(prop)}`);
3014
- }
3015
- return value;
3016
- },
3017
- set(target, prop, value) {
3018
- console.error(`[JQHTML] ERROR: Component "${component_name}" attempted to modify ${path}.${String(prop)} during on_load().\n\n` +
3019
- `RESTRICTION: this.args is READ-ONLY during on_load().\n\n` +
3020
- `WHY: this.args configures what data to fetch. Modifying it during on_load() creates circular dependencies.\n\n` +
3021
- `FIX: Modify this.args BEFORE on_load() runs (in on_create() or before calling reload()):\n` +
3022
- ` ❌ Inside on_load(): ${path}.${String(prop)} = ${JSON.stringify(value)};\n` +
3023
- ` ✅ In on_create(): this.args.${String(prop)} = defaultValue;`);
3024
- throw new Error(`[JQHTML] Cannot modify ${path}.${String(prop)} during on_load(). ` +
3025
- `this.args is read-only in on_load().`);
3026
- },
3027
- deleteProperty(target, prop) {
3028
- console.error(`[JQHTML] ERROR: Component "${component_name}" attempted to delete ${path}.${String(prop)} during on_load().\n\n` +
3029
- `RESTRICTION: this.args is READ-ONLY during on_load().`);
3030
- throw new Error(`[JQHTML] Cannot delete ${path}.${String(prop)} during on_load(). ` +
3031
- `this.args is read-only in on_load().`);
3032
- }
3033
- });
3034
- };
3035
- // Create a detached context object that on_load will operate on
3036
- const detached_context = {
3037
- args: create_readonly_proxy(this.args), // Read-only proxy wrapping real args
3038
- data: data_clone // Cloned data - modifications stay isolated
3039
- };
3040
- // Create restricted proxy that operates on the detached context
3041
- const component_name = this.component_name();
3042
- const restricted_this = new Proxy(detached_context, {
3043
- get(target, prop) {
3044
- // Only allow access to args and data
3045
- if (prop === 'args') {
3046
- return target.args;
3047
- }
3048
- if (prop === 'data') {
3049
- return target.data;
3050
- }
3051
- // Block everything else
3052
- console.error(`[JQHTML] ERROR: Component "${component_name}" attempted to access this.${String(prop)} during on_load().\n\n` +
3053
- `RESTRICTION: on_load() may ONLY access:\n` +
3054
- ` - this.args (read-only)\n` +
3055
- ` - this.data (read/write)\n\n` +
3056
- `WHY: on_load() is for data fetching only. All other component functionality should happen in other lifecycle methods.\n\n` +
3057
- `FIX:\n` +
3058
- ` - DOM manipulation → use on_render() or on_ready()\n` +
3059
- ` - Component methods → call them before/after on_load(), not inside it\n` +
3060
- ` - Other properties → restructure code to only use this.args and this.data in on_load()`);
3061
- throw new Error(`[JQHTML] Cannot access this.${String(prop)} during on_load(). ` +
3062
- `on_load() may only access this.args and this.data.`);
3063
- },
3064
- set(target, prop, value) {
3065
- // Only allow setting data
3066
- if (prop === 'data') {
3067
- target.data = value;
3068
- return true;
3069
- }
3070
- // Block setting args
3071
- if (prop === 'args') {
3072
- console.error(`[JQHTML] ERROR: Component "${component_name}" attempted to modify this.args during on_load().\n\n` +
3073
- `RESTRICTION: on_load() may ONLY modify:\n` +
3074
- ` - this.data (read/write)\n\n` +
3075
- `WHY: this.args is component state that on_load() depends on. Modifying it inside on_load() creates circular dependencies.\n\n` +
3076
- `FIX: Modify this.args BEFORE calling on_load() (in on_create() or other lifecycle methods), not inside on_load():\n` +
3077
- ` ❌ Inside on_load(): this.args.filter = 'new_value';\n` +
3078
- ` ✅ In on_create(): this.args.filter = this.args.initial_filter || 'default';`);
3079
- throw new Error(`[JQHTML] Cannot modify this.args during on_load(). ` +
3080
- `Modify this.args in other lifecycle methods, not inside on_load().`);
3081
- }
3082
- // Block setting any other properties
3083
- console.error(`[JQHTML] ERROR: Component "${component_name}" attempted to modify this.${String(prop)} during on_load().\n\n` +
3084
- `RESTRICTION: on_load() may ONLY modify:\n` +
3085
- ` - this.data (read/write)\n\n` +
3086
- `WHY: on_load() is for data fetching only. Setting properties on the component instance should happen in other lifecycle methods.\n\n` +
3087
- `FIX: Store your data in this.data instead:\n` +
3088
- ` ❌ this.${String(prop)} = value;\n` +
3089
- ` ✅ this.data.${String(prop)} = value;`);
3090
- throw new Error(`[JQHTML] Cannot modify this.${String(prop)} during on_load(). ` +
3091
- `Only this.data can be modified in on_load().`);
3092
- }
3093
- });
3094
- // Create promise for this on_load() call
3095
- const on_load_promise = (async () => {
3096
- try {
3097
- await this._call_lifecycle('on_load', restricted_this);
3098
- }
3099
- catch (error) {
3100
- if (use_load_coordinator) {
3101
- // Handle error and notify coordinator
3102
- Load_Coordinator.handle_leader_error(this, error);
3103
- }
3104
- throw error;
3105
- }
3106
- })();
3107
- // If using Load_Coordinator, register as leader
3108
- // Note: We store the completion function but DON'T call it here
3109
- // It will be called by _load() after _apply_load_result() updates this.data
3110
- let complete_coordination = null;
3111
- if (use_load_coordinator) {
3112
- complete_coordination = Load_Coordinator.register_leader(this, on_load_promise);
3113
- }
3114
- await on_load_promise;
3115
- // Note: We don't validate args changes here because external code (like parent
3116
- // components calling reload()) is allowed to modify component.args during on_load().
3117
- // The read-only proxy only prevents code INSIDE on_load() from modifying args.
3118
- // Return the data from the detached context AND the completion function
3119
- return {
3120
- data: detached_context.data,
3121
- complete_coordination
3122
- };
3889
+ return execute_on_load_detached(this, use_load_coordinator);
3123
3890
  }
3124
3891
  /**
3125
3892
  * Apply the result of on_load() to this.data via the sequential queue.
@@ -3157,34 +3924,30 @@ class Jqhtml_Component {
3157
3924
  }
3158
3925
  // Freeze this.data
3159
3926
  this.__data_frozen = true;
3927
+ // SSR data capture: record this component's data for preloading
3928
+ if (is_capture_enabled() && this._has_on_load()) {
3929
+ capture_component_data(this.component_name(), this.args, this.data, this._cache_key);
3930
+ }
3160
3931
  // Calculate if data changed
3161
3932
  const data_after_load = JSON.stringify(this.data);
3162
3933
  const data_changed = data_before_load !== null && data_after_load !== data_before_load;
3163
3934
  // Track if component is "dynamic" (this.data changed during on_load)
3164
3935
  // Used by HTML cache mode for synchronization - static parents don't block children
3165
3936
  this._is_dynamic = data_changed && data_after_load !== '{}';
3166
- // CACHE WRITE - If data changed during on_load(), write to cache based on mode
3167
- if (this._is_dynamic && this._cache_key) {
3168
- if (cache_mode === 'html') {
3169
- // HTML cache mode - flag to cache HTML after children ready in _ready()
3170
- this._should_cache_html_after_ready = true;
3171
- if (window.jqhtml?.debug?.verbose) {
3172
- console.log(`[Cache html] Component ${this._cid} (${this.component_name()}) will cache HTML after ready`, { cache_key: this._cache_key });
3173
- }
3174
- }
3175
- else {
3176
- // Data cache mode (default) - write this.data to cache
3177
- Jqhtml_Local_Storage.set(this._cache_key, this.data);
3178
- if (window.jqhtml?.debug?.verbose) {
3179
- console.log(`[Cache data] Component ${this._cid} (${this.component_name()}) cached data after on_load()`, { cache_key: this._cache_key, data: this.data });
3180
- }
3181
- }
3182
- }
3937
+ // CACHE WRITE - @see component-cache.ts
3938
+ write_cache_on_loaded(this, this._is_dynamic);
3183
3939
  this._ready_state = 2;
3184
3940
  this._update_debug_attrs();
3185
3941
  this._log_lifecycle('load', 'complete');
3186
3942
  // Emit lifecycle event
3187
3943
  this.trigger('load');
3944
+ // Call on_loaded() - runs on the REAL component (not detached proxy)
3945
+ // this.data is frozen (read-only), but this.$, this.state, this.args are accessible
3946
+ // Suppressed by _load_only and _load_render_only flags (preloading mode)
3947
+ if (!this._load_only && !this._load_render_only) {
3948
+ await this._call_lifecycle('on_loaded');
3949
+ this.trigger('loaded');
3950
+ }
3188
3951
  }
3189
3952
  finally {
3190
3953
  // Signal next in queue
@@ -3200,32 +3963,11 @@ class Jqhtml_Component {
3200
3963
  if (this._stopped || this._ready_state >= 4)
3201
3964
  return;
3202
3965
  this._log_lifecycle('ready', 'start');
3203
- // HTML CACHE MODE - New synchronization architecture:
3204
- // 1. Wait for all children to complete on_render (post-on_load)
3205
- // 2. Take HTML snapshot BEFORE waiting for children ready
3206
- // 3. This ensures we capture the DOM after on_render but before on_ready manipulations
3966
+ // HTML CACHE MODE - Wait for children on_render, then snapshot
3967
+ // @see component-cache.ts for write_html_cache_snapshot implementation
3207
3968
  if (this._should_cache_html_after_ready && this._cache_key) {
3208
- // Wait for all children to complete their on_render
3209
3969
  await this._wait_for_children_on_render();
3210
- // Only cache if this component is dynamic (data changed during on_load)
3211
- // Static parents don't cache - they just let children proceed
3212
- if (this._is_dynamic) {
3213
- this._should_cache_html_after_ready = false;
3214
- // Cache the rendered HTML
3215
- const html = this.$.html();
3216
- const html_cache_key = `${this._cache_key}::html`;
3217
- Jqhtml_Local_Storage.set(html_cache_key, html);
3218
- if (window.jqhtml?.debug?.verbose) {
3219
- console.log(`[Cache html] Component ${this._cid} (${this.component_name()}) cached HTML after children on_render complete`, { cache_key: html_cache_key, html_length: html.length });
3220
- }
3221
- }
3222
- else {
3223
- // Static component - just clear the flag, don't cache
3224
- this._should_cache_html_after_ready = false;
3225
- if (window.jqhtml?.debug?.verbose) {
3226
- console.log(`[Cache html] Component ${this._cid} (${this.component_name()}) is static (no data change) - skipping HTML cache`);
3227
- }
3228
- }
3970
+ write_html_cache_snapshot(this);
3229
3971
  }
3230
3972
  // Wait for all children to reach ready state (bottom-up execution)
3231
3973
  await this._wait_for_children_ready();
@@ -3386,6 +4128,17 @@ class Jqhtml_Component {
3386
4128
  * If false, only re-render if data actually changed.
3387
4129
  */
3388
4130
  async reload(always_render) {
4131
+ // Load-gate short-circuit: if a gate is currently holding the first on_load,
4132
+ // reload()/refresh() resumes the paused boot lifecycle instead of running its
4133
+ // normal debounced re-fetch. The boot lifecycle then proceeds to run on_load
4134
+ // (the fresh fetch) exactly as reload() would want. Any later gate settlement
4135
+ // becomes a no-op. Return a promise that resolves when the component is ready.
4136
+ if (this.__gate_resume) {
4137
+ const resume = this.__gate_resume;
4138
+ this.__gate_resume = null;
4139
+ resume();
4140
+ return this.ready();
4141
+ }
3389
4142
  // Default to true if undefined
3390
4143
  const force_refresh = always_render !== undefined ? always_render : true;
3391
4144
  // State machine: reload(true) takes precedence over reload(false)
@@ -3398,11 +4151,9 @@ class Jqhtml_Component {
3398
4151
  this.next_reload_force_refresh = false;
3399
4152
  }
3400
4153
  }
3401
- // Lazy-create debounced _reload function on first use
3402
- if (!this._reload_debounced) {
3403
- this._reload_debounced = this._create_debounced_function(this._reload.bind(this), 0);
3404
- }
3405
- return this._reload_debounced();
4154
+ // Enqueue through component queue (replaces _create_debounced_function)
4155
+ // Same-type pending operations collapse (multiple reload() calls share one execution)
4156
+ return this._queue.enqueue('reload', () => this._reload());
3406
4157
  }
3407
4158
  /**
3408
4159
  * Refresh component - re-fetch data and re-render only if data changed (debounced)
@@ -3484,57 +4235,8 @@ class Jqhtml_Component {
3484
4235
  }
3485
4236
  }
3486
4237
  if (args_changed) {
3487
- // Check if component implements cache_id() for custom cache key
3488
- let cache_key = null;
3489
- if (typeof this.cache_id === 'function') {
3490
- try {
3491
- const custom_cache_id = this.cache_id();
3492
- cache_key = `${this.component_name()}::${String(custom_cache_id)}`;
3493
- }
3494
- catch (error) {
3495
- // cache_id() threw error - disable caching
3496
- cache_key = null;
3497
- }
3498
- }
3499
- else {
3500
- // Use standard args-based cache key generation
3501
- const result = Load_Coordinator.generate_invocation_key(this.component_name(), this.args);
3502
- cache_key = result.key;
3503
- }
3504
- // Check for cached data/html when args changed
3505
- if (cache_key !== null) {
3506
- const cache_mode = Jqhtml_Local_Storage.get_cache_mode();
3507
- this._cache_key = cache_key;
3508
- if (cache_mode === 'html') {
3509
- // HTML cache mode - check for cached HTML
3510
- const html_cache_key = `${cache_key}::html`;
3511
- const cached_html = Jqhtml_Local_Storage.get(html_cache_key);
3512
- if (cached_html !== null && typeof cached_html === 'string') {
3513
- if (window.jqhtml?.debug?.verbose) {
3514
- console.log(`[Cache html] reload() - Component ${this._cid} (${this.component_name()}) found cached HTML (args changed)`, { cache_key: html_cache_key, html_length: cached_html.length });
3515
- }
3516
- // Store cached HTML for injection in _render()
3517
- this._cached_html = cached_html;
3518
- this.render();
3519
- rendered_from_cache = true;
3520
- }
3521
- }
3522
- else {
3523
- // Data cache mode (default) - check for cached data
3524
- const cached_data = Jqhtml_Local_Storage.get(cache_key);
3525
- if (cached_data !== null && typeof cached_data === 'object' && JSON.stringify(cached_data) !== '{}') {
3526
- if (window.jqhtml?.debug?.verbose) {
3527
- console.log(`[Cache data] reload() - Component ${this._cid} (${this.component_name()}) hydrated from cache (args changed)`, { cache_key, data: cached_data });
3528
- }
3529
- // Hydrate this.data with cached data
3530
- this.__data_frozen = false;
3531
- this.data = cached_data;
3532
- this.__data_frozen = true;
3533
- this.render();
3534
- rendered_from_cache = true;
3535
- }
3536
- }
3537
- }
4238
+ // @see component-cache.ts for full implementation
4239
+ rendered_from_cache = check_cache_on_reload(this);
3538
4240
  }
3539
4241
  // Capture data state before on_load for comparison
3540
4242
  data_before_load = JSON.stringify(this.data);
@@ -3608,11 +4310,18 @@ class Jqhtml_Component {
3608
4310
  if (this._stopped)
3609
4311
  return;
3610
4312
  this._stopped = true;
4313
+ // If a load gate is holding the first on_load, release the wait so the boot
4314
+ // lifecycle unwinds cleanly (it will see _stopped and abandon the load).
4315
+ if (this.__gate_resume) {
4316
+ const resume = this.__gate_resume;
4317
+ this.__gate_resume = null;
4318
+ resume();
4319
+ }
3611
4320
  // Early bailout: skip expensive cleanup if no handlers registered
3612
4321
  // Only matters for aborting boot() lifecycle - minimal cleanup sufficient
3613
4322
  const has_custom_stop = this.on_stop !== Jqhtml_Component.prototype.on_stop;
3614
- const has_destroy_callbacks = this._on_registered('destroy');
3615
- if (!has_custom_stop && !has_destroy_callbacks) {
4323
+ const has_stop_callbacks = this._on_registered('stop');
4324
+ if (!has_custom_stop && !has_stop_callbacks) {
3616
4325
  // Fast path: no cleanup logic defined, just mark as stopped
3617
4326
  this._lifecycle_manager.unregister_component(this);
3618
4327
  this._ready_state = 99;
@@ -3660,6 +4369,7 @@ class Jqhtml_Component {
3660
4369
  on_render() { }
3661
4370
  on_create() { }
3662
4371
  on_load() { } // Override to fetch data asynchronously
4372
+ on_loaded() { } // Override to process loaded data (e.g., clone this.data to this.state)
3663
4373
  async on_ready() { }
3664
4374
  on_stop() { }
3665
4375
  /**
@@ -3705,85 +4415,39 @@ class Jqhtml_Component {
3705
4415
  return this.constructor.name;
3706
4416
  }
3707
4417
  /**
3708
- * Register event callback
3709
- * Supports lifecycle events ('render', 'create', 'load', 'ready', 'stop') and custom events
3710
- * Lifecycle event callbacks fire after the lifecycle method completes
3711
- * If a lifecycle event has already occurred, the callback fires immediately AND registers for future occurrences
3712
- * Custom events only fire when explicitly triggered via .trigger()
3713
- *
3714
- * Callback signature: (component, data?) => void
3715
- * - component: The component instance that triggered the event
3716
- * - data: Optional data passed as second parameter to trigger()
4418
+ * Register event callback - delegates to component-events.ts
4419
+ * @see component-events.ts for full documentation
3717
4420
  */
3718
4421
  on(event_name, callback) {
3719
- // Initialize callback array for this event if needed
3720
- if (!this._lifecycle_callbacks.has(event_name)) {
3721
- this._lifecycle_callbacks.set(event_name, []);
3722
- }
3723
- // Add callback to queue
3724
- this._lifecycle_callbacks.get(event_name).push(callback);
3725
- // If this lifecycle event has already occurred, fire the callback immediately
3726
- // with the stored data from when trigger() was called
3727
- if (this._lifecycle_states.has(event_name)) {
3728
- try {
3729
- const stored_data = this._lifecycle_states.get(event_name);
3730
- callback(this, stored_data);
3731
- }
3732
- catch (error) {
3733
- console.error(`[JQHTML] Error in ${event_name} callback:`, error);
3734
- }
3735
- }
3736
- return this;
4422
+ return event_on(this, event_name, callback);
3737
4423
  }
3738
4424
  /**
3739
- * Trigger a lifecycle event - fires all registered callbacks
3740
- * Marks event as occurred so future .on() calls fire immediately
3741
- *
3742
- * @param event_name - Name of the event to trigger
3743
- * @param data - Optional data to pass to callbacks as second parameter
4425
+ * Register a callback that fires exactly once - delegates to component-events.ts
4426
+ * If the event already occurred, fires immediately and does not register.
4427
+ * @see component-events.ts for full documentation
4428
+ */
4429
+ once(event_name, callback) {
4430
+ return event_once(this, event_name, callback);
4431
+ }
4432
+ /**
4433
+ * Trigger a lifecycle event - delegates to component-events.ts
4434
+ * @see component-events.ts for full documentation
3744
4435
  */
3745
4436
  trigger(event_name, data) {
3746
- // Mark this event as occurred and store the data for late subscribers
3747
- this._lifecycle_states.set(event_name, data);
3748
- // Fire all registered callbacks for this event
3749
- const callbacks = this._lifecycle_callbacks.get(event_name);
3750
- if (callbacks) {
3751
- for (const callback of callbacks) {
3752
- try {
3753
- callback.bind(this)(this, data);
3754
- }
3755
- catch (error) {
3756
- console.error(`[JQHTML] Error in ${event_name} callback:`, error);
3757
- }
3758
- }
3759
- }
4437
+ event_trigger(this, event_name, data);
3760
4438
  }
3761
4439
  /**
3762
4440
  * Check if any callbacks are registered for a given event
3763
- * Used to determine if cleanup logic needs to run
3764
4441
  */
3765
4442
  _on_registered(event_name) {
3766
- const callbacks = this._lifecycle_callbacks.get(event_name);
3767
- return !!(callbacks && callbacks.length > 0);
4443
+ return event_on_registered(this, event_name);
3768
4444
  }
3769
4445
  /**
3770
- * Invalidate a lifecycle event - removes the "already occurred" marker
3771
- *
3772
- * This is the opposite of trigger(). After invalidate() is called:
3773
- * - New .on() handlers will NOT fire immediately
3774
- * - The ready() promise will NOT resolve immediately
3775
- * - Handlers wait for the next trigger() call
3776
- *
3777
- * Existing registered callbacks are NOT removed - they'll fire on next trigger().
3778
- *
3779
- * Use case: Call invalidate('ready') at the start of reload() or render()
3780
- * so that any new .on('ready') handlers wait for the reload/render to complete
3781
- * rather than firing immediately based on the previous lifecycle's state.
3782
- *
3783
- * @param event_name - Name of the event to invalidate
4446
+ * Invalidate a lifecycle event - delegates to component-events.ts
4447
+ * @see component-events.ts for full documentation
3784
4448
  */
3785
4449
  invalidate(event_name) {
3786
- this._lifecycle_states.delete(event_name);
4450
+ event_invalidate(this, event_name);
3787
4451
  }
3788
4452
  /**
3789
4453
  * Find element by scoped ID
@@ -4155,84 +4819,6 @@ class Jqhtml_Component {
4155
4819
  window.JQHTML_DEBUG.log(this.component_name(), 'debug', `${action}: ${args.map(a => JSON.stringify(a)).join(', ')}`);
4156
4820
  }
4157
4821
  }
4158
- /**
4159
- * Creates a debounced function with exclusivity and promise fan-in
4160
- *
4161
- * When invoked, immediately runs the callback exclusively.
4162
- * For subsequent invocations, applies a delay before running the callback exclusively again.
4163
- * The delay starts after the current asynchronous operation resolves.
4164
- *
4165
- * If delay is 0, the function only prevents enqueueing multiple executions,
4166
- * but will still run them immediately in an exclusive sequential manner.
4167
- *
4168
- * The most recent invocation's parameters are used when the function executes.
4169
- * Returns a promise that resolves when the next exclusive execution completes.
4170
- *
4171
- * @private
4172
- */
4173
- _create_debounced_function(callback, delay) {
4174
- let running = false;
4175
- let queued = false;
4176
- let last_end_time = 0; // timestamp of last completed run
4177
- let timer = null;
4178
- let next_args = [];
4179
- let resolve_queue = [];
4180
- let reject_queue = [];
4181
- const run_function = async () => {
4182
- const these_resolves = resolve_queue;
4183
- const these_rejects = reject_queue;
4184
- const args = next_args;
4185
- resolve_queue = [];
4186
- reject_queue = [];
4187
- next_args = [];
4188
- queued = false;
4189
- running = true;
4190
- try {
4191
- const result = await callback(...args);
4192
- for (const resolve of these_resolves)
4193
- resolve(result);
4194
- }
4195
- catch (err) {
4196
- for (const reject of these_rejects)
4197
- reject(err);
4198
- }
4199
- finally {
4200
- running = false;
4201
- last_end_time = Date.now();
4202
- if (queued) {
4203
- clearTimeout(timer);
4204
- timer = setTimeout(run_function, Math.max(delay, 0));
4205
- }
4206
- else {
4207
- timer = null;
4208
- }
4209
- }
4210
- };
4211
- return function (...args) {
4212
- next_args = args;
4213
- return new Promise((resolve, reject) => {
4214
- resolve_queue.push(resolve);
4215
- reject_queue.push(reject);
4216
- // Nothing running and nothing scheduled
4217
- if (!running && !timer) {
4218
- const first_call = last_end_time === 0;
4219
- const since = first_call ? Infinity : Date.now() - last_end_time;
4220
- if (since >= delay) {
4221
- run_function();
4222
- }
4223
- else {
4224
- const wait = Math.max(delay - since, 0);
4225
- clearTimeout(timer);
4226
- timer = setTimeout(run_function, wait);
4227
- }
4228
- return;
4229
- }
4230
- // If already running or timer exists, just mark queued
4231
- // The finally{} of run_function handles scheduling after full delay
4232
- queued = true;
4233
- });
4234
- };
4235
- }
4236
4822
  }
4237
4823
  // Static properties
4238
4824
  Jqhtml_Component.__jqhtml_component = true; // Marker for unified register() detection
@@ -4888,6 +5474,61 @@ function init_jquery_plugin(jQuery) {
4888
5474
  const originalEmpty = jQuery.fn.empty;
4889
5475
  const originalHtml = jQuery.fn.html;
4890
5476
  const originalText = jQuery.fn.text;
5477
+ // ---------------------------------------------------------------------------
5478
+ // Guard against hand-creating elements with data-sid via jQuery.
5479
+ //
5480
+ // $sid / data-sid is provisioned ONLY by the jqhtml template renderer, which
5481
+ // ALWAYS emits data-sid paired with a scoped id ("<sid>:<component_cid>").
5482
+ // That scoped id is what binds the element to its component; data-sid on its
5483
+ // own does nothing. So an element whose data-sid is NOT paired with such an id
5484
+ // was hand-written (e.g. .html('<div data-sid="x">')) and the framework never
5485
+ // provisioned it - this.$sid('x') can never find it. We detect exactly that.
5486
+ //
5487
+ // The framework's own rendering injects data-sid via native innerHTML, never
5488
+ // through these jQuery methods, and the one internal jQuery .html() copy
5489
+ // (the .component() tag-mismatch path) carries the provisioned id - so neither
5490
+ // trips this guard.
5491
+ // ---------------------------------------------------------------------------
5492
+ // Return the offending data-sid value if `html` contains a hand-written
5493
+ // data-sid element (data-sid without the scoped "<sid>:<cid>" id), else null.
5494
+ const find_manual_sid = (html) => {
5495
+ if (typeof html !== 'string' || html.indexOf('data-sid') === -1)
5496
+ return null;
5497
+ if (typeof document === 'undefined')
5498
+ return null; // no DOM to parse (SSR)
5499
+ const tpl = document.createElement('template');
5500
+ tpl.innerHTML = html; // native parse - does not route back through jQuery
5501
+ const candidates = tpl.content.querySelectorAll('[data-sid]');
5502
+ for (let i = 0; i < candidates.length; i++) {
5503
+ const el = candidates[i];
5504
+ const sid = el.getAttribute('data-sid') || '';
5505
+ const id = el.getAttribute('id') || '';
5506
+ // Provisioned elements have id="<sid>:<cid>". Anything else is hand-written.
5507
+ if (id.indexOf(sid + ':') !== 0)
5508
+ return sid;
5509
+ }
5510
+ return null;
5511
+ };
5512
+ const assert_no_manual_sid = (value, where) => {
5513
+ const sid = find_manual_sid(value);
5514
+ if (sid === null)
5515
+ return;
5516
+ throw new Error(`[JQHTML] Manually creating an element with data-sid="${sid}" via jQuery (${where}) is not allowed.\n\n` +
5517
+ `data-sid is NOT a normal attribute you can hand-write. It is provisioned by the jqhtml template\n` +
5518
+ `renderer, which scopes the element to its component by pairing data-sid with a unique id\n` +
5519
+ `("${sid}:<component_cid>"). An element you create yourself has no such scoped id, so\n` +
5520
+ `this.$sid('${sid}') / this.sid('${sid}') can never find it - scoping to a component is the entire\n` +
5521
+ `point of data-sid.\n\n` +
5522
+ `CORRECT USAGE:\n` +
5523
+ ` • Put the element in your component template with $sid:\n` +
5524
+ ` <div $sid="${sid}"></div>\n` +
5525
+ ` then access it from the component: this.$sid('${sid}')\n` +
5526
+ ` • Need it created dynamically? Use a child component or a $redrawable element in the template\n` +
5527
+ ` and render() it, instead of injecting raw HTML.\n\n` +
5528
+ `If you only need to select or mark a plain element, use a normal attribute or class instead:\n` +
5529
+ ` • <div data-role="${sid}"> → .find('[data-role="${sid}"]')\n` +
5530
+ ` • <div class="MyComponent__${sid}"> → .find('.MyComponent__${sid}')`);
5531
+ };
4891
5532
  /**
4892
5533
  * Override jQuery.fn.empty() to stop child components before clearing DOM
4893
5534
  * This ensures component cleanup hooks fire when DOM is cleared
@@ -4914,6 +5555,8 @@ function init_jquery_plugin(jQuery) {
4914
5555
  if (arguments.length === 0) {
4915
5556
  return originalHtml.call(this);
4916
5557
  }
5558
+ // Reject hand-written data-sid before mutating the DOM
5559
+ assert_no_manual_sid(value, '.html()');
4917
5560
  // Setter - empty first (which stops components), then set content
4918
5561
  return this.each(function () {
4919
5562
  jQuery(this).empty();
@@ -5016,6 +5659,33 @@ function init_jquery_plugin(jQuery) {
5016
5659
  // Pass through to original .find()
5017
5660
  return originalFind.call(this, selector);
5018
5661
  };
5662
+ // Guard the content-insertion methods that build elements from HTML strings,
5663
+ // plus $() construction. Wrapped once so repeated init() calls don't re-wrap.
5664
+ if (!jQuery.fn.__jqhtml_sid_guarded) {
5665
+ jQuery.fn.__jqhtml_sid_guarded = true;
5666
+ // .append('<div data-sid>'), .prepend, .before, .after, .replaceWith
5667
+ for (const name of ['append', 'prepend', 'before', 'after', 'replaceWith']) {
5668
+ const original = jQuery.fn[name];
5669
+ if (typeof original !== 'function')
5670
+ continue;
5671
+ jQuery.fn[name] = function (...args) {
5672
+ for (const arg of args)
5673
+ assert_no_manual_sid(arg, '.' + name + '()');
5674
+ return original.apply(this, args);
5675
+ };
5676
+ }
5677
+ // $('<div data-sid="x">') - catch the element at construction time. A
5678
+ // selector like $('[data-sid="x"]') parses to no data-sid element, so it is
5679
+ // not flagged here (selector misuse is handled by .find()/.on()).
5680
+ const originalInit = jQuery.fn.init;
5681
+ const PatchedInit = function (selector, context, root) {
5682
+ if (typeof selector === 'string')
5683
+ assert_no_manual_sid(selector, '$()');
5684
+ return new originalInit(selector, context, root);
5685
+ };
5686
+ PatchedInit.prototype = jQuery.fn;
5687
+ jQuery.fn.init = PatchedInit;
5688
+ }
5019
5689
  }
5020
5690
  // Try to auto-initialize if global jQuery exists
5021
5691
  if (typeof window !== 'undefined' && window.jQuery) {
@@ -5043,7 +5713,7 @@ function init(jQuery) {
5043
5713
  }
5044
5714
  }
5045
5715
  // Version - will be replaced during build with actual version from package.json
5046
- const version = '2.3.35';
5716
+ const version = '2.3.50';
5047
5717
  // Default export with all functionality
5048
5718
  const jqhtml = {
5049
5719
  // Core
@@ -5140,7 +5810,13 @@ const jqhtml = {
5140
5810
  // Required for ES6 class instances to be stored and restored from localStorage
5141
5811
  register_cache_class,
5142
5812
  // Boot - hydrate server-rendered component placeholders
5143
- boot
5813
+ boot,
5814
+ // SSR Preload - capture data during SSR, replay on client to skip on_load()
5815
+ start_data_capture,
5816
+ get_captured_data,
5817
+ stop_data_capture,
5818
+ set_preload_data,
5819
+ clear_preload_data
5144
5820
  };
5145
5821
  // Auto-register on window for browser environments
5146
5822
  // This is REQUIRED for compiled templates which use window.jqhtml.register_template()
@@ -5177,12 +5853,14 @@ exports.LifecycleManager = LifecycleManager;
5177
5853
  exports.Load_Coordinator = Load_Coordinator;
5178
5854
  exports.applyDebugDelay = applyDebugDelay;
5179
5855
  exports.boot = boot;
5856
+ exports.clear_preload_data = clear_preload_data;
5180
5857
  exports.create_component = create_component;
5181
5858
  exports.default = jqhtml;
5182
5859
  exports.devWarn = devWarn;
5183
5860
  exports.escape_html = escape_html;
5184
5861
  exports.escape_html_nl2br = escape_html_nl2br;
5185
5862
  exports.extract_slots = extract_slots;
5863
+ exports.get_captured_data = get_captured_data;
5186
5864
  exports.get_component_class = get_component_class;
5187
5865
  exports.get_component_names = get_component_names;
5188
5866
  exports.get_registered_templates = get_registered_templates;
@@ -5204,5 +5882,8 @@ exports.register_cache_class = register_cache_class;
5204
5882
  exports.register_component = register_component;
5205
5883
  exports.register_template = register_template;
5206
5884
  exports.render_template = render_template;
5885
+ exports.set_preload_data = set_preload_data;
5886
+ exports.start_data_capture = start_data_capture;
5887
+ exports.stop_data_capture = stop_data_capture;
5207
5888
  exports.version = version;
5208
5889
  //# sourceMappingURL=index.cjs.map