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