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