eleva 1.2.7-alpha → 1.2.9-alpha

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/eleva.umd.js CHANGED
@@ -1,3 +1,4 @@
1
+ /*! Eleva v1.2.9-alpha | MIT License | https://elevajs.com */
1
2
  (function (global, factory) {
2
3
  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
3
4
  typeof define === 'function' && define.amd ? define(factory) :
@@ -6,43 +7,58 @@
6
7
 
7
8
  /**
8
9
  * @class 🔒 TemplateEngine
9
- * @classdesc Secure interpolation & dynamic attribute parsing.
10
- * Provides methods to parse template strings by replacing interpolation expressions
11
- * with dynamic data values and to evaluate expressions within a given data context.
10
+ * @classdesc A secure template engine that handles interpolation and dynamic attribute parsing.
11
+ * Provides a safe way to evaluate expressions in templates while preventing XSS attacks.
12
+ * All methods are static and can be called directly on the class.
13
+ *
14
+ * @example
15
+ * const template = "Hello, {{name}}!";
16
+ * const data = { name: "World" };
17
+ * const result = TemplateEngine.parse(template, data); // Returns: "Hello, World!"
12
18
  */
13
19
  class TemplateEngine {
14
20
  /**
15
- * Parses a template string and replaces interpolation expressions with corresponding values.
21
+ * @private {RegExp} Regular expression for matching template expressions in the format {{ expression }}
22
+ */
23
+ static expressionPattern = /\{\{\s*(.*?)\s*\}\}/g;
24
+
25
+ /**
26
+ * Parses a template string, replacing expressions with their evaluated values.
27
+ * Expressions are evaluated in the provided data context.
16
28
  *
17
- * @param {string} template - The template string containing expressions in the format `{{ expression }}`.
18
- * @param {Object<string, any>} data - The data object to use for evaluating expressions.
19
- * @returns {string} The resulting string with evaluated values.
29
+ * @public
30
+ * @static
31
+ * @param {string} template - The template string to parse.
32
+ * @param {Object} data - The data context for evaluating expressions.
33
+ * @returns {string} The parsed template with expressions replaced by their values.
34
+ * @example
35
+ * const result = TemplateEngine.parse("{{user.name}} is {{user.age}} years old", {
36
+ * user: { name: "John", age: 30 }
37
+ * }); // Returns: "John is 30 years old"
20
38
  */
21
39
  static parse(template, data) {
22
- if (!template || typeof template !== "string") return template;
23
- return template.replace(/\{\{\s*(.*?)\s*\}\}/g, (_, expr) => {
24
- return this.evaluate(expr, data);
25
- });
40
+ if (typeof template !== "string") return template;
41
+ return template.replace(this.expressionPattern, (_, expression) => this.evaluate(expression, data));
26
42
  }
27
43
 
28
44
  /**
29
- * Evaluates a JavaScript expression using the provided data context.
45
+ * Evaluates an expression in the context of the provided data object.
46
+ * Note: This does not provide a true sandbox and evaluated expressions may access global scope.
30
47
  *
31
- * @param {string} expr - The JavaScript expression to evaluate.
32
- * @param {Object<string, any>} data - The data context for evaluating the expression.
33
- * @returns {any} The result of the evaluated expression, or an empty string if undefined or on error.
48
+ * @public
49
+ * @static
50
+ * @param {string} expression - The expression to evaluate.
51
+ * @param {Object} data - The data context for evaluation.
52
+ * @returns {*} The result of the evaluation, or an empty string if evaluation fails.
53
+ * @example
54
+ * const result = TemplateEngine.evaluate("user.name", { user: { name: "John" } }); // Returns: "John"
55
+ * const age = TemplateEngine.evaluate("user.age", { user: { age: 30 } }); // Returns: 30
34
56
  */
35
- static evaluate(expr, data) {
36
- if (!expr || typeof expr !== "string") return expr;
57
+ static evaluate(expression, data) {
58
+ if (typeof expression !== "string") return expression;
37
59
  try {
38
- const compiledFn = new Function("data", `with(data) { return ${expr} }`);
39
- return compiledFn(data);
40
- } catch (error) {
41
- console.error(`Template evaluation error:`, {
42
- expression: expr,
43
- data,
44
- error: error.message
45
- });
60
+ return new Function("data", `with(data) { return ${expression}; }`)(data);
61
+ } catch {
46
62
  return "";
47
63
  }
48
64
  }
@@ -50,20 +66,26 @@
50
66
 
51
67
  /**
52
68
  * @class ⚡ Signal
53
- * @classdesc Fine-grained reactivity.
54
- * A reactive data holder that notifies registered watchers when its value changes,
55
- * enabling fine-grained DOM patching rather than full re-renders.
69
+ * @classdesc A reactive data holder that enables fine-grained reactivity in the Eleva framework.
70
+ * Signals notify registered watchers when their value changes, enabling efficient DOM updates
71
+ * through targeted patching rather than full re-renders.
72
+ *
73
+ * @example
74
+ * const count = new Signal(0);
75
+ * count.watch((value) => console.log(`Count changed to: ${value}`));
76
+ * count.value = 1; // Logs: "Count changed to: 1"
56
77
  */
57
78
  class Signal {
58
79
  /**
59
- * Creates a new Signal instance.
80
+ * Creates a new Signal instance with the specified initial value.
60
81
  *
82
+ * @public
61
83
  * @param {*} value - The initial value of the signal.
62
84
  */
63
85
  constructor(value) {
64
- /** @private {*} Internal storage for the signal's current value */
86
+ /** @private {T} Internal storage for the signal's current value, where T is the type of the initial value */
65
87
  this._value = value;
66
- /** @private {Set<function>} Collection of callback functions to be notified when value changes */
88
+ /** @private {Set<function(T): void>} Collection of callback functions to be notified when value changes, where T is the value type */
67
89
  this._watchers = new Set();
68
90
  /** @private {boolean} Flag to prevent multiple synchronous watcher notifications and batch updates into microtasks */
69
91
  this._pending = false;
@@ -72,7 +94,8 @@
72
94
  /**
73
95
  * Gets the current value of the signal.
74
96
  *
75
- * @returns {*} The current value.
97
+ * @public
98
+ * @returns {T} The current value, where T is the type of the initial value.
76
99
  */
77
100
  get value() {
78
101
  return this._value;
@@ -80,21 +103,29 @@
80
103
 
81
104
  /**
82
105
  * Sets a new value for the signal and notifies all registered watchers if the value has changed.
106
+ * The notification is batched using microtasks to prevent multiple synchronous updates.
83
107
  *
84
- * @param {*} newVal - The new value to set.
108
+ * @public
109
+ * @param {T} newVal - The new value to set, where T is the type of the initial value.
110
+ * @returns {void}
85
111
  */
86
112
  set value(newVal) {
87
- if (newVal !== this._value) {
88
- this._value = newVal;
89
- this._notifyWatchers();
90
- }
113
+ if (this._value === newVal) return;
114
+ this._value = newVal;
115
+ this._notify();
91
116
  }
92
117
 
93
118
  /**
94
119
  * Registers a watcher function that will be called whenever the signal's value changes.
120
+ * The watcher will receive the new value as its argument.
95
121
  *
96
- * @param {function(any): void} fn - The callback function to invoke on value change.
122
+ * @public
123
+ * @param {function(T): void} fn - The callback function to invoke on value change, where T is the value type.
97
124
  * @returns {function(): boolean} A function to unsubscribe the watcher.
125
+ * @example
126
+ * const unsubscribe = signal.watch((value) => console.log(value));
127
+ * // Later...
128
+ * unsubscribe(); // Stops watching for changes
98
129
  */
99
130
  watch(fn) {
100
131
  this._watchers.add(fn);
@@ -109,78 +140,116 @@
109
140
  * @private
110
141
  * @returns {void}
111
142
  */
112
- _notifyWatchers() {
113
- if (!this._pending) {
114
- this._pending = true;
115
- queueMicrotask(() => {
116
- this._pending = false;
117
- this._watchers.forEach(fn => fn(this._value));
118
- });
119
- }
143
+ _notify() {
144
+ if (this._pending) return;
145
+ this._pending = true;
146
+ queueMicrotask(() => {
147
+ this._watchers.forEach(fn => fn(this._value));
148
+ this._pending = false;
149
+ });
120
150
  }
121
151
  }
122
152
 
123
153
  /**
124
- * @class 🎙️ Emitter
125
- * @classdesc Robust inter-component communication with event bubbling.
126
- * Implements a basic publish-subscribe pattern for event handling, allowing components
127
- * to communicate through custom events.
154
+ * @class 📡 Emitter
155
+ * @classdesc A robust event emitter that enables inter-component communication through a publish-subscribe pattern.
156
+ * Components can emit events and listen for events from other components, facilitating loose coupling
157
+ * and reactive updates across the application.
158
+ *
159
+ * @example
160
+ * const emitter = new Emitter();
161
+ * emitter.on('user:login', (user) => console.log(`User logged in: ${user.name}`));
162
+ * emitter.emit('user:login', { name: 'John' }); // Logs: "User logged in: John"
128
163
  */
129
164
  class Emitter {
130
165
  /**
131
166
  * Creates a new Emitter instance.
167
+ *
168
+ * @public
132
169
  */
133
170
  constructor() {
134
- /** @type {Object.<string, Function[]>} Storage for event handlers mapped by event name */
135
- this.events = {};
171
+ /** @private {Map<string, Set<function(any): void>>} Map of event names to their registered handler functions */
172
+ this._events = new Map();
136
173
  }
137
174
 
138
175
  /**
139
- * Registers an event handler for the specified event.
176
+ * Registers an event handler for the specified event name.
177
+ * The handler will be called with the event data when the event is emitted.
140
178
  *
141
- * @param {string} event - The name of the event.
142
- * @param {function(...any): void} handler - The function to call when the event is emitted.
179
+ * @public
180
+ * @param {string} event - The name of the event to listen for.
181
+ * @param {function(any): void} handler - The callback function to invoke when the event occurs.
182
+ * @returns {function(): boolean} A function to unsubscribe the event handler.
183
+ * @example
184
+ * const unsubscribe = emitter.on('user:login', (user) => console.log(user));
185
+ * // Later...
186
+ * unsubscribe(); // Stops listening for the event
143
187
  */
144
188
  on(event, handler) {
145
- (this.events[event] || (this.events[event] = [])).push(handler);
189
+ if (!this._events.has(event)) this._events.set(event, new Set());
190
+ this._events.get(event).add(handler);
191
+ return () => this.off(event, handler);
146
192
  }
147
193
 
148
194
  /**
149
- * Removes a previously registered event handler.
195
+ * Removes an event handler for the specified event name.
196
+ * If no handler is provided, all handlers for the event are removed.
150
197
  *
198
+ * @public
151
199
  * @param {string} event - The name of the event.
152
- * @param {function(...any): void} handler - The handler function to remove.
200
+ * @param {function(any): void} [handler] - The specific handler function to remove.
201
+ * @returns {void}
153
202
  */
154
203
  off(event, handler) {
155
- if (this.events[event]) {
156
- this.events[event] = this.events[event].filter(h => h !== handler);
204
+ if (!this._events.has(event)) return;
205
+ if (handler) {
206
+ const handlers = this._events.get(event);
207
+ handlers.delete(handler);
208
+ // Remove the event if there are no handlers left
209
+ if (handlers.size === 0) this._events.delete(event);
210
+ } else {
211
+ this._events.delete(event);
157
212
  }
158
213
  }
159
214
 
160
215
  /**
161
- * Emits an event, invoking all handlers registered for that event.
216
+ * Emits an event with the specified data to all registered handlers.
217
+ * Handlers are called synchronously in the order they were registered.
162
218
  *
163
- * @param {string} event - The event name.
164
- * @param {...any} args - Additional arguments to pass to the event handlers.
219
+ * @public
220
+ * @param {string} event - The name of the event to emit.
221
+ * @param {...any} args - Optional arguments to pass to the event handlers.
222
+ * @returns {void}
165
223
  */
166
224
  emit(event, ...args) {
167
- (this.events[event] || []).forEach(handler => handler(...args));
225
+ if (!this._events.has(event)) return;
226
+ this._events.get(event).forEach(handler => handler(...args));
168
227
  }
169
228
  }
170
229
 
171
230
  /**
172
231
  * @class 🎨 Renderer
173
- * @classdesc Handles DOM patching, diffing, and attribute updates.
174
- * Provides methods for efficient DOM updates by diffing the new and old DOM structures
175
- * and applying only the necessary changes.
232
+ * @classdesc A DOM renderer that handles efficient DOM updates through patching and diffing.
233
+ * Provides methods for updating the DOM by comparing new and old structures and applying
234
+ * only the necessary changes, minimizing layout thrashing and improving performance.
235
+ *
236
+ * @example
237
+ * const renderer = new Renderer();
238
+ * const container = document.getElementById("app");
239
+ * const newHtml = "<div>Updated content</div>";
240
+ * renderer.patchDOM(container, newHtml);
176
241
  */
177
242
  class Renderer {
178
243
  /**
179
244
  * Patches the DOM of a container element with new HTML content.
245
+ * This method efficiently updates the DOM by comparing the new content with the existing
246
+ * content and applying only the necessary changes.
180
247
  *
248
+ * @public
181
249
  * @param {HTMLElement} container - The container element to patch.
182
250
  * @param {string} newHtml - The new HTML content to apply.
183
- * @throws {Error} If container is not an HTMLElement or newHtml is not a string
251
+ * @returns {void}
252
+ * @throws {Error} If container is not an HTMLElement or newHtml is not a string.
184
253
  */
185
254
  patchDOM(container, newHtml) {
186
255
  if (!(container instanceof HTMLElement)) {
@@ -197,10 +266,14 @@
197
266
 
198
267
  /**
199
268
  * Diffs two DOM trees (old and new) and applies updates to the old DOM.
269
+ * This method recursively compares nodes and their attributes, applying only
270
+ * the necessary changes to minimize DOM operations.
200
271
  *
272
+ * @private
201
273
  * @param {HTMLElement} oldParent - The original DOM element.
202
274
  * @param {HTMLElement} newParent - The new DOM element.
203
- * @throws {Error} If either parent is not an HTMLElement
275
+ * @returns {void}
276
+ * @throws {Error} If either parent is not an HTMLElement.
204
277
  */
205
278
  diff(oldParent, newParent) {
206
279
  if (!(oldParent instanceof HTMLElement) || !(newParent instanceof HTMLElement)) {
@@ -247,10 +320,13 @@
247
320
 
248
321
  /**
249
322
  * Updates the attributes of an element to match those of a new element.
323
+ * Handles special cases for ARIA attributes, data attributes, and boolean properties.
250
324
  *
325
+ * @private
251
326
  * @param {HTMLElement} oldEl - The element to update.
252
327
  * @param {HTMLElement} newEl - The element providing the updated attributes.
253
- * @throws {Error} If either element is not an HTMLElement
328
+ * @returns {void}
329
+ * @throws {Error} If either element is not an HTMLElement.
254
330
  */
255
331
  updateAttributes(oldEl, newEl) {
256
332
  if (!(oldEl instanceof HTMLElement) || !(newEl instanceof HTMLElement)) {
@@ -305,101 +381,143 @@
305
381
  }
306
382
 
307
383
  /**
308
- * Defines the structure and behavior of a component.
309
384
  * @typedef {Object} ComponentDefinition
310
385
  * @property {function(Object<string, any>): (Object<string, any>|Promise<Object<string, any>>)} [setup]
311
- * Optional setup function that initializes the component's reactive state and lifecycle.
312
- * Receives props and context as an argument and should return an object containing the component's state.
313
- * Can return either a synchronous object or a Promise that resolves to an object for async initialization.
314
- *
386
+ * Optional setup function that initializes the component's state and returns reactive data
315
387
  * @property {function(Object<string, any>): string} template
316
- * Required function that defines the component's HTML structure.
317
- * Receives the merged context (props + setup data) and must return an HTML template string.
318
- * Supports dynamic expressions using {{ }} syntax for reactive data binding.
319
- *
388
+ * Required function that defines the component's HTML structure
320
389
  * @property {function(Object<string, any>): string} [style]
321
- * Optional function that defines component-scoped CSS styles.
322
- * Receives the merged context and returns a CSS string that will be automatically scoped to the component.
323
- * Styles are injected into the component's container and only affect elements within it.
324
- *
390
+ * Optional function that provides component-scoped CSS styles
325
391
  * @property {Object<string, ComponentDefinition>} [children]
326
- * Optional object that defines nested child components.
327
- * Keys are CSS selectors that match elements in the template where child components should be mounted.
328
- * Values are ComponentDefinition objects that define the structure and behavior of each child component.
392
+ * Optional object defining nested child components
393
+ */
394
+
395
+ /**
396
+ * @typedef {Object} ElevaPlugin
397
+ * @property {function(Eleva, Object<string, any>): void} install
398
+ * Function that installs the plugin into the Eleva instance
399
+ * @property {string} name
400
+ * Unique identifier name for the plugin
401
+ */
402
+
403
+ /**
404
+ * @typedef {Object} MountResult
405
+ * @property {HTMLElement} container
406
+ * The DOM element where the component is mounted
407
+ * @property {Object<string, any>} data
408
+ * The component's reactive state and context data
409
+ * @property {function(): void} unmount
410
+ * Function to clean up and unmount the component
329
411
  */
330
412
 
331
413
  /**
332
414
  * @class 🧩 Eleva
333
- * @classdesc Signal-based component runtime framework with lifecycle hooks, scoped styles, and plugin support.
334
- * Manages component registration, plugin integration, event handling, and DOM rendering.
415
+ * @classdesc A modern, signal-based component runtime framework that provides lifecycle hooks,
416
+ * scoped styles, and plugin support. Eleva manages component registration, plugin integration,
417
+ * event handling, and DOM rendering with a focus on performance and developer experience.
418
+ *
419
+ * @example
420
+ * const app = new Eleva("myApp");
421
+ * app.component("myComponent", {
422
+ * template: (ctx) => `<div>Hello ${ctx.props.name}</div>`,
423
+ * setup: (ctx) => ({ count: new Signal(0) })
424
+ * });
425
+ * app.mount(document.getElementById("app"), "myComponent", { name: "World" });
335
426
  */
336
427
  class Eleva {
337
428
  /**
338
- * Creates a new Eleva instance.
429
+ * Creates a new Eleva instance with the specified name and configuration.
339
430
  *
340
- * @param {string} name - The name of the Eleva instance.
341
- * @param {Object<string, any>} [config={}] - Optional configuration for the instance.
431
+ * @public
432
+ * @param {string} name - The unique identifier name for this Eleva instance.
433
+ * @param {Object<string, any>} [config={}] - Optional configuration object for the instance.
434
+ * May include framework-wide settings and default behaviors.
342
435
  */
343
436
  constructor(name, config = {}) {
344
- /** @type {string} The unique identifier name for this Eleva instance */
437
+ /** @public {string} The unique identifier name for this Eleva instance */
345
438
  this.name = name;
346
- /** @type {Object<string, any>} Optional configuration object for the Eleva instance */
439
+ /** @public {Object<string, any>} Optional configuration object for the Eleva instance */
347
440
  this.config = config;
348
- /** @type {Object<string, ComponentDefinition>} Object storing registered component definitions by name */
349
- this._components = {};
350
- /** @private {Array<Object>} Collection of installed plugin instances */
351
- this._plugins = [];
352
- /** @private {string[]} Array of lifecycle hook names supported by the component */
353
- this._lifecycleHooks = ["onBeforeMount", "onMount", "onBeforeUpdate", "onUpdate", "onUnmount"];
354
- /** @private {boolean} Flag indicating if component is currently mounted */
355
- this._isMounted = false;
356
- /** @private {Emitter} Instance of the event emitter for handling component events */
441
+ /** @public {Emitter} Instance of the event emitter for handling component events */
357
442
  this.emitter = new Emitter();
358
- /** @private {Signal} Instance of the signal for handling plugin and component signals */
443
+ /** @public {typeof Signal} Static reference to the Signal class for creating reactive state */
359
444
  this.signal = Signal;
360
- /** @private {Renderer} Instance of the renderer for handling DOM updates and patching */
445
+ /** @public {Renderer} Instance of the renderer for handling DOM updates and patching */
361
446
  this.renderer = new Renderer();
447
+
448
+ /** @private {Map<string, ComponentDefinition>} Registry of all component definitions by name */
449
+ this._components = new Map();
450
+ /** @private {Map<string, ElevaPlugin>} Collection of installed plugin instances by name */
451
+ this._plugins = new Map();
452
+ /** @private {string[]} Array of lifecycle hook names supported by components */
453
+ this._lifecycleHooks = ["onBeforeMount", "onMount", "onBeforeUpdate", "onUpdate", "onUnmount"];
454
+ /** @private {boolean} Flag indicating if the root component is currently mounted */
455
+ this._isMounted = false;
362
456
  }
363
457
 
364
458
  /**
365
459
  * Integrates a plugin with the Eleva framework.
460
+ * The plugin's install function will be called with the Eleva instance and provided options.
461
+ * After installation, the plugin will be available for use by components.
366
462
  *
367
- * @param {Object} plugin - The plugin object which should have an `install` function.
368
- * @param {Object<string, any>} [options={}] - Optional options to pass to the plugin.
369
- * @returns {Eleva} The Eleva instance (for chaining).
463
+ * @public
464
+ * @param {ElevaPlugin} plugin - The plugin object which must have an `install` function.
465
+ * @param {Object<string, any>} [options={}] - Optional configuration options for the plugin.
466
+ * @returns {Eleva} The Eleva instance (for method chaining).
467
+ * @example
468
+ * app.use(myPlugin, { option1: "value1" });
370
469
  */
371
470
  use(plugin, options = {}) {
372
- if (typeof plugin.install === "function") {
373
- plugin.install(this, options);
374
- }
375
- this._plugins.push(plugin);
471
+ plugin.install(this, options);
472
+ this._plugins.set(plugin.name, plugin);
376
473
  return this;
377
474
  }
378
475
 
379
476
  /**
380
- * Registers a component with the Eleva instance.
477
+ * Registers a new component with the Eleva instance.
478
+ * The component will be available for mounting using its registered name.
381
479
  *
382
- * @param {string} name - The name of the component.
480
+ * @public
481
+ * @param {string} name - The unique name of the component to register.
383
482
  * @param {ComponentDefinition} definition - The component definition including setup, template, style, and children.
384
- * @returns {Eleva} The Eleva instance (for chaining).
483
+ * @returns {Eleva} The Eleva instance (for method chaining).
484
+ * @throws {Error} If the component name is already registered.
485
+ * @example
486
+ * app.component("myButton", {
487
+ * template: (ctx) => `<button>${ctx.props.text}</button>`,
488
+ * style: () => "button { color: blue; }"
489
+ * });
385
490
  */
386
491
  component(name, definition) {
387
- this._components[name] = definition;
492
+ /** @type {Map<string, ComponentDefinition>} */
493
+ this._components.set(name, definition);
388
494
  return this;
389
495
  }
390
496
 
391
497
  /**
392
498
  * Mounts a registered component to a DOM element.
499
+ * This will initialize the component, set up its reactive state, and render it to the DOM.
393
500
  *
394
- * @param {HTMLElement} container - A DOM element where the component will be mounted.
395
- * @param {string|ComponentDefinition} compName - The name of the component to mount or a component definition.
501
+ * @public
502
+ * @param {HTMLElement} container - The DOM element where the component will be mounted.
503
+ * @param {string|ComponentDefinition} compName - The name of the registered component or a direct component definition.
396
504
  * @param {Object<string, any>} [props={}] - Optional properties to pass to the component.
397
- * @returns {object|Promise<object>} An object representing the mounted component instance, or a Promise that resolves to it for asynchronous setups.
398
- * @throws {Error} If the container is not found or if the component is not registered.
505
+ * @returns {Promise<MountResult>}
506
+ * A Promise that resolves to an object containing:
507
+ * - container: The mounted component's container element
508
+ * - data: The component's reactive state and context
509
+ * - unmount: Function to clean up and unmount the component
510
+ * @throws {Error} If the container is not found, or component is not registered.
511
+ * @example
512
+ * const instance = await app.mount(document.getElementById("app"), "myComponent", { text: "Click me" });
513
+ * // Later...
514
+ * instance.unmount();
399
515
  */
400
- mount(container, compName, props = {}) {
516
+ async mount(container, compName, props = {}) {
401
517
  if (!container) throw new Error(`Container not found: ${container}`);
402
- const definition = typeof compName === "string" ? this._components[compName] : compName;
518
+
519
+ /** @type {ComponentDefinition} */
520
+ const definition = typeof compName === "string" ? this._components.get(compName) : compName;
403
521
  if (!definition) throw new Error(`Component "${compName}" not registered.`);
404
522
  if (typeof definition.template !== "function") throw new Error("Component template must be a function");
405
523
 
@@ -429,23 +547,35 @@
429
547
  const context = {
430
548
  props,
431
549
  emitter: this.emitter,
550
+ /** @type {(v: any) => Signal} */
432
551
  signal: v => new this.signal(v),
433
552
  ...this._prepareLifecycleHooks()
434
553
  };
435
554
 
436
555
  /**
437
556
  * Processes the mounting of the component.
557
+ * This function handles:
558
+ * 1. Merging setup data with the component context
559
+ * 2. Setting up reactive watchers
560
+ * 3. Rendering the component
561
+ * 4. Managing component lifecycle
438
562
  *
439
- * @param {Object<string, any>} data - Data returned from the component's setup function.
440
- * @returns {object} An object with the container, merged context data, and an unmount function.
563
+ * @param {Object<string, any>} data - Data returned from the component's setup function
564
+ * @returns {MountResult} An object containing:
565
+ * - container: The mounted component's container element
566
+ * - data: The component's reactive state and context
567
+ * - unmount: Function to clean up and unmount the component
441
568
  */
442
- const processMount = data => {
569
+ const processMount = async data => {
443
570
  const mergedContext = {
444
571
  ...context,
445
572
  ...data
446
573
  };
574
+ /** @type {Array<() => void>} */
447
575
  const watcherUnsubscribers = [];
576
+ /** @type {Array<MountResult>} */
448
577
  const childInstances = [];
578
+ /** @type {Array<() => void>} */
449
579
  const cleanupListeners = [];
450
580
 
451
581
  // Execute before hooks
@@ -459,12 +589,12 @@
459
589
  * Renders the component by parsing the template, patching the DOM,
460
590
  * processing events, injecting styles, and mounting child components.
461
591
  */
462
- const render = () => {
592
+ const render = async () => {
463
593
  const newHtml = TemplateEngine.parse(template(mergedContext), mergedContext);
464
594
  this.renderer.patchDOM(container, newHtml);
465
595
  this._processEvents(container, mergedContext, cleanupListeners);
466
596
  this._injectStyles(container, compName, style, mergedContext);
467
- this._mountChildren(container, children, childInstances);
597
+ await this._mountComponents(container, children, childInstances);
468
598
  if (!this._isMounted) {
469
599
  mergedContext.onMount && mergedContext.onMount();
470
600
  this._isMounted = true;
@@ -478,10 +608,10 @@
478
608
  * When a Signal's value changes, the component will re-render to reflect the updates.
479
609
  * Stores unsubscribe functions to clean up watchers when component unmounts.
480
610
  */
481
- Object.values(data).forEach(val => {
611
+ for (const val of Object.values(data)) {
482
612
  if (val instanceof Signal) watcherUnsubscribers.push(val.watch(render));
483
- });
484
- render();
613
+ }
614
+ await render();
485
615
  return {
486
616
  container,
487
617
  data: mergedContext,
@@ -491,9 +621,9 @@
491
621
  * @returns {void}
492
622
  */
493
623
  unmount: () => {
494
- watcherUnsubscribers.forEach(fn => fn());
495
- cleanupListeners.forEach(fn => fn());
496
- childInstances.forEach(child => child.unmount());
624
+ for (const fn of watcherUnsubscribers) fn();
625
+ for (const fn of cleanupListeners) fn();
626
+ for (const child of childInstances) child.unmount();
497
627
  mergedContext.onUnmount && mergedContext.onUnmount();
498
628
  container.innerHTML = "";
499
629
  }
@@ -505,26 +635,31 @@
505
635
  }
506
636
 
507
637
  /**
508
- * Prepares default no-operation lifecycle hook functions.
638
+ * Prepares default no-operation lifecycle hook functions for a component.
639
+ * These hooks will be called at various stages of the component's lifecycle.
509
640
  *
510
- * @returns {Object<string, function(): void>} An object with keys for lifecycle hooks mapped to empty functions.
511
641
  * @private
642
+ * @returns {Object<string, function(): void>} An object mapping lifecycle hook names to empty functions.
643
+ * The returned object will be merged with the component's context.
512
644
  */
513
645
  _prepareLifecycleHooks() {
514
- return this._lifecycleHooks.reduce((acc, hook) => {
515
- acc[hook] = () => {};
516
- return acc;
517
- }, {});
646
+ /** @type {Object<string, () => void>} */
647
+ const hooks = {};
648
+ for (const hook of this._lifecycleHooks) {
649
+ hooks[hook] = () => {};
650
+ }
651
+ return hooks;
518
652
  }
519
653
 
520
654
  /**
521
655
  * Processes DOM elements for event binding based on attributes starting with "@".
522
- * Tracks listeners for cleanup during unmount.
656
+ * This method handles the event delegation system and ensures proper cleanup of event listeners.
523
657
  *
524
- * @param {HTMLElement} container - The container element in which to search for events.
525
- * @param {Object<string, any>} context - The current context containing event handler definitions.
526
- * @param {Array<Function>} cleanupListeners - Array to collect cleanup functions for each event listener.
527
658
  * @private
659
+ * @param {HTMLElement} container - The container element in which to search for event attributes.
660
+ * @param {Object<string, any>} context - The current component context containing event handler definitions.
661
+ * @param {Array<Function>} cleanupListeners - Array to collect cleanup functions for each event listener.
662
+ * @returns {void}
528
663
  */
529
664
  _processEvents(container, context, cleanupListeners) {
530
665
  const elements = container.querySelectorAll("*");
@@ -547,12 +682,14 @@
547
682
 
548
683
  /**
549
684
  * Injects scoped styles into the component's container.
685
+ * The styles are automatically prefixed to prevent style leakage to other components.
550
686
  *
551
- * @param {HTMLElement} container - The container element.
552
- * @param {string} compName - The component name used to identify the style element.
553
- * @param {function(Object<string, any>): string} [styleFn] - A function that returns CSS styles as a string.
554
- * @param {Object<string, any>} context - The current context for style interpolation.
555
687
  * @private
688
+ * @param {HTMLElement} container - The container element where styles should be injected.
689
+ * @param {string} compName - The component name used to identify the style element.
690
+ * @param {function(Object<string, any>): string} [styleFn] - Optional function that returns CSS styles as a string.
691
+ * @param {Object<string, any>} context - The current component context for style interpolation.
692
+ * @returns {void}
556
693
  */
557
694
  _injectStyles(container, compName, styleFn, context) {
558
695
  if (!styleFn) return;
@@ -566,31 +703,112 @@
566
703
  }
567
704
 
568
705
  /**
569
- * Mounts child components within the parent component's container.
706
+ * Extracts props from an element's attributes that start with 'eleva-prop-'.
707
+ * This method is used to collect component properties from DOM elements.
570
708
  *
571
- * @param {HTMLElement} container - The parent container element.
572
- * @param {Object<string, ComponentDefinition>} [children] - An object mapping child component selectors to their definitions.
573
- * @param {Array<object>} childInstances - An array to store the mounted child component instances.
574
709
  * @private
710
+ * @param {HTMLElement} element - The DOM element to extract props from
711
+ * @returns {Object<string, any>} An object containing the extracted props
712
+ * @example
713
+ * // For an element with attributes:
714
+ * // <div eleva-prop-name="John" eleva-prop-age="25">
715
+ * // Returns: { name: "John", age: "25" }
575
716
  */
576
- _mountChildren(container, children, childInstances) {
577
- childInstances.forEach(child => child.unmount());
717
+ _extractProps(element) {
718
+ const props = {};
719
+ for (const {
720
+ name,
721
+ value
722
+ } of [...element.attributes]) {
723
+ if (name.startsWith("eleva-prop-")) {
724
+ props[name.replace("eleva-prop-", "")] = value;
725
+ }
726
+ }
727
+ return props;
728
+ }
729
+
730
+ /**
731
+ * Mounts a single component instance to a container element.
732
+ * This method handles the actual mounting of a component with its props.
733
+ *
734
+ * @private
735
+ * @param {HTMLElement} container - The container element to mount the component to
736
+ * @param {string|ComponentDefinition} component - The component to mount, either as a name or definition
737
+ * @param {Object<string, any>} props - The props to pass to the component
738
+ * @returns {Promise<MountResult>} A promise that resolves to the mounted component instance
739
+ * @throws {Error} If the container is not a valid HTMLElement
740
+ */
741
+ async _mountComponentInstance(container, component, props) {
742
+ if (!(container instanceof HTMLElement)) return null;
743
+ return await this.mount(container, component, props);
744
+ }
745
+
746
+ /**
747
+ * Mounts components found by a selector in the container.
748
+ * This method handles mounting multiple instances of the same component type.
749
+ *
750
+ * @private
751
+ * @param {HTMLElement} container - The container to search for components
752
+ * @param {string} selector - The CSS selector to find components
753
+ * @param {string|ComponentDefinition} component - The component to mount
754
+ * @param {Array<MountResult>} instances - Array to store the mounted component instances
755
+ * @returns {Promise<void>}
756
+ */
757
+ async _mountComponentsBySelector(container, selector, component, instances) {
758
+ for (const el of container.querySelectorAll(selector)) {
759
+ const props = this._extractProps(el);
760
+ const instance = await this._mountComponentInstance(el, component, props);
761
+ if (instance) instances.push(instance);
762
+ }
763
+ }
764
+
765
+ /**
766
+ * Mounts all components within the parent component's container.
767
+ * This method implements a dual mounting system that handles both:
768
+ * 1. Explicitly defined children components (passed through the children parameter)
769
+ * 2. Template-referenced components (found in the template using component names)
770
+ *
771
+ * The mounting process follows these steps:
772
+ * 1. Cleans up any existing component instances
773
+ * 2. Mounts explicitly defined children components
774
+ * 3. Mounts template-referenced components
775
+ *
776
+ * @private
777
+ * @param {HTMLElement} container - The container element to mount components in
778
+ * @param {Object<string, ComponentDefinition>} children - Map of selectors to component definitions for explicit children
779
+ * @param {Array<MountResult>} childInstances - Array to store all mounted component instances
780
+ * @returns {Promise<void>}
781
+ *
782
+ * @example
783
+ * // Explicit children mounting:
784
+ * const children = {
785
+ * '.user-profile': UserProfileComponent,
786
+ * '.settings-panel': SettingsComponent
787
+ * };
788
+ *
789
+ * // Template-referenced components:
790
+ * // <div>
791
+ * // <user-profile eleva-prop-name="John"></user-profile>
792
+ * // <settings-panel eleva-prop-theme="dark"></settings-panel>
793
+ * // </div>
794
+ */
795
+ async _mountComponents(container, children, childInstances) {
796
+ // Clean up existing instances
797
+ for (const child of childInstances) child.unmount();
578
798
  childInstances.length = 0;
579
- Object.keys(children || {}).forEach(childSelector => {
580
- container.querySelectorAll(childSelector).forEach(childEl => {
581
- const props = {};
582
- [...childEl.attributes].forEach(({
583
- name,
584
- value
585
- }) => {
586
- if (name.startsWith("eleva-prop-")) {
587
- props[name.replace("eleva-prop-", "")] = value;
588
- }
589
- });
590
- const instance = this.mount(childEl, children[childSelector], props);
591
- childInstances.push(instance);
592
- });
593
- });
799
+
800
+ // Mount explicitly defined children components
801
+ if (children) {
802
+ for (const [selector, component] of Object.entries(children)) {
803
+ if (!selector) continue;
804
+ await this._mountComponentsBySelector(container, selector, component, childInstances);
805
+ }
806
+ }
807
+
808
+ // Mount components referenced in the template
809
+ for (const [compName] of this._components) {
810
+ await this._mountComponentsBySelector(container, compName, compName, childInstances);
811
+ }
594
812
  }
595
813
  }
596
814