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