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