eleva 1.2.17-beta → 1.2.19-beta

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,4 +1,4 @@
1
- /*! Eleva v1.2.17-beta | MIT License | https://elevajs.com */
1
+ /*! Eleva v1.2.19-beta | MIT License | https://elevajs.com */
2
2
  /**
3
3
  * @class 🔒 TemplateEngine
4
4
  * @classdesc A secure template engine that handles interpolation and dynamic attribute parsing.
@@ -13,6 +13,7 @@
13
13
  class TemplateEngine {
14
14
  /**
15
15
  * @private {RegExp} Regular expression for matching template expressions in the format {{ expression }}
16
+ * @type {RegExp}
16
17
  */
17
18
  static expressionPattern = /\{\{\s*(.*?)\s*\}\}/g;
18
19
 
@@ -23,7 +24,7 @@ class TemplateEngine {
23
24
  * @public
24
25
  * @static
25
26
  * @param {string} template - The template string to parse.
26
- * @param {Object} data - The data context for evaluating expressions.
27
+ * @param {Record<string, unknown>} data - The data context for evaluating expressions.
27
28
  * @returns {string} The parsed template with expressions replaced by their values.
28
29
  * @example
29
30
  * const result = TemplateEngine.parse("{{user.name}} is {{user.age}} years old", {
@@ -38,12 +39,14 @@ class TemplateEngine {
38
39
  /**
39
40
  * Evaluates an expression in the context of the provided data object.
40
41
  * Note: This does not provide a true sandbox and evaluated expressions may access global scope.
42
+ * The use of the `with` statement is necessary for expression evaluation but has security implications.
43
+ * Expressions should be carefully validated before evaluation.
41
44
  *
42
45
  * @public
43
46
  * @static
44
47
  * @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.
48
+ * @param {Record<string, unknown>} data - The data context for evaluation.
49
+ * @returns {unknown} The result of the evaluation, or an empty string if evaluation fails.
47
50
  * @example
48
51
  * const result = TemplateEngine.evaluate("user.name", { user: { name: "John" } }); // Returns: "John"
49
52
  * const age = TemplateEngine.evaluate("user.age", { user: { age: 30 } }); // Returns: 30
@@ -63,6 +66,8 @@ class TemplateEngine {
63
66
  * @classdesc A reactive data holder that enables fine-grained reactivity in the Eleva framework.
64
67
  * Signals notify registered watchers when their value changes, enabling efficient DOM updates
65
68
  * through targeted patching rather than full re-renders.
69
+ * Updates are batched using microtasks to prevent multiple synchronous notifications.
70
+ * The class is generic, allowing type-safe handling of any value type T.
66
71
  *
67
72
  * @example
68
73
  * const count = new Signal(0);
@@ -75,12 +80,12 @@ class Signal {
75
80
  * Creates a new Signal instance with the specified initial value.
76
81
  *
77
82
  * @public
78
- * @param {*} value - The initial value of the signal.
83
+ * @param {T} value - The initial value of the signal.
79
84
  */
80
85
  constructor(value) {
81
- /** @private {T} Internal storage for the signal's current value, where T is the type of the initial value */
86
+ /** @private {T} Internal storage for the signal's current value */
82
87
  this._value = value;
83
- /** @private {Set<function(T): void>} Collection of callback functions to be notified when value changes, where T is the value type */
88
+ /** @private {Set<(value: T) => void>} Collection of callback functions to be notified when value changes */
84
89
  this._watchers = new Set();
85
90
  /** @private {boolean} Flag to prevent multiple synchronous watcher notifications and batch updates into microtasks */
86
91
  this._pending = false;
@@ -90,7 +95,7 @@ class Signal {
90
95
  * Gets the current value of the signal.
91
96
  *
92
97
  * @public
93
- * @returns {T} The current value, where T is the type of the initial value.
98
+ * @returns {T} The current value.
94
99
  */
95
100
  get value() {
96
101
  return this._value;
@@ -101,7 +106,7 @@ class Signal {
101
106
  * The notification is batched using microtasks to prevent multiple synchronous updates.
102
107
  *
103
108
  * @public
104
- * @param {T} newVal - The new value to set, where T is the type of the initial value.
109
+ * @param {T} newVal - The new value to set.
105
110
  * @returns {void}
106
111
  */
107
112
  set value(newVal) {
@@ -115,8 +120,8 @@ class Signal {
115
120
  * The watcher will receive the new value as its argument.
116
121
  *
117
122
  * @public
118
- * @param {function(T): void} fn - The callback function to invoke on value change, where T is the value type.
119
- * @returns {function(): boolean} A function to unsubscribe the watcher.
123
+ * @param {(value: T) => void} fn - The callback function to invoke on value change.
124
+ * @returns {() => boolean} A function to unsubscribe the watcher.
120
125
  * @example
121
126
  * const unsubscribe = signal.watch((value) => console.log(value));
122
127
  * // Later...
@@ -139,6 +144,7 @@ class Signal {
139
144
  if (this._pending) return;
140
145
  this._pending = true;
141
146
  queueMicrotask(() => {
147
+ /** @type {(fn: (value: T) => void) => void} */
142
148
  this._watchers.forEach(fn => fn(this._value));
143
149
  this._pending = false;
144
150
  });
@@ -150,6 +156,9 @@ class Signal {
150
156
  * @classdesc A robust event emitter that enables inter-component communication through a publish-subscribe pattern.
151
157
  * Components can emit events and listen for events from other components, facilitating loose coupling
152
158
  * and reactive updates across the application.
159
+ * Events are handled synchronously in the order they were registered, with proper cleanup
160
+ * of unsubscribed handlers.
161
+ * Event names should follow the format 'namespace:action' (e.g., 'user:login', 'cart:update').
153
162
  *
154
163
  * @example
155
164
  * const emitter = new Emitter();
@@ -163,18 +172,19 @@ class Emitter {
163
172
  * @public
164
173
  */
165
174
  constructor() {
166
- /** @private {Map<string, Set<function(any): void>>} Map of event names to their registered handler functions */
175
+ /** @private {Map<string, Set<(data: unknown) => void>>} Map of event names to their registered handler functions */
167
176
  this._events = new Map();
168
177
  }
169
178
 
170
179
  /**
171
180
  * Registers an event handler for the specified event name.
172
181
  * The handler will be called with the event data when the event is emitted.
182
+ * Event names should follow the format 'namespace:action' for consistency.
173
183
  *
174
184
  * @public
175
- * @param {string} event - The name of the event to listen for.
176
- * @param {function(any): void} handler - The callback function to invoke when the event occurs.
177
- * @returns {function(): void} A function to unsubscribe the event handler.
185
+ * @param {string} event - The name of the event to listen for (e.g., 'user:login').
186
+ * @param {(data: unknown) => void} handler - The callback function to invoke when the event occurs.
187
+ * @returns {() => void} A function to unsubscribe the event handler.
178
188
  * @example
179
189
  * const unsubscribe = emitter.on('user:login', (user) => console.log(user));
180
190
  * // Later...
@@ -189,11 +199,17 @@ class Emitter {
189
199
  /**
190
200
  * Removes an event handler for the specified event name.
191
201
  * If no handler is provided, all handlers for the event are removed.
202
+ * Automatically cleans up empty event sets to prevent memory leaks.
192
203
  *
193
204
  * @public
194
- * @param {string} event - The name of the event.
195
- * @param {function(any): void} [handler] - The specific handler function to remove.
205
+ * @param {string} event - The name of the event to remove handlers from.
206
+ * @param {(data: unknown) => void} [handler] - The specific handler function to remove.
196
207
  * @returns {void}
208
+ * @example
209
+ * // Remove a specific handler
210
+ * emitter.off('user:login', loginHandler);
211
+ * // Remove all handlers for an event
212
+ * emitter.off('user:login');
197
213
  */
198
214
  off(event, handler) {
199
215
  if (!this._events.has(event)) return;
@@ -210,11 +226,17 @@ class Emitter {
210
226
  /**
211
227
  * Emits an event with the specified data to all registered handlers.
212
228
  * Handlers are called synchronously in the order they were registered.
229
+ * If no handlers are registered for the event, the emission is silently ignored.
213
230
  *
214
231
  * @public
215
232
  * @param {string} event - The name of the event to emit.
216
- * @param {...any} args - Optional arguments to pass to the event handlers.
233
+ * @param {...unknown} args - Optional arguments to pass to the event handlers.
217
234
  * @returns {void}
235
+ * @example
236
+ * // Emit an event with data
237
+ * emitter.emit('user:login', { name: 'John', role: 'admin' });
238
+ * // Emit an event with multiple arguments
239
+ * emitter.emit('cart:update', { items: [] }, { total: 0 });
218
240
  */
219
241
  emit(event, ...args) {
220
242
  if (!this._events.has(event)) return;
@@ -222,11 +244,27 @@ class Emitter {
222
244
  }
223
245
  }
224
246
 
247
+ /**
248
+ * A regular expression to match hyphenated lowercase letters.
249
+ * @private
250
+ * @type {RegExp}
251
+ */
252
+ const CAMEL_RE = /-([a-z])/g;
253
+
225
254
  /**
226
255
  * @class 🎨 Renderer
227
- * @classdesc A DOM renderer that handles efficient DOM updates through patching and diffing.
228
- * Provides methods for updating the DOM by comparing new and old structures and applying
229
- * only the necessary changes, minimizing layout thrashing and improving performance.
256
+ * @classdesc A high-performance DOM renderer that implements an optimized direct DOM diffing algorithm.
257
+ *
258
+ * Key features:
259
+ * - Single-pass diffing algorithm for efficient DOM updates
260
+ * - Key-based node reconciliation for optimal performance
261
+ * - Intelligent attribute handling for ARIA, data attributes, and boolean properties
262
+ * - Preservation of special Eleva-managed instances and style elements
263
+ * - Memory-efficient with reusable temporary containers
264
+ *
265
+ * The renderer is designed to minimize DOM operations while maintaining
266
+ * exact attribute synchronization and proper node identity preservation.
267
+ * It's particularly optimized for frequent updates and complex DOM structures.
230
268
  *
231
269
  * @example
232
270
  * const renderer = new Renderer();
@@ -236,45 +274,45 @@ class Emitter {
236
274
  */
237
275
  class Renderer {
238
276
  /**
239
- * Creates a new Renderer instance with a reusable temporary container for parsing HTML.
277
+ * Creates a new Renderer instance.
240
278
  * @public
241
279
  */
242
280
  constructor() {
243
- /** @private {HTMLElement} Reusable temporary container for parsing new HTML */
281
+ /**
282
+ * A temporary container to hold the new HTML content while diffing.
283
+ * @private
284
+ * @type {HTMLElement}
285
+ */
244
286
  this._tempContainer = document.createElement("div");
245
287
  }
246
288
 
247
289
  /**
248
- * Patches the DOM of a container element with new HTML content.
249
- * Efficiently updates the DOM by parsing new HTML into a reusable container
250
- * and applying only the necessary changes.
290
+ * Patches the DOM of the given container with the provided HTML string.
251
291
  *
252
292
  * @public
253
293
  * @param {HTMLElement} container - The container element to patch.
254
- * @param {string} newHtml - The new HTML content to apply.
294
+ * @param {string} newHtml - The new HTML string.
255
295
  * @returns {void}
256
- * @throws {Error} If container is not an HTMLElement, newHtml is not a string, or patching fails.
296
+ * @throws {TypeError} If container is not an HTMLElement or newHtml is not a string.
297
+ * @throws {Error} If DOM patching fails.
257
298
  */
258
299
  patchDOM(container, newHtml) {
259
300
  if (!(container instanceof HTMLElement)) {
260
- throw new Error("Container must be an HTMLElement");
301
+ throw new TypeError("Container must be an HTMLElement");
261
302
  }
262
303
  if (typeof newHtml !== "string") {
263
- throw new Error("newHtml must be a string");
304
+ throw new TypeError("newHtml must be a string");
264
305
  }
265
306
  try {
266
- // Directly set new HTML, replacing any existing content
267
307
  this._tempContainer.innerHTML = newHtml;
268
308
  this._diff(container, this._tempContainer);
269
- } catch {
270
- throw new Error("Failed to patch DOM");
309
+ } catch (error) {
310
+ throw new Error(`Failed to patch DOM: ${error.message}`);
271
311
  }
272
312
  }
273
313
 
274
314
  /**
275
- * Diffs two DOM trees (old and new) and applies updates to the old DOM.
276
- * This method recursively compares nodes and their attributes, applying only
277
- * the necessary changes to minimize DOM operations.
315
+ * Performs a diff between two DOM nodes and patches the old node to match the new node.
278
316
  *
279
317
  * @private
280
318
  * @param {HTMLElement} oldParent - The original DOM element.
@@ -282,75 +320,114 @@ class Renderer {
282
320
  * @returns {void}
283
321
  */
284
322
  _diff(oldParent, newParent) {
285
- if (oldParent.isEqualNode(newParent)) return;
286
- const oldChildren = oldParent.childNodes;
287
- const newChildren = newParent.childNodes;
288
- const maxLength = Math.max(oldChildren.length, newChildren.length);
289
- for (let i = 0; i < maxLength; i++) {
290
- const oldNode = oldChildren[i];
291
- const newNode = newChildren[i];
292
- if (oldNode?._eleva_instance) {
293
- continue;
294
- }
295
- if (!oldNode && newNode) {
296
- oldParent.appendChild(newNode.cloneNode(true));
297
- continue;
298
- }
299
- if (oldNode && !newNode) {
300
- if (oldNode.nodeName === "STYLE" && oldNode.hasAttribute("data-e-style")) {
301
- continue;
323
+ if (oldParent === newParent || oldParent.isEqualNode?.(newParent)) return;
324
+ const oldChildren = Array.from(oldParent.childNodes);
325
+ const newChildren = Array.from(newParent.childNodes);
326
+ let oldStartIdx = 0,
327
+ newStartIdx = 0;
328
+ let oldEndIdx = oldChildren.length - 1;
329
+ let newEndIdx = newChildren.length - 1;
330
+ let oldKeyMap = null;
331
+ while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
332
+ let oldStartNode = oldChildren[oldStartIdx];
333
+ let newStartNode = newChildren[newStartIdx];
334
+ if (!oldStartNode) {
335
+ oldStartNode = oldChildren[++oldStartIdx];
336
+ } else if (this._isSameNode(oldStartNode, newStartNode)) {
337
+ this._patchNode(oldStartNode, newStartNode);
338
+ oldStartIdx++;
339
+ newStartIdx++;
340
+ } else {
341
+ if (!oldKeyMap) {
342
+ oldKeyMap = this._createKeyMap(oldChildren, oldStartIdx, oldEndIdx);
343
+ }
344
+ const key = this._getNodeKey(newStartNode);
345
+ const oldNodeToMove = key ? oldKeyMap.get(key) : null;
346
+ if (oldNodeToMove) {
347
+ this._patchNode(oldNodeToMove, newStartNode);
348
+ oldParent.insertBefore(oldNodeToMove, oldStartNode);
349
+ oldChildren[oldChildren.indexOf(oldNodeToMove)] = null;
350
+ } else {
351
+ oldParent.insertBefore(newStartNode.cloneNode(true), oldStartNode);
302
352
  }
303
- oldParent.removeChild(oldNode);
304
- continue;
353
+ newStartIdx++;
305
354
  }
306
- const isSameType = oldNode.nodeType === newNode.nodeType && oldNode.nodeName === newNode.nodeName;
307
- if (!isSameType) {
308
- oldParent.replaceChild(newNode.cloneNode(true), oldNode);
309
- continue;
355
+ }
356
+ if (oldStartIdx > oldEndIdx) {
357
+ const refNode = newChildren[newEndIdx + 1] ? oldChildren[oldStartIdx] : null;
358
+ for (let i = newStartIdx; i <= newEndIdx; i++) {
359
+ if (newChildren[i]) oldParent.insertBefore(newChildren[i].cloneNode(true), refNode);
310
360
  }
311
- if (oldNode.nodeType === Node.ELEMENT_NODE) {
312
- const oldKey = oldNode.getAttribute("key");
313
- const newKey = newNode.getAttribute("key");
314
- if (oldKey !== newKey && (oldKey || newKey)) {
315
- oldParent.replaceChild(newNode.cloneNode(true), oldNode);
316
- continue;
317
- }
318
- this._updateAttributes(oldNode, newNode);
319
- this._diff(oldNode, newNode);
320
- } else if (oldNode.nodeType === Node.TEXT_NODE && oldNode.nodeValue !== newNode.nodeValue) {
321
- oldNode.nodeValue = newNode.nodeValue;
361
+ } else if (newStartIdx > newEndIdx) {
362
+ for (let i = oldStartIdx; i <= oldEndIdx; i++) {
363
+ if (oldChildren[i]) this._removeNode(oldParent, oldChildren[i]);
322
364
  }
323
365
  }
324
366
  }
325
367
 
326
368
  /**
327
- * Updates the attributes of an element to match those of a new element.
328
- * Handles special cases for ARIA attributes, data attributes, and boolean properties.
369
+ * Patches a single node.
370
+ *
371
+ * @private
372
+ * @param {Node} oldNode - The original DOM node.
373
+ * @param {Node} newNode - The new DOM node.
374
+ * @returns {void}
375
+ */
376
+ _patchNode(oldNode, newNode) {
377
+ if (oldNode?._eleva_instance) return;
378
+ if (!this._isSameNode(oldNode, newNode)) {
379
+ oldNode.replaceWith(newNode.cloneNode(true));
380
+ return;
381
+ }
382
+ if (oldNode.nodeType === Node.ELEMENT_NODE) {
383
+ this._updateAttributes(oldNode, newNode);
384
+ this._diff(oldNode, newNode);
385
+ } else if (oldNode.nodeType === Node.TEXT_NODE && oldNode.nodeValue !== newNode.nodeValue) {
386
+ oldNode.nodeValue = newNode.nodeValue;
387
+ }
388
+ }
389
+
390
+ /**
391
+ * Removes a node from its parent.
392
+ *
393
+ * @private
394
+ * @param {HTMLElement} parent - The parent element containing the node to remove.
395
+ * @param {Node} node - The node to remove.
396
+ * @returns {void}
397
+ */
398
+ _removeNode(parent, node) {
399
+ if (node.nodeName === "STYLE" && node.hasAttribute("data-e-style")) return;
400
+ parent.removeChild(node);
401
+ }
402
+
403
+ /**
404
+ * Updates the attributes of an element to match a new element's attributes.
329
405
  *
330
406
  * @private
331
- * @param {HTMLElement} oldEl - The element to update.
332
- * @param {HTMLElement} newEl - The element providing the updated attributes.
407
+ * @param {HTMLElement} oldEl - The original element to update.
408
+ * @param {HTMLElement} newEl - The new element to update.
333
409
  * @returns {void}
334
410
  */
335
411
  _updateAttributes(oldEl, newEl) {
336
412
  const oldAttrs = oldEl.attributes;
337
413
  const newAttrs = newEl.attributes;
338
414
 
339
- // Update/add new attributes
340
- for (const {
341
- name,
342
- value
343
- } of newAttrs) {
415
+ // Single pass for new/updated attributes
416
+ for (let i = 0; i < newAttrs.length; i++) {
417
+ const {
418
+ name,
419
+ value
420
+ } = newAttrs[i];
344
421
  if (name.startsWith("@")) continue;
345
422
  if (oldEl.getAttribute(name) === value) continue;
346
423
  oldEl.setAttribute(name, value);
347
424
  if (name.startsWith("aria-")) {
348
- const prop = "aria" + name.slice(5).replace(/-([a-z])/g, (_, l) => l.toUpperCase());
425
+ const prop = "aria" + name.slice(5).replace(CAMEL_RE, (_, l) => l.toUpperCase());
349
426
  oldEl[prop] = value;
350
427
  } else if (name.startsWith("data-")) {
351
428
  oldEl.dataset[name.slice(5)] = value;
352
429
  } else {
353
- const prop = name.replace(/-([a-z])/g, (_, l) => l.toUpperCase());
430
+ const prop = name.replace(CAMEL_RE, (_, l) => l.toUpperCase());
354
431
  if (prop in oldEl) {
355
432
  const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(oldEl), prop);
356
433
  const isBoolean = typeof oldEl[prop] === "boolean" || descriptor?.get && typeof descriptor.get.call(oldEl) === "boolean";
@@ -363,47 +440,134 @@ class Renderer {
363
440
  }
364
441
  }
365
442
 
366
- // Remove old attributes
367
- for (const {
368
- name
369
- } of oldAttrs) {
443
+ // Remove any attributes no longer present
444
+ for (let i = oldAttrs.length - 1; i >= 0; i--) {
445
+ const name = oldAttrs[i].name;
370
446
  if (!newEl.hasAttribute(name)) {
371
447
  oldEl.removeAttribute(name);
372
448
  }
373
449
  }
374
450
  }
451
+
452
+ /**
453
+ * Determines if two nodes are the same based on their type, name, and key attributes.
454
+ *
455
+ * @private
456
+ * @param {Node} oldNode - The first node to compare.
457
+ * @param {Node} newNode - The second node to compare.
458
+ * @returns {boolean} True if the nodes are considered the same, false otherwise.
459
+ */
460
+ _isSameNode(oldNode, newNode) {
461
+ if (!oldNode || !newNode) return false;
462
+ const oldKey = oldNode.nodeType === Node.ELEMENT_NODE ? oldNode.getAttribute("key") : null;
463
+ const newKey = newNode.nodeType === Node.ELEMENT_NODE ? newNode.getAttribute("key") : null;
464
+ if (oldKey && newKey) return oldKey === newKey;
465
+ return !oldKey && !newKey && oldNode.nodeType === newNode.nodeType && oldNode.nodeName === newNode.nodeName;
466
+ }
467
+
468
+ /**
469
+ * Creates a key map for the children of a parent node.
470
+ *
471
+ * @private
472
+ * @param {Array<Node>} children - The children of the parent node.
473
+ * @param {number} start - The start index of the children.
474
+ * @param {number} end - The end index of the children.
475
+ * @returns {Map<string, Node>} A key map for the children.
476
+ */
477
+ _createKeyMap(children, start, end) {
478
+ const map = new Map();
479
+ for (let i = start; i <= end; i++) {
480
+ const child = children[i];
481
+ const key = this._getNodeKey(child);
482
+ if (key) map.set(key, child);
483
+ }
484
+ return map;
485
+ }
486
+
487
+ /**
488
+ * Extracts the key attribute from a node if it exists.
489
+ *
490
+ * @private
491
+ * @param {Node} node - The node to extract the key from.
492
+ * @returns {string|null} The key attribute value or null if not found.
493
+ */
494
+ _getNodeKey(node) {
495
+ return node?.nodeType === Node.ELEMENT_NODE ? node.getAttribute("key") : null;
496
+ }
375
497
  }
376
498
 
377
499
  /**
378
500
  * @typedef {Object} ComponentDefinition
379
- * @property {function(Object<string, any>): (Object<string, any>|Promise<Object<string, any>>)} [setup]
501
+ * @property {function(ComponentContext): (Record<string, unknown>|Promise<Record<string, unknown>>)} [setup]
380
502
  * Optional setup function that initializes the component's state and returns reactive data
381
- * @property {(function(Object<string, any>): string|Promise<string>|string)} template
503
+ * @property {(function(ComponentContext): string|Promise<string>)} template
382
504
  * Required function that defines the component's HTML structure
383
- * @property {(function(Object<string, any>): string)|string} [style]
505
+ * @property {(function(ComponentContext): string)|string} [style]
384
506
  * Optional function or string that provides component-scoped CSS styles
385
- * @property {Object<string, ComponentDefinition>} [children]
507
+ * @property {Record<string, ComponentDefinition>} [children]
386
508
  * Optional object defining nested child components
387
509
  */
388
510
 
389
511
  /**
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
512
+ * @typedef {Object} ComponentContext
513
+ * @property {Record<string, unknown>} props
514
+ * Component properties passed during mounting
515
+ * @property {Emitter} emitter
516
+ * Event emitter instance for component event handling
517
+ * @property {function<T>(value: T): Signal<T>} signal
518
+ * Factory function to create reactive Signal instances
519
+ * @property {function(LifecycleHookContext): Promise<void>} [onBeforeMount]
520
+ * Hook called before component mounting
521
+ * @property {function(LifecycleHookContext): Promise<void>} [onMount]
522
+ * Hook called after component mounting
523
+ * @property {function(LifecycleHookContext): Promise<void>} [onBeforeUpdate]
524
+ * Hook called before component update
525
+ * @property {function(LifecycleHookContext): Promise<void>} [onUpdate]
526
+ * Hook called after component update
527
+ * @property {function(UnmountHookContext): Promise<void>} [onUnmount]
528
+ * Hook called during component unmounting
529
+ */
530
+
531
+ /**
532
+ * @typedef {Object} LifecycleHookContext
533
+ * @property {HTMLElement} container
534
+ * The DOM element where the component is mounted
535
+ * @property {ComponentContext} context
536
+ * The component's reactive state and context data
537
+ */
538
+
539
+ /**
540
+ * @typedef {Object} UnmountHookContext
541
+ * @property {HTMLElement} container
542
+ * The DOM element where the component is mounted
543
+ * @property {ComponentContext} context
544
+ * The component's reactive state and context data
545
+ * @property {{
546
+ * watchers: Array<() => void>, // Signal watcher cleanup functions
547
+ * listeners: Array<() => void>, // Event listener cleanup functions
548
+ * children: Array<MountResult> // Child component instances
549
+ * }} cleanup
550
+ * Object containing cleanup functions and instances
395
551
  */
396
552
 
397
553
  /**
398
554
  * @typedef {Object} MountResult
399
555
  * @property {HTMLElement} container
400
556
  * The DOM element where the component is mounted
401
- * @property {Object<string, any>} data
557
+ * @property {ComponentContext} data
402
558
  * The component's reactive state and context data
403
- * @property {function(): void} unmount
559
+ * @property {function(): Promise<void>} unmount
404
560
  * Function to clean up and unmount the component
405
561
  */
406
562
 
563
+ /**
564
+ * @typedef {Object} ElevaPlugin
565
+ * @property {function(Eleva, Record<string, unknown>): void} install
566
+ * Function that installs the plugin into the Eleva instance
567
+ * @property {string} name
568
+ * Unique identifier name for the plugin
569
+ */
570
+
407
571
  /**
408
572
  * @class 🧩 Eleva
409
573
  * @classdesc A modern, signal-based component runtime framework that provides lifecycle hooks,
@@ -411,12 +575,26 @@ class Renderer {
411
575
  * event handling, and DOM rendering with a focus on performance and developer experience.
412
576
  *
413
577
  * @example
578
+ * // Basic component creation and mounting
414
579
  * const app = new Eleva("myApp");
415
580
  * app.component("myComponent", {
416
- * template: (ctx) => `<div>Hello ${ctx.props.name}</div>`,
417
- * setup: (ctx) => ({ count: new Signal(0) })
581
+ * setup: (ctx) => ({ count: ctx.signal(0) }),
582
+ * template: (ctx) => `<div>Hello ${ctx.props.name}</div>`
418
583
  * });
419
584
  * app.mount(document.getElementById("app"), "myComponent", { name: "World" });
585
+ *
586
+ * @example
587
+ * // Using lifecycle hooks
588
+ * app.component("lifecycleDemo", {
589
+ * setup: () => {
590
+ * return {
591
+ * onMount: ({ container, context }) => {
592
+ * console.log('Component mounted!');
593
+ * }
594
+ * };
595
+ * },
596
+ * template: `<div>Lifecycle Demo</div>`
597
+ * });
420
598
  */
421
599
  class Eleva {
422
600
  /**
@@ -424,13 +602,24 @@ class Eleva {
424
602
  *
425
603
  * @public
426
604
  * @param {string} name - The unique identifier name for this Eleva instance.
427
- * @param {Object<string, any>} [config={}] - Optional configuration object for the instance.
605
+ * @param {Record<string, unknown>} [config={}] - Optional configuration object for the instance.
428
606
  * May include framework-wide settings and default behaviors.
607
+ * @throws {Error} If the name is not provided or is not a string.
608
+ * @returns {Eleva} A new Eleva instance.
609
+ *
610
+ * @example
611
+ * const app = new Eleva("myApp");
612
+ * app.component("myComponent", {
613
+ * setup: (ctx) => ({ count: ctx.signal(0) }),
614
+ * template: (ctx) => `<div>Hello ${ctx.props.name}!</div>`
615
+ * });
616
+ * app.mount(document.getElementById("app"), "myComponent", { name: "World" });
617
+ *
429
618
  */
430
619
  constructor(name, config = {}) {
431
620
  /** @public {string} The unique identifier name for this Eleva instance */
432
621
  this.name = name;
433
- /** @public {Object<string, any>} Optional configuration object for the Eleva instance */
622
+ /** @public {Object<string, unknown>} Optional configuration object for the Eleva instance */
434
623
  this.config = config;
435
624
  /** @public {Emitter} Instance of the event emitter for handling component events */
436
625
  this.emitter = new Emitter();
@@ -443,8 +632,6 @@ class Eleva {
443
632
  this._components = new Map();
444
633
  /** @private {Map<string, ElevaPlugin>} Collection of installed plugin instances by name */
445
634
  this._plugins = new Map();
446
- /** @private {string[]} Array of lifecycle hook names supported by components */
447
- this._lifecycleHooks = ["onBeforeMount", "onMount", "onBeforeUpdate", "onUpdate", "onUnmount"];
448
635
  /** @private {boolean} Flag indicating if the root component is currently mounted */
449
636
  this._isMounted = false;
450
637
  }
@@ -456,7 +643,7 @@ class Eleva {
456
643
  *
457
644
  * @public
458
645
  * @param {ElevaPlugin} plugin - The plugin object which must have an `install` function.
459
- * @param {Object<string, any>} [options={}] - Optional configuration options for the plugin.
646
+ * @param {Object<string, unknown>} [options={}] - Optional configuration options for the plugin.
460
647
  * @returns {Eleva} The Eleva instance (for method chaining).
461
648
  * @example
462
649
  * app.use(myPlugin, { option1: "value1" });
@@ -495,7 +682,7 @@ class Eleva {
495
682
  * @public
496
683
  * @param {HTMLElement} container - The DOM element where the component will be mounted.
497
684
  * @param {string|ComponentDefinition} compName - The name of the registered component or a direct component definition.
498
- * @param {Object<string, any>} [props={}] - Optional properties to pass to the component.
685
+ * @param {Object<string, unknown>} [props={}] - Optional properties to pass to the component.
499
686
  * @returns {Promise<MountResult>}
500
687
  * A Promise that resolves to an object containing:
501
688
  * - container: The mounted component's container element
@@ -529,21 +716,12 @@ class Eleva {
529
716
  children
530
717
  } = definition;
531
718
 
532
- /**
533
- * Creates the initial context object for the component instance.
534
- * This context provides core functionality and will be merged with setup data.
535
- * @type {Object<string, any>}
536
- * @property {Object<string, any>} props - Component properties passed during mounting
537
- * @property {Emitter} emitter - Event emitter instance for component event handling
538
- * @property {function(any): Signal} signal - Factory function to create reactive Signal instances
539
- * @property {Object<string, function(): void>} ...lifecycleHooks - Prepared lifecycle hook functions
540
- */
719
+ /** @type {ComponentContext} */
541
720
  const context = {
542
721
  props,
543
722
  emitter: this.emitter,
544
- /** @type {(v: any) => Signal<any>} */
545
- signal: v => new this.signal(v),
546
- ...this._prepareLifecycleHooks()
723
+ /** @type {(v: unknown) => Signal<unknown>} */
724
+ signal: v => new this.signal(v)
547
725
  };
548
726
 
549
727
  /**
@@ -554,30 +732,38 @@ class Eleva {
554
732
  * 3. Rendering the component
555
733
  * 4. Managing component lifecycle
556
734
  *
557
- * @param {Object<string, any>} data - Data returned from the component's setup function
735
+ * @param {Object<string, unknown>} data - Data returned from the component's setup function
558
736
  * @returns {Promise<MountResult>} An object containing:
559
737
  * - container: The mounted component's container element
560
738
  * - data: The component's reactive state and context
561
739
  * - unmount: Function to clean up and unmount the component
562
740
  */
563
741
  const processMount = async data => {
564
- /** @type {Object<string, any>} */
742
+ /** @type {ComponentContext} */
565
743
  const mergedContext = {
566
744
  ...context,
567
745
  ...data
568
746
  };
569
747
  /** @type {Array<() => void>} */
570
- const watcherUnsubscribers = [];
748
+ const watchers = [];
571
749
  /** @type {Array<MountResult>} */
572
750
  const childInstances = [];
573
751
  /** @type {Array<() => void>} */
574
- const cleanupListeners = [];
752
+ const listeners = [];
575
753
 
576
754
  // Execute before hooks
577
755
  if (!this._isMounted) {
578
- mergedContext.onBeforeMount && mergedContext.onBeforeMount();
756
+ /** @type {LifecycleHookContext} */
757
+ await mergedContext.onBeforeMount?.({
758
+ container,
759
+ context: mergedContext
760
+ });
579
761
  } else {
580
- mergedContext.onBeforeUpdate && mergedContext.onBeforeUpdate();
762
+ /** @type {LifecycleHookContext} */
763
+ await mergedContext.onBeforeUpdate?.({
764
+ container,
765
+ context: mergedContext
766
+ });
581
767
  }
582
768
 
583
769
  /**
@@ -590,14 +776,22 @@ class Eleva {
590
776
  const templateResult = typeof template === "function" ? await template(mergedContext) : template;
591
777
  const newHtml = TemplateEngine.parse(templateResult, mergedContext);
592
778
  this.renderer.patchDOM(container, newHtml);
593
- this._processEvents(container, mergedContext, cleanupListeners);
779
+ this._processEvents(container, mergedContext, listeners);
594
780
  if (style) this._injectStyles(container, compName, style, mergedContext);
595
781
  if (children) await this._mountComponents(container, children, childInstances);
596
782
  if (!this._isMounted) {
597
- mergedContext.onMount && mergedContext.onMount();
783
+ /** @type {LifecycleHookContext} */
784
+ await mergedContext.onMount?.({
785
+ container,
786
+ context: mergedContext
787
+ });
598
788
  this._isMounted = true;
599
789
  } else {
600
- mergedContext.onUpdate && mergedContext.onUpdate();
790
+ /** @type {LifecycleHookContext} */
791
+ await mergedContext.onUpdate?.({
792
+ container,
793
+ context: mergedContext
794
+ });
601
795
  }
602
796
  };
603
797
 
@@ -607,7 +801,7 @@ class Eleva {
607
801
  * Stores unsubscribe functions to clean up watchers when component unmounts.
608
802
  */
609
803
  for (const val of Object.values(data)) {
610
- if (val instanceof Signal) watcherUnsubscribers.push(val.watch(render));
804
+ if (val instanceof Signal) watchers.push(val.watch(render));
611
805
  }
612
806
  await render();
613
807
  const instance = {
@@ -618,11 +812,20 @@ class Eleva {
618
812
  *
619
813
  * @returns {void}
620
814
  */
621
- unmount: () => {
622
- for (const fn of watcherUnsubscribers) fn();
623
- for (const fn of cleanupListeners) fn();
624
- for (const child of childInstances) child.unmount();
625
- mergedContext.onUnmount && mergedContext.onUnmount();
815
+ unmount: async () => {
816
+ /** @type {UnmountHookContext} */
817
+ await mergedContext.onUnmount?.({
818
+ container,
819
+ context: mergedContext,
820
+ cleanup: {
821
+ watchers: watchers,
822
+ listeners: listeners,
823
+ children: childInstances
824
+ }
825
+ });
826
+ for (const fn of watchers) fn();
827
+ for (const fn of listeners) fn();
828
+ for (const child of childInstances) await child.unmount();
626
829
  container.innerHTML = "";
627
830
  delete container._eleva_instance;
628
831
  }
@@ -636,47 +839,37 @@ class Eleva {
636
839
  return await processMount(setupResult);
637
840
  }
638
841
 
639
- /**
640
- * Prepares default no-operation lifecycle hook functions for a component.
641
- * These hooks will be called at various stages of the component's lifecycle.
642
- *
643
- * @private
644
- * @returns {Object<string, function(): void>} An object mapping lifecycle hook names to empty functions.
645
- * The returned object will be merged with the component's context.
646
- */
647
- _prepareLifecycleHooks() {
648
- /** @type {Object<string, () => void>} */
649
- const hooks = {};
650
- for (const hook of this._lifecycleHooks) {
651
- hooks[hook] = () => {};
652
- }
653
- return hooks;
654
- }
655
-
656
842
  /**
657
843
  * Processes DOM elements for event binding based on attributes starting with "@".
658
844
  * This method handles the event delegation system and ensures proper cleanup of event listeners.
659
845
  *
660
846
  * @private
661
847
  * @param {HTMLElement} container - The container element in which to search for event attributes.
662
- * @param {Object<string, any>} context - The current component context containing event handler definitions.
663
- * @param {Array<Function>} cleanupListeners - Array to collect cleanup functions for each event listener.
848
+ * @param {ComponentContext} context - The current component context containing event handler definitions.
849
+ * @param {Array<() => void>} listeners - Array to collect cleanup functions for each event listener.
664
850
  * @returns {void}
665
851
  */
666
- _processEvents(container, context, cleanupListeners) {
852
+ _processEvents(container, context, listeners) {
853
+ /** @type {NodeListOf<Element>} */
667
854
  const elements = container.querySelectorAll("*");
668
855
  for (const el of elements) {
856
+ /** @type {NamedNodeMap} */
669
857
  const attrs = el.attributes;
670
858
  for (let i = 0; i < attrs.length; i++) {
859
+ /** @type {Attr} */
671
860
  const attr = attrs[i];
672
861
  if (!attr.name.startsWith("@")) continue;
862
+
863
+ /** @type {keyof HTMLElementEventMap} */
673
864
  const event = attr.name.slice(1);
865
+ /** @type {string} */
674
866
  const handlerName = attr.value;
867
+ /** @type {(event: Event) => void} */
675
868
  const handler = context[handlerName] || TemplateEngine.evaluate(handlerName, context);
676
869
  if (typeof handler === "function") {
677
870
  el.addEventListener(event, handler);
678
871
  el.removeAttribute(attr.name);
679
- cleanupListeners.push(() => el.removeEventListener(event, handler));
872
+ listeners.push(() => el.removeEventListener(event, handler));
680
873
  }
681
874
  }
682
875
  }
@@ -689,12 +882,14 @@ class Eleva {
689
882
  * @private
690
883
  * @param {HTMLElement} container - The container element where styles should be injected.
691
884
  * @param {string} compName - The component name used to identify the style element.
692
- * @param {(function(Object<string, any>): string)|string} styleDef - The component's style definition (function or string).
693
- * @param {Object<string, any>} context - The current component context for style interpolation.
885
+ * @param {(function(ComponentContext): string)|string} styleDef - The component's style definition (function or string).
886
+ * @param {ComponentContext} context - The current component context for style interpolation.
694
887
  * @returns {void}
695
888
  */
696
889
  _injectStyles(container, compName, styleDef, context) {
890
+ /** @type {string} */
697
891
  const newStyle = typeof styleDef === "function" ? TemplateEngine.parse(styleDef(context), context) : styleDef;
892
+ /** @type {HTMLStyleElement|null} */
698
893
  let styleEl = container.querySelector(`style[data-e-style="${compName}"]`);
699
894
  if (styleEl && styleEl.textContent === newStyle) return;
700
895
  if (!styleEl) {
@@ -712,7 +907,7 @@ class Eleva {
712
907
  * @private
713
908
  * @param {HTMLElement} element - The DOM element to extract props from
714
909
  * @param {string} prefix - The prefix to look for in attributes
715
- * @returns {Object<string, any>} An object containing the extracted props
910
+ * @returns {Record<string, string>} An object containing the extracted props
716
911
  * @example
717
912
  * // For an element with attributes:
718
913
  * // <div :name="John" :age="25">
@@ -758,7 +953,9 @@ class Eleva {
758
953
  if (!selector) continue;
759
954
  for (const el of container.querySelectorAll(selector)) {
760
955
  if (!(el instanceof HTMLElement)) continue;
956
+ /** @type {Record<string, string>} */
761
957
  const props = this._extractProps(el, ":");
958
+ /** @type {MountResult} */
762
959
  const instance = await this.mount(el, component, props);
763
960
  if (instance && !childInstances.includes(instance)) {
764
961
  childInstances.push(instance);