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