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