eleva 1.0.0-alpha → 1.0.0-rc.2

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