eleva 1.2.7-alpha → 1.2.8-alpha

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,730 @@
1
+ /*! Eleva v1.2.8-alpha | 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
+ */
19
+ static expressionPattern = /\{\{\s*(.*?)\s*\}\}/g;
20
+
21
+ /**
22
+ * Parses a template string, replacing expressions with their evaluated values.
23
+ * Expressions are evaluated in the provided data context.
24
+ *
25
+ * @public
26
+ * @static
27
+ * @param {string} template - The template string to parse.
28
+ * @param {Object} data - The data context for evaluating expressions.
29
+ * @returns {string} The parsed template with expressions replaced by their values.
30
+ * @example
31
+ * const result = TemplateEngine.parse("{{user.name}} is {{user.age}} years old", {
32
+ * user: { name: "John", age: 30 }
33
+ * }); // Returns: "John is 30 years old"
34
+ */
35
+ static parse(template, data) {
36
+ if (typeof template !== "string") return template;
37
+ return template.replace(this.expressionPattern, (_, expression) => this.evaluate(expression, data));
38
+ }
39
+
40
+ /**
41
+ * Evaluates an expression in the context of the provided data object.
42
+ * Note: This does not provide a true sandbox and evaluated expressions may access global scope.
43
+ *
44
+ * @public
45
+ * @static
46
+ * @param {string} expression - The expression to evaluate.
47
+ * @param {Object} data - The data context for evaluation.
48
+ * @returns {*} The result of the evaluation, or an empty string if evaluation fails.
49
+ * @example
50
+ * const result = TemplateEngine.evaluate("user.name", { user: { name: "John" } }); // Returns: "John"
51
+ * const age = TemplateEngine.evaluate("user.age", { user: { age: 30 } }); // Returns: 30
52
+ */
53
+ static evaluate(expression, data) {
54
+ if (typeof expression !== "string") return expression;
55
+ try {
56
+ return new Function("data", `with(data) { return ${expression}; }`)(data);
57
+ } catch {
58
+ return "";
59
+ }
60
+ }
61
+ }
62
+
63
+ /**
64
+ * @class ⚡ Signal
65
+ * @classdesc A reactive data holder that enables fine-grained reactivity in the Eleva framework.
66
+ * Signals notify registered watchers when their value changes, enabling efficient DOM updates
67
+ * through targeted patching rather than full re-renders.
68
+ *
69
+ * @example
70
+ * const count = new Signal(0);
71
+ * count.watch((value) => console.log(`Count changed to: ${value}`));
72
+ * count.value = 1; // Logs: "Count changed to: 1"
73
+ */
74
+ class Signal {
75
+ /**
76
+ * Creates a new Signal instance with the specified initial value.
77
+ *
78
+ * @public
79
+ * @param {*} value - The initial value of the signal.
80
+ */
81
+ constructor(value) {
82
+ /** @private {T} Internal storage for the signal's current value, where T is the type of the initial value */
83
+ this._value = value;
84
+ /** @private {Set<function(T): void>} Collection of callback functions to be notified when value changes, where T is the value type */
85
+ this._watchers = new Set();
86
+ /** @private {boolean} Flag to prevent multiple synchronous watcher notifications and batch updates into microtasks */
87
+ this._pending = false;
88
+ }
89
+
90
+ /**
91
+ * Gets the current value of the signal.
92
+ *
93
+ * @public
94
+ * @returns {T} The current value, where T is the type of the initial value.
95
+ */
96
+ get value() {
97
+ return this._value;
98
+ }
99
+
100
+ /**
101
+ * Sets a new value for the signal and notifies all registered watchers if the value has changed.
102
+ * The notification is batched using microtasks to prevent multiple synchronous updates.
103
+ *
104
+ * @public
105
+ * @param {T} newVal - The new value to set, where T is the type of the initial value.
106
+ * @returns {void}
107
+ */
108
+ set value(newVal) {
109
+ if (newVal !== this._value) {
110
+ this._value = newVal;
111
+ this._notifyWatchers();
112
+ }
113
+ }
114
+
115
+ /**
116
+ * Registers a watcher function that will be called whenever the signal's value changes.
117
+ * The watcher will receive the new value as its argument.
118
+ *
119
+ * @public
120
+ * @param {function(T): void} fn - The callback function to invoke on value change, where T is the value type.
121
+ * @returns {function(): boolean} A function to unsubscribe the watcher.
122
+ * @example
123
+ * const unsubscribe = signal.watch((value) => console.log(value));
124
+ * // Later...
125
+ * unsubscribe(); // Stops watching for changes
126
+ */
127
+ watch(fn) {
128
+ this._watchers.add(fn);
129
+ return () => this._watchers.delete(fn);
130
+ }
131
+
132
+ /**
133
+ * Notifies all registered watchers of a value change using microtask scheduling.
134
+ * Uses a pending flag to batch multiple synchronous updates into a single notification.
135
+ * All watcher callbacks receive the current value when executed.
136
+ *
137
+ * @private
138
+ * @returns {void}
139
+ */
140
+ _notifyWatchers() {
141
+ if (!this._pending) {
142
+ this._pending = true;
143
+ queueMicrotask(() => {
144
+ this._pending = false;
145
+ this._watchers.forEach(fn => fn(this._value));
146
+ });
147
+ }
148
+ }
149
+ }
150
+
151
+ /**
152
+ * @class 📡 Emitter
153
+ * @classdesc A robust event emitter that enables inter-component communication through a publish-subscribe pattern.
154
+ * Components can emit events and listen for events from other components, facilitating loose coupling
155
+ * and reactive updates across the application.
156
+ *
157
+ * @example
158
+ * const emitter = new Emitter();
159
+ * emitter.on('user:login', (user) => console.log(`User logged in: ${user.name}`));
160
+ * emitter.emit('user:login', { name: 'John' }); // Logs: "User logged in: John"
161
+ */
162
+ class Emitter {
163
+ /**
164
+ * Creates a new Emitter instance.
165
+ *
166
+ * @public
167
+ */
168
+ constructor() {
169
+ /** @private {Map<string, Set<function(any): void>>} Map of event names to their registered handler functions */
170
+ this._events = new Map();
171
+ }
172
+
173
+ /**
174
+ * Registers an event handler for the specified event name.
175
+ * The handler will be called with the event data when the event is emitted.
176
+ *
177
+ * @public
178
+ * @param {string} event - The name of the event to listen for.
179
+ * @param {function(any): void} handler - The callback function to invoke when the event occurs.
180
+ * @returns {function(): boolean} A function to unsubscribe the event handler.
181
+ * @example
182
+ * const unsubscribe = emitter.on('user:login', (user) => console.log(user));
183
+ * // Later...
184
+ * unsubscribe(); // Stops listening for the event
185
+ */
186
+ on(event, handler) {
187
+ if (!this._events.has(event)) this._events.set(event, new Set());
188
+ this._events.get(event).add(handler);
189
+ return () => this.off(event, handler);
190
+ }
191
+
192
+ /**
193
+ * Removes an event handler for the specified event name.
194
+ * If no handler is provided, all handlers for the event are removed.
195
+ *
196
+ * @public
197
+ * @param {string} event - The name of the event.
198
+ * @param {function(any): void} [handler] - The specific handler function to remove.
199
+ * @returns {void}
200
+ */
201
+ off(event, handler) {
202
+ if (!this._events.has(event)) return;
203
+ if (handler) {
204
+ const handlers = this._events.get(event);
205
+ handlers.delete(handler);
206
+ // Remove the event if there are no handlers left
207
+ if (handlers.size === 0) this._events.delete(event);
208
+ } else {
209
+ this._events.delete(event);
210
+ }
211
+ }
212
+
213
+ /**
214
+ * Emits an event with the specified data to all registered handlers.
215
+ * Handlers are called synchronously in the order they were registered.
216
+ *
217
+ * @public
218
+ * @param {string} event - The name of the event to emit.
219
+ * @param {...any} args - Optional arguments to pass to the event handlers.
220
+ * @returns {void}
221
+ */
222
+ emit(event, ...args) {
223
+ if (!this._events.has(event)) return;
224
+ this._events.get(event).forEach(handler => handler(...args));
225
+ }
226
+ }
227
+
228
+ /**
229
+ * @class 🎨 Renderer
230
+ * @classdesc A DOM renderer that handles efficient DOM updates through patching and diffing.
231
+ * Provides methods for updating the DOM by comparing new and old structures and applying
232
+ * only the necessary changes, minimizing layout thrashing and improving performance.
233
+ *
234
+ * @example
235
+ * const renderer = new Renderer();
236
+ * const container = document.getElementById("app");
237
+ * const newHtml = "<div>Updated content</div>";
238
+ * renderer.patchDOM(container, newHtml);
239
+ */
240
+ class Renderer {
241
+ /**
242
+ * Patches the DOM of a container element with new HTML content.
243
+ * This method efficiently updates the DOM by comparing the new content with the existing
244
+ * content and applying only the necessary changes.
245
+ *
246
+ * @public
247
+ * @param {HTMLElement} container - The container element to patch.
248
+ * @param {string} newHtml - The new HTML content to apply.
249
+ * @returns {void}
250
+ * @throws {Error} If container is not an HTMLElement or newHtml is not a string.
251
+ */
252
+ patchDOM(container, newHtml) {
253
+ if (!(container instanceof HTMLElement)) {
254
+ throw new Error("Container must be an HTMLElement");
255
+ }
256
+ if (typeof newHtml !== "string") {
257
+ throw new Error("newHtml must be a string");
258
+ }
259
+ const temp = document.createElement("div");
260
+ temp.innerHTML = newHtml;
261
+ this.diff(container, temp);
262
+ temp.innerHTML = "";
263
+ }
264
+
265
+ /**
266
+ * Diffs two DOM trees (old and new) and applies updates to the old DOM.
267
+ * This method recursively compares nodes and their attributes, applying only
268
+ * the necessary changes to minimize DOM operations.
269
+ *
270
+ * @private
271
+ * @param {HTMLElement} oldParent - The original DOM element.
272
+ * @param {HTMLElement} newParent - The new DOM element.
273
+ * @returns {void}
274
+ * @throws {Error} If either parent is not an HTMLElement.
275
+ */
276
+ diff(oldParent, newParent) {
277
+ if (!(oldParent instanceof HTMLElement) || !(newParent instanceof HTMLElement)) {
278
+ throw new Error("Both parents must be HTMLElements");
279
+ }
280
+ if (oldParent.isEqualNode(newParent)) return;
281
+ const oldC = oldParent.childNodes;
282
+ const newC = newParent.childNodes;
283
+ const len = Math.max(oldC.length, newC.length);
284
+ const operations = [];
285
+ for (let i = 0; i < len; i++) {
286
+ const oldNode = oldC[i];
287
+ const newNode = newC[i];
288
+ if (!oldNode && newNode) {
289
+ operations.push(() => oldParent.appendChild(newNode.cloneNode(true)));
290
+ continue;
291
+ }
292
+ if (oldNode && !newNode) {
293
+ operations.push(() => oldParent.removeChild(oldNode));
294
+ continue;
295
+ }
296
+ const isSameType = oldNode.nodeType === newNode.nodeType && oldNode.nodeName === newNode.nodeName;
297
+ if (!isSameType) {
298
+ operations.push(() => oldParent.replaceChild(newNode.cloneNode(true), oldNode));
299
+ continue;
300
+ }
301
+ if (oldNode.nodeType === Node.ELEMENT_NODE) {
302
+ const oldKey = oldNode.getAttribute("key");
303
+ const newKey = newNode.getAttribute("key");
304
+ if (oldKey !== newKey && (oldKey || newKey)) {
305
+ operations.push(() => oldParent.replaceChild(newNode.cloneNode(true), oldNode));
306
+ continue;
307
+ }
308
+ this.updateAttributes(oldNode, newNode);
309
+ this.diff(oldNode, newNode);
310
+ } else if (oldNode.nodeType === Node.TEXT_NODE && oldNode.nodeValue !== newNode.nodeValue) {
311
+ oldNode.nodeValue = newNode.nodeValue;
312
+ }
313
+ }
314
+ if (operations.length) {
315
+ operations.forEach(op => op());
316
+ }
317
+ }
318
+
319
+ /**
320
+ * Updates the attributes of an element to match those of a new element.
321
+ * Handles special cases for ARIA attributes, data attributes, and boolean properties.
322
+ *
323
+ * @private
324
+ * @param {HTMLElement} oldEl - The element to update.
325
+ * @param {HTMLElement} newEl - The element providing the updated attributes.
326
+ * @returns {void}
327
+ * @throws {Error} If either element is not an HTMLElement.
328
+ */
329
+ updateAttributes(oldEl, newEl) {
330
+ if (!(oldEl instanceof HTMLElement) || !(newEl instanceof HTMLElement)) {
331
+ throw new Error("Both elements must be HTMLElements");
332
+ }
333
+ const oldAttrs = oldEl.attributes;
334
+ const newAttrs = newEl.attributes;
335
+ const operations = [];
336
+
337
+ // Remove old attributes
338
+ for (const {
339
+ name
340
+ } of oldAttrs) {
341
+ if (!name.startsWith("@") && !newEl.hasAttribute(name)) {
342
+ operations.push(() => oldEl.removeAttribute(name));
343
+ }
344
+ }
345
+
346
+ // Update/add new attributes
347
+ for (const attr of newAttrs) {
348
+ const {
349
+ name,
350
+ value
351
+ } = attr;
352
+ if (name.startsWith("@")) continue;
353
+ if (oldEl.getAttribute(name) === value) continue;
354
+ operations.push(() => {
355
+ oldEl.setAttribute(name, value);
356
+ if (name.startsWith("aria-")) {
357
+ const prop = "aria" + name.slice(5).replace(/-([a-z])/g, (_, l) => l.toUpperCase());
358
+ oldEl[prop] = value;
359
+ } else if (name.startsWith("data-")) {
360
+ oldEl.dataset[name.slice(5)] = value;
361
+ } else {
362
+ const prop = name.replace(/-([a-z])/g, (_, l) => l.toUpperCase());
363
+ if (prop in oldEl) {
364
+ const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(oldEl), prop);
365
+ const isBoolean = typeof oldEl[prop] === "boolean" || descriptor?.get && typeof descriptor.get.call(oldEl) === "boolean";
366
+ if (isBoolean) {
367
+ oldEl[prop] = value !== "false" && (value === "" || value === prop || value === "true");
368
+ } else {
369
+ oldEl[prop] = value;
370
+ }
371
+ }
372
+ }
373
+ });
374
+ }
375
+ if (operations.length) {
376
+ operations.forEach(op => op());
377
+ }
378
+ }
379
+ }
380
+
381
+ /**
382
+ * @typedef {Object} ComponentDefinition
383
+ * @property {function(Object<string, any>): (Object<string, any>|Promise<Object<string, any>>)} [setup]
384
+ * Optional setup function that initializes the component's state and returns reactive data
385
+ * @property {function(Object<string, any>): string} template
386
+ * Required function that defines the component's HTML structure
387
+ * @property {function(Object<string, any>): string} [style]
388
+ * Optional function that provides component-scoped CSS styles
389
+ * @property {Object<string, ComponentDefinition>} [children]
390
+ * Optional object defining nested child components
391
+ */
392
+
393
+ /**
394
+ * @typedef {Object} ElevaPlugin
395
+ * @property {function(Eleva, Object<string, any>): void} install
396
+ * Function that installs the plugin into the Eleva instance
397
+ * @property {string} name
398
+ * Unique identifier name for the plugin
399
+ */
400
+
401
+ /**
402
+ * @typedef {Object} MountResult
403
+ * @property {HTMLElement} container
404
+ * The DOM element where the component is mounted
405
+ * @property {Object<string, any>} data
406
+ * The component's reactive state and context data
407
+ * @property {function(): void} unmount
408
+ * Function to clean up and unmount the component
409
+ */
410
+
411
+ /**
412
+ * @class 🧩 Eleva
413
+ * @classdesc A modern, signal-based component runtime framework that provides lifecycle hooks,
414
+ * scoped styles, and plugin support. Eleva manages component registration, plugin integration,
415
+ * event handling, and DOM rendering with a focus on performance and developer experience.
416
+ *
417
+ * @example
418
+ * const app = new Eleva("myApp");
419
+ * app.component("myComponent", {
420
+ * template: (ctx) => `<div>Hello ${ctx.props.name}</div>`,
421
+ * setup: (ctx) => ({ count: new Signal(0) })
422
+ * });
423
+ * app.mount(document.getElementById("app"), "myComponent", { name: "World" });
424
+ */
425
+ class Eleva {
426
+ /**
427
+ * Creates a new Eleva instance with the specified name and configuration.
428
+ *
429
+ * @public
430
+ * @param {string} name - The unique identifier name for this Eleva instance.
431
+ * @param {Object<string, any>} [config={}] - Optional configuration object for the instance.
432
+ * May include framework-wide settings and default behaviors.
433
+ */
434
+ constructor(name, config = {}) {
435
+ /** @public {string} The unique identifier name for this Eleva instance */
436
+ this.name = name;
437
+ /** @public {Object<string, any>} Optional configuration object for the Eleva instance */
438
+ this.config = config;
439
+ /** @public {Emitter} Instance of the event emitter for handling component events */
440
+ this.emitter = new Emitter();
441
+ /** @public {typeof Signal} Static reference to the Signal class for creating reactive state */
442
+ this.signal = Signal;
443
+ /** @public {Renderer} Instance of the renderer for handling DOM updates and patching */
444
+ this.renderer = new Renderer();
445
+
446
+ /** @private {Map<string, ComponentDefinition>} Registry of all component definitions by name */
447
+ this._components = new Map();
448
+ /** @private {Map<string, ElevaPlugin>} Collection of installed plugin instances by name */
449
+ this._plugins = new Map();
450
+ /** @private {string[]} Array of lifecycle hook names supported by components */
451
+ this._lifecycleHooks = ["onBeforeMount", "onMount", "onBeforeUpdate", "onUpdate", "onUnmount"];
452
+ /** @private {boolean} Flag indicating if the root component is currently mounted */
453
+ this._isMounted = false;
454
+ }
455
+
456
+ /**
457
+ * Integrates a plugin with the Eleva framework.
458
+ * The plugin's install function will be called with the Eleva instance and provided options.
459
+ * After installation, the plugin will be available for use by components.
460
+ *
461
+ * @public
462
+ * @param {ElevaPlugin} plugin - The plugin object which must have an `install` function.
463
+ * @param {Object<string, any>} [options={}] - Optional configuration options for the plugin.
464
+ * @returns {Eleva} The Eleva instance (for method chaining).
465
+ * @example
466
+ * app.use(myPlugin, { option1: "value1" });
467
+ */
468
+ use(plugin, options = {}) {
469
+ plugin.install(this, options);
470
+ this._plugins.set(plugin.name, plugin);
471
+ return this;
472
+ }
473
+
474
+ /**
475
+ * Registers a new component with the Eleva instance.
476
+ * The component will be available for mounting using its registered name.
477
+ *
478
+ * @public
479
+ * @param {string} name - The unique name of the component to register.
480
+ * @param {ComponentDefinition} definition - The component definition including setup, template, style, and children.
481
+ * @returns {Eleva} The Eleva instance (for method chaining).
482
+ * @throws {Error} If the component name is already registered.
483
+ * @example
484
+ * app.component("myButton", {
485
+ * template: (ctx) => `<button>${ctx.props.text}</button>`,
486
+ * style: () => "button { color: blue; }"
487
+ * });
488
+ */
489
+ component(name, definition) {
490
+ /** @type {Map<string, ComponentDefinition>} */
491
+ this._components.set(name, definition);
492
+ return this;
493
+ }
494
+
495
+ /**
496
+ * Mounts a registered component to a DOM element.
497
+ * This will initialize the component, set up its reactive state, and render it to the DOM.
498
+ *
499
+ * @public
500
+ * @param {HTMLElement} container - The DOM element where the component will be mounted.
501
+ * @param {string|ComponentDefinition} compName - The name of the registered component or a direct component definition.
502
+ * @param {Object<string, any>} [props={}] - Optional properties to pass to the component.
503
+ * @returns {Promise<MountResult>}
504
+ * A Promise that resolves to an object containing:
505
+ * - container: The mounted component's container element
506
+ * - data: The component's reactive state and context
507
+ * - unmount: Function to clean up and unmount the component
508
+ * @throws {Error} If the container is not found, or component is not registered.
509
+ * @example
510
+ * const instance = await app.mount(document.getElementById("app"), "myComponent", { text: "Click me" });
511
+ * // Later...
512
+ * instance.unmount();
513
+ */
514
+ async mount(container, compName, props = {}) {
515
+ if (!container) throw new Error(`Container not found: ${container}`);
516
+
517
+ /** @type {ComponentDefinition} */
518
+ const definition = typeof compName === "string" ? this._components.get(compName) : compName;
519
+ if (!definition) throw new Error(`Component "${compName}" not registered.`);
520
+ if (typeof definition.template !== "function") throw new Error("Component template must be a function");
521
+
522
+ /**
523
+ * Destructure the component definition to access core functionality.
524
+ * - setup: Optional function for component initialization and state management
525
+ * - template: Required function that returns the component's HTML structure
526
+ * - style: Optional function for component-scoped CSS styles
527
+ * - children: Optional object defining nested child components
528
+ */
529
+ const {
530
+ setup,
531
+ template,
532
+ style,
533
+ children
534
+ } = definition;
535
+
536
+ /**
537
+ * Creates the initial context object for the component instance.
538
+ * This context provides core functionality and will be merged with setup data.
539
+ * @type {Object<string, any>}
540
+ * @property {Object<string, any>} props - Component properties passed during mounting
541
+ * @property {Emitter} emitter - Event emitter instance for component event handling
542
+ * @property {function(any): Signal} signal - Factory function to create reactive Signal instances
543
+ * @property {Object<string, function(): void>} ...lifecycleHooks - Prepared lifecycle hook functions
544
+ */
545
+ const context = {
546
+ props,
547
+ emitter: this.emitter,
548
+ /** @type {(v: any) => Signal} */
549
+ signal: v => new this.signal(v),
550
+ ...this._prepareLifecycleHooks()
551
+ };
552
+
553
+ /**
554
+ * Processes the mounting of the component.
555
+ *
556
+ * @param {Object<string, any>} data - Data returned from the component's setup function.
557
+ * @returns {MountResult} An object with the container, merged context data, and an unmount function.
558
+ */
559
+ const processMount = data => {
560
+ const mergedContext = {
561
+ ...context,
562
+ ...data
563
+ };
564
+ /** @type {Array<() => void>} */
565
+ const watcherUnsubscribers = [];
566
+ /** @type {Array<MountResult>} */
567
+ const childInstances = [];
568
+ /** @type {Array<() => void>} */
569
+ const cleanupListeners = [];
570
+
571
+ // Execute before hooks
572
+ if (!this._isMounted) {
573
+ mergedContext.onBeforeMount && mergedContext.onBeforeMount();
574
+ } else {
575
+ mergedContext.onBeforeUpdate && mergedContext.onBeforeUpdate();
576
+ }
577
+
578
+ /**
579
+ * Renders the component by parsing the template, patching the DOM,
580
+ * processing events, injecting styles, and mounting child components.
581
+ */
582
+ const render = () => {
583
+ const newHtml = TemplateEngine.parse(template(mergedContext), mergedContext);
584
+ this.renderer.patchDOM(container, newHtml);
585
+ this._processEvents(container, mergedContext, cleanupListeners);
586
+ this._injectStyles(container, compName, style, mergedContext);
587
+ this._mountChildren(container, children, childInstances);
588
+ if (!this._isMounted) {
589
+ mergedContext.onMount && mergedContext.onMount();
590
+ this._isMounted = true;
591
+ } else {
592
+ mergedContext.onUpdate && mergedContext.onUpdate();
593
+ }
594
+ };
595
+
596
+ /**
597
+ * Sets up reactive watchers for all Signal instances in the component's data.
598
+ * When a Signal's value changes, the component will re-render to reflect the updates.
599
+ * Stores unsubscribe functions to clean up watchers when component unmounts.
600
+ */
601
+ for (const val of Object.values(data)) {
602
+ if (val instanceof Signal) watcherUnsubscribers.push(val.watch(render));
603
+ }
604
+ render();
605
+ return {
606
+ container,
607
+ data: mergedContext,
608
+ /**
609
+ * Unmounts the component, cleaning up watchers and listeners, child components, and clearing the container.
610
+ *
611
+ * @returns {void}
612
+ */
613
+ unmount: () => {
614
+ for (const fn of watcherUnsubscribers) fn();
615
+ for (const fn of cleanupListeners) fn();
616
+ for (const child of childInstances) child.unmount();
617
+ mergedContext.onUnmount && mergedContext.onUnmount();
618
+ container.innerHTML = "";
619
+ }
620
+ };
621
+ };
622
+
623
+ // Handle asynchronous setup.
624
+ return Promise.resolve(typeof setup === "function" ? setup(context) : {}).then(processMount);
625
+ }
626
+
627
+ /**
628
+ * Prepares default no-operation lifecycle hook functions for a component.
629
+ * These hooks will be called at various stages of the component's lifecycle.
630
+ *
631
+ * @private
632
+ * @returns {Object<string, function(): void>} An object mapping lifecycle hook names to empty functions.
633
+ * The returned object will be merged with the component's context.
634
+ */
635
+ _prepareLifecycleHooks() {
636
+ /** @type {Object<string, () => void>} */
637
+ const hooks = {};
638
+ for (const hook of this._lifecycleHooks) {
639
+ hooks[hook] = () => {};
640
+ }
641
+ return hooks;
642
+ }
643
+
644
+ /**
645
+ * Processes DOM elements for event binding based on attributes starting with "@".
646
+ * This method handles the event delegation system and ensures proper cleanup of event listeners.
647
+ *
648
+ * @private
649
+ * @param {HTMLElement} container - The container element in which to search for event attributes.
650
+ * @param {Object<string, any>} context - The current component context containing event handler definitions.
651
+ * @param {Array<Function>} cleanupListeners - Array to collect cleanup functions for each event listener.
652
+ * @returns {void}
653
+ */
654
+ _processEvents(container, context, cleanupListeners) {
655
+ const elements = container.querySelectorAll("*");
656
+ for (const el of elements) {
657
+ const attrs = el.attributes;
658
+ for (let i = 0; i < attrs.length; i++) {
659
+ const attr = attrs[i];
660
+ if (attr.name.startsWith("@")) {
661
+ const event = attr.name.slice(1);
662
+ const handler = TemplateEngine.evaluate(attr.value, context);
663
+ if (typeof handler === "function") {
664
+ el.addEventListener(event, handler);
665
+ el.removeAttribute(attr.name);
666
+ cleanupListeners.push(() => el.removeEventListener(event, handler));
667
+ }
668
+ }
669
+ }
670
+ }
671
+ }
672
+
673
+ /**
674
+ * Injects scoped styles into the component's container.
675
+ * The styles are automatically prefixed to prevent style leakage to other components.
676
+ *
677
+ * @private
678
+ * @param {HTMLElement} container - The container element where styles should be injected.
679
+ * @param {string} compName - The component name used to identify the style element.
680
+ * @param {function(Object<string, any>): string} [styleFn] - Optional function that returns CSS styles as a string.
681
+ * @param {Object<string, any>} context - The current component context for style interpolation.
682
+ * @returns {void}
683
+ */
684
+ _injectStyles(container, compName, styleFn, context) {
685
+ if (!styleFn) return;
686
+ let styleEl = container.querySelector(`style[data-eleva-style="${compName}"]`);
687
+ if (!styleEl) {
688
+ styleEl = document.createElement("style");
689
+ styleEl.setAttribute("data-eleva-style", compName);
690
+ container.appendChild(styleEl);
691
+ }
692
+ styleEl.textContent = TemplateEngine.parse(styleFn(context), context);
693
+ }
694
+
695
+ /**
696
+ * Mounts child components within the parent component's container.
697
+ * This method handles the recursive mounting of nested components.
698
+ *
699
+ * @private
700
+ * @param {HTMLElement} container - The parent container element.
701
+ * @param {Object<string, ComponentDefinition>} [children] - Object mapping of child component selectors to their definitions.
702
+ * @param {Array<MountResult>} childInstances - Array to store the mounted child component instances.
703
+ * @returns {void}
704
+ */
705
+ async _mountChildren(container, children, childInstances) {
706
+ for (const child of childInstances) child.unmount();
707
+ childInstances.length = 0;
708
+ if (!children) return;
709
+ for (const childSelector of Object.keys(children)) {
710
+ if (!childSelector) continue;
711
+ for (const childEl of container.querySelectorAll(childSelector)) {
712
+ if (!(childEl instanceof HTMLElement)) continue;
713
+ const props = {};
714
+ for (const {
715
+ name,
716
+ value
717
+ } of [...childEl.attributes]) {
718
+ if (name.startsWith("eleva-prop-")) {
719
+ props[name.replace("eleva-prop-", "")] = value;
720
+ }
721
+ }
722
+ const instance = await this.mount(childEl, children[childSelector], props);
723
+ childInstances.push(instance);
724
+ }
725
+ }
726
+ }
727
+ }
728
+
729
+ module.exports = Eleva;
730
+ //# sourceMappingURL=eleva.cjs.js.map