@jqhtml/core 2.3.61 → 2.3.67

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.61
2
+ * JQHTML Core v2.3.67
3
3
  * (c) 2025 JQHTML Team
4
4
  * Released under the MIT License
5
5
  */
@@ -204,6 +204,38 @@ class LifecycleManager {
204
204
  }
205
205
  }
206
206
 
207
+ /**
208
+ * The one rule for "is this name a component?"
209
+ *
210
+ * An optional SINGLE leading underscore, then a capital letter, then letters,
211
+ * digits and underscores. The underscore prefix is a namespace reserved for
212
+ * framework-provided components (`_Root_Layout`) so they cannot collide with
213
+ * application components. Two or more leading underscores are not a component
214
+ * name; a lower-case first letter after the optional underscore is an HTML tag.
215
+ */
216
+ const COMPONENT_NAME_PATTERN = /^_?[A-Z][A-Za-z0-9_]*$/;
217
+ const COMPONENT_NAME_RULE = 'must start with a capital letter, optionally preceded by a single underscore';
218
+ function is_component_name(name) {
219
+ return COMPONENT_NAME_PATTERN.test(name);
220
+ }
221
+ /**
222
+ * The render-time check behind <{expression}>: the expression must evaluate
223
+ * to a component name string that a literal tag would accept - no more, no
224
+ * less. A valid name that names nothing renders the ordinary placeholder
225
+ * component, exactly as an undefined literal tag does.
226
+ */
227
+ function dynamic_component_name(value) {
228
+ if (typeof value !== 'string' || value === '') {
229
+ const shown = value === '' ? 'an empty string' : typeof value === 'string' ? `'${value}'` : `${value === null ? 'null' : typeof value}`;
230
+ throw new Error(`[JQHTML] Dynamic component tag <{...}> evaluated to ${shown}; expected a non-empty component name string`);
231
+ }
232
+ if (!is_component_name(value)) {
233
+ throw new Error(`[JQHTML] Dynamic component tag <{...}> evaluated to '${value}', which is not a valid component name: ` +
234
+ `a component name ${COMPONENT_NAME_RULE}, then letters, digits and underscores`);
235
+ }
236
+ return value;
237
+ }
238
+
207
239
  /**
208
240
  * JQHTML v2 Component Registry
209
241
  *
@@ -250,9 +282,9 @@ function register_component(nameOrClass, component_class, template) {
250
282
  if (!component_class) {
251
283
  throw new Error('Component class is required when registering by name');
252
284
  }
253
- // Validate component name starts with capital letter
254
- if (!/^[A-Z]/.test(name)) {
255
- throw new Error(`Component name '${name}' must start with a capital letter. Convention is First_Letter_With_Underscores.`);
285
+ // Validate component name against the shared rule
286
+ if (!is_component_name(name)) {
287
+ throw new Error(`Component name '${name}' ${COMPONENT_NAME_RULE}. Convention is First_Letter_With_Underscores.`);
256
288
  }
257
289
  component_classes.set(name, component_class);
258
290
  // If template provided, register it
@@ -321,9 +353,9 @@ function register_template(template_def) {
321
353
  if (!name) {
322
354
  throw new Error('Template must have a name property');
323
355
  }
324
- // Validate template name starts with capital letter
325
- if (!/^[A-Z]/.test(name)) {
326
- throw new Error(`Template name '${name}' must start with a capital letter. Convention is First_Letter_With_Underscores.`);
356
+ // Validate template name against the shared rule
357
+ if (!is_component_name(name)) {
358
+ throw new Error(`Template name '${name}' ${COMPONENT_NAME_RULE}. Convention is First_Letter_With_Underscores.`);
327
359
  }
328
360
  // Check for duplicate registration
329
361
  if (component_templates.has(name)) {
@@ -1101,13 +1133,10 @@ async function initialize_component(element, compData) {
1101
1133
  if (slots) {
1102
1134
  options._slots = slots;
1103
1135
  }
1104
- // Always pass _component_name when component name differs from class name
1105
- // This happens when:
1106
- // 1. No class registered for component (uses Jqhtml_Component)
1107
- // 2. Class inherited from parent via extends chain (uses parent class but child template)
1108
- if (ComponentClass.name !== name) {
1109
- options._component_name = name;
1110
- }
1136
+ // Always pass the invocation name: it is what component_name() reports, it
1137
+ // selects the template when the class is inherited via an extends chain or
1138
+ // is the bare Jqhtml_Component, and it is the class the element carries.
1139
+ options._component_name = name;
1111
1140
  // Pass lifecycle truncation flags via options (not DOM attributes, since _ prefix is filtered).
1112
1141
  // Accept both the plain key (cascaded/programmatic) and the '$'-prefixed key (template-authored).
1113
1142
  if (props._load_only === true || props['$_load_only'] === true) {
@@ -1852,7 +1881,7 @@ Load_Coordinator._registry = new Map();
1852
1881
  const class_registry = Object.create(null);
1853
1882
  // Markers for serialized class instances (unique to avoid collisions with user data)
1854
1883
  // Replaced at build time by rollup (see rollup.config.js).
1855
- const CORE_VERSION = '2.3.61';
1884
+ const CORE_VERSION = '2.3.67';
1856
1885
  const CLASS_MARKER = '__jqhtml_class__';
1857
1886
  const PROPS_MARKER = '__jqhtml_props__';
1858
1887
  /**
@@ -3100,511 +3129,910 @@ function write_cache_on_loaded(component, data_changed) {
3100
3129
  }
3101
3130
 
3102
3131
  /**
3103
- * JQHTML Component Lifecycle Queue
3132
+ * JQHTML v2 Template Renderer
3104
3133
  *
3105
- * Serializes lifecycle operations (render, reload, refresh) per component.
3106
- * Replaces _create_debounced_function with a proper queue that:
3134
+ * Connects compiled templates to components
3135
+ * Processes instruction arrays and handles bindings
3136
+ */
3137
+ /**
3138
+ * Process slot-only template inheritance
3107
3139
  *
3108
- * - At most one operation runs at a time per component
3109
- * - At most one operation is pending (waiting for the current to finish)
3110
- * - Same-type pending operations collapse (fan-in: all callers share one execution)
3111
- * - Different-type pending operations: new replaces old (old callers get the new result)
3140
+ * When a component's template returns {_slots: {...}}, walk the prototype
3141
+ * chain to find a parent template and invoke it with the child's slots as content.
3112
3142
  *
3113
- * Boot bypasses this queue entirely - it runs the lifecycle directly.
3143
+ * @param component The component instance
3144
+ * @param childSlots The slots object from the child template
3145
+ * @returns [instructions, context] tuple or null if no parent found
3114
3146
  */
3115
- class Component_Queue {
3116
- constructor() {
3117
- /** Currently executing operation */
3118
- this._current = null;
3119
- /** Next operation waiting to execute after current completes */
3120
- this._pending = null;
3121
- }
3122
- /**
3123
- * Enqueue a lifecycle operation.
3124
- *
3125
- * Behavior:
3126
- * - Nothing running → execute immediately
3127
- * - Something running, no pending → create pending entry
3128
- * - Something running, same type pending → collapse (share pending promise)
3129
- * - Something running, different type pending → replace pending (all callers get new result)
3130
- *
3131
- * @param type - Operation type ('render', 'reload', 'refresh', 'load')
3132
- * @param executor - The async function to execute
3133
- * @returns Promise that resolves when the operation completes
3134
- */
3135
- enqueue(type, executor) {
3136
- // If nothing running, execute immediately
3137
- if (!this._current) {
3138
- return this._execute(type, executor);
3139
- }
3140
- // Something is running — add to pending
3141
- if (this._pending) {
3142
- if (this._pending.type === type) {
3143
- // Same type pending → collapse (fan-in)
3144
- // All callers share the same future execution
3145
- return new Promise((resolve, reject) => {
3146
- this._pending.resolvers.push(resolve);
3147
- this._pending.rejecters.push(reject);
3148
- });
3149
- }
3150
- else {
3151
- // Different type pending → replace
3152
- // Old pending callers join the new operation
3153
- // (their operation was superseded by a different type)
3154
- const old_resolvers = this._pending.resolvers;
3155
- const old_rejecters = this._pending.rejecters;
3156
- return new Promise((resolve, reject) => {
3157
- this._pending = {
3158
- type,
3159
- executor,
3160
- resolvers: [...old_resolvers, resolve],
3161
- rejecters: [...old_rejecters, reject]
3162
- };
3163
- });
3164
- }
3147
+ async function process_slot_inheritance(component, childSlots) {
3148
+ // Walk the prototype chain to find parent class with template
3149
+ let currentClass = Object.getPrototypeOf(component.constructor);
3150
+ console.log(`[JQHTML] Walking prototype chain for ${component.constructor.name}`);
3151
+ while (currentClass && currentClass !== Jqhtml_Component && currentClass.name !== 'Object') {
3152
+ const className = currentClass.name;
3153
+ console.log(`[JQHTML] Checking parent class: ${className}`);
3154
+ // Skip internal framework classes
3155
+ if (className === '_Jqhtml_Component' || className === '_Base_Jqhtml_Component') {
3156
+ currentClass = Object.getPrototypeOf(currentClass);
3157
+ continue;
3165
3158
  }
3166
- // No pending entry yet — create one
3167
- return new Promise((resolve, reject) => {
3168
- this._pending = {
3169
- type,
3170
- executor,
3171
- resolvers: [resolve],
3172
- rejecters: [reject]
3173
- };
3174
- });
3175
- }
3176
- /**
3177
- * Execute an operation and handle pending queue after completion.
3178
- * @private
3179
- */
3180
- _execute(type, executor) {
3181
- const promise = (async () => {
3182
- try {
3183
- await executor();
3184
- }
3185
- finally {
3186
- this._current = null;
3187
- // Run pending if exists
3188
- if (this._pending) {
3189
- const pending = this._pending;
3190
- this._pending = null;
3191
- try {
3192
- await this._execute(pending.type, pending.executor);
3193
- for (const resolve of pending.resolvers)
3194
- resolve();
3195
- }
3196
- catch (err) {
3197
- for (const reject of pending.rejecters)
3198
- reject(err);
3199
- }
3159
+ // Try to find template for this parent class
3160
+ try {
3161
+ const parentTemplate = get_template(className);
3162
+ console.log(`[JQHTML] Template found for ${className}:`, parentTemplate ? parentTemplate.name : 'null');
3163
+ // Check if we got the default template (means no real template found)
3164
+ if (parentTemplate && parentTemplate.name !== 'Jqhtml_Component') {
3165
+ console.log(`[JQHTML] Invoking parent template ${className}`);
3166
+ // Found a real parent template - invoke it with child's slots as content
3167
+ const [parentInstructions, parentContext] = parentTemplate.render.call(component, component.data, component.args, childSlots // Pass child slots as content parameter
3168
+ );
3169
+ // Check if parent also returns slots (recursive inheritance)
3170
+ if (parentInstructions && typeof parentInstructions === 'object' && parentInstructions._slots) {
3171
+ // Parent also has slot-only template - recurse
3172
+ console.log(`[JQHTML] Parent also slot-only, recursing`);
3173
+ return await process_slot_inheritance(component, parentInstructions._slots);
3200
3174
  }
3175
+ // Parent returned HTML - we're done
3176
+ console.log(`[JQHTML] Parent returned instructions, inheritance complete`);
3177
+ return [parentInstructions, parentContext];
3201
3178
  }
3202
- })();
3203
- this._current = { type, promise };
3204
- return promise;
3205
- }
3206
- /**
3207
- * Check if any operation is currently running.
3208
- */
3209
- get is_busy() {
3210
- return this._current !== null;
3211
- }
3212
- /**
3213
- * Check if there's a pending operation waiting.
3214
- */
3215
- get has_pending() {
3216
- return this._pending !== null;
3179
+ }
3180
+ catch (error) {
3181
+ console.warn(`[JQHTML] Error looking up parent template for ${className}:`, error);
3182
+ }
3183
+ // Move to next parent
3184
+ currentClass = Object.getPrototypeOf(currentClass);
3217
3185
  }
3218
- }
3219
-
3220
- /**
3221
- * JQHTML SSR Preload Data System
3222
- *
3223
- * Captures component data during SSR rendering and replays it on the client
3224
- * to skip redundant on_load() calls during hydration.
3225
- *
3226
- * Server-side: start_data_capture() → render → get_captured_data()
3227
- * Client-side: set_preload_data(entries) → components boot with preloaded data → clear_preload_data()
3228
- */
3229
- // --- Capture (Server Side) ---
3230
- let _capture_enabled = false;
3231
- let _capture_buffer = [];
3232
- // Track captured keys to avoid duplicates from Load Coordinator followers
3233
- let _captured_keys = new Set();
3234
- /**
3235
- * Enable data capture mode. After this call, every component that completes
3236
- * on_load() has its final this.data recorded.
3237
- *
3238
- * Idempotent — calling twice is fine.
3239
- */
3240
- function start_data_capture() {
3241
- _capture_enabled = true;
3242
- _capture_buffer = [];
3243
- _captured_keys.clear();
3186
+ // No parent template found
3187
+ console.warn(`[JQHTML] No parent template found after walking chain`);
3188
+ return null;
3244
3189
  }
3245
3190
  /**
3246
- * Record a component's data after on_load() completes.
3247
- * Called internally from _apply_load_result().
3248
- *
3249
- * @param component_name - Component name
3250
- * @param args - Component args at time of on_load()
3251
- * @param data - this.data after on_load() completed
3252
- * @param cache_key - The cache key for deduplication (null = always capture)
3191
+ * Render a template for a component
3192
+ * Templates are functions that return [instructions, context] tuples
3253
3193
  */
3254
- function capture_component_data(component_name, args, data, cache_key) {
3255
- if (!_capture_enabled)
3256
- return;
3257
- // Deduplicate: if Load Coordinator already captured this key, skip
3258
- if (cache_key !== null) {
3259
- if (_captured_keys.has(cache_key))
3260
- return;
3261
- _captured_keys.add(cache_key);
3194
+ async function render_template(component, template_fn) {
3195
+ // Get template from registry if not provided
3196
+ let render_fn = template_fn;
3197
+ if (!render_fn) {
3198
+ const template_def = get_template_by_class(component.constructor);
3199
+ render_fn = template_def.render;
3262
3200
  }
3263
- // Deep clone args and data to plain objects (no proxies, no class instances)
3264
- try {
3265
- const cloned_args = JSON.parse(JSON.stringify(args));
3266
- const cloned_data = JSON.parse(JSON.stringify(data));
3267
- _capture_buffer.push({
3268
- component: component_name,
3269
- args: cloned_args,
3270
- data: cloned_data,
3271
- });
3201
+ if (!render_fn) {
3202
+ // No template, component should handle its own rendering
3203
+ return;
3272
3204
  }
3273
- catch (error) {
3274
- // Non-serializable data — skip capture for this component
3275
- if (typeof console !== 'undefined') {
3276
- console.warn(`[JQHTML SSR Capture] Failed to serialize data for ${component_name}:`, error);
3205
+ // Clear existing content
3206
+ component.$.empty();
3207
+ // Execute template function
3208
+ // Templates receive: (data, args, content)
3209
+ // Provide a default empty content function if none provided
3210
+ const defaultContent = () => '';
3211
+ let [instructions, context] = render_fn.call(component, component.data, component.args, defaultContent // Default content function that returns empty string
3212
+ );
3213
+ // Check for slot-only template inheritance
3214
+ // If instructions is {_slots: {...}}, this is a slot-only template
3215
+ // We need to find the parent template and invoke it with these slots
3216
+ if (instructions && typeof instructions === 'object' && instructions._slots) {
3217
+ console.log(`[JQHTML] Slot-only template detected for ${component.constructor.name}, invoking inheritance`);
3218
+ const result = await process_slot_inheritance(component, instructions._slots);
3219
+ if (result) {
3220
+ console.log(`[JQHTML] Parent template found, using parent instructions`);
3221
+ instructions = result[0];
3222
+ context = result[1];
3223
+ }
3224
+ else {
3225
+ console.warn(`[JQHTML] No parent template found for ${component.constructor.name}, rendering empty`);
3226
+ // No parent template found - return empty
3227
+ instructions = [];
3277
3228
  }
3278
3229
  }
3230
+ // Process instructions to generate DOM
3231
+ await process_instructions(instructions, component.$, component);
3232
+ // Process bindings after DOM is created
3233
+ await process_bindings(component);
3234
+ // Attach event handlers
3235
+ await attach_event_handlers(component);
3279
3236
  }
3280
3237
  /**
3281
- * Returns all captured component data and resets the capture buffer.
3282
- * One-shot: calling clears the buffer.
3283
- */
3284
- function get_captured_data() {
3285
- const result = _capture_buffer;
3286
- _capture_buffer = [];
3287
- _captured_keys.clear();
3288
- return result;
3289
- }
3290
- /**
3291
- * Check if data capture is currently enabled.
3238
+ * Process data bindings (attributes created by :prop syntax)
3292
3239
  */
3293
- function is_capture_enabled() {
3294
- return _capture_enabled;
3240
+ async function process_bindings(component) {
3241
+ // Find all elements with data-bind-* attributes
3242
+ component.$.find('[data-bind-prop], [data-bind-value], [data-bind-text], [data-bind-html], [data-bind-class], [data-bind-style]').each((_, element) => {
3243
+ const el = $(element);
3244
+ const attrs = element.attributes;
3245
+ for (let i = 0; i < attrs.length; i++) {
3246
+ const attr = attrs[i];
3247
+ if (attr.name.startsWith('data-bind-')) {
3248
+ const binding_type = attr.name.substring(10); // Remove 'data-bind-'
3249
+ const expression = attr.value;
3250
+ try {
3251
+ // Evaluate expression in component context
3252
+ const value = evaluate_expression(expression, component);
3253
+ // Apply binding based on type
3254
+ switch (binding_type) {
3255
+ case 'prop':
3256
+ // Generic property binding
3257
+ const prop_name = el.attr('data-bind-prop-name') || 'value';
3258
+ el.prop(prop_name, value);
3259
+ break;
3260
+ case 'value':
3261
+ el.val(value);
3262
+ break;
3263
+ case 'text':
3264
+ el.text(value);
3265
+ break;
3266
+ case 'html':
3267
+ el.html(value);
3268
+ break;
3269
+ case 'class':
3270
+ if (typeof value === 'object') {
3271
+ // Object syntax: {active: true, disabled: false}
3272
+ Object.entries(value).forEach(([className, enabled]) => {
3273
+ el.toggleClass(className, !!enabled);
3274
+ });
3275
+ }
3276
+ else {
3277
+ // String syntax
3278
+ el.addClass(String(value));
3279
+ }
3280
+ break;
3281
+ case 'style':
3282
+ if (typeof value === 'object') {
3283
+ el.css(value);
3284
+ }
3285
+ else {
3286
+ el.attr('style', String(value));
3287
+ }
3288
+ break;
3289
+ default:
3290
+ // Custom binding - set as attribute
3291
+ el.attr(binding_type, value);
3292
+ }
3293
+ }
3294
+ catch (error) {
3295
+ console.error(`Error evaluating binding "${expression}":`, error);
3296
+ }
3297
+ }
3298
+ }
3299
+ });
3295
3300
  }
3296
3301
  /**
3297
- * Stop data capture and clear all state.
3302
+ * Attach event handlers (attributes created by @event syntax)
3298
3303
  */
3299
- function stop_data_capture() {
3300
- _capture_enabled = false;
3301
- _capture_buffer = [];
3302
- _captured_keys.clear();
3304
+ async function attach_event_handlers(component) {
3305
+ // Find all elements with data-on-* attributes
3306
+ component.$.find('[data-on-click], [data-on-change], [data-on-submit], [data-on-keyup], [data-on-keydown], [data-on-focus], [data-on-blur]').each((_, element) => {
3307
+ const el = $(element);
3308
+ const attrs = element.attributes;
3309
+ for (let i = 0; i < attrs.length; i++) {
3310
+ const attr = attrs[i];
3311
+ if (attr.name.startsWith('data-on-')) {
3312
+ const event_name = attr.name.substring(8); // Remove 'data-on-'
3313
+ const handler_expr = attr.value;
3314
+ // Remove the attribute to avoid re-processing
3315
+ el.removeAttr(attr.name);
3316
+ // Attach event handler
3317
+ el.on(event_name, function (event) {
3318
+ try {
3319
+ // Create handler function in component context
3320
+ const handler = evaluate_handler(handler_expr, component);
3321
+ if (typeof handler === 'function') {
3322
+ // Call with component as 'this' and pass event
3323
+ handler.call(component, event);
3324
+ }
3325
+ else {
3326
+ // Expression to execute
3327
+ evaluate_expression(handler_expr, component, { $event: event });
3328
+ }
3329
+ }
3330
+ catch (error) {
3331
+ console.error(`Error in ${event_name} handler "${handler_expr}":`, error);
3332
+ }
3333
+ });
3334
+ }
3335
+ }
3336
+ });
3303
3337
  }
3304
- // --- Preload (Client Side) ---
3305
- let _preload_cache = new Map();
3306
3338
  /**
3307
- * Seed the preload cache with SSR-captured data.
3308
- * Must be called before any component _load() runs.
3309
- *
3310
- * @param entries - Array of { component, args, data } entries from get_captured_data()
3339
+ * Evaluate an expression in component context
3311
3340
  */
3312
- function set_preload_data(entries) {
3313
- if (!entries || entries.length === 0)
3314
- return;
3315
- _preload_cache.clear();
3316
- for (const entry of entries) {
3317
- // Generate key using the same algorithm as Load Coordinator
3318
- const result = Load_Coordinator.generate_invocation_key(entry.component, entry.args);
3319
- if (result.key !== null) {
3320
- _preload_cache.set(result.key, entry.data);
3321
- }
3341
+ function evaluate_expression(expression, component, locals = {}) {
3342
+ // Create evaluation context
3343
+ const context = {
3344
+ // Component properties
3345
+ data: component.data,
3346
+ args: component.args,
3347
+ $: component.$,
3348
+ // Component methods
3349
+ $sid: component.$sid.bind(component),
3350
+ // Locals (like $event)
3351
+ ...locals
3352
+ };
3353
+ // Build function that evaluates in context
3354
+ const keys = Object.keys(context);
3355
+ const values = Object.values(context);
3356
+ try {
3357
+ // Use Function constructor for better performance than eval
3358
+ const fn = new Function(...keys, `return (${expression})`);
3359
+ return fn(...values);
3360
+ }
3361
+ catch (error) {
3362
+ console.error(`Invalid expression: ${expression}`, error);
3363
+ return undefined;
3322
3364
  }
3323
3365
  }
3324
3366
  /**
3325
- * Check if preloaded data exists for a given cache key.
3326
- * If found, returns the data and removes the entry (one-shot).
3327
- *
3328
- * @param cache_key - The cache key (same format as Load Coordinator)
3329
- * @returns The preloaded data, or null if no match
3367
+ * Evaluate a handler expression (might be method name or inline code)
3330
3368
  */
3331
- function consume_preload_data(cache_key) {
3332
- if (_preload_cache.size === 0)
3369
+ function evaluate_handler(expression, component) {
3370
+ // Check if it's a method name on the component
3371
+ if (expression in component && typeof component[expression] === 'function') {
3372
+ return component[expression];
3373
+ }
3374
+ // Otherwise treat as inline code
3375
+ try {
3376
+ return new Function('$event', `
3377
+ const { data, args, $, emit, $sid } = this;
3378
+ ${expression}
3379
+ `).bind(component);
3380
+ }
3381
+ catch (error) {
3382
+ console.error(`Invalid handler: ${expression}`, error);
3333
3383
  return null;
3334
- const data = _preload_cache.get(cache_key);
3335
- if (data !== undefined) {
3336
- _preload_cache.delete(cache_key);
3337
- return data;
3338
3384
  }
3339
- return null;
3340
3385
  }
3341
3386
  /**
3342
- * Clear any remaining unconsumed preload entries.
3343
- * Call after initial page hydration is complete.
3387
+ * Helper to escape HTML for safe output
3344
3388
  */
3345
- function clear_preload_data() {
3346
- _preload_cache.clear();
3389
+ function escape_html(str) {
3390
+ const div = document.createElement('div');
3391
+ div.textContent = str;
3392
+ return div.innerHTML;
3347
3393
  }
3348
3394
  /**
3349
- * Check if any preload data is available (for fast early exit in _load).
3395
+ * Helper to escape HTML and convert newlines to <br /> tags
3396
+ * Used by <%br= %> syntax for displaying user-entered text with line breaks
3350
3397
  */
3351
- function has_preload_data() {
3352
- return _preload_cache.size > 0;
3398
+ function escape_html_nl2br(str) {
3399
+ const div = document.createElement('div');
3400
+ div.textContent = str;
3401
+ // Escape HTML first, then replace newlines with <br />
3402
+ return div.innerHTML.replace(/\n/g, '<br />');
3353
3403
  }
3354
3404
 
3355
3405
  /**
3356
- * JQHTML Viewport Resize Dispatch
3406
+ * Value printers: how <%= %> renders an OBJECT.
3357
3407
  *
3358
- * One framework-owned, debounced window 'resize' listener fans out to every live
3359
- * component in the document by calling on_viewport_resize(viewport_width).
3408
+ * Primitives never come here - the generated template code routes only
3409
+ * non-null, non-array objects to print_object(), so a hundred-row list of
3410
+ * strings costs exactly what it did before. An object reaching an
3411
+ * interpolation is walked through the printer chain in registration order;
3412
+ * the first printer to return anything but undefined handles it. A printer
3413
+ * returns a string (escaped or not according to the construct, exactly as a
3414
+ * string literal at that site) or a component descriptor:
3360
3415
  *
3361
- * Components never bind their own window listener, so there is nothing to unbind
3362
- * in on_stop() - a component that is stopped or removed from the document simply
3363
- * stops being found by the dispatcher.
3364
- */
3365
- /** Trailing-edge debounce applied to the window resize listener. */
3366
- const VIEWPORT_RESIZE_DEBOUNCE_MS = 30;
3367
- let debounce_timer = null;
3368
- let listener_installed = false;
3369
- /**
3370
- * Current viewport width in CSS pixels.
3416
+ * { component: { name: 'Rich_Text_Display', args: { value }, attrs: { class: 'x' } } }
3371
3417
  *
3372
- * window.innerWidth is used (not $(window).width()) because it matches the width
3373
- * CSS media queries resolve against. It includes the scrollbar gutter.
3418
+ * which jqhtml mounts as if the template had written the tag - live in the
3419
+ * browser, server-rendered under SSR - with no environment awareness on the
3420
+ * printer's side. A descriptor carries no content.
3374
3421
  *
3375
- * Returns 0 outside a browser (SSR).
3422
+ * Attribute position (<div title="<%= v %>">) compiles through a different
3423
+ * path and never consults printers.
3376
3424
  */
3377
- function get_viewport_width() {
3378
- return typeof window !== 'undefined' ? window.innerWidth : 0;
3379
- }
3425
+ const printers = [];
3380
3426
  /**
3381
- * Call on_viewport_resize(width) on every component currently in the document.
3382
- *
3383
- * Walks $('.Component') in document order (parents before children). Elements
3384
- * with no component instance and stopped components are skipped. A component
3385
- * that throws is logged and the walk continues - one bad handler must not stop
3386
- * the rest of the page from resizing.
3427
+ * Register a printer at the end of the chain. Printers run in registration
3428
+ * order; return undefined to decline, a string, or a component descriptor.
3387
3429
  */
3388
- function dispatch_viewport_resize(jQuery) {
3389
- const viewport_width = get_viewport_width();
3390
- jQuery('.Component').each(function () {
3391
- const component = jQuery(this).data('_component');
3392
- if (!component || component._stopped)
3393
- return;
3394
- if (typeof component.on_viewport_resize !== 'function')
3395
- return;
3396
- try {
3397
- component.on_viewport_resize(viewport_width);
3398
- }
3399
- catch (error) {
3400
- console.error(`[JQHTML] Error in on_viewport_resize() for ${component.component_name?.() || 'component'}:`, error);
3401
- }
3402
- });
3430
+ function add_object_printer(printer) {
3431
+ if (typeof printer !== 'function') {
3432
+ throw new Error('[JQHTML] add_object_printer() expects a function (value) => undefined | string | descriptor');
3433
+ }
3434
+ printers.push(printer);
3435
+ }
3436
+ /** The registered printers, in order. Read-only view for diagnostics. */
3437
+ function get_object_printers() {
3438
+ return printers;
3403
3439
  }
3404
3440
  /**
3405
- * Install the single window resize listener. Idempotent - repeated init() calls
3406
- * and non-browser environments are no-ops.
3441
+ * Render an object at an interpolation site. Called by compiled templates for
3442
+ * every non-null, non-array object reaching <%= %>, <%!= %> or <%br= %>.
3443
+ * Throws when nothing handles the value or a printer returns garbage.
3407
3444
  */
3408
- function init_viewport_resize(jQuery) {
3409
- if (typeof window === 'undefined')
3410
- return;
3411
- if (listener_installed)
3412
- return;
3413
- listener_installed = true;
3414
- jQuery(window).on('resize.jqhtml_viewport', function () {
3415
- if (debounce_timer !== null)
3416
- clearTimeout(debounce_timer);
3417
- debounce_timer = setTimeout(function () {
3418
- debounce_timer = null;
3419
- dispatch_viewport_resize(jQuery);
3420
- }, VIEWPORT_RESIZE_DEBOUNCE_MS);
3421
- });
3445
+ function print_object(value, mode) {
3446
+ if (value === null || typeof value !== 'object') {
3447
+ throw new TypeError(`[JQHTML] print_object() is the object branch of interpolation; got ${typeof value}`);
3448
+ }
3449
+ for (let i = 0; i < printers.length; i++) {
3450
+ const result = printers[i](value);
3451
+ if (result === undefined)
3452
+ continue;
3453
+ if (typeof result === 'string')
3454
+ return print_string(result, mode);
3455
+ if (is_descriptor(result))
3456
+ return descriptor_to_instruction(result, i);
3457
+ throw new Error(`[JQHTML] Object printer #${i + 1} of ${printers.length} returned ${describe(result)}; ` +
3458
+ `a printer must return undefined (decline), a string, or a { component: { name, args, attrs } } descriptor`);
3459
+ }
3460
+ throw new Error(`[JQHTML] Cannot interpolate a ${constructor_name(value)} object: ` +
3461
+ (printers.length
3462
+ ? `none of the ${printers.length} registered object printer(s) handled it. `
3463
+ : `no object printers are registered. `) +
3464
+ `Register one with jqhtml.add_object_printer(fn), or interpolate a primitive.`);
3465
+ }
3466
+ function print_string(text, mode) {
3467
+ if (mode === 'escape')
3468
+ return escape_html(text);
3469
+ if (mode === 'nl2br')
3470
+ return escape_html_nl2br(text);
3471
+ return text;
3472
+ }
3473
+ function is_descriptor(value) {
3474
+ return !!value && typeof value === 'object' && !Array.isArray(value) &&
3475
+ !!value.component && typeof value.component === 'object' && !Array.isArray(value.component);
3476
+ }
3477
+ function descriptor_to_instruction(descriptor, index) {
3478
+ const { name, args, attrs } = descriptor.component;
3479
+ const where = `Object printer #${index + 1}`;
3480
+ if (typeof name !== 'string' || !is_component_name(name)) {
3481
+ throw new Error(`[JQHTML] ${where} returned a descriptor whose component name ${describe(name)} is invalid: ` +
3482
+ `a component name ${COMPONENT_NAME_RULE}, then letters, digits and underscores`);
3483
+ }
3484
+ const props = {};
3485
+ if (attrs !== undefined) {
3486
+ if (!is_plain_object(attrs))
3487
+ throw new Error(`[JQHTML] ${where}: descriptor attrs must be a plain object`);
3488
+ for (const [key, value] of Object.entries(attrs)) {
3489
+ if (key.startsWith('$'))
3490
+ throw new Error(`[JQHTML] ${where}: descriptor attrs key '${key}' - component arguments go in args, without the $ sigil`);
3491
+ props[key] = value;
3492
+ }
3493
+ }
3494
+ if (args !== undefined) {
3495
+ if (!is_plain_object(args))
3496
+ throw new Error(`[JQHTML] ${where}: descriptor args must be a plain object`);
3497
+ for (const [key, value] of Object.entries(args)) {
3498
+ if (key.startsWith('$'))
3499
+ throw new Error(`[JQHTML] ${where}: descriptor args key '${key}' - the $ sigil is template syntax, not part of the argument name`);
3500
+ props[`$${key}`] = value;
3501
+ }
3502
+ }
3503
+ return { comp: [name, props] };
3504
+ }
3505
+ function is_plain_object(value) {
3506
+ return !!value && typeof value === 'object' && !Array.isArray(value);
3507
+ }
3508
+ function constructor_name(value) {
3509
+ const ctor = value.constructor;
3510
+ return ctor && ctor.name ? ctor.name : 'Object';
3511
+ }
3512
+ function describe(value) {
3513
+ if (value === null)
3514
+ return 'null';
3515
+ if (typeof value === 'string')
3516
+ return `'${value}'`;
3517
+ if (typeof value === 'object')
3518
+ return Array.isArray(value) ? 'an array' : `a ${constructor_name(value)} object without a valid component property`;
3519
+ return `${typeof value} ${String(value)}`;
3422
3520
  }
3423
3521
 
3424
3522
  /**
3425
- * JQHTML v2 Component Base Class
3523
+ * JQHTML Component Lifecycle Queue
3426
3524
  *
3427
- * Core component implementation following v2 specification:
3428
- * - 5-stage lifecycle coordinated by LifecycleManager
3429
- * - Direct jQuery manipulation (no virtual DOM)
3430
- * - Scoped IDs using _cid pattern
3431
- * - Event emission and CSS class hierarchy
3525
+ * Serializes lifecycle operations (render, reload, refresh) per component.
3526
+ * Replaces _create_debounced_function with a proper queue that:
3527
+ *
3528
+ * - At most one operation runs at a time per component
3529
+ * - At most one operation is pending (waiting for the current to finish)
3530
+ * - Same-type pending operations collapse (fan-in: all callers share one execution)
3531
+ * - Different-type pending operations: new replaces old (old callers get the new result)
3532
+ *
3533
+ * Boot bypasses this queue entirely - it runs the lifecycle directly.
3432
3534
  */
3433
- // WeakMap storage for protected lifecycle method implementations (Option 2)
3434
- // See docs/internal/lifecycle-method-protection.md for design details
3435
- const lifecycle_impls = new WeakMap();
3436
- class Jqhtml_Component {
3437
- constructor(element, args = {}) {
3438
- this._ready_state = 0; // 0=created, 1=init, 2=loaded, 3=rendered, 4=ready
3439
- this._instantiator = null; // Component that instantiated this one
3440
- this._dom_parent = null; // Closest component in DOM tree (for lifecycle)
3441
- this._dom_children = new Set(); // Components in DOM subtree (for lifecycle)
3442
- this._use_dom_fallback = false; // If true, use find() fallback instead of _dom_children optimization
3443
- this._stopped = false;
3444
- this._booted = false; // Guard to prevent double boot() calls
3445
- this._data_before_render = null; // Store data state before initial render
3446
- this._lifecycle_callbacks = new Map();
3447
- this._lifecycle_states = new Map(); // Track which lifecycle events have occurred and their data
3448
- this._did_first_render = false; // Track if component has rendered at least once
3449
- this._render_count = 0; // Incremented each time _render() is called, used to detect stale renders
3450
- this._args_on_last_render = null; // Args snapshot from last render (for reload() comparison)
3451
- this._data_on_last_render = null; // Data snapshot from last render (for refresh() comparison)
3452
- this.__initial_data_snapshot = null; // Snapshot of this.data after on_create() for restoration before on_load()
3453
- this.__data_frozen = false; // Track if this.data is currently frozen
3454
- this._queue = new Component_Queue(); // Lifecycle operation queue (render/reload/refresh)
3455
- this.next_reload_force_refresh = null; // State machine for reload()/refresh() debounce precedence
3456
- this.__lifecycle_authorized = false; // Flag for lifecycle method protection
3457
- // Cache mode properties
3458
- this._cache_key = null; // Cache key for caching
3459
- // 'html' mode caching
3460
- this._cached_html = null; // Cached HTML to inject on first render
3461
- this._used_cached_html = false; // Flag if cached HTML was used (forces re-render after on_load)
3462
- this._should_cache_html_after_ready = false; // Flag to cache HTML after on_ready lifecycle
3463
- this._is_dynamic = false; // True if this.data changed during on_load() (used for HTML cache sync)
3464
- // on_render synchronization (HTML cache mode)
3465
- this._on_render_complete = false; // True after on_render() has been called post-on_load
3466
- // use_cached_data feature - skip on_load() when cache hit occurs
3467
- this._use_cached_data_hit = false; // True if use_cached_data=true AND cache was used
3468
- // _load_only: create + load only. No render, no children, no on_render, no on_loaded, no on_ready.
3469
- this._load_only = false;
3470
- // _load_render_only: create + render + load + re-render. No on_render, no on_loaded, no on_ready.
3471
- this._load_render_only = false;
3472
- // Detached optimization: true when element is not in the DOM at boot time.
3473
- // Skips initial render and cache read — just on_load then render.
3474
- // Override with _force_initial_render to keep normal double-render behavior.
3475
- this._is_detached = false;
3476
- // _force_initial_render: override detached optimization — render even when not in DOM.
3477
- // Use when you need the loading spinner visible immediately after appending.
3478
- this._force_initial_render = false;
3479
- // rendered event - fires once after the synchronous render chain completes
3480
- // (after on_load's re-render if applicable, or after first render if no on_load)
3481
- this._has_rendered = false;
3482
- // Sequential queue for setting this.data after on_load completes
3483
- // Multiple _load calls can run on_load in parallel, but setting this.data is serialized
3484
- this._load_queue = Promise.resolve();
3485
- // Cached flag: true if this component has a custom on_load() override
3486
- // Set in constructor (prototype chain is established before constructor runs)
3487
- // Used to skip expensive cache/load operations for static components
3488
- this.__has_custom_on_load = false;
3489
- // gate_load() — "load gates" registered during on_create() that must settle
3490
- // before the component's FIRST on_load() runs. See gate_load() / _await_load_gates().
3491
- this.__load_gates = []; // Pending gates (cleared once the first load begins)
3492
- this.__first_load_started = false; // Latch: true once the first load phase begins (enforces one-shot + throw-after)
3493
- this.__gate_resume = null; // Resolver to release an in-progress gate wait early (reload/refresh/stop)
3494
- // Detect custom on_load() override immediately
3495
- // Prototype chain is set up before constructor runs, so this.on_load
3496
- // correctly resolves to child class override if one exists
3497
- this.__has_custom_on_load = this.on_load !== Jqhtml_Component.prototype.on_load;
3498
- this._cid = this._generate_cid();
3499
- this._lifecycle_manager = LifecycleManager.get_instance();
3500
- // Create or wrap element
3501
- if (element) {
3502
- this.$ = $(element);
3503
- }
3504
- else {
3505
- // Use native createElement for better performance
3506
- const div = document.createElement('div');
3507
- this.$ = $(div);
3508
- }
3509
- // Extract $ attributes from element and merge with args
3510
- // $ attributes are stored via jQuery .data() (not as data-* attributes in DOM)
3511
- const dataAttrs = {};
3512
- // Get all jQuery .data() values from the element
3513
- if (this.$.length > 0) {
3514
- // Get all data via jQuery .data() without arguments (returns all data as object)
3515
- const allData = this.$.data() || {};
3516
- for (const key in allData) {
3517
- // Skip internal attributes
3518
- if (key !== 'cid' && key !== 'tid' && key !== 'componentName' && key !== 'readyState' &&
3519
- key !== '_lifecycleState' && !key.startsWith('_')) {
3520
- dataAttrs[key] = allData[key];
3521
- }
3522
- }
3523
- }
3524
- // Get template to check for defineArgs
3525
- let template_for_args;
3526
- if (args._component_name) {
3527
- template_for_args = get_template(args._component_name);
3528
- }
3529
- else {
3530
- template_for_args = get_template_by_class(this.constructor);
3531
- }
3532
- // Merge in order: defineArgs (defaults from Define tag) < dataAttrs < args (invocation overrides)
3533
- const defineArgs = template_for_args?.defineArgs || {};
3534
- this.args = { ...defineArgs, ...dataAttrs, ...args };
3535
- // Set lifecycle truncation flags from args
3536
- if (this.args._load_only === true) {
3537
- this._load_only = true;
3538
- }
3539
- if (this.args._load_render_only === true) {
3540
- this._load_render_only = true;
3541
- }
3542
- if (this.args._force_initial_render === true) {
3543
- this._force_initial_render = true;
3544
- }
3545
- // Attach component to element
3546
- this.$.data('_component', this);
3547
- // Apply CSS classes and attributes
3548
- this._apply_css_classes();
3549
- this._apply_default_attributes(); // Apply defaultAttributes from template
3550
- this._set_attributes();
3551
- // Find DOM parent component (for lifecycle coordination)
3552
- this._find_dom_parent();
3553
- // Setup data property with freeze enforcement using Proxy
3554
- // @see data-proxy.ts for full implementation
3555
- setup_data_property(this);
3556
- // Initialize this.state as an empty object (convention for arbitrary component state)
3557
- // No special meaning to framework - mutable anywhere, not cached, not frozen
3558
- this.state = {};
3559
- this._log_lifecycle('construct', 'complete');
3535
+ class Component_Queue {
3536
+ constructor() {
3537
+ /** Currently executing operation */
3538
+ this._current = null;
3539
+ /** Next operation waiting to execute after current completes */
3540
+ this._pending = null;
3560
3541
  }
3561
3542
  /**
3562
- * Protect lifecycle methods from manual invocation
3563
- * Stores original implementations in WeakMap, replaces with guarded wrappers
3564
- * @private
3543
+ * Enqueue a lifecycle operation.
3544
+ *
3545
+ * Behavior:
3546
+ * - Nothing running → execute immediately
3547
+ * - Something running, no pending → create pending entry
3548
+ * - Something running, same type pending → collapse (share pending promise)
3549
+ * - Something running, different type pending → replace pending (all callers get new result)
3550
+ *
3551
+ * @param type - Operation type ('render', 'reload', 'refresh', 'load')
3552
+ * @param executor - The async function to execute
3553
+ * @returns Promise that resolves when the operation completes
3565
3554
  */
3566
- _protect_lifecycle_methods() {
3567
- const methods = {
3568
- on_create: 'Called automatically during creation.',
3569
- on_render: 'Use render() to trigger a re-render.',
3570
- on_load: 'Use reload() to refresh data.',
3571
- on_ready: 'Called automatically when ready.',
3572
- on_stop: 'Use stop() to stop the component.'
3573
- };
3574
- const impls = {};
3575
- const self = this;
3576
- for (const [name, help] of Object.entries(methods)) {
3577
- const original = this[name];
3578
- // Skip if using base class default (empty method)
3579
- if (original === Jqhtml_Component.prototype[name])
3580
- continue;
3581
- impls[name] = original;
3582
- // Create wrapper with same function name (for stack traces)
3583
- this[name] = {
3584
- [name](...args) {
3585
- if (!self.__lifecycle_authorized) {
3586
- throw new Error(`[JQHTML] ${name}() cannot be called manually. ${help}\n` +
3587
- `Component: ${self.component_name()} (_cid: ${self._cid})`);
3588
- }
3589
- return lifecycle_impls.get(self)[name].apply(self, args);
3590
- }
3591
- }[name];
3555
+ enqueue(type, executor) {
3556
+ // If nothing running, execute immediately
3557
+ if (!this._current) {
3558
+ return this._execute(type, executor);
3592
3559
  }
3593
- lifecycle_impls.set(this, impls);
3560
+ // Something is running — add to pending
3561
+ if (this._pending) {
3562
+ if (this._pending.type === type) {
3563
+ // Same type pending → collapse (fan-in)
3564
+ // All callers share the same future execution
3565
+ return new Promise((resolve, reject) => {
3566
+ this._pending.resolvers.push(resolve);
3567
+ this._pending.rejecters.push(reject);
3568
+ });
3569
+ }
3570
+ else {
3571
+ // Different type pending → replace
3572
+ // Old pending callers join the new operation
3573
+ // (their operation was superseded by a different type)
3574
+ const old_resolvers = this._pending.resolvers;
3575
+ const old_rejecters = this._pending.rejecters;
3576
+ return new Promise((resolve, reject) => {
3577
+ this._pending = {
3578
+ type,
3579
+ executor,
3580
+ resolvers: [...old_resolvers, resolve],
3581
+ rejecters: [...old_rejecters, reject]
3582
+ };
3583
+ });
3584
+ }
3585
+ }
3586
+ // No pending entry yet — create one
3587
+ return new Promise((resolve, reject) => {
3588
+ this._pending = {
3589
+ type,
3590
+ executor,
3591
+ resolvers: [resolve],
3592
+ rejecters: [reject]
3593
+ };
3594
+ });
3594
3595
  }
3595
3596
  /**
3596
- * Call a lifecycle method with authorization (async)
3597
- * Framework calls this to invoke lifecycle methods, bypassing the protection wrapper.
3598
- * The flag is set momentarily for the wrapper check, then reset BEFORE user code runs.
3599
- * This ensures any nested lifecycle calls from user code will fail the flag check.
3597
+ * Execute an operation and handle pending queue after completion.
3600
3598
  * @private
3601
3599
  */
3602
- async _call_lifecycle(name, context) {
3603
- // Get the original implementation (bypasses wrapper entirely)
3604
- const impl = lifecycle_impls.get(this)?.[name] || this[name];
3605
- // Call original directly - no flag needed since we bypass the wrapper
3606
- return await impl.call(context || this);
3607
- }
3600
+ _execute(type, executor) {
3601
+ const promise = (async () => {
3602
+ try {
3603
+ await executor();
3604
+ }
3605
+ finally {
3606
+ this._current = null;
3607
+ // Run pending if exists
3608
+ if (this._pending) {
3609
+ const pending = this._pending;
3610
+ this._pending = null;
3611
+ try {
3612
+ await this._execute(pending.type, pending.executor);
3613
+ for (const resolve of pending.resolvers)
3614
+ resolve();
3615
+ }
3616
+ catch (err) {
3617
+ for (const reject of pending.rejecters)
3618
+ reject(err);
3619
+ }
3620
+ }
3621
+ }
3622
+ })();
3623
+ this._current = { type, promise };
3624
+ return promise;
3625
+ }
3626
+ /**
3627
+ * Check if any operation is currently running.
3628
+ */
3629
+ get is_busy() {
3630
+ return this._current !== null;
3631
+ }
3632
+ /**
3633
+ * Check if there's a pending operation waiting.
3634
+ */
3635
+ get has_pending() {
3636
+ return this._pending !== null;
3637
+ }
3638
+ }
3639
+
3640
+ /**
3641
+ * JQHTML SSR Preload Data System
3642
+ *
3643
+ * Captures component data during SSR rendering and replays it on the client
3644
+ * to skip redundant on_load() calls during hydration.
3645
+ *
3646
+ * Server-side: start_data_capture() → render → get_captured_data()
3647
+ * Client-side: set_preload_data(entries) → components boot with preloaded data → clear_preload_data()
3648
+ */
3649
+ // --- Capture (Server Side) ---
3650
+ let _capture_enabled = false;
3651
+ let _capture_buffer = [];
3652
+ // Track captured keys to avoid duplicates from Load Coordinator followers
3653
+ let _captured_keys = new Set();
3654
+ /**
3655
+ * Enable data capture mode. After this call, every component that completes
3656
+ * on_load() has its final this.data recorded.
3657
+ *
3658
+ * Idempotent — calling twice is fine.
3659
+ */
3660
+ function start_data_capture() {
3661
+ _capture_enabled = true;
3662
+ _capture_buffer = [];
3663
+ _captured_keys.clear();
3664
+ }
3665
+ /**
3666
+ * Record a component's data after on_load() completes.
3667
+ * Called internally from _apply_load_result().
3668
+ *
3669
+ * @param component_name - Component name
3670
+ * @param args - Component args at time of on_load()
3671
+ * @param data - this.data after on_load() completed
3672
+ * @param cache_key - The cache key for deduplication (null = always capture)
3673
+ */
3674
+ function capture_component_data(component_name, args, data, cache_key) {
3675
+ if (!_capture_enabled)
3676
+ return;
3677
+ // Deduplicate: if Load Coordinator already captured this key, skip
3678
+ if (cache_key !== null) {
3679
+ if (_captured_keys.has(cache_key))
3680
+ return;
3681
+ _captured_keys.add(cache_key);
3682
+ }
3683
+ // Deep clone args and data to plain objects (no proxies, no class instances)
3684
+ try {
3685
+ const cloned_args = JSON.parse(JSON.stringify(args));
3686
+ const cloned_data = JSON.parse(JSON.stringify(data));
3687
+ _capture_buffer.push({
3688
+ component: component_name,
3689
+ args: cloned_args,
3690
+ data: cloned_data,
3691
+ });
3692
+ }
3693
+ catch (error) {
3694
+ // Non-serializable data — skip capture for this component
3695
+ if (typeof console !== 'undefined') {
3696
+ console.warn(`[JQHTML SSR Capture] Failed to serialize data for ${component_name}:`, error);
3697
+ }
3698
+ }
3699
+ }
3700
+ /**
3701
+ * Returns all captured component data and resets the capture buffer.
3702
+ * One-shot: calling clears the buffer.
3703
+ */
3704
+ function get_captured_data() {
3705
+ const result = _capture_buffer;
3706
+ _capture_buffer = [];
3707
+ _captured_keys.clear();
3708
+ return result;
3709
+ }
3710
+ /**
3711
+ * Check if data capture is currently enabled.
3712
+ */
3713
+ function is_capture_enabled() {
3714
+ return _capture_enabled;
3715
+ }
3716
+ /**
3717
+ * Stop data capture and clear all state.
3718
+ */
3719
+ function stop_data_capture() {
3720
+ _capture_enabled = false;
3721
+ _capture_buffer = [];
3722
+ _captured_keys.clear();
3723
+ }
3724
+ // --- Preload (Client Side) ---
3725
+ let _preload_cache = new Map();
3726
+ /**
3727
+ * Seed the preload cache with SSR-captured data.
3728
+ * Must be called before any component _load() runs.
3729
+ *
3730
+ * @param entries - Array of { component, args, data } entries from get_captured_data()
3731
+ */
3732
+ function set_preload_data(entries) {
3733
+ if (!entries || entries.length === 0)
3734
+ return;
3735
+ _preload_cache.clear();
3736
+ for (const entry of entries) {
3737
+ // Generate key using the same algorithm as Load Coordinator
3738
+ const result = Load_Coordinator.generate_invocation_key(entry.component, entry.args);
3739
+ if (result.key !== null) {
3740
+ _preload_cache.set(result.key, entry.data);
3741
+ }
3742
+ }
3743
+ }
3744
+ /**
3745
+ * Check if preloaded data exists for a given cache key.
3746
+ * If found, returns the data and removes the entry (one-shot).
3747
+ *
3748
+ * @param cache_key - The cache key (same format as Load Coordinator)
3749
+ * @returns The preloaded data, or null if no match
3750
+ */
3751
+ function consume_preload_data(cache_key) {
3752
+ if (_preload_cache.size === 0)
3753
+ return null;
3754
+ const data = _preload_cache.get(cache_key);
3755
+ if (data !== undefined) {
3756
+ _preload_cache.delete(cache_key);
3757
+ return data;
3758
+ }
3759
+ return null;
3760
+ }
3761
+ /**
3762
+ * Clear any remaining unconsumed preload entries.
3763
+ * Call after initial page hydration is complete.
3764
+ */
3765
+ function clear_preload_data() {
3766
+ _preload_cache.clear();
3767
+ }
3768
+ /**
3769
+ * Check if any preload data is available (for fast early exit in _load).
3770
+ */
3771
+ function has_preload_data() {
3772
+ return _preload_cache.size > 0;
3773
+ }
3774
+
3775
+ /**
3776
+ * JQHTML Viewport Resize Dispatch
3777
+ *
3778
+ * One framework-owned, debounced window 'resize' listener fans out to every live
3779
+ * component in the document by calling on_viewport_resize(viewport_width).
3780
+ *
3781
+ * Components never bind their own window listener, so there is nothing to unbind
3782
+ * in on_stop() - a component that is stopped or removed from the document simply
3783
+ * stops being found by the dispatcher.
3784
+ */
3785
+ /** Trailing-edge debounce applied to the window resize listener. */
3786
+ const VIEWPORT_RESIZE_DEBOUNCE_MS = 30;
3787
+ let debounce_timer = null;
3788
+ let listener_installed = false;
3789
+ /**
3790
+ * Current viewport width in CSS pixels.
3791
+ *
3792
+ * window.innerWidth is used (not $(window).width()) because it matches the width
3793
+ * CSS media queries resolve against. It includes the scrollbar gutter.
3794
+ *
3795
+ * Returns 0 outside a browser (SSR).
3796
+ */
3797
+ function get_viewport_width() {
3798
+ return typeof window !== 'undefined' ? window.innerWidth : 0;
3799
+ }
3800
+ /**
3801
+ * Call on_viewport_resize(width) on every component currently in the document.
3802
+ *
3803
+ * Walks $('.Component') in document order (parents before children). Elements
3804
+ * with no component instance and stopped components are skipped. A component
3805
+ * that throws is logged and the walk continues - one bad handler must not stop
3806
+ * the rest of the page from resizing.
3807
+ */
3808
+ function dispatch_viewport_resize(jQuery) {
3809
+ const viewport_width = get_viewport_width();
3810
+ jQuery('.Component').each(function () {
3811
+ const component = jQuery(this).data('_component');
3812
+ if (!component || component._stopped)
3813
+ return;
3814
+ if (typeof component.on_viewport_resize !== 'function')
3815
+ return;
3816
+ try {
3817
+ component.on_viewport_resize(viewport_width);
3818
+ }
3819
+ catch (error) {
3820
+ console.error(`[JQHTML] Error in on_viewport_resize() for ${component.component_name?.() || 'component'}:`, error);
3821
+ }
3822
+ });
3823
+ }
3824
+ /**
3825
+ * Install the single window resize listener. Idempotent - repeated init() calls
3826
+ * and non-browser environments are no-ops.
3827
+ */
3828
+ function init_viewport_resize(jQuery) {
3829
+ if (typeof window === 'undefined')
3830
+ return;
3831
+ if (listener_installed)
3832
+ return;
3833
+ listener_installed = true;
3834
+ jQuery(window).on('resize.jqhtml_viewport', function () {
3835
+ if (debounce_timer !== null)
3836
+ clearTimeout(debounce_timer);
3837
+ debounce_timer = setTimeout(function () {
3838
+ debounce_timer = null;
3839
+ dispatch_viewport_resize(jQuery);
3840
+ }, VIEWPORT_RESIZE_DEBOUNCE_MS);
3841
+ });
3842
+ }
3843
+
3844
+ /**
3845
+ * JQHTML v2 Component Base Class
3846
+ *
3847
+ * Core component implementation following v2 specification:
3848
+ * - 5-stage lifecycle coordinated by LifecycleManager
3849
+ * - Direct jQuery manipulation (no virtual DOM)
3850
+ * - Scoped IDs using _cid pattern
3851
+ * - Event emission and CSS class hierarchy
3852
+ */
3853
+ // WeakMap storage for protected lifecycle method implementations (Option 2)
3854
+ // See docs/internal/lifecycle-method-protection.md for design details
3855
+ const lifecycle_impls = new WeakMap();
3856
+ class Jqhtml_Component {
3857
+ constructor(element, args = {}) {
3858
+ this._ready_state = 0; // 0=created, 1=init, 2=loaded, 3=rendered, 4=ready
3859
+ this._instantiator = null; // Component that instantiated this one
3860
+ this._dom_parent = null; // Closest component in DOM tree (for lifecycle)
3861
+ this._dom_children = new Set(); // Components in DOM subtree (for lifecycle)
3862
+ this._use_dom_fallback = false; // If true, use find() fallback instead of _dom_children optimization
3863
+ this._stopped = false;
3864
+ this._booted = false; // Guard to prevent double boot() calls
3865
+ this._data_before_render = null; // Store data state before initial render
3866
+ this._lifecycle_callbacks = new Map();
3867
+ this._lifecycle_states = new Map(); // Track which lifecycle events have occurred and their data
3868
+ this._did_first_render = false; // Track if component has rendered at least once
3869
+ this._render_count = 0; // Incremented each time _render() is called, used to detect stale renders
3870
+ this._args_on_last_render = null; // Args snapshot from last render (for reload() comparison)
3871
+ this._data_on_last_render = null; // Data snapshot from last render (for refresh() comparison)
3872
+ this.__initial_data_snapshot = null; // Snapshot of this.data after on_create() for restoration before on_load()
3873
+ this.__data_frozen = false; // Track if this.data is currently frozen
3874
+ this._queue = new Component_Queue(); // Lifecycle operation queue (render/reload/refresh)
3875
+ this.next_reload_force_refresh = null; // State machine for reload()/refresh() debounce precedence
3876
+ this.__lifecycle_authorized = false; // Flag for lifecycle method protection
3877
+ // Cache mode properties
3878
+ this._cache_key = null; // Cache key for caching
3879
+ // 'html' mode caching
3880
+ this._cached_html = null; // Cached HTML to inject on first render
3881
+ this._used_cached_html = false; // Flag if cached HTML was used (forces re-render after on_load)
3882
+ this._should_cache_html_after_ready = false; // Flag to cache HTML after on_ready lifecycle
3883
+ this._is_dynamic = false; // True if this.data changed during on_load() (used for HTML cache sync)
3884
+ // on_render synchronization (HTML cache mode)
3885
+ this._on_render_complete = false; // True after on_render() has been called post-on_load
3886
+ // use_cached_data feature - skip on_load() when cache hit occurs
3887
+ this._use_cached_data_hit = false; // True if use_cached_data=true AND cache was used
3888
+ // _load_only: create + load only. No render, no children, no on_render, no on_loaded, no on_ready.
3889
+ this._load_only = false;
3890
+ // _load_render_only: create + render + load + re-render. No on_render, no on_loaded, no on_ready.
3891
+ this._load_render_only = false;
3892
+ // Detached optimization: true when element is not in the DOM at boot time.
3893
+ // Skips initial render and cache read — just on_load then render.
3894
+ // Override with _force_initial_render to keep normal double-render behavior.
3895
+ this._is_detached = false;
3896
+ // _force_initial_render: override detached optimization — render even when not in DOM.
3897
+ // Use when you need the loading spinner visible immediately after appending.
3898
+ this._force_initial_render = false;
3899
+ // rendered event - fires once after the synchronous render chain completes
3900
+ // (after on_load's re-render if applicable, or after first render if no on_load)
3901
+ this._has_rendered = false;
3902
+ // Sequential queue for setting this.data after on_load completes
3903
+ // Multiple _load calls can run on_load in parallel, but setting this.data is serialized
3904
+ this._load_queue = Promise.resolve();
3905
+ // Cached flag: true if this component has a custom on_load() override
3906
+ // Set in constructor (prototype chain is established before constructor runs)
3907
+ // Used to skip expensive cache/load operations for static components
3908
+ this.__has_custom_on_load = false;
3909
+ // gate_load() — "load gates" registered during on_create() that must settle
3910
+ // before the component's FIRST on_load() runs. See gate_load() / _await_load_gates().
3911
+ this.__load_gates = []; // Pending gates (cleared once the first load begins)
3912
+ this.__first_load_started = false; // Latch: true once the first load phase begins (enforces one-shot + throw-after)
3913
+ this.__gate_resume = null; // Resolver to release an in-progress gate wait early (reload/refresh/stop)
3914
+ // Detect custom on_load() override immediately
3915
+ // Prototype chain is set up before constructor runs, so this.on_load
3916
+ // correctly resolves to child class override if one exists
3917
+ this.__has_custom_on_load = this.on_load !== Jqhtml_Component.prototype.on_load;
3918
+ this._cid = this._generate_cid();
3919
+ this._lifecycle_manager = LifecycleManager.get_instance();
3920
+ // Create or wrap element
3921
+ if (element) {
3922
+ this.$ = $(element);
3923
+ }
3924
+ else {
3925
+ // Use native createElement for better performance
3926
+ const div = document.createElement('div');
3927
+ this.$ = $(div);
3928
+ }
3929
+ // Extract $ attributes from element and merge with args
3930
+ // $ attributes are stored via jQuery .data() (not as data-* attributes in DOM)
3931
+ const dataAttrs = {};
3932
+ // Get all jQuery .data() values from the element
3933
+ if (this.$.length > 0) {
3934
+ // Get all data via jQuery .data() without arguments (returns all data as object)
3935
+ const allData = this.$.data() || {};
3936
+ for (const key in allData) {
3937
+ // Skip internal attributes
3938
+ if (key !== 'cid' && key !== 'tid' && key !== 'componentName' && key !== 'readyState' &&
3939
+ key !== '_lifecycleState' && !key.startsWith('_')) {
3940
+ dataAttrs[key] = allData[key];
3941
+ }
3942
+ }
3943
+ }
3944
+ // Get template to check for defineArgs
3945
+ let template_for_args;
3946
+ if (args._component_name) {
3947
+ template_for_args = get_template(args._component_name);
3948
+ }
3949
+ else {
3950
+ template_for_args = get_template_by_class(this.constructor);
3951
+ }
3952
+ // Merge in order: defineArgs (defaults from Define tag) < dataAttrs < args (invocation overrides)
3953
+ const defineArgs = template_for_args?.defineArgs || {};
3954
+ this.args = { ...defineArgs, ...dataAttrs, ...args };
3955
+ // The name this instance was invoked as. Every invocation path passes it
3956
+ // in args._component_name (template tag, $(el).component('Name'), boot
3957
+ // placeholder); a class handed directly to $(el).component(Class) has
3958
+ // only its own name to offer.
3959
+ const ctor = this.constructor;
3960
+ this._component_name = (typeof args._component_name === 'string' && args._component_name)
3961
+ || ctor.component_name
3962
+ || ctor.name;
3963
+ // Set lifecycle truncation flags from args
3964
+ if (this.args._load_only === true) {
3965
+ this._load_only = true;
3966
+ }
3967
+ if (this.args._load_render_only === true) {
3968
+ this._load_render_only = true;
3969
+ }
3970
+ if (this.args._force_initial_render === true) {
3971
+ this._force_initial_render = true;
3972
+ }
3973
+ // Attach component to element
3974
+ this.$.data('_component', this);
3975
+ // Apply CSS classes and attributes
3976
+ this._apply_css_classes();
3977
+ this._apply_default_attributes(); // Apply defaultAttributes from template
3978
+ this._set_attributes();
3979
+ // Find DOM parent component (for lifecycle coordination)
3980
+ this._find_dom_parent();
3981
+ // Setup data property with freeze enforcement using Proxy
3982
+ // @see data-proxy.ts for full implementation
3983
+ setup_data_property(this);
3984
+ // Initialize this.state as an empty object (convention for arbitrary component state)
3985
+ // No special meaning to framework - mutable anywhere, not cached, not frozen
3986
+ this.state = {};
3987
+ this._log_lifecycle('construct', 'complete');
3988
+ }
3989
+ /**
3990
+ * Protect lifecycle methods from manual invocation
3991
+ * Stores original implementations in WeakMap, replaces with guarded wrappers
3992
+ * @private
3993
+ */
3994
+ _protect_lifecycle_methods() {
3995
+ const methods = {
3996
+ on_create: 'Called automatically during creation.',
3997
+ on_render: 'Use render() to trigger a re-render.',
3998
+ on_load: 'Use reload() to refresh data.',
3999
+ on_ready: 'Called automatically when ready.',
4000
+ on_stop: 'Use stop() to stop the component.'
4001
+ };
4002
+ const impls = {};
4003
+ const self = this;
4004
+ for (const [name, help] of Object.entries(methods)) {
4005
+ const original = this[name];
4006
+ // Skip if using base class default (empty method)
4007
+ if (original === Jqhtml_Component.prototype[name])
4008
+ continue;
4009
+ impls[name] = original;
4010
+ // Create wrapper with same function name (for stack traces)
4011
+ this[name] = {
4012
+ [name](...args) {
4013
+ if (!self.__lifecycle_authorized) {
4014
+ throw new Error(`[JQHTML] ${name}() cannot be called manually. ${help}\n` +
4015
+ `Component: ${self.component_name()} (_cid: ${self._cid})`);
4016
+ }
4017
+ return lifecycle_impls.get(self)[name].apply(self, args);
4018
+ }
4019
+ }[name];
4020
+ }
4021
+ lifecycle_impls.set(this, impls);
4022
+ }
4023
+ /**
4024
+ * Call a lifecycle method with authorization (async)
4025
+ * Framework calls this to invoke lifecycle methods, bypassing the protection wrapper.
4026
+ * The flag is set momentarily for the wrapper check, then reset BEFORE user code runs.
4027
+ * This ensures any nested lifecycle calls from user code will fail the flag check.
4028
+ * @private
4029
+ */
4030
+ async _call_lifecycle(name, context) {
4031
+ // Get the original implementation (bypasses wrapper entirely)
4032
+ const impl = lifecycle_impls.get(this)?.[name] || this[name];
4033
+ // Call original directly - no flag needed since we bypass the wrapper
4034
+ return await impl.call(context || this);
4035
+ }
3608
4036
  /**
3609
4037
  * Call a lifecycle method with authorization (sync version for sync methods like on_stop)
3610
4038
  * @private
@@ -3784,7 +4212,11 @@ class Jqhtml_Component {
3784
4212
  div.textContent = String(str);
3785
4213
  // Escape HTML first, then replace newlines with <br />
3786
4214
  return div.innerHTML.replace(/\n/g, '<br />');
3787
- }
4215
+ },
4216
+ // Objects reaching <%= %> / <%!= %> / <%br= %> - see value-printers.ts
4217
+ print_object,
4218
+ // <{expression}> name validation - see component-name.ts
4219
+ dynamic_component_name
3788
4220
  };
3789
4221
  // Execute template function
3790
4222
  // Commented out debug logging
@@ -4786,771 +5218,919 @@ class Jqhtml_Component {
4786
5218
  if (stopResult && typeof stopResult.then === 'function') {
4787
5219
  console.warn(`[JQHTML] Component "${this.component_name()}" returned a Promise from on_stop(). ` +
4788
5220
  `on_stop() must be synchronous code. Remove 'async' from the function declaration.`);
4789
- }
4790
- // Fire registered stop callbacks
4791
- this.trigger('stop');
4792
- // Remove from DOM parent's children
4793
- if (this._dom_parent) {
4794
- this._dom_parent._dom_children.delete(this);
4795
- }
4796
- this._ready_state = 99;
4797
- this._update_debug_attrs();
4798
- this._log_lifecycle('destroy', 'complete');
4799
- }
4800
- /**
4801
- * Stop component lifecycle - stops all descendant components then self
4802
- * Leaves DOM intact, just stops lifecycle engine and fires cleanup hooks
4803
- */
4804
- stop() {
4805
- // Stop all descendant components (flat iteration, no recursion needed)
4806
- this.$.find('.Component').each(function () {
4807
- const child = $(this).data('_component');
4808
- if (child && !child._stopped) {
4809
- child._stop(); // Not recursive - we already have all descendants
4810
- }
4811
- });
4812
- // Then stop self
4813
- this._stop();
4814
- }
4815
- // -------------------------------------------------------------------------
4816
- // Overridable Lifecycle Hooks
4817
- // -------------------------------------------------------------------------
4818
- on_render() { }
4819
- on_create() { }
4820
- on_load() { } // Override to fetch data asynchronously
4821
- on_loaded() { } // Override to process loaded data (e.g., clone this.data to this.state)
4822
- async on_ready() { }
4823
- on_stop() { }
4824
- /**
4825
- * Called with the viewport width in CSS pixels:
4826
- * - after every on_render()
4827
- * - after every on_ready()
4828
- * - on window resize, debounced 30ms, for every component in the document
4829
- *
4830
- * MUST be synchronous. Prefer CSS media/container queries for pure styling -
4831
- * override this only when layout requires imperative measurement.
4832
- */
4833
- on_viewport_resize(viewport_width) { }
4834
- /**
4835
- * Should component re-render after load?
4836
- * By default, only re-renders if data has changed
4837
- * Override to control re-rendering behavior
4838
- */
4839
- /**
4840
- * Internal method to determine if component should re-render after on_load()
4841
- * @private
4842
- */
4843
- _should_rerender() {
4844
- // HTML CACHE MODE - If we used cached HTML, always re-render to get live components
4845
- if (this._used_cached_html) {
4846
- if (window.jqhtml?.debug?.verbose) {
4847
- console.log(`[Cache html] Component ${this._cid} (${this.component_name()}) forcing re-render after cached HTML`);
4848
- }
4849
- // Clear the flag
4850
- this._used_cached_html = false;
4851
- return true;
4852
- }
4853
- // OPTIMIZATION: If no custom on_load(), data cannot change, skip serialization
4854
- // Data is frozen after on_create() and only unfrozen during on_load()
4855
- if (!this.__has_custom_on_load) {
4856
- return false;
4857
- }
4858
- // Compare current data state with data state before initial render
4859
- const currentDataState = JSON.stringify(this.data);
4860
- const dataChanged = this._data_before_render !== currentDataState;
4861
- // Update stored state for next comparison
4862
- if (dataChanged) {
4863
- this._data_before_render = currentDataState;
4864
- }
4865
- return dataChanged;
4866
- }
4867
- // -------------------------------------------------------------------------
4868
- // Public API
4869
- // -------------------------------------------------------------------------
4870
- /**
4871
- * Get component name for debugging
4872
- */
4873
- component_name() {
4874
- return this.constructor.name;
4875
- }
4876
- /**
4877
- * Register event callback - delegates to component-events.ts
4878
- * @see component-events.ts for full documentation
4879
- */
4880
- on(event_name, callback) {
4881
- return event_on(this, event_name, callback);
4882
- }
4883
- /**
4884
- * Register a callback that fires exactly once - delegates to component-events.ts
4885
- * If the event already occurred, fires immediately and does not register.
4886
- * @see component-events.ts for full documentation
4887
- */
4888
- once(event_name, callback) {
4889
- return event_once(this, event_name, callback);
4890
- }
4891
- /**
4892
- * Trigger a lifecycle event - delegates to component-events.ts
4893
- * @see component-events.ts for full documentation
4894
- */
4895
- trigger(event_name, data) {
4896
- event_trigger(this, event_name, data);
4897
- }
4898
- /**
4899
- * Check if any callbacks are registered for a given event
4900
- */
4901
- _on_registered(event_name) {
4902
- return event_on_registered(this, event_name);
4903
- }
4904
- /**
4905
- * Invalidate a lifecycle event - delegates to component-events.ts
4906
- * @see component-events.ts for full documentation
4907
- */
4908
- invalidate(event_name) {
4909
- event_invalidate(this, event_name);
4910
- }
4911
- /**
4912
- * Find element by scoped ID
4913
- *
4914
- * Searches for elements with id="local_id:THIS_COMPONENT_CID"
4915
- *
4916
- * Example:
4917
- * Template: <button $sid="save_btn">Save</button>
4918
- * Rendered: <button id="save_btn:abc123" data-sid="save_btn">Save</button>
4919
- * Access: this.$sid('save_btn') // Returns jQuery element
4920
- *
4921
- * Performance: Uses native document.getElementById() when component is in DOM,
4922
- * falls back to jQuery.find() for components not yet attached to DOM.
4923
- *
4924
- * @param local_id The local ID (without _cid suffix)
4925
- * @returns jQuery element with id="local_id:_cid", or empty jQuery object if not found
4926
- */
4927
- $sid(local_id) {
4928
- const scopedId = `${local_id}:${this._cid}`;
4929
- // Try getElementById first (fast path - works when component is in DOM)
4930
- const el = document.getElementById(scopedId);
4931
- if (el) {
4932
- return $(el);
4933
- }
4934
- // Fallback: component not in DOM yet, search within component subtree
4935
- // This allows $sid() to work on components before they're appended to body
4936
- // Must escape the ID because it contains ':' which jQuery treats as a pseudo-selector
4937
- return this.$.find(`#${$.escapeSelector(scopedId)}`);
4938
- }
4939
- /**
4940
- * Get component instance by scoped ID
4941
- *
4942
- * Convenience method that finds element by scoped ID and returns the component instance.
4943
- *
4944
- * Example:
4945
- * Template: <User_Card $sid="active_user" />
4946
- * Access: const user = this.sid('active_user'); // Returns User_Card instance
4947
- * user.data.name // Access component's data
4948
- *
4949
- * To get the scoped ID string itself:
4950
- * this.$sid('active_user').attr('id') // Returns "active_user:abc123xyz"
4951
- *
4952
- * @param local_id The local ID (without _cid suffix)
4953
- * @returns Component instance or null if not found or not a component
4954
- */
4955
- sid(local_id) {
4956
- const element = this.$sid(local_id);
4957
- const component = element.data('_component');
4958
- // If no component found but element exists, warn developer
4959
- if (!component && element.length > 0) {
4960
- console.warn(`Component ${this.constructor.name} tried to call .sid('${local_id}') - ` +
4961
- `${local_id} exists, however, it is not a component or $redrawable. ` +
4962
- `Did you forget to add $redrawable to the tag?`);
4963
- }
4964
- return component || null;
4965
- }
4966
- /**
4967
- * Get the component that instantiated this component (rendered it in their template)
4968
- * Returns null if component was created programmatically via $().component()
4969
- */
4970
- instantiator() {
4971
- return this._instantiator;
5221
+ }
5222
+ // Fire registered stop callbacks
5223
+ this.trigger('stop');
5224
+ // Remove from DOM parent's children
5225
+ if (this._dom_parent) {
5226
+ this._dom_parent._dom_children.delete(this);
5227
+ }
5228
+ this._ready_state = 99;
5229
+ this._update_debug_attrs();
5230
+ this._log_lifecycle('destroy', 'complete');
4972
5231
  }
4973
5232
  /**
4974
- * Find descendant components by CSS selector
5233
+ * Stop component lifecycle - stops all descendant components then self
5234
+ * Leaves DOM intact, just stops lifecycle engine and fires cleanup hooks
4975
5235
  */
4976
- find(selector) {
4977
- const components = [];
4978
- this.$.find(selector).each((_, el) => {
4979
- const comp = $(el).data('_component');
4980
- if (comp instanceof Jqhtml_Component) {
4981
- components.push(comp);
5236
+ stop() {
5237
+ // Stop all descendant components (flat iteration, no recursion needed)
5238
+ this.$.find('.Component').each(function () {
5239
+ const child = $(this).data('_component');
5240
+ if (child && !child._stopped) {
5241
+ child._stop(); // Not recursive - we already have all descendants
4982
5242
  }
4983
5243
  });
4984
- return components;
5244
+ // Then stop self
5245
+ this._stop();
4985
5246
  }
5247
+ // -------------------------------------------------------------------------
5248
+ // Overridable Lifecycle Hooks
5249
+ // -------------------------------------------------------------------------
5250
+ on_render() { }
5251
+ on_create() { }
5252
+ on_load() { } // Override to fetch data asynchronously
5253
+ on_loaded() { } // Override to process loaded data (e.g., clone this.data to this.state)
5254
+ async on_ready() { }
5255
+ on_stop() { }
4986
5256
  /**
4987
- * Find closest ancestor component matching selector
5257
+ * Called with the viewport width in CSS pixels:
5258
+ * - after every on_render()
5259
+ * - after every on_ready()
5260
+ * - on window resize, debounced 30ms, for every component in the document
4988
5261
  *
4989
- * A bare component name - a plain identifier starting with a capital letter,
4990
- * such as 'Parent_Dashboard' - is treated as the component-name class
4991
- * selector '.Parent_Dashboard'. Components carry a CSS class for every name
4992
- * in their prototype chain, so a base class name matches its subclasses too.
4993
- * Every other selector ('.Foo', '#id', '[attr]', 'div > .Component') is
4994
- * passed to jQuery unchanged.
5262
+ * MUST be synchronous. Prefer CSS media/container queries for pure styling -
5263
+ * override this only when layout requires imperative measurement.
4995
5264
  */
4996
- closest(selector) {
4997
- const search = Jqhtml_Component.COMPONENT_NAME_PATTERN.test(selector)
4998
- ? `.${selector}`
4999
- : selector;
5000
- let current = this.$.parent();
5001
- while (current.length > 0) {
5002
- if (current.is(search)) {
5003
- const comp = current.data('_component');
5004
- if (comp instanceof Jqhtml_Component) {
5005
- return comp;
5006
- }
5007
- }
5008
- current = current.parent();
5009
- }
5010
- return null;
5011
- }
5012
- // -------------------------------------------------------------------------
5013
- // Static Methods
5014
- // -------------------------------------------------------------------------
5265
+ on_viewport_resize(viewport_width) { }
5015
5266
  /**
5016
- * Get CSS class hierarchy for this component type
5267
+ * Should component re-render after load?
5268
+ * By default, only re-renders if data has changed
5269
+ * Override to control re-rendering behavior
5017
5270
  */
5018
- static get_class_hierarchy() {
5019
- // v2.2.13 - Fixed to handle undefined values in prototype chain
5020
- const classes = [];
5021
- let ctor = this;
5022
- while (ctor) {
5023
- // Check if constructor has a valid name property
5024
- if (!ctor.name || typeof ctor.name !== 'string') {
5025
- // console.warn('[JQHTML v2.2.13] Invalid constructor name in hierarchy:', ctor);
5026
- break;
5027
- }
5028
- // Only add valid class names (non-empty strings, not 'Object')
5029
- if (ctor.name !== 'Object' && ctor.name !== '') {
5030
- // Normalize base class names - handle different import patterns
5031
- let normalizedName = ctor.name;
5032
- if (normalizedName === '_Jqhtml_Component' || normalizedName === '_Base_Jqhtml_Component') {
5033
- normalizedName = 'Component'; // Use 'Component' instead of 'Jqhtml_Component' for CSS class
5034
- }
5035
- else if (normalizedName === 'Jqhtml_Component') {
5036
- normalizedName = 'Component'; // Use 'Component' instead of 'Jqhtml_Component' for CSS class
5037
- }
5038
- classes.push(normalizedName);
5039
- }
5040
- // Get the next prototype
5041
- const nextProto = Object.getPrototypeOf(ctor);
5042
- // Stop if we've reached the end of the chain
5043
- if (!nextProto || nextProto === Object.prototype || nextProto.constructor === Object) {
5044
- break;
5045
- }
5046
- ctor = nextProto;
5047
- }
5048
- return classes;
5049
- }
5050
- // -------------------------------------------------------------------------
5051
- // Private Implementation
5052
- // -------------------------------------------------------------------------
5053
- _generate_cid() {
5054
- return uid();
5055
- }
5056
- _apply_css_classes() {
5057
- const hierarchy = this.constructor.get_class_hierarchy();
5058
- // If component name differs from class name, add component name to hierarchy
5059
- // This happens when:
5060
- // 1. Using base Jqhtml_Component with _component_name
5061
- // 2. Using parent class via extends chain (e.g., Contacts_DataGrid using DataGrid_Abstract class)
5062
- const classesToAdd = [...hierarchy];
5063
- if (this.args._component_name && this.args._component_name !== this.constructor.name) {
5064
- // Add component name at the beginning (most specific)
5065
- classesToAdd.unshift(this.args._component_name);
5066
- }
5067
- // Filter out private classes (starting with _) and invalid class names
5068
- const publicClasses = classesToAdd.filter(className => {
5069
- // Guard against undefined, null, or non-string values
5070
- if (!className || typeof className !== 'string') {
5071
- console.warn('[JQHTML] Filtered out invalid class name:', className);
5072
- return false;
5073
- }
5074
- return !className.startsWith('_');
5075
- });
5076
- if (publicClasses.length > 0) {
5077
- this.$.addClass(publicClasses.join(' '));
5078
- }
5079
- }
5080
- _apply_default_attributes() {
5081
- // Get template using same logic as render() method
5082
- let template;
5083
- // If we have a component name, try looking up by name first (for unregistered components)
5084
- if (this.args._component_name) {
5085
- template = get_template(this.args._component_name);
5086
- }
5087
- else {
5088
- // Otherwise look up by class
5089
- template = get_template_by_class(this.constructor);
5090
- }
5091
- if (!template)
5092
- return;
5093
- // Walk the extends chain to collect all defaultAttributes from parent templates
5094
- // Apply from parent to child so child attributes take precedence
5095
- const templateChain = [];
5096
- let currentTemplate = template;
5097
- // Build chain from child to parent
5098
- while (currentTemplate) {
5099
- templateChain.unshift(currentTemplate); // Add to front so parent comes first
5100
- // Check if this template extends another
5101
- if (currentTemplate.extends) {
5102
- try {
5103
- currentTemplate = get_template(currentTemplate.extends);
5104
- }
5105
- catch (error) {
5106
- // Parent template not found, stop chain
5107
- break;
5108
- }
5109
- }
5110
- else {
5111
- break;
5112
- }
5113
- }
5114
- // Apply defaultAttributes from each template in the chain (parent first, child last)
5115
- for (const tmpl of templateChain) {
5116
- if (!tmpl.defaultAttributes)
5117
- continue;
5118
- // Filter out 'tag' since it determines tag name, not an attribute
5119
- const defineAttrs = { ...tmpl.defaultAttributes };
5120
- delete defineAttrs.tag;
5121
- // Debug logging
5122
- if (window.jqhtml?.debug?.enabled) {
5123
- const componentName = tmpl.name || this.args._component_name || this.constructor.name;
5124
- console.log(`[Component] Applying defaultAttributes for ${componentName}:`, defineAttrs);
5125
- }
5126
- // Apply each default attribute
5127
- for (const [key, value] of Object.entries(defineAttrs)) {
5128
- if (key === 'class') {
5129
- // Special handling for class - merge with existing
5130
- const existingClasses = this.$.attr('class');
5131
- if (existingClasses) {
5132
- const existing = existingClasses.split(/\s+/).filter(c => c);
5133
- const newClasses = String(value).split(/\s+/).filter(c => c);
5134
- for (const newClass of newClasses) {
5135
- if (!existing.includes(newClass)) {
5136
- existing.push(newClass);
5137
- }
5138
- }
5139
- this.$.attr('class', existing.join(' '));
5140
- }
5141
- else {
5142
- this.$.attr('class', value);
5143
- }
5144
- }
5145
- else if (key === 'style') {
5146
- // Special handling for style - merge with existing
5147
- // Define attributes are applied AFTER invocation attributes
5148
- // So we only add Define style properties that don't already exist
5149
- // This ensures invocation wins conflicts (invocation overrides Define)
5150
- const existingStyle = this.$.attr('style');
5151
- if (existingStyle) {
5152
- // Parse existing styles (from invocation)
5153
- const existingRules = new Map();
5154
- existingStyle.split(';').forEach(rule => {
5155
- const [prop, val] = rule.split(':').map(s => s.trim());
5156
- if (prop && val)
5157
- existingRules.set(prop, val);
5158
- });
5159
- // Parse Define styles and only add if not already present
5160
- String(value).split(';').forEach(rule => {
5161
- const [prop, val] = rule.split(':').map(s => s.trim());
5162
- if (prop && val && !existingRules.has(prop)) {
5163
- // Only add if property doesn't exist (invocation wins)
5164
- existingRules.set(prop, val);
5165
- }
5166
- });
5167
- // Build merged style string
5168
- const merged = Array.from(existingRules.entries())
5169
- .map(([prop, val]) => `${prop}: ${val}`)
5170
- .join('; ');
5171
- this.$.attr('style', merged);
5172
- }
5173
- else {
5174
- this.$.attr('style', value);
5175
- }
5176
- }
5177
- else if (key.startsWith('$') || key.startsWith('data-')) {
5178
- // Data attributes - also update args
5179
- const dataKey = key.startsWith('$') ? key.substring(1) :
5180
- key.startsWith('data-') ? key.substring(5) : key;
5181
- // Only apply if not already set in args
5182
- if (!(dataKey in this.args)) {
5183
- this.args[dataKey] = value;
5184
- this.$.data(dataKey, value);
5185
- this.$.attr(key.startsWith('$') ? `data-${dataKey}` : key, String(value));
5186
- }
5187
- }
5188
- else {
5189
- // Regular attributes - apply directly if not already set
5190
- if (!this.$.attr(key)) {
5191
- this.$.attr(key, value);
5192
- }
5193
- }
5271
+ /**
5272
+ * Internal method to determine if component should re-render after on_load()
5273
+ * @private
5274
+ */
5275
+ _should_rerender() {
5276
+ // HTML CACHE MODE - If we used cached HTML, always re-render to get live components
5277
+ if (this._used_cached_html) {
5278
+ if (window.jqhtml?.debug?.verbose) {
5279
+ console.log(`[Cache html] Component ${this._cid} (${this.component_name()}) forcing re-render after cached HTML`);
5194
5280
  }
5281
+ // Clear the flag
5282
+ this._used_cached_html = false;
5283
+ return true;
5195
5284
  }
5196
- }
5197
- _set_attributes() {
5198
- // data-cid on the rendered element is debug-only: it mirrors this._cid so component
5199
- // boundaries are legible in DevTools. The runtime never reads it - scoping uses the
5200
- // _cid property, and the transient data-cid placeholder the instruction processor
5201
- // matches on is written and removed before this ever runs.
5202
- if (debug_attributes_enabled()) {
5203
- this.$.attr('data-cid', this._cid);
5285
+ // OPTIMIZATION: If no custom on_load(), data cannot change, skip serialization
5286
+ // Data is frozen after on_create() and only unfrozen during on_load()
5287
+ if (!this.__has_custom_on_load) {
5288
+ return false;
5204
5289
  }
5205
- // Only set lifecycle state attribute if verbose mode enabled
5206
- if (window.jqhtml?.debug?.verbose) {
5207
- this.$.attr('data-_lifecycle-state', this._ready_state.toString());
5290
+ // Compare current data state with data state before initial render
5291
+ const currentDataState = JSON.stringify(this.data);
5292
+ const dataChanged = this._data_before_render !== currentDataState;
5293
+ // Update stored state for next comparison
5294
+ if (dataChanged) {
5295
+ this._data_before_render = currentDataState;
5208
5296
  }
5297
+ return dataChanged;
5209
5298
  }
5210
- _update_debug_attrs() {
5211
- // Only update lifecycle state attribute if verbose mode enabled
5212
- if (window.jqhtml?.debug?.verbose) {
5213
- this.$.attr('data-_lifecycle-state', this._ready_state.toString());
5214
- }
5299
+ // -------------------------------------------------------------------------
5300
+ // Public API
5301
+ // -------------------------------------------------------------------------
5302
+ /**
5303
+ * Get component name for debugging
5304
+ */
5305
+ /**
5306
+ * The name this component was invoked as - the tag written in the template
5307
+ * (<User_Card> -> 'User_Card'), the name given to $(el).component('User_Card'),
5308
+ * or the boot placeholder's data-component-init-name. For a template-only
5309
+ * component this is the template name, not 'Jqhtml_Component'. Falls back to
5310
+ * the class's static component_name, then its JS class name.
5311
+ */
5312
+ component_name() {
5313
+ return this._component_name;
5215
5314
  }
5216
- _find_dom_parent() {
5217
- let current = this.$.parent();
5218
- while (current.length > 0) {
5219
- const parent = current.data('_component');
5220
- if (parent instanceof Jqhtml_Component) {
5221
- this._dom_parent = parent;
5222
- parent._dom_children.add(this);
5223
- break;
5224
- }
5225
- current = current.parent();
5226
- }
5315
+ /**
5316
+ * Register event callback - delegates to component-events.ts
5317
+ * @see component-events.ts for full documentation
5318
+ */
5319
+ on(event_name, callback) {
5320
+ return event_on(this, event_name, callback);
5227
5321
  }
5228
5322
  /**
5229
- * Get DOM children (components in DOM subtree)
5230
- * Uses fast _dom_children registry when possible, falls back to DOM traversal for off-DOM components
5231
- * @private - Used internally for lifecycle coordination
5323
+ * Register a callback that fires exactly once - delegates to component-events.ts
5324
+ * If the event already occurred, fires immediately and does not register.
5325
+ * @see component-events.ts for full documentation
5232
5326
  */
5233
- _get_dom_children() {
5234
- // If component was off-DOM during render, children couldn't register via _find_dom_parent()
5235
- // Use DOM traversal to find direct children (works off-DOM, slightly slower)
5236
- if (this._use_dom_fallback) {
5237
- const directChildren = [];
5238
- this.$.find('.Component').each((_, el) => {
5239
- const $el = $(el);
5240
- const comp = $el.data('_component');
5241
- if (comp instanceof Jqhtml_Component) {
5242
- // Only include if this component is the direct parent (not a grandparent)
5243
- // Check: closest parent component is us (or no parent = we're the root)
5244
- const closestParent = $el.parent().closest('.Component');
5245
- if (closestParent.length === 0 || closestParent.data('_component') === this) {
5246
- directChildren.push(comp);
5247
- }
5248
- }
5249
- });
5250
- return directChildren;
5251
- }
5252
- // Fast path: component was in-DOM during render, children registered normally
5253
- // Filter out any that have since been removed from DOM (destroyed/replaced)
5254
- const children = Array.from(this._dom_children);
5255
- return children.filter(child => {
5256
- return $.contains(document.documentElement, child.$[0]);
5257
- });
5327
+ once(event_name, callback) {
5328
+ return event_once(this, event_name, callback);
5258
5329
  }
5259
- _log_lifecycle(phase, status) {
5260
- // Use new debug module
5261
- logLifecycle(this, phase, status);
5262
- // Keep legacy support for window.JQHTML_DEBUG
5263
- if (typeof window !== 'undefined' && window.JQHTML_DEBUG) {
5264
- window.JQHTML_DEBUG.log(this.component_name(), phase, status, {
5265
- cid: this._cid,
5266
- ready_state: this._ready_state,
5267
- args: this.args
5268
- });
5269
- }
5330
+ /**
5331
+ * Trigger a lifecycle event - delegates to component-events.ts
5332
+ * @see component-events.ts for full documentation
5333
+ */
5334
+ trigger(event_name, data) {
5335
+ event_trigger(this, event_name, data);
5270
5336
  }
5271
- _log_debug(action, ...args) {
5272
- if (typeof window !== 'undefined' && window.JQHTML_DEBUG) {
5273
- window.JQHTML_DEBUG.log(this.component_name(), 'debug', `${action}: ${args.map(a => JSON.stringify(a)).join(', ')}`);
5337
+ /**
5338
+ * Check if any callbacks are registered for a given event
5339
+ */
5340
+ _on_registered(event_name) {
5341
+ return event_on_registered(this, event_name);
5342
+ }
5343
+ /**
5344
+ * Invalidate a lifecycle event - delegates to component-events.ts
5345
+ * @see component-events.ts for full documentation
5346
+ */
5347
+ invalidate(event_name) {
5348
+ event_invalidate(this, event_name);
5349
+ }
5350
+ /**
5351
+ * Find element by scoped ID
5352
+ *
5353
+ * Searches for elements with id="local_id:THIS_COMPONENT_CID"
5354
+ *
5355
+ * Example:
5356
+ * Template: <button $sid="save_btn">Save</button>
5357
+ * Rendered: <button id="save_btn:abc123" data-sid="save_btn">Save</button>
5358
+ * Access: this.$sid('save_btn') // Returns jQuery element
5359
+ *
5360
+ * Performance: Uses native document.getElementById() when component is in DOM,
5361
+ * falls back to jQuery.find() for components not yet attached to DOM.
5362
+ *
5363
+ * @param local_id The local ID (without _cid suffix)
5364
+ * @returns jQuery element with id="local_id:_cid", or empty jQuery object if not found
5365
+ */
5366
+ $sid(local_id) {
5367
+ const scopedId = `${local_id}:${this._cid}`;
5368
+ // Try getElementById first (fast path - works when component is in DOM)
5369
+ const el = document.getElementById(scopedId);
5370
+ if (el) {
5371
+ return $(el);
5274
5372
  }
5373
+ // Fallback: component not in DOM yet, search within component subtree
5374
+ // This allows $sid() to work on components before they're appended to body
5375
+ // Must escape the ID because it contains ':' which jQuery treats as a pseudo-selector
5376
+ return this.$.find(`#${$.escapeSelector(scopedId)}`);
5275
5377
  }
5276
- }
5277
- // Static properties
5278
- Jqhtml_Component.__jqhtml_component = true; // Marker for unified register() detection
5279
- // A bare component name, as accepted by closest() in place of a class selector
5280
- Jqhtml_Component.COMPONENT_NAME_PATTERN = /^[A-Z][A-Za-z0-9_]*$/;
5281
-
5282
- /**
5283
- * JQHTML v2 Template Renderer
5284
- *
5285
- * Connects compiled templates to components
5286
- * Processes instruction arrays and handles bindings
5287
- */
5288
- /**
5289
- * Process slot-only template inheritance
5290
- *
5291
- * When a component's template returns {_slots: {...}}, walk the prototype
5292
- * chain to find a parent template and invoke it with the child's slots as content.
5293
- *
5294
- * @param component The component instance
5295
- * @param childSlots The slots object from the child template
5296
- * @returns [instructions, context] tuple or null if no parent found
5297
- */
5298
- async function process_slot_inheritance(component, childSlots) {
5299
- // Walk the prototype chain to find parent class with template
5300
- let currentClass = Object.getPrototypeOf(component.constructor);
5301
- console.log(`[JQHTML] Walking prototype chain for ${component.constructor.name}`);
5302
- while (currentClass && currentClass !== Jqhtml_Component && currentClass.name !== 'Object') {
5303
- const className = currentClass.name;
5304
- console.log(`[JQHTML] Checking parent class: ${className}`);
5305
- // Skip internal framework classes
5306
- if (className === '_Jqhtml_Component' || className === '_Base_Jqhtml_Component') {
5307
- currentClass = Object.getPrototypeOf(currentClass);
5308
- continue;
5378
+ /**
5379
+ * Get component instance by scoped ID
5380
+ *
5381
+ * Convenience method that finds element by scoped ID and returns the component instance.
5382
+ *
5383
+ * Example:
5384
+ * Template: <User_Card $sid="active_user" />
5385
+ * Access: const user = this.sid('active_user'); // Returns User_Card instance
5386
+ * user.data.name // Access component's data
5387
+ *
5388
+ * To get the scoped ID string itself:
5389
+ * this.$sid('active_user').attr('id') // Returns "active_user:abc123xyz"
5390
+ *
5391
+ * @param local_id The local ID (without _cid suffix)
5392
+ * @returns Component instance or null if not found or not a component
5393
+ */
5394
+ sid(local_id) {
5395
+ const element = this.$sid(local_id);
5396
+ const component = element.data('_component');
5397
+ // If no component found but element exists, warn developer
5398
+ if (!component && element.length > 0) {
5399
+ console.warn(`Component ${this.constructor.name} tried to call .sid('${local_id}') - ` +
5400
+ `${local_id} exists, however, it is not a component or $redrawable. ` +
5401
+ `Did you forget to add $redrawable to the tag?`);
5309
5402
  }
5310
- // Try to find template for this parent class
5311
- try {
5312
- const parentTemplate = get_template(className);
5313
- console.log(`[JQHTML] Template found for ${className}:`, parentTemplate ? parentTemplate.name : 'null');
5314
- // Check if we got the default template (means no real template found)
5315
- if (parentTemplate && parentTemplate.name !== 'Jqhtml_Component') {
5316
- console.log(`[JQHTML] Invoking parent template ${className}`);
5317
- // Found a real parent template - invoke it with child's slots as content
5318
- const [parentInstructions, parentContext] = parentTemplate.render.call(component, component.data, component.args, childSlots // Pass child slots as content parameter
5319
- );
5320
- // Check if parent also returns slots (recursive inheritance)
5321
- if (parentInstructions && typeof parentInstructions === 'object' && parentInstructions._slots) {
5322
- // Parent also has slot-only template - recurse
5323
- console.log(`[JQHTML] Parent also slot-only, recursing`);
5324
- return await process_slot_inheritance(component, parentInstructions._slots);
5403
+ return component || null;
5404
+ }
5405
+ /**
5406
+ * Get the component that instantiated this component (rendered it in their template)
5407
+ * Returns null if component was created programmatically via $().component()
5408
+ */
5409
+ instantiator() {
5410
+ return this._instantiator;
5411
+ }
5412
+ /**
5413
+ * Find descendant components by CSS selector
5414
+ */
5415
+ find(selector) {
5416
+ const components = [];
5417
+ this.$.find(selector).each((_, el) => {
5418
+ const comp = $(el).data('_component');
5419
+ if (comp instanceof Jqhtml_Component) {
5420
+ components.push(comp);
5421
+ }
5422
+ });
5423
+ return components;
5424
+ }
5425
+ /**
5426
+ * Find closest ancestor component matching selector
5427
+ *
5428
+ * A bare component name - a plain identifier starting with a capital letter,
5429
+ * optionally preceded by a single underscore, such as 'Parent_Dashboard' or
5430
+ * '_Root_Layout' - is treated as the component-name class
5431
+ * selector '.Parent_Dashboard'. Components carry a CSS class for every name
5432
+ * in their prototype chain, so a base class name matches its subclasses too.
5433
+ * Every other selector ('.Foo', '#id', '[attr]', 'div > .Component') is
5434
+ * passed to jQuery unchanged.
5435
+ */
5436
+ closest(selector) {
5437
+ const search = Jqhtml_Component.COMPONENT_NAME_PATTERN.test(selector)
5438
+ ? `.${selector}`
5439
+ : selector;
5440
+ let current = this.$.parent();
5441
+ while (current.length > 0) {
5442
+ if (current.is(search)) {
5443
+ const comp = current.data('_component');
5444
+ if (comp instanceof Jqhtml_Component) {
5445
+ return comp;
5325
5446
  }
5326
- // Parent returned HTML - we're done
5327
- console.log(`[JQHTML] Parent returned instructions, inheritance complete`);
5328
- return [parentInstructions, parentContext];
5329
5447
  }
5448
+ current = current.parent();
5330
5449
  }
5331
- catch (error) {
5332
- console.warn(`[JQHTML] Error looking up parent template for ${className}:`, error);
5450
+ return null;
5451
+ }
5452
+ // -------------------------------------------------------------------------
5453
+ // Static Methods
5454
+ // -------------------------------------------------------------------------
5455
+ /**
5456
+ * Get CSS class hierarchy for this component type
5457
+ */
5458
+ static get_class_hierarchy() {
5459
+ // v2.2.13 - Fixed to handle undefined values in prototype chain
5460
+ const classes = [];
5461
+ let ctor = this;
5462
+ while (ctor) {
5463
+ // Check if constructor has a valid name property
5464
+ if (!ctor.name || typeof ctor.name !== 'string') {
5465
+ // console.warn('[JQHTML v2.2.13] Invalid constructor name in hierarchy:', ctor);
5466
+ break;
5467
+ }
5468
+ // Only add valid class names (non-empty strings, not 'Object')
5469
+ if (ctor.name !== 'Object' && ctor.name !== '') {
5470
+ // Normalize base class names - handle different import patterns
5471
+ let normalizedName = ctor.name;
5472
+ if (normalizedName === '_Jqhtml_Component' || normalizedName === '_Base_Jqhtml_Component') {
5473
+ normalizedName = 'Component'; // Use 'Component' instead of 'Jqhtml_Component' for CSS class
5474
+ }
5475
+ else if (normalizedName === 'Jqhtml_Component') {
5476
+ normalizedName = 'Component'; // Use 'Component' instead of 'Jqhtml_Component' for CSS class
5477
+ }
5478
+ classes.push(normalizedName);
5479
+ }
5480
+ // Get the next prototype
5481
+ const nextProto = Object.getPrototypeOf(ctor);
5482
+ // Stop if we've reached the end of the chain
5483
+ if (!nextProto || nextProto === Object.prototype || nextProto.constructor === Object) {
5484
+ break;
5485
+ }
5486
+ ctor = nextProto;
5333
5487
  }
5334
- // Move to next parent
5335
- currentClass = Object.getPrototypeOf(currentClass);
5488
+ return classes;
5336
5489
  }
5337
- // No parent template found
5338
- console.warn(`[JQHTML] No parent template found after walking chain`);
5339
- return null;
5340
- }
5341
- /**
5342
- * Render a template for a component
5343
- * Templates are functions that return [instructions, context] tuples
5344
- */
5345
- async function render_template(component, template_fn) {
5346
- // Get template from registry if not provided
5347
- let render_fn = template_fn;
5348
- if (!render_fn) {
5349
- const template_def = get_template_by_class(component.constructor);
5350
- render_fn = template_def.render;
5490
+ // -------------------------------------------------------------------------
5491
+ // Private Implementation
5492
+ // -------------------------------------------------------------------------
5493
+ _generate_cid() {
5494
+ return uid();
5351
5495
  }
5352
- if (!render_fn) {
5353
- // No template, component should handle its own rendering
5354
- return;
5496
+ _apply_css_classes() {
5497
+ const hierarchy = this.constructor.get_class_hierarchy();
5498
+ // If component name differs from class name, add component name to hierarchy
5499
+ // This happens when:
5500
+ // 1. Using base Jqhtml_Component with _component_name
5501
+ // 2. Using parent class via extends chain (e.g., Contacts_DataGrid using DataGrid_Abstract class)
5502
+ const classesToAdd = [...hierarchy];
5503
+ if (this.args._component_name && this.args._component_name !== this.constructor.name) {
5504
+ // Add component name at the beginning (most specific)
5505
+ classesToAdd.unshift(this.args._component_name);
5506
+ }
5507
+ // Filter out private/mangled classes (starting with _) and invalid class names.
5508
+ // A component name with the reserved single-underscore prefix (_Root_Layout)
5509
+ // is public and is kept - see component-name.ts.
5510
+ const publicClasses = classesToAdd.filter(className => {
5511
+ // Guard against undefined, null, or non-string values
5512
+ if (!className || typeof className !== 'string') {
5513
+ console.warn('[JQHTML] Filtered out invalid class name:', className);
5514
+ return false;
5515
+ }
5516
+ return !className.startsWith('_') || is_component_name(className);
5517
+ });
5518
+ if (publicClasses.length > 0) {
5519
+ this.$.addClass(publicClasses.join(' '));
5520
+ }
5355
5521
  }
5356
- // Clear existing content
5357
- component.$.empty();
5358
- // Execute template function
5359
- // Templates receive: (data, args, content)
5360
- // Provide a default empty content function if none provided
5361
- const defaultContent = () => '';
5362
- let [instructions, context] = render_fn.call(component, component.data, component.args, defaultContent // Default content function that returns empty string
5363
- );
5364
- // Check for slot-only template inheritance
5365
- // If instructions is {_slots: {...}}, this is a slot-only template
5366
- // We need to find the parent template and invoke it with these slots
5367
- if (instructions && typeof instructions === 'object' && instructions._slots) {
5368
- console.log(`[JQHTML] Slot-only template detected for ${component.constructor.name}, invoking inheritance`);
5369
- const result = await process_slot_inheritance(component, instructions._slots);
5370
- if (result) {
5371
- console.log(`[JQHTML] Parent template found, using parent instructions`);
5372
- instructions = result[0];
5373
- context = result[1];
5522
+ _apply_default_attributes() {
5523
+ // Get template using same logic as render() method
5524
+ let template;
5525
+ // If we have a component name, try looking up by name first (for unregistered components)
5526
+ if (this.args._component_name) {
5527
+ template = get_template(this.args._component_name);
5374
5528
  }
5375
5529
  else {
5376
- console.warn(`[JQHTML] No parent template found for ${component.constructor.name}, rendering empty`);
5377
- // No parent template found - return empty
5378
- instructions = [];
5530
+ // Otherwise look up by class
5531
+ template = get_template_by_class(this.constructor);
5379
5532
  }
5380
- }
5381
- // Process instructions to generate DOM
5382
- await process_instructions(instructions, component.$, component);
5383
- // Process bindings after DOM is created
5384
- await process_bindings(component);
5385
- // Attach event handlers
5386
- await attach_event_handlers(component);
5387
- }
5388
- /**
5389
- * Process data bindings (attributes created by :prop syntax)
5390
- */
5391
- async function process_bindings(component) {
5392
- // Find all elements with data-bind-* attributes
5393
- component.$.find('[data-bind-prop], [data-bind-value], [data-bind-text], [data-bind-html], [data-bind-class], [data-bind-style]').each((_, element) => {
5394
- const el = $(element);
5395
- const attrs = element.attributes;
5396
- for (let i = 0; i < attrs.length; i++) {
5397
- const attr = attrs[i];
5398
- if (attr.name.startsWith('data-bind-')) {
5399
- const binding_type = attr.name.substring(10); // Remove 'data-bind-'
5400
- const expression = attr.value;
5533
+ if (!template)
5534
+ return;
5535
+ // Walk the extends chain to collect all defaultAttributes from parent templates
5536
+ // Apply from parent to child so child attributes take precedence
5537
+ const templateChain = [];
5538
+ let currentTemplate = template;
5539
+ // Build chain from child to parent
5540
+ while (currentTemplate) {
5541
+ templateChain.unshift(currentTemplate); // Add to front so parent comes first
5542
+ // Check if this template extends another
5543
+ if (currentTemplate.extends) {
5401
5544
  try {
5402
- // Evaluate expression in component context
5403
- const value = evaluate_expression(expression, component);
5404
- // Apply binding based on type
5405
- switch (binding_type) {
5406
- case 'prop':
5407
- // Generic property binding
5408
- const prop_name = el.attr('data-bind-prop-name') || 'value';
5409
- el.prop(prop_name, value);
5410
- break;
5411
- case 'value':
5412
- el.val(value);
5413
- break;
5414
- case 'text':
5415
- el.text(value);
5416
- break;
5417
- case 'html':
5418
- el.html(value);
5419
- break;
5420
- case 'class':
5421
- if (typeof value === 'object') {
5422
- // Object syntax: {active: true, disabled: false}
5423
- Object.entries(value).forEach(([className, enabled]) => {
5424
- el.toggleClass(className, !!enabled);
5425
- });
5426
- }
5427
- else {
5428
- // String syntax
5429
- el.addClass(String(value));
5430
- }
5431
- break;
5432
- case 'style':
5433
- if (typeof value === 'object') {
5434
- el.css(value);
5545
+ currentTemplate = get_template(currentTemplate.extends);
5546
+ }
5547
+ catch (error) {
5548
+ // Parent template not found, stop chain
5549
+ break;
5550
+ }
5551
+ }
5552
+ else {
5553
+ break;
5554
+ }
5555
+ }
5556
+ // Apply defaultAttributes from each template in the chain (parent first, child last)
5557
+ for (const tmpl of templateChain) {
5558
+ if (!tmpl.defaultAttributes)
5559
+ continue;
5560
+ // Filter out 'tag' since it determines tag name, not an attribute
5561
+ const defineAttrs = { ...tmpl.defaultAttributes };
5562
+ delete defineAttrs.tag;
5563
+ // Debug logging
5564
+ if (window.jqhtml?.debug?.enabled) {
5565
+ const componentName = tmpl.name || this.args._component_name || this.constructor.name;
5566
+ console.log(`[Component] Applying defaultAttributes for ${componentName}:`, defineAttrs);
5567
+ }
5568
+ // Apply each default attribute
5569
+ for (const [key, value] of Object.entries(defineAttrs)) {
5570
+ if (key === 'class') {
5571
+ // Special handling for class - merge with existing
5572
+ const existingClasses = this.$.attr('class');
5573
+ if (existingClasses) {
5574
+ const existing = existingClasses.split(/\s+/).filter(c => c);
5575
+ const newClasses = String(value).split(/\s+/).filter(c => c);
5576
+ for (const newClass of newClasses) {
5577
+ if (!existing.includes(newClass)) {
5578
+ existing.push(newClass);
5435
5579
  }
5436
- else {
5437
- el.attr('style', String(value));
5580
+ }
5581
+ this.$.attr('class', existing.join(' '));
5582
+ }
5583
+ else {
5584
+ this.$.attr('class', value);
5585
+ }
5586
+ }
5587
+ else if (key === 'style') {
5588
+ // Special handling for style - merge with existing
5589
+ // Define attributes are applied AFTER invocation attributes
5590
+ // So we only add Define style properties that don't already exist
5591
+ // This ensures invocation wins conflicts (invocation overrides Define)
5592
+ const existingStyle = this.$.attr('style');
5593
+ if (existingStyle) {
5594
+ // Parse existing styles (from invocation)
5595
+ const existingRules = new Map();
5596
+ existingStyle.split(';').forEach(rule => {
5597
+ const [prop, val] = rule.split(':').map(s => s.trim());
5598
+ if (prop && val)
5599
+ existingRules.set(prop, val);
5600
+ });
5601
+ // Parse Define styles and only add if not already present
5602
+ String(value).split(';').forEach(rule => {
5603
+ const [prop, val] = rule.split(':').map(s => s.trim());
5604
+ if (prop && val && !existingRules.has(prop)) {
5605
+ // Only add if property doesn't exist (invocation wins)
5606
+ existingRules.set(prop, val);
5438
5607
  }
5439
- break;
5440
- default:
5441
- // Custom binding - set as attribute
5442
- el.attr(binding_type, value);
5608
+ });
5609
+ // Build merged style string
5610
+ const merged = Array.from(existingRules.entries())
5611
+ .map(([prop, val]) => `${prop}: ${val}`)
5612
+ .join('; ');
5613
+ this.$.attr('style', merged);
5614
+ }
5615
+ else {
5616
+ this.$.attr('style', value);
5443
5617
  }
5444
5618
  }
5445
- catch (error) {
5446
- console.error(`Error evaluating binding "${expression}":`, error);
5619
+ else if (key.startsWith('$') || key.startsWith('data-')) {
5620
+ // Data attributes - also update args
5621
+ const dataKey = key.startsWith('$') ? key.substring(1) :
5622
+ key.startsWith('data-') ? key.substring(5) : key;
5623
+ // Only apply if not already set in args
5624
+ if (!(dataKey in this.args)) {
5625
+ this.args[dataKey] = value;
5626
+ this.$.data(dataKey, value);
5627
+ this.$.attr(key.startsWith('$') ? `data-${dataKey}` : key, String(value));
5628
+ }
5629
+ }
5630
+ else {
5631
+ // Regular attributes - apply directly if not already set
5632
+ if (!this.$.attr(key)) {
5633
+ this.$.attr(key, value);
5634
+ }
5447
5635
  }
5448
5636
  }
5449
5637
  }
5450
- });
5638
+ }
5639
+ _set_attributes() {
5640
+ // data-cid on the rendered element is debug-only: it mirrors this._cid so component
5641
+ // boundaries are legible in DevTools. The runtime never reads it - scoping uses the
5642
+ // _cid property, and the transient data-cid placeholder the instruction processor
5643
+ // matches on is written and removed before this ever runs.
5644
+ if (debug_attributes_enabled()) {
5645
+ this.$.attr('data-cid', this._cid);
5646
+ }
5647
+ // Only set lifecycle state attribute if verbose mode enabled
5648
+ if (window.jqhtml?.debug?.verbose) {
5649
+ this.$.attr('data-_lifecycle-state', this._ready_state.toString());
5650
+ }
5651
+ }
5652
+ _update_debug_attrs() {
5653
+ // Only update lifecycle state attribute if verbose mode enabled
5654
+ if (window.jqhtml?.debug?.verbose) {
5655
+ this.$.attr('data-_lifecycle-state', this._ready_state.toString());
5656
+ }
5657
+ }
5658
+ _find_dom_parent() {
5659
+ let current = this.$.parent();
5660
+ while (current.length > 0) {
5661
+ const parent = current.data('_component');
5662
+ if (parent instanceof Jqhtml_Component) {
5663
+ this._dom_parent = parent;
5664
+ parent._dom_children.add(this);
5665
+ break;
5666
+ }
5667
+ current = current.parent();
5668
+ }
5669
+ }
5670
+ /**
5671
+ * Get DOM children (components in DOM subtree)
5672
+ * Uses fast _dom_children registry when possible, falls back to DOM traversal for off-DOM components
5673
+ * @private - Used internally for lifecycle coordination
5674
+ */
5675
+ _get_dom_children() {
5676
+ // If component was off-DOM during render, children couldn't register via _find_dom_parent()
5677
+ // Use DOM traversal to find direct children (works off-DOM, slightly slower)
5678
+ if (this._use_dom_fallback) {
5679
+ const directChildren = [];
5680
+ this.$.find('.Component').each((_, el) => {
5681
+ const $el = $(el);
5682
+ const comp = $el.data('_component');
5683
+ if (comp instanceof Jqhtml_Component) {
5684
+ // Only include if this component is the direct parent (not a grandparent)
5685
+ // Check: closest parent component is us (or no parent = we're the root)
5686
+ const closestParent = $el.parent().closest('.Component');
5687
+ if (closestParent.length === 0 || closestParent.data('_component') === this) {
5688
+ directChildren.push(comp);
5689
+ }
5690
+ }
5691
+ });
5692
+ return directChildren;
5693
+ }
5694
+ // Fast path: component was in-DOM during render, children registered normally
5695
+ // Filter out any that have since been removed from DOM (destroyed/replaced)
5696
+ const children = Array.from(this._dom_children);
5697
+ return children.filter(child => {
5698
+ return $.contains(document.documentElement, child.$[0]);
5699
+ });
5700
+ }
5701
+ _log_lifecycle(phase, status) {
5702
+ // Use new debug module
5703
+ logLifecycle(this, phase, status);
5704
+ // Keep legacy support for window.JQHTML_DEBUG
5705
+ if (typeof window !== 'undefined' && window.JQHTML_DEBUG) {
5706
+ window.JQHTML_DEBUG.log(this.component_name(), phase, status, {
5707
+ cid: this._cid,
5708
+ ready_state: this._ready_state,
5709
+ args: this.args
5710
+ });
5711
+ }
5712
+ }
5713
+ _log_debug(action, ...args) {
5714
+ if (typeof window !== 'undefined' && window.JQHTML_DEBUG) {
5715
+ window.JQHTML_DEBUG.log(this.component_name(), 'debug', `${action}: ${args.map(a => JSON.stringify(a)).join(', ')}`);
5716
+ }
5717
+ }
5451
5718
  }
5719
+ // Static properties
5720
+ Jqhtml_Component.__jqhtml_component = true; // Marker for unified register() detection
5721
+ // A bare component name, as accepted by closest() in place of a class selector
5722
+ Jqhtml_Component.COMPONENT_NAME_PATTERN = COMPONENT_NAME_PATTERN;
5723
+
5724
+ var light_css = "html[data-jqhtml-debug] .jqhtml-debug-hit {\n outline: 2px solid #e5322d;\n outline-offset: -2px;\n}\n\nhtml[data-jqhtml-debug] .jqhtml-debug-hit.jqhtml-debug-depth-0 {\n outline-color: #e5322d;\n}\n\nhtml[data-jqhtml-debug] .jqhtml-debug-hit.jqhtml-debug-depth-1 {\n outline-color: #2f6fe4;\n}\n\nhtml[data-jqhtml-debug] .jqhtml-debug-hit.jqhtml-debug-depth-2 {\n outline-color: #1f9d55;\n}\n\nhtml[data-jqhtml-debug] .jqhtml-debug-hit.jqhtml-debug-depth-3 {\n outline-color: #d97706;\n}\n\nhtml[data-jqhtml-debug] .jqhtml-debug-hit.jqhtml-debug-depth-4 {\n outline-color: #7c3aed;\n}\n\nhtml[data-jqhtml-debug] .jqhtml-debug-hit.jqhtml-debug-depth-5 {\n outline-color: #0e7490;\n}";
5725
+
5726
+ var shadow_css = ":host {\n all: initial;\n display: block;\n position: fixed;\n box-sizing: border-box;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n z-index: 2147483647;\n pointer-events: none;\n font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, \"Liberation Mono\", monospace;\n font-size: 12px;\n font-weight: normal;\n font-style: normal;\n font-variant: normal;\n line-height: 1.4;\n color: #1c1c1c;\n text-align: left;\n text-transform: none;\n text-indent: 0;\n text-shadow: none;\n letter-spacing: normal;\n word-spacing: normal;\n white-space: normal;\n word-break: normal;\n overflow-wrap: anywhere;\n hyphens: none;\n tab-size: 4;\n direction: ltr;\n visibility: visible;\n cursor: default;\n list-style: none;\n quotes: none;\n}\n\n.jqhtml-debug-layer {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n overflow: hidden;\n pointer-events: none;\n}\n\n.jqhtml-debug-label {\n position: absolute;\n box-sizing: border-box;\n display: block;\n padding: 1px 5px;\n min-height: 18px;\n color: #ffffff;\n background: #e5322d;\n border-radius: 0 0 3px 0;\n font-size: 11px;\n line-height: 16px;\n white-space: normal;\n overflow-wrap: anywhere;\n overflow: hidden;\n pointer-events: none;\n}\n\n.jqhtml-debug-label.jqhtml-debug-depth-0 {\n background: #e5322d;\n}\n\n.jqhtml-debug-label.jqhtml-debug-depth-1 {\n background: #2f6fe4;\n}\n\n.jqhtml-debug-label.jqhtml-debug-depth-2 {\n background: #1f9d55;\n}\n\n.jqhtml-debug-label.jqhtml-debug-depth-3 {\n background: #d97706;\n}\n\n.jqhtml-debug-label.jqhtml-debug-depth-4 {\n background: #7c3aed;\n}\n\n.jqhtml-debug-label.jqhtml-debug-depth-5 {\n background: #0e7490;\n}\n\n.jqhtml-debug-label-name {\n font-weight: bold;\n}\n\n.jqhtml-debug-label-args {\n opacity: 0.9;\n margin-left: 6px;\n}\n\n.jqhtml-debug-modal {\n display: none;\n position: absolute;\n box-sizing: border-box;\n top: 24px;\n right: 24px;\n width: 520px;\n max-width: calc(100% - 48px);\n max-height: calc(100% - 48px);\n overflow: auto;\n padding: 0 0 12px 0;\n background: #ffffff;\n color: #1c1c1c;\n border: 1px solid #d0d0d0;\n border-radius: 6px;\n box-shadow: 0 8px 32px rgba(0, 0, 0, 0.25);\n pointer-events: auto;\n}\n\n.jqhtml-debug-modal.jqhtml-debug-modal-open {\n display: block;\n}\n\n.jqhtml-debug-title {\n display: flex;\n align-items: center;\n gap: 8px;\n position: sticky;\n top: 0;\n padding: 8px 12px;\n background: #1c1c1c;\n color: #ffffff;\n font-weight: bold;\n}\n\n.jqhtml-debug-title-name {\n flex: 1 1 auto;\n font-size: 13px;\n}\n\n.jqhtml-debug-button {\n all: unset;\n display: inline-block;\n box-sizing: border-box;\n padding: 2px 8px;\n border: 1px solid rgba(255, 255, 255, 0.6);\n border-radius: 3px;\n color: #ffffff;\n font-size: 11px;\n line-height: 16px;\n cursor: pointer;\n user-select: none;\n}\n\n.jqhtml-debug-button:hover {\n background: rgba(255, 255, 255, 0.15);\n}\n\n.jqhtml-debug-section {\n padding: 8px 12px 0 12px;\n}\n\n.jqhtml-debug-h {\n margin: 4px 0;\n color: #666666;\n font-size: 11px;\n text-transform: uppercase;\n letter-spacing: 0.06em;\n}\n\n.jqhtml-debug-table {\n display: grid;\n grid-template-columns: max-content max-content 1fr;\n column-gap: 12px;\n row-gap: 2px;\n align-items: baseline;\n}\n\n.jqhtml-debug-key {\n color: #005cc5;\n white-space: nowrap;\n}\n\n.jqhtml-debug-type {\n color: #666666;\n font-size: 11px;\n white-space: nowrap;\n}\n\n.jqhtml-debug-value {\n white-space: pre-wrap;\n overflow-wrap: anywhere;\n}\n\n.jqhtml-debug-empty {\n color: #666666;\n font-style: italic;\n}\n\n.jqhtml-debug-list {\n display: block;\n margin: 0;\n padding: 0;\n}\n\n.jqhtml-debug-link {\n display: block;\n padding: 2px 4px;\n margin: 0 -4px;\n border-radius: 3px;\n cursor: pointer;\n}\n\n.jqhtml-debug-link:hover {\n background: #eef3ff;\n}\n\n.jqhtml-debug-link-cid {\n color: #666666;\n margin-left: 6px;\n}\n\n.jqhtml-debug-note {\n margin-top: 4px;\n color: #92400e;\n font-size: 11px;\n}";
5727
+
5452
5728
  /**
5453
- * Attach event handlers (attributes created by @event syntax)
5729
+ * Component debug overlay.
5730
+ *
5731
+ * `jqhtml.debug_overlay.enable()` turns the page into an inspector: hovering
5732
+ * any element outlines the component under the pointer and every component
5733
+ * above it, each with a small tab naming the component and its simple args;
5734
+ * clicking opens a modal describing the innermost component (identity, args,
5735
+ * data, state, ancestry, instantiator) instead of firing the click. Alt+click
5736
+ * passes through. `disable()` puts everything back.
5737
+ *
5738
+ * Non-invasiveness, the design goal (details in ./CLAUDE.md):
5739
+ * - The overlay's own UI lives in a shadow root on a host element appended to
5740
+ * <body>, styled by shadow.scss. Page CSS cannot select into it and :host
5741
+ * cuts inheritance, so its look is fixed whatever the page does.
5742
+ * - The only thing added to application elements is a pair of classes,
5743
+ * .jqhtml-debug-hit / .jqhtml-debug-depth-N, which light.scss paints as an
5744
+ * inset outline (no layout effect) and only while <html data-jqhtml-debug>.
5745
+ * - Listeners are attached on enable and removed on disable. The stylesheets
5746
+ * and the (detached) host stay once installed: inert, and cheap to re-enable.
5747
+ * - Nothing is registered per component, so components created after enable
5748
+ * are covered automatically.
5454
5749
  */
5455
- async function attach_event_handlers(component) {
5456
- // Find all elements with data-on-* attributes
5457
- component.$.find('[data-on-click], [data-on-change], [data-on-submit], [data-on-keyup], [data-on-keydown], [data-on-focus], [data-on-blur]').each((_, element) => {
5458
- const el = $(element);
5459
- const attrs = element.attributes;
5460
- for (let i = 0; i < attrs.length; i++) {
5461
- const attr = attrs[i];
5462
- if (attr.name.startsWith('data-on-')) {
5463
- const event_name = attr.name.substring(8); // Remove 'data-on-'
5464
- const handler_expr = attr.value;
5465
- // Remove the attribute to avoid re-processing
5466
- el.removeAttr(attr.name);
5467
- // Attach event handler
5468
- el.on(event_name, function (event) {
5469
- try {
5470
- // Create handler function in component context
5471
- const handler = evaluate_handler(handler_expr, component);
5472
- if (typeof handler === 'function') {
5473
- // Call with component as 'this' and pass event
5474
- handler.call(component, event);
5475
- }
5476
- else {
5477
- // Expression to execute
5478
- evaluate_expression(handler_expr, component, { $event: event });
5479
- }
5480
- }
5481
- catch (error) {
5482
- console.error(`Error in ${event_name} handler "${handler_expr}":`, error);
5483
- }
5484
- });
5485
- }
5486
- }
5750
+ const PREFIX = 'jqhtml-debug-';
5751
+ const ROOT_ATTR = 'data-jqhtml-debug'; // on <html> while enabled - gates light.scss
5752
+ const HOST_ATTR = 'data-jqhtml-debug-root'; // the shadow host
5753
+ const LIGHT_STYLE_ID = 'jqhtml-debug-light-styles';
5754
+ const HIT_CLASS = `${PREFIX}hit`;
5755
+ const DEPTH_CLASS = `${PREFIX}depth-`;
5756
+ const DEPTH_COLORS = 6; // keep in step with $depth-colors in _tokens.scss
5757
+ const LABEL_HEIGHT = 18;
5758
+ const READY_STATES = ['created', 'init', 'loaded', 'rendered', 'ready'];
5759
+ const state = {
5760
+ enabled: false,
5761
+ host: null,
5762
+ shadow: null,
5763
+ layer: null,
5764
+ modal: null,
5765
+ chain: [],
5766
+ hit_elements: [],
5767
+ modal_component: null,
5768
+ };
5769
+ // ---------------------------------------------------------------------------
5770
+ // Public API
5771
+ // ---------------------------------------------------------------------------
5772
+ const debug_overlay = {
5773
+ /** Turn the overlay on. Returns false where there is no DOM (SSR). */
5774
+ enable() {
5775
+ if (typeof document === 'undefined' || !document.documentElement)
5776
+ return false;
5777
+ if (state.enabled)
5778
+ return true;
5779
+ install();
5780
+ if (!state.host.isConnected)
5781
+ (document.body || document.documentElement).appendChild(state.host);
5782
+ document.documentElement.setAttribute(ROOT_ATTR, '');
5783
+ document.addEventListener('mouseover', on_mouseover, true);
5784
+ document.addEventListener('mouseout', on_mouseout, true);
5785
+ document.addEventListener('click', on_click, true);
5786
+ document.addEventListener('keydown', on_keydown, true);
5787
+ document.addEventListener('scroll', on_reposition, true);
5788
+ window.addEventListener('resize', on_reposition);
5789
+ state.enabled = true;
5790
+ return true;
5791
+ },
5792
+ /** Turn the overlay off. Styles stay installed but match nothing. */
5793
+ disable() {
5794
+ if (!state.enabled)
5795
+ return;
5796
+ document.removeEventListener('mouseover', on_mouseover, true);
5797
+ document.removeEventListener('mouseout', on_mouseout, true);
5798
+ document.removeEventListener('click', on_click, true);
5799
+ document.removeEventListener('keydown', on_keydown, true);
5800
+ document.removeEventListener('scroll', on_reposition, true);
5801
+ window.removeEventListener('resize', on_reposition);
5802
+ clear_hover();
5803
+ close_modal();
5804
+ document.documentElement.removeAttribute(ROOT_ATTR);
5805
+ if (state.host && state.host.isConnected)
5806
+ state.host.remove();
5807
+ state.enabled = false;
5808
+ },
5809
+ is_enabled() {
5810
+ return state.enabled;
5811
+ },
5812
+ /**
5813
+ * Open the modal for a component, an element inside one, or a jQuery
5814
+ * object, without needing a click. Handy from the console and from tests.
5815
+ */
5816
+ inspect(target) {
5817
+ if (!state.enabled)
5818
+ return false;
5819
+ const component = target instanceof Jqhtml_Component
5820
+ ? target
5821
+ : chain_for(target && target.jquery ? target[0] : target)[0];
5822
+ if (!component)
5823
+ return false;
5824
+ open_modal(component);
5825
+ return true;
5826
+ },
5827
+ };
5828
+ // ---------------------------------------------------------------------------
5829
+ // Installation (once)
5830
+ // ---------------------------------------------------------------------------
5831
+ function install() {
5832
+ if (state.host)
5833
+ return;
5834
+ if (!document.getElementById(LIGHT_STYLE_ID)) {
5835
+ const style = document.createElement('style');
5836
+ style.id = LIGHT_STYLE_ID;
5837
+ style.textContent = light_css;
5838
+ document.head.appendChild(style);
5839
+ }
5840
+ const host = document.createElement('div');
5841
+ host.setAttribute(HOST_ATTR, '');
5842
+ const shadow = host.attachShadow({ mode: 'open' });
5843
+ const style = document.createElement('style');
5844
+ style.textContent = shadow_css;
5845
+ shadow.appendChild(style);
5846
+ const layer = el('div', 'layer');
5847
+ shadow.appendChild(layer);
5848
+ const modal = el('div', 'modal');
5849
+ shadow.appendChild(modal);
5850
+ state.host = host;
5851
+ state.shadow = shadow;
5852
+ state.layer = layer;
5853
+ state.modal = modal;
5854
+ }
5855
+ // ---------------------------------------------------------------------------
5856
+ // Component chain
5857
+ // ---------------------------------------------------------------------------
5858
+ /** Components from the one containing `node` outward to the root. */
5859
+ function chain_for(node) {
5860
+ const chain = [];
5861
+ let element = node instanceof Element ? node : (node && node.parentElement) || null;
5862
+ while (element) {
5863
+ const owner = element.closest('.Component');
5864
+ if (!owner)
5865
+ break;
5866
+ const component = $(owner).data('_component');
5867
+ if (component instanceof Jqhtml_Component && !component.$.hasClass('_Component_Stopped'))
5868
+ chain.push(component);
5869
+ element = owner.parentElement;
5870
+ }
5871
+ return chain;
5872
+ }
5873
+ function is_ours(event) {
5874
+ return !!state.host && event.composedPath().includes(state.host);
5875
+ }
5876
+ // ---------------------------------------------------------------------------
5877
+ // Hover
5878
+ // ---------------------------------------------------------------------------
5879
+ function on_mouseover(event) {
5880
+ if (is_ours(event))
5881
+ return;
5882
+ const chain = chain_for(event.target);
5883
+ if (chain[0] === state.chain[0])
5884
+ return;
5885
+ set_hover(chain);
5886
+ }
5887
+ function on_mouseout(event) {
5888
+ if (!event.relatedTarget)
5889
+ clear_hover(); // pointer left the document
5890
+ }
5891
+ function on_reposition() {
5892
+ if (state.chain.length)
5893
+ render_labels();
5894
+ }
5895
+ function set_hover(chain) {
5896
+ clear_hover();
5897
+ state.chain = chain;
5898
+ chain.forEach((component, depth) => {
5899
+ const element = component.$[0];
5900
+ element.classList.add(HIT_CLASS, DEPTH_CLASS + (depth % DEPTH_COLORS));
5901
+ state.hit_elements.push(element);
5487
5902
  });
5903
+ render_labels();
5904
+ }
5905
+ function clear_hover() {
5906
+ for (const element of state.hit_elements) {
5907
+ element.classList.remove(HIT_CLASS);
5908
+ for (let i = 0; i < DEPTH_COLORS; i++)
5909
+ element.classList.remove(DEPTH_CLASS + i);
5910
+ }
5911
+ state.hit_elements = [];
5912
+ state.chain = [];
5913
+ if (state.layer)
5914
+ state.layer.textContent = '';
5488
5915
  }
5489
5916
  /**
5490
- * Evaluate an expression in component context
5917
+ * One tab per component in the chain, pinned to the component's top-left
5918
+ * corner and no wider than the component. Outermost first so the innermost
5919
+ * paints on top; tabs that share a corner (a child filling its parent, the
5920
+ * usual case) stack downward instead of hiding each other.
5491
5921
  */
5492
- function evaluate_expression(expression, component, locals = {}) {
5493
- // Create evaluation context
5494
- const context = {
5495
- // Component properties
5496
- data: component.data,
5497
- args: component.args,
5498
- $: component.$,
5499
- // Component methods
5500
- $sid: component.$sid.bind(component),
5501
- // Locals (like $event)
5502
- ...locals
5503
- };
5504
- // Build function that evaluates in context
5505
- const keys = Object.keys(context);
5506
- const values = Object.values(context);
5507
- try {
5508
- // Use Function constructor for better performance than eval
5509
- const fn = new Function(...keys, `return (${expression})`);
5510
- return fn(...values);
5922
+ function render_labels() {
5923
+ const layer = state.layer;
5924
+ layer.textContent = '';
5925
+ const taken = new Map();
5926
+ for (let depth = state.chain.length - 1; depth >= 0; depth--) {
5927
+ const component = state.chain[depth];
5928
+ const rect = component.$[0].getBoundingClientRect();
5929
+ if (rect.width <= 0 || rect.height <= 0)
5930
+ continue;
5931
+ const left = Math.max(0, Math.round(rect.left));
5932
+ const top = Math.max(0, Math.round(rect.top));
5933
+ const key = `${left},${top}`;
5934
+ const stacked = taken.get(key) || 0;
5935
+ taken.set(key, stacked + 1);
5936
+ const label = el('div', `label ${PREFIX}depth-${depth % DEPTH_COLORS}`);
5937
+ label.style.left = `${left}px`;
5938
+ label.style.top = `${top + stacked * LABEL_HEIGHT}px`;
5939
+ label.style.maxWidth = `${Math.max(24, Math.round(rect.width))}px`;
5940
+ label.appendChild(el('span', 'label-name', component.component_name()));
5941
+ const args = simple_args(component);
5942
+ if (args)
5943
+ label.appendChild(el('span', 'label-args', args));
5944
+ layer.appendChild(label);
5511
5945
  }
5512
- catch (error) {
5513
- console.error(`Invalid expression: ${expression}`, error);
5514
- return undefined;
5946
+ }
5947
+ /** `$id=7 $title="Users"` - only strings, numbers and booleans, never internals. */
5948
+ function simple_args(component) {
5949
+ const parts = [];
5950
+ for (const [key, value] of Object.entries(component.args || {})) {
5951
+ if (key.startsWith('_'))
5952
+ continue;
5953
+ if (typeof value === 'string')
5954
+ parts.push(`$${key}=${JSON.stringify(truncate(value, 24))}`);
5955
+ else if (typeof value === 'number' || typeof value === 'boolean')
5956
+ parts.push(`$${key}=${value}`);
5515
5957
  }
5958
+ return parts.join(' ');
5516
5959
  }
5517
- /**
5518
- * Evaluate a handler expression (might be method name or inline code)
5519
- */
5520
- function evaluate_handler(expression, component) {
5521
- // Check if it's a method name on the component
5522
- if (expression in component && typeof component[expression] === 'function') {
5523
- return component[expression];
5960
+ // ---------------------------------------------------------------------------
5961
+ // Click -> modal
5962
+ // ---------------------------------------------------------------------------
5963
+ function on_click(event) {
5964
+ if (is_ours(event) || event.altKey)
5965
+ return;
5966
+ event.preventDefault();
5967
+ event.stopPropagation();
5968
+ event.stopImmediatePropagation();
5969
+ const chain = chain_for(event.target);
5970
+ if (!chain.length) {
5971
+ close_modal();
5972
+ return;
5524
5973
  }
5525
- // Otherwise treat as inline code
5974
+ open_modal(chain[0]);
5975
+ }
5976
+ function on_keydown(event) {
5977
+ if (event.key === 'Escape' && state.modal_component) {
5978
+ close_modal();
5979
+ event.stopPropagation();
5980
+ }
5981
+ }
5982
+ function close_modal() {
5983
+ if (!state.modal)
5984
+ return;
5985
+ state.modal.classList.remove(`${PREFIX}modal-open`);
5986
+ state.modal.textContent = '';
5987
+ state.modal_component = null;
5988
+ }
5989
+ function open_modal(component) {
5990
+ const modal = state.modal;
5991
+ modal.textContent = '';
5992
+ state.modal_component = component;
5993
+ const chain = chain_for(component.$[0]);
5994
+ const ancestors = chain.slice(1);
5995
+ const element = component.$[0];
5996
+ // Title bar
5997
+ const title = el('div', 'title');
5998
+ title.appendChild(el('span', 'title-name', `<${component.component_name()}>`));
5999
+ const log = el('button', 'button', 'Log to console');
6000
+ log.addEventListener('click', () => {
6001
+ console.log(`[JQHTML debug] <${component.component_name()}>`, component, element);
6002
+ });
6003
+ title.appendChild(log);
6004
+ const close = el('button', 'button', 'Close');
6005
+ close.addEventListener('click', close_modal);
6006
+ title.appendChild(close);
6007
+ modal.appendChild(title);
6008
+ // Identity
6009
+ const ctor = component.constructor;
6010
+ const hierarchy = ctor.get_class_hierarchy ? ctor.get_class_hierarchy() : [ctor.name];
6011
+ const identity = table();
6012
+ row(identity, 'name', '', component.component_name());
6013
+ row(identity, 'class', '', hierarchy.join(' → '));
6014
+ row(identity, 'element', '', describe_element(element));
6015
+ row(identity, '_cid', '', String(component._cid));
6016
+ row(identity, 'lifecycle', '', READY_STATES[component._ready_state] || String(component._ready_state));
6017
+ const nocache = element.getAttribute('data-nocache');
6018
+ if (nocache)
6019
+ row(identity, 'cache', '', `declined: ${nocache}`);
6020
+ modal.appendChild(section('Identity', identity));
6021
+ // Args / data / state
6022
+ modal.appendChild(section('Args', object_table(component.args)));
6023
+ modal.appendChild(section('Data', object_table(component.data)));
6024
+ modal.appendChild(section('State', object_table(component.state)));
6025
+ // Ancestry
6026
+ const list = el('div', 'list');
6027
+ if (!ancestors.length)
6028
+ list.appendChild(el('div', 'empty', 'none - this is a root component'));
6029
+ for (const ancestor of ancestors) {
6030
+ const link = el('div', 'link');
6031
+ link.appendChild(el('span', 'link-name', `<${ancestor.component_name()}>`));
6032
+ link.appendChild(el('span', 'link-cid', String(ancestor._cid)));
6033
+ link.addEventListener('click', () => open_modal(ancestor));
6034
+ list.appendChild(link);
6035
+ }
6036
+ modal.appendChild(section('Ancestry (DOM, nearest first)', list));
6037
+ // Instantiator - the component whose template wrote this tag. Differs from
6038
+ // the DOM parent for markup written in a slot body or default content.
6039
+ const instantiator = component.instantiator ? component.instantiator() : null;
6040
+ const inst = el('div', 'list');
6041
+ if (instantiator) {
6042
+ const link = el('div', 'link');
6043
+ link.appendChild(el('span', 'link-name', `<${instantiator.component_name()}>`));
6044
+ link.appendChild(el('span', 'link-cid', String(instantiator._cid)));
6045
+ link.addEventListener('click', () => open_modal(instantiator));
6046
+ inst.appendChild(link);
6047
+ if (ancestors[0] && instantiator !== ancestors[0]) {
6048
+ inst.appendChild(el('div', 'note', 'Written in this component\'s template but rendered inside a different parent (slot or default content): handlers and $sid bind here.'));
6049
+ }
6050
+ }
6051
+ else {
6052
+ inst.appendChild(el('div', 'empty', 'none - created directly'));
6053
+ }
6054
+ modal.appendChild(section('Instantiator', inst));
6055
+ modal.classList.add(`${PREFIX}modal-open`);
6056
+ }
6057
+ // ---------------------------------------------------------------------------
6058
+ // DOM helpers (shadow side)
6059
+ // ---------------------------------------------------------------------------
6060
+ function el(tag, classes, text) {
6061
+ const node = document.createElement(tag);
6062
+ node.className = classes.split(' ').map((c) => (c.startsWith(PREFIX) ? c : PREFIX + c)).join(' ');
6063
+ if (text !== undefined)
6064
+ node.textContent = text;
6065
+ return node;
6066
+ }
6067
+ function section(heading, body) {
6068
+ const wrap = el('div', 'section');
6069
+ wrap.appendChild(el('div', 'h', heading));
6070
+ wrap.appendChild(body);
6071
+ return wrap;
6072
+ }
6073
+ function table() {
6074
+ return el('div', 'table');
6075
+ }
6076
+ function row(t, key, type, value) {
6077
+ t.appendChild(el('span', 'key', key));
6078
+ t.appendChild(el('span', 'type', type));
6079
+ t.appendChild(el('span', 'value', value));
6080
+ }
6081
+ function object_table(source) {
6082
+ const entries = source && typeof source === 'object' ? Object.entries(source) : [];
6083
+ if (!entries.length)
6084
+ return el('div', 'empty', 'empty');
6085
+ const t = table();
6086
+ for (const [key, value] of entries)
6087
+ row(t, key, type_of(value), preview(value));
6088
+ return t;
6089
+ }
6090
+ function type_of(value) {
6091
+ if (value === null)
6092
+ return 'null';
6093
+ if (Array.isArray(value))
6094
+ return `array(${value.length})`;
6095
+ if (value instanceof Jqhtml_Component)
6096
+ return 'component';
6097
+ if (value && value.jquery)
6098
+ return `jQuery(${value.length})`;
6099
+ if (typeof value === 'object' && value instanceof Element)
6100
+ return 'element';
6101
+ return typeof value;
6102
+ }
6103
+ function preview(value) {
6104
+ if (value === undefined)
6105
+ return 'undefined';
6106
+ if (value === null)
6107
+ return 'null';
6108
+ if (typeof value === 'string')
6109
+ return JSON.stringify(truncate(value, 200));
6110
+ if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint')
6111
+ return String(value);
6112
+ if (typeof value === 'function')
6113
+ return `ƒ ${value.name || 'anonymous'}()`;
6114
+ if (value instanceof Jqhtml_Component)
6115
+ return `<${value.component_name()}> ${value._cid}`;
6116
+ if (value.jquery)
6117
+ return value.length ? describe_element(value[0]) : 'empty';
6118
+ if (value instanceof Element)
6119
+ return describe_element(value);
5526
6120
  try {
5527
- return new Function('$event', `
5528
- const { data, args, $, emit, $sid } = this;
5529
- ${expression}
5530
- `).bind(component);
6121
+ return truncate(JSON.stringify(value), 200);
5531
6122
  }
5532
- catch (error) {
5533
- console.error(`Invalid handler: ${expression}`, error);
5534
- return null;
6123
+ catch {
6124
+ return `{${Object.keys(value).join(', ')}}`;
5535
6125
  }
5536
6126
  }
5537
- /**
5538
- * Helper to escape HTML for safe output
5539
- */
5540
- function escape_html(str) {
5541
- const div = document.createElement('div');
5542
- div.textContent = str;
5543
- return div.innerHTML;
6127
+ function describe_element(element) {
6128
+ const id = element.id ? `#${element.id}` : '';
6129
+ const classes = element.classList.length ? `.${Array.from(element.classList).join('.')}` : '';
6130
+ return `${element.tagName.toLowerCase()}${id}${classes}`;
5544
6131
  }
5545
- /**
5546
- * Helper to escape HTML and convert newlines to <br /> tags
5547
- * Used by <%br= %> syntax for displaying user-entered text with line breaks
5548
- */
5549
- function escape_html_nl2br(str) {
5550
- const div = document.createElement('div');
5551
- div.textContent = str;
5552
- // Escape HTML first, then replace newlines with <br />
5553
- return div.innerHTML.replace(/\n/g, '<br />');
6132
+ function truncate(text, max) {
6133
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
5554
6134
  }
5555
6135
 
5556
6136
  /**
@@ -5799,16 +6379,20 @@ function init_jquery_plugin(jQuery) {
5799
6379
  catch (error) {
5800
6380
  console.warn('[JQHTML] Error stopping existing component during replacement:', error);
5801
6381
  }
5802
- // Remove component classes (any class starting with capital letter, except BEM classes)
6382
+ // Remove component classes (any class starting with a capital letter, or a
6383
+ // component name with the reserved underscore prefix - except BEM classes)
5803
6384
  const classes = element.attr('class');
5804
6385
  if (classes) {
5805
6386
  const classList = classes.split(/\s+/);
5806
6387
  const nonComponentClasses = classList.filter((cls) => {
5807
6388
  // Keep class if:
5808
6389
  // 1. It's empty
5809
- // 2. It doesn't start with a capital letter
6390
+ // 2. It is neither capital-first nor a component name (see component-name.ts)
5810
6391
  // 3. It's a BEM-style class (contains __) - these persist across reinitialization
5811
- return !cls || cls[0] !== cls[0].toUpperCase() || cls[0] === cls[0].toLowerCase() || cls.includes('__');
6392
+ if (!cls || cls.includes('__'))
6393
+ return true;
6394
+ const capital_first = cls[0] === cls[0].toUpperCase() && cls[0] !== cls[0].toLowerCase();
6395
+ return !capital_first && !is_component_name(cls);
5812
6396
  });
5813
6397
  element.attr('class', nonComponentClasses.join(' '));
5814
6398
  }
@@ -5837,8 +6421,11 @@ function init_jquery_plugin(jQuery) {
5837
6421
  }
5838
6422
  }
5839
6423
  else {
5840
- // Direct class reference
6424
+ // Direct class reference. The invocation name is the class's own; it is
6425
+ // recorded for component_name() but does not drive the template tag
6426
+ // check below, which is for named (template-backed) invocations.
5841
6427
  ComponentClass = componentOrName;
6428
+ args = { ...args, _component_name: componentOrName.component_name || componentOrName.name };
5842
6429
  }
5843
6430
  // Check if element tag matches expected tag from template
5844
6431
  let targetElement = element;
@@ -6174,7 +6761,7 @@ function init(jQuery, config) {
6174
6761
  }
6175
6762
  }
6176
6763
  // Version - will be replaced during build with actual version from package.json
6177
- const version = '2.3.61';
6764
+ const version = '2.3.67';
6178
6765
  // Default export with all functionality
6179
6766
  const jqhtml = {
6180
6767
  // Core
@@ -6205,6 +6792,14 @@ const jqhtml = {
6205
6792
  // Integration configuration - see config.ts
6206
6793
  configure,
6207
6794
  get_config,
6795
+ // Value printers: how <%= %> renders an object (see value-printers.ts).
6796
+ // print_object and dynamic_component_name are called by compiled templates.
6797
+ add_object_printer,
6798
+ print_object,
6799
+ dynamic_component_name,
6800
+ // Component debug overlay: hover outlines + click-to-inspect modal.
6801
+ // jqhtml.debug_overlay.enable() / .disable() / .is_enabled() / .inspect(x)
6802
+ debug_overlay,
6208
6803
  // Debug settings
6209
6804
  debug: {
6210
6805
  enabled: false,
@@ -6310,5 +6905,5 @@ if (typeof window !== 'undefined' && !window.jqhtml) {
6310
6905
  }
6311
6906
  }
6312
6907
 
6313
- export { Jqhtml_Component, LifecycleManager as Jqhtml_LifecycleManager, Jqhtml_Local_Storage, LifecycleManager, Load_Coordinator, applyDebugDelay, boot, clear_preload_data, configure, create_component, jqhtml as default, devWarn, escape_html, escape_html_nl2br, extract_slots, get_captured_data, get_component_class, get_component_names, get_config, get_registered_templates, get_template, get_template_by_class, handleComponentError, has_component, init, init_jquery_plugin, isSequentialProcessing, 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 };
6908
+ export { COMPONENT_NAME_PATTERN, COMPONENT_NAME_RULE, Jqhtml_Component, LifecycleManager as Jqhtml_LifecycleManager, Jqhtml_Local_Storage, LifecycleManager, Load_Coordinator, add_object_printer, applyDebugDelay, boot, clear_preload_data, configure, create_component, debug_overlay, jqhtml as default, devWarn, dynamic_component_name, escape_html, escape_html_nl2br, extract_slots, get_captured_data, get_component_class, get_component_names, get_config, get_object_printers, get_registered_templates, get_template, get_template_by_class, handleComponentError, has_component, init, init_jquery_plugin, isSequentialProcessing, is_component_name, list_components, logDataChange, logDispatch, logInstruction, logLifecycle, print_object, process_instructions, register, register_cache_class, register_component, register_template, render_template, set_preload_data, start_data_capture, stop_data_capture, version };
6314
6909
  //# sourceMappingURL=jqhtml-core.esm.js.map