eleva 1.2.17-beta → 1.2.18-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.18-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,121 +274,173 @@ 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
- * @param {HTMLElement} container - The container element to patch.
254
- * @param {string} newHtml - The new HTML content to apply.
293
+ * @param {HTMLElement} container - The container whose DOM will be patched.
294
+ * @param {string} newHtml - The new HTML string.
295
+ * @throws {TypeError} If the container is not an HTMLElement or newHtml is not a string.
296
+ * @throws {Error} If the DOM patching fails.
255
297
  * @returns {void}
256
- * @throws {Error} If container is not an HTMLElement, newHtml is not a string, or 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
- * @param {HTMLElement} oldParent - The original DOM element.
281
- * @param {HTMLElement} newParent - The new DOM element.
318
+ * @param {Node} oldParent - The old parent node to be patched.
319
+ * @param {Node} newParent - The new parent node to compare.
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) {
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
+ oldStartIdx++;
293
336
  continue;
294
337
  }
295
- if (!oldNode && newNode) {
296
- oldParent.appendChild(newNode.cloneNode(true));
338
+ if (!newStartNode) {
339
+ newStartIdx++;
297
340
  continue;
298
341
  }
299
- if (oldNode && !newNode) {
300
- if (oldNode.nodeName === "STYLE" && oldNode.hasAttribute("data-e-style")) {
301
- continue;
342
+ if (this._keysMatch(oldStartNode, newStartNode)) {
343
+ this._patchNode(oldStartNode, newStartNode);
344
+ oldStartIdx++;
345
+ newStartIdx++;
346
+ } else {
347
+ oldKeyMap ??= this._createKeyMap(oldChildren, oldStartIdx, oldEndIdx);
348
+ const newKey = newStartNode.nodeType === Node.ELEMENT_NODE ? newStartNode.getAttribute("key") : null;
349
+ const moveIndex = newKey ? oldKeyMap.get(newKey) : undefined;
350
+ const oldNodeToMove = moveIndex !== undefined ? oldChildren[moveIndex] : null;
351
+ if (oldNodeToMove) {
352
+ this._patchNode(oldNodeToMove, newStartNode);
353
+ oldParent.insertBefore(oldNodeToMove, oldStartNode);
354
+ if (moveIndex !== undefined) oldChildren[moveIndex] = null;
355
+ } else {
356
+ oldParent.insertBefore(newStartNode.cloneNode(true), oldStartNode);
302
357
  }
303
- oldParent.removeChild(oldNode);
304
- continue;
358
+ newStartIdx++;
305
359
  }
306
- const isSameType = oldNode.nodeType === newNode.nodeType && oldNode.nodeName === newNode.nodeName;
307
- if (!isSameType) {
308
- oldParent.replaceChild(newNode.cloneNode(true), oldNode);
309
- continue;
360
+ }
361
+
362
+ // Cleanup
363
+ if (oldStartIdx > oldEndIdx) {
364
+ const refNode = newChildren[newEndIdx + 1] ? oldChildren[oldStartIdx] : null;
365
+ for (let i = newStartIdx; i <= newEndIdx; i++) {
366
+ if (newChildren[i]) oldParent.insertBefore(newChildren[i].cloneNode(true), refNode);
310
367
  }
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;
368
+ } else if (newStartIdx > newEndIdx) {
369
+ for (let i = oldStartIdx; i <= oldEndIdx; i++) {
370
+ const node = oldChildren[i];
371
+ if (node && !(node.nodeName === "STYLE" && node.hasAttribute("data-e-style"))) {
372
+ oldParent.removeChild(node);
317
373
  }
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;
322
374
  }
323
375
  }
324
376
  }
325
377
 
326
378
  /**
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.
379
+ * Checks if the node types match.
380
+ *
381
+ * @private
382
+ * @param {Node} oldNode - The old node.
383
+ * @param {Node} newNode - The new node.
384
+ * @returns {boolean} True if the nodes match, false otherwise.
385
+ */
386
+ _keysMatch(oldNode, newNode) {
387
+ if (oldNode.nodeType !== Node.ELEMENT_NODE) return true;
388
+ const oldKey = oldNode.getAttribute("key");
389
+ const newKey = newNode.getAttribute("key");
390
+ return oldKey === newKey;
391
+ }
392
+
393
+ /**
394
+ * Patches a node.
395
+ *
396
+ * @private
397
+ * @param {Node} oldNode - The old node to patch.
398
+ * @param {Node} newNode - The new node to patch.
399
+ * @returns {void}
400
+ */
401
+ _patchNode(oldNode, newNode) {
402
+ if (oldNode?._eleva_instance) return;
403
+ if (oldNode.nodeType !== newNode.nodeType || oldNode.nodeName !== newNode.nodeName) {
404
+ oldNode.replaceWith(newNode.cloneNode(true));
405
+ return;
406
+ }
407
+ if (oldNode.nodeType === Node.ELEMENT_NODE) {
408
+ const oldEl = oldNode;
409
+ const newEl = newNode;
410
+ this._updateAttributes(oldEl, newEl);
411
+ this._diff(oldEl, newEl);
412
+ } else if (oldNode.nodeType === Node.TEXT_NODE && oldNode.nodeValue !== newNode.nodeValue) {
413
+ oldNode.nodeValue = newNode.nodeValue;
414
+ }
415
+ }
416
+
417
+ /**
418
+ * Updates the attributes of an element.
329
419
  *
330
420
  * @private
331
- * @param {HTMLElement} oldEl - The element to update.
332
- * @param {HTMLElement} newEl - The element providing the updated attributes.
421
+ * @param {HTMLElement} oldEl - The old element to update.
422
+ * @param {HTMLElement} newEl - The new element to update.
333
423
  * @returns {void}
334
424
  */
335
425
  _updateAttributes(oldEl, newEl) {
336
426
  const oldAttrs = oldEl.attributes;
337
427
  const newAttrs = newEl.attributes;
338
428
 
339
- // Update/add new attributes
340
- for (const {
341
- name,
342
- value
343
- } of newAttrs) {
344
- if (name.startsWith("@")) continue;
345
- if (oldEl.getAttribute(name) === value) continue;
429
+ // Single pass for new/updated attributes
430
+ for (let i = 0; i < newAttrs.length; i++) {
431
+ const {
432
+ name,
433
+ value
434
+ } = newAttrs[i];
435
+ if (name[0] === "@" || oldEl.getAttribute(name) === value) continue;
346
436
  oldEl.setAttribute(name, value);
347
- if (name.startsWith("aria-")) {
348
- const prop = "aria" + name.slice(5).replace(/-([a-z])/g, (_, l) => l.toUpperCase());
349
- oldEl[prop] = value;
350
- } else if (name.startsWith("data-")) {
437
+ if (name[0] === "a" && name[4] === "-") {
438
+ const s = name.slice(5);
439
+ oldEl["aria" + s.replace(CAMEL_RE, (_, l) => l.toUpperCase())] = value;
440
+ } else if (name[0] === "d" && name[3] === "-") {
351
441
  oldEl.dataset[name.slice(5)] = value;
352
442
  } else {
353
- const prop = name.replace(/-([a-z])/g, (_, l) => l.toUpperCase());
443
+ const prop = name.includes("-") ? name.replace(CAMEL_RE, (_, l) => l.toUpperCase()) : name;
354
444
  if (prop in oldEl) {
355
445
  const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(oldEl), prop);
356
446
  const isBoolean = typeof oldEl[prop] === "boolean" || descriptor?.get && typeof descriptor.get.call(oldEl) === "boolean";
@@ -363,47 +453,109 @@ class Renderer {
363
453
  }
364
454
  }
365
455
 
366
- // Remove old attributes
367
- for (const {
368
- name
369
- } of oldAttrs) {
456
+ // Remove any attributes no longer present
457
+ for (let i = oldAttrs.length - 1; i >= 0; i--) {
458
+ const name = oldAttrs[i].name;
370
459
  if (!newEl.hasAttribute(name)) {
371
460
  oldEl.removeAttribute(name);
372
461
  }
373
462
  }
374
463
  }
464
+
465
+ /**
466
+ * Creates a key map for the children of a parent node.
467
+ *
468
+ * @private
469
+ * @param {Array<Node>} children - The children of the parent node.
470
+ * @param {number} start - The start index of the children.
471
+ * @param {number} end - The end index of the children.
472
+ * @returns {Map<string, number>} A map of key to child index.
473
+ */
474
+ _createKeyMap(children, start, end) {
475
+ const map = new Map();
476
+ for (let i = start; i <= end; i++) {
477
+ const child = children[i];
478
+ if (child?.nodeType === Node.ELEMENT_NODE) {
479
+ const key = child.getAttribute("key");
480
+ if (key) map.set(key, i);
481
+ }
482
+ }
483
+ return map;
484
+ }
375
485
  }
376
486
 
377
487
  /**
378
488
  * @typedef {Object} ComponentDefinition
379
- * @property {function(Object<string, any>): (Object<string, any>|Promise<Object<string, any>>)} [setup]
489
+ * @property {function(ComponentContext): (Record<string, unknown>|Promise<Record<string, unknown>>)} [setup]
380
490
  * Optional setup function that initializes the component's state and returns reactive data
381
- * @property {(function(Object<string, any>): string|Promise<string>|string)} template
491
+ * @property {(function(ComponentContext): string|Promise<string>)} template
382
492
  * Required function that defines the component's HTML structure
383
- * @property {(function(Object<string, any>): string)|string} [style]
493
+ * @property {(function(ComponentContext): string)|string} [style]
384
494
  * Optional function or string that provides component-scoped CSS styles
385
- * @property {Object<string, ComponentDefinition>} [children]
495
+ * @property {Record<string, ComponentDefinition>} [children]
386
496
  * Optional object defining nested child components
387
497
  */
388
498
 
389
499
  /**
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
500
+ * @typedef {Object} ComponentContext
501
+ * @property {Record<string, unknown>} props
502
+ * Component properties passed during mounting
503
+ * @property {Emitter} emitter
504
+ * Event emitter instance for component event handling
505
+ * @property {function<T>(value: T): Signal<T>} signal
506
+ * Factory function to create reactive Signal instances
507
+ * @property {function(LifecycleHookContext): Promise<void>} [onBeforeMount]
508
+ * Hook called before component mounting
509
+ * @property {function(LifecycleHookContext): Promise<void>} [onMount]
510
+ * Hook called after component mounting
511
+ * @property {function(LifecycleHookContext): Promise<void>} [onBeforeUpdate]
512
+ * Hook called before component update
513
+ * @property {function(LifecycleHookContext): Promise<void>} [onUpdate]
514
+ * Hook called after component update
515
+ * @property {function(UnmountHookContext): Promise<void>} [onUnmount]
516
+ * Hook called during component unmounting
517
+ */
518
+
519
+ /**
520
+ * @typedef {Object} LifecycleHookContext
521
+ * @property {HTMLElement} container
522
+ * The DOM element where the component is mounted
523
+ * @property {ComponentContext} context
524
+ * The component's reactive state and context data
525
+ */
526
+
527
+ /**
528
+ * @typedef {Object} UnmountHookContext
529
+ * @property {HTMLElement} container
530
+ * The DOM element where the component is mounted
531
+ * @property {ComponentContext} context
532
+ * The component's reactive state and context data
533
+ * @property {{
534
+ * watchers: Array<() => void>, // Signal watcher cleanup functions
535
+ * listeners: Array<() => void>, // Event listener cleanup functions
536
+ * children: Array<MountResult> // Child component instances
537
+ * }} cleanup
538
+ * Object containing cleanup functions and instances
395
539
  */
396
540
 
397
541
  /**
398
542
  * @typedef {Object} MountResult
399
543
  * @property {HTMLElement} container
400
544
  * The DOM element where the component is mounted
401
- * @property {Object<string, any>} data
545
+ * @property {ComponentContext} data
402
546
  * The component's reactive state and context data
403
- * @property {function(): void} unmount
547
+ * @property {function(): Promise<void>} unmount
404
548
  * Function to clean up and unmount the component
405
549
  */
406
550
 
551
+ /**
552
+ * @typedef {Object} ElevaPlugin
553
+ * @property {function(Eleva, Record<string, unknown>): void} install
554
+ * Function that installs the plugin into the Eleva instance
555
+ * @property {string} name
556
+ * Unique identifier name for the plugin
557
+ */
558
+
407
559
  /**
408
560
  * @class 🧩 Eleva
409
561
  * @classdesc A modern, signal-based component runtime framework that provides lifecycle hooks,
@@ -411,12 +563,26 @@ class Renderer {
411
563
  * event handling, and DOM rendering with a focus on performance and developer experience.
412
564
  *
413
565
  * @example
566
+ * // Basic component creation and mounting
414
567
  * const app = new Eleva("myApp");
415
568
  * app.component("myComponent", {
416
- * template: (ctx) => `<div>Hello ${ctx.props.name}</div>`,
417
- * setup: (ctx) => ({ count: new Signal(0) })
569
+ * setup: (ctx) => ({ count: ctx.signal(0) }),
570
+ * template: (ctx) => `<div>Hello ${ctx.props.name}</div>`
418
571
  * });
419
572
  * app.mount(document.getElementById("app"), "myComponent", { name: "World" });
573
+ *
574
+ * @example
575
+ * // Using lifecycle hooks
576
+ * app.component("lifecycleDemo", {
577
+ * setup: () => {
578
+ * return {
579
+ * onMount: ({ container, context }) => {
580
+ * console.log('Component mounted!');
581
+ * }
582
+ * };
583
+ * },
584
+ * template: `<div>Lifecycle Demo</div>`
585
+ * });
420
586
  */
421
587
  class Eleva {
422
588
  /**
@@ -424,13 +590,24 @@ class Eleva {
424
590
  *
425
591
  * @public
426
592
  * @param {string} name - The unique identifier name for this Eleva instance.
427
- * @param {Object<string, any>} [config={}] - Optional configuration object for the instance.
593
+ * @param {Record<string, unknown>} [config={}] - Optional configuration object for the instance.
428
594
  * May include framework-wide settings and default behaviors.
595
+ * @throws {Error} If the name is not provided or is not a string.
596
+ * @returns {Eleva} A new Eleva instance.
597
+ *
598
+ * @example
599
+ * const app = new Eleva("myApp");
600
+ * app.component("myComponent", {
601
+ * setup: (ctx) => ({ count: ctx.signal(0) }),
602
+ * template: (ctx) => `<div>Hello ${ctx.props.name}!</div>`
603
+ * });
604
+ * app.mount(document.getElementById("app"), "myComponent", { name: "World" });
605
+ *
429
606
  */
430
607
  constructor(name, config = {}) {
431
608
  /** @public {string} The unique identifier name for this Eleva instance */
432
609
  this.name = name;
433
- /** @public {Object<string, any>} Optional configuration object for the Eleva instance */
610
+ /** @public {Object<string, unknown>} Optional configuration object for the Eleva instance */
434
611
  this.config = config;
435
612
  /** @public {Emitter} Instance of the event emitter for handling component events */
436
613
  this.emitter = new Emitter();
@@ -443,8 +620,6 @@ class Eleva {
443
620
  this._components = new Map();
444
621
  /** @private {Map<string, ElevaPlugin>} Collection of installed plugin instances by name */
445
622
  this._plugins = new Map();
446
- /** @private {string[]} Array of lifecycle hook names supported by components */
447
- this._lifecycleHooks = ["onBeforeMount", "onMount", "onBeforeUpdate", "onUpdate", "onUnmount"];
448
623
  /** @private {boolean} Flag indicating if the root component is currently mounted */
449
624
  this._isMounted = false;
450
625
  }
@@ -456,7 +631,7 @@ class Eleva {
456
631
  *
457
632
  * @public
458
633
  * @param {ElevaPlugin} plugin - The plugin object which must have an `install` function.
459
- * @param {Object<string, any>} [options={}] - Optional configuration options for the plugin.
634
+ * @param {Object<string, unknown>} [options={}] - Optional configuration options for the plugin.
460
635
  * @returns {Eleva} The Eleva instance (for method chaining).
461
636
  * @example
462
637
  * app.use(myPlugin, { option1: "value1" });
@@ -495,7 +670,7 @@ class Eleva {
495
670
  * @public
496
671
  * @param {HTMLElement} container - The DOM element where the component will be mounted.
497
672
  * @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.
673
+ * @param {Object<string, unknown>} [props={}] - Optional properties to pass to the component.
499
674
  * @returns {Promise<MountResult>}
500
675
  * A Promise that resolves to an object containing:
501
676
  * - container: The mounted component's container element
@@ -529,21 +704,12 @@ class Eleva {
529
704
  children
530
705
  } = definition;
531
706
 
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
- */
707
+ /** @type {ComponentContext} */
541
708
  const context = {
542
709
  props,
543
710
  emitter: this.emitter,
544
- /** @type {(v: any) => Signal<any>} */
545
- signal: v => new this.signal(v),
546
- ...this._prepareLifecycleHooks()
711
+ /** @type {(v: unknown) => Signal<unknown>} */
712
+ signal: v => new this.signal(v)
547
713
  };
548
714
 
549
715
  /**
@@ -554,30 +720,38 @@ class Eleva {
554
720
  * 3. Rendering the component
555
721
  * 4. Managing component lifecycle
556
722
  *
557
- * @param {Object<string, any>} data - Data returned from the component's setup function
723
+ * @param {Object<string, unknown>} data - Data returned from the component's setup function
558
724
  * @returns {Promise<MountResult>} An object containing:
559
725
  * - container: The mounted component's container element
560
726
  * - data: The component's reactive state and context
561
727
  * - unmount: Function to clean up and unmount the component
562
728
  */
563
729
  const processMount = async data => {
564
- /** @type {Object<string, any>} */
730
+ /** @type {ComponentContext} */
565
731
  const mergedContext = {
566
732
  ...context,
567
733
  ...data
568
734
  };
569
735
  /** @type {Array<() => void>} */
570
- const watcherUnsubscribers = [];
736
+ const watchers = [];
571
737
  /** @type {Array<MountResult>} */
572
738
  const childInstances = [];
573
739
  /** @type {Array<() => void>} */
574
- const cleanupListeners = [];
740
+ const listeners = [];
575
741
 
576
742
  // Execute before hooks
577
743
  if (!this._isMounted) {
578
- mergedContext.onBeforeMount && mergedContext.onBeforeMount();
744
+ /** @type {LifecycleHookContext} */
745
+ await mergedContext.onBeforeMount?.({
746
+ container,
747
+ context: mergedContext
748
+ });
579
749
  } else {
580
- mergedContext.onBeforeUpdate && mergedContext.onBeforeUpdate();
750
+ /** @type {LifecycleHookContext} */
751
+ await mergedContext.onBeforeUpdate?.({
752
+ container,
753
+ context: mergedContext
754
+ });
581
755
  }
582
756
 
583
757
  /**
@@ -590,14 +764,22 @@ class Eleva {
590
764
  const templateResult = typeof template === "function" ? await template(mergedContext) : template;
591
765
  const newHtml = TemplateEngine.parse(templateResult, mergedContext);
592
766
  this.renderer.patchDOM(container, newHtml);
593
- this._processEvents(container, mergedContext, cleanupListeners);
767
+ this._processEvents(container, mergedContext, listeners);
594
768
  if (style) this._injectStyles(container, compName, style, mergedContext);
595
769
  if (children) await this._mountComponents(container, children, childInstances);
596
770
  if (!this._isMounted) {
597
- mergedContext.onMount && mergedContext.onMount();
771
+ /** @type {LifecycleHookContext} */
772
+ await mergedContext.onMount?.({
773
+ container,
774
+ context: mergedContext
775
+ });
598
776
  this._isMounted = true;
599
777
  } else {
600
- mergedContext.onUpdate && mergedContext.onUpdate();
778
+ /** @type {LifecycleHookContext} */
779
+ await mergedContext.onUpdate?.({
780
+ container,
781
+ context: mergedContext
782
+ });
601
783
  }
602
784
  };
603
785
 
@@ -607,7 +789,7 @@ class Eleva {
607
789
  * Stores unsubscribe functions to clean up watchers when component unmounts.
608
790
  */
609
791
  for (const val of Object.values(data)) {
610
- if (val instanceof Signal) watcherUnsubscribers.push(val.watch(render));
792
+ if (val instanceof Signal) watchers.push(val.watch(render));
611
793
  }
612
794
  await render();
613
795
  const instance = {
@@ -618,11 +800,20 @@ class Eleva {
618
800
  *
619
801
  * @returns {void}
620
802
  */
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();
803
+ unmount: async () => {
804
+ /** @type {UnmountHookContext} */
805
+ await mergedContext.onUnmount?.({
806
+ container,
807
+ context: mergedContext,
808
+ cleanup: {
809
+ watchers: watchers,
810
+ listeners: listeners,
811
+ children: childInstances
812
+ }
813
+ });
814
+ for (const fn of watchers) fn();
815
+ for (const fn of listeners) fn();
816
+ for (const child of childInstances) await child.unmount();
626
817
  container.innerHTML = "";
627
818
  delete container._eleva_instance;
628
819
  }
@@ -636,47 +827,37 @@ class Eleva {
636
827
  return await processMount(setupResult);
637
828
  }
638
829
 
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
830
  /**
657
831
  * Processes DOM elements for event binding based on attributes starting with "@".
658
832
  * This method handles the event delegation system and ensures proper cleanup of event listeners.
659
833
  *
660
834
  * @private
661
835
  * @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.
836
+ * @param {ComponentContext} context - The current component context containing event handler definitions.
837
+ * @param {Array<() => void>} listeners - Array to collect cleanup functions for each event listener.
664
838
  * @returns {void}
665
839
  */
666
- _processEvents(container, context, cleanupListeners) {
840
+ _processEvents(container, context, listeners) {
841
+ /** @type {NodeListOf<Element>} */
667
842
  const elements = container.querySelectorAll("*");
668
843
  for (const el of elements) {
844
+ /** @type {NamedNodeMap} */
669
845
  const attrs = el.attributes;
670
846
  for (let i = 0; i < attrs.length; i++) {
847
+ /** @type {Attr} */
671
848
  const attr = attrs[i];
672
849
  if (!attr.name.startsWith("@")) continue;
850
+
851
+ /** @type {keyof HTMLElementEventMap} */
673
852
  const event = attr.name.slice(1);
853
+ /** @type {string} */
674
854
  const handlerName = attr.value;
855
+ /** @type {(event: Event) => void} */
675
856
  const handler = context[handlerName] || TemplateEngine.evaluate(handlerName, context);
676
857
  if (typeof handler === "function") {
677
858
  el.addEventListener(event, handler);
678
859
  el.removeAttribute(attr.name);
679
- cleanupListeners.push(() => el.removeEventListener(event, handler));
860
+ listeners.push(() => el.removeEventListener(event, handler));
680
861
  }
681
862
  }
682
863
  }
@@ -689,12 +870,14 @@ class Eleva {
689
870
  * @private
690
871
  * @param {HTMLElement} container - The container element where styles should be injected.
691
872
  * @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.
873
+ * @param {(function(ComponentContext): string)|string} styleDef - The component's style definition (function or string).
874
+ * @param {ComponentContext} context - The current component context for style interpolation.
694
875
  * @returns {void}
695
876
  */
696
877
  _injectStyles(container, compName, styleDef, context) {
878
+ /** @type {string} */
697
879
  const newStyle = typeof styleDef === "function" ? TemplateEngine.parse(styleDef(context), context) : styleDef;
880
+ /** @type {HTMLStyleElement|null} */
698
881
  let styleEl = container.querySelector(`style[data-e-style="${compName}"]`);
699
882
  if (styleEl && styleEl.textContent === newStyle) return;
700
883
  if (!styleEl) {
@@ -712,7 +895,7 @@ class Eleva {
712
895
  * @private
713
896
  * @param {HTMLElement} element - The DOM element to extract props from
714
897
  * @param {string} prefix - The prefix to look for in attributes
715
- * @returns {Object<string, any>} An object containing the extracted props
898
+ * @returns {Record<string, string>} An object containing the extracted props
716
899
  * @example
717
900
  * // For an element with attributes:
718
901
  * // <div :name="John" :age="25">
@@ -758,7 +941,9 @@ class Eleva {
758
941
  if (!selector) continue;
759
942
  for (const el of container.querySelectorAll(selector)) {
760
943
  if (!(el instanceof HTMLElement)) continue;
944
+ /** @type {Record<string, string>} */
761
945
  const props = this._extractProps(el, ":");
946
+ /** @type {MountResult} */
762
947
  const instance = await this.mount(el, component, props);
763
948
  if (instance && !childInstances.includes(instance)) {
764
949
  childInstances.push(instance);