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