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.
package/src/core/Eleva.js CHANGED
@@ -6,51 +6,75 @@ import { Emitter } from "../modules/Emitter.js";
6
6
  import { Renderer } from "../modules/Renderer.js";
7
7
 
8
8
  /**
9
- * Defines the structure and behavior of a component.
10
9
  * @typedef {Object} ComponentDefinition
11
10
  * @property {function(Object<string, any>): (Object<string, any>|Promise<Object<string, any>>)} [setup]
12
- * Optional setup function that initializes the component's reactive state and lifecycle.
13
- * Receives props and context as an argument and should return an object containing the component's state.
14
- * Can return either a synchronous object or a Promise that resolves to an object for async initialization.
15
- *
11
+ * Optional setup function that initializes the component's state and returns reactive data
16
12
  * @property {function(Object<string, any>): string} template
17
- * Required function that defines the component's HTML structure.
18
- * Receives the merged context (props + setup data) and must return an HTML template string.
19
- * Supports dynamic expressions using {{ }} syntax for reactive data binding.
20
- *
13
+ * Required function that defines the component's HTML structure
21
14
  * @property {function(Object<string, any>): string} [style]
22
- * Optional function that defines component-scoped CSS styles.
23
- * Receives the merged context and returns a CSS string that will be automatically scoped to the component.
24
- * Styles are injected into the component's container and only affect elements within it.
25
- *
15
+ * Optional function that provides component-scoped CSS styles
26
16
  * @property {Object<string, ComponentDefinition>} [children]
27
- * Optional object that defines nested child components.
28
- * Keys are CSS selectors that match elements in the template where child components should be mounted.
29
- * Values are ComponentDefinition objects that define the structure and behavior of each child component.
17
+ * Optional object defining nested child components
18
+ */
19
+
20
+ /**
21
+ * @typedef {Object} ElevaPlugin
22
+ * @property {function(Eleva, Object<string, any>): void} install
23
+ * Function that installs the plugin into the Eleva instance
24
+ * @property {string} name
25
+ * Unique identifier name for the plugin
26
+ */
27
+
28
+ /**
29
+ * @typedef {Object} MountResult
30
+ * @property {HTMLElement} container
31
+ * The DOM element where the component is mounted
32
+ * @property {Object<string, any>} data
33
+ * The component's reactive state and context data
34
+ * @property {function(): void} unmount
35
+ * Function to clean up and unmount the component
30
36
  */
31
37
 
32
38
  /**
33
39
  * @class 🧩 Eleva
34
- * @classdesc Signal-based component runtime framework with lifecycle hooks, scoped styles, and plugin support.
35
- * Manages component registration, plugin integration, event handling, and DOM rendering.
40
+ * @classdesc A modern, signal-based component runtime framework that provides lifecycle hooks,
41
+ * scoped styles, and plugin support. Eleva manages component registration, plugin integration,
42
+ * event handling, and DOM rendering with a focus on performance and developer experience.
43
+ *
44
+ * @example
45
+ * const app = new Eleva("myApp");
46
+ * app.component("myComponent", {
47
+ * template: (ctx) => `<div>Hello ${ctx.props.name}</div>`,
48
+ * setup: (ctx) => ({ count: new Signal(0) })
49
+ * });
50
+ * app.mount(document.getElementById("app"), "myComponent", { name: "World" });
36
51
  */
37
52
  export class Eleva {
38
53
  /**
39
- * Creates a new Eleva instance.
54
+ * Creates a new Eleva instance with the specified name and configuration.
40
55
  *
41
- * @param {string} name - The name of the Eleva instance.
42
- * @param {Object<string, any>} [config={}] - Optional configuration for the instance.
56
+ * @public
57
+ * @param {string} name - The unique identifier name for this Eleva instance.
58
+ * @param {Object<string, any>} [config={}] - Optional configuration object for the instance.
59
+ * May include framework-wide settings and default behaviors.
43
60
  */
44
61
  constructor(name, config = {}) {
45
- /** @type {string} The unique identifier name for this Eleva instance */
62
+ /** @public {string} The unique identifier name for this Eleva instance */
46
63
  this.name = name;
47
- /** @type {Object<string, any>} Optional configuration object for the Eleva instance */
64
+ /** @public {Object<string, any>} Optional configuration object for the Eleva instance */
48
65
  this.config = config;
49
- /** @type {Object<string, ComponentDefinition>} Object storing registered component definitions by name */
50
- this._components = {};
51
- /** @private {Array<Object>} Collection of installed plugin instances */
52
- this._plugins = [];
53
- /** @private {string[]} Array of lifecycle hook names supported by the component */
66
+ /** @public {Emitter} Instance of the event emitter for handling component events */
67
+ this.emitter = new Emitter();
68
+ /** @public {typeof Signal} Static reference to the Signal class for creating reactive state */
69
+ this.signal = Signal;
70
+ /** @public {Renderer} Instance of the renderer for handling DOM updates and patching */
71
+ this.renderer = new Renderer();
72
+
73
+ /** @private {Map<string, ComponentDefinition>} Registry of all component definitions by name */
74
+ this._components = new Map();
75
+ /** @private {Map<string, ElevaPlugin>} Collection of installed plugin instances by name */
76
+ this._plugins = new Map();
77
+ /** @private {string[]} Array of lifecycle hook names supported by components */
54
78
  this._lifecycleHooks = [
55
79
  "onBeforeMount",
56
80
  "onMount",
@@ -58,57 +82,75 @@ export class Eleva {
58
82
  "onUpdate",
59
83
  "onUnmount",
60
84
  ];
61
- /** @private {boolean} Flag indicating if component is currently mounted */
85
+ /** @private {boolean} Flag indicating if the root component is currently mounted */
62
86
  this._isMounted = false;
63
- /** @private {Emitter} Instance of the event emitter for handling component events */
64
- this.emitter = new Emitter();
65
- /** @private {Signal} Instance of the signal for handling plugin and component signals */
66
- this.signal = Signal;
67
- /** @private {Renderer} Instance of the renderer for handling DOM updates and patching */
68
- this.renderer = new Renderer();
69
87
  }
70
88
 
71
89
  /**
72
90
  * Integrates a plugin with the Eleva framework.
91
+ * The plugin's install function will be called with the Eleva instance and provided options.
92
+ * After installation, the plugin will be available for use by components.
73
93
  *
74
- * @param {Object} plugin - The plugin object which should have an `install` function.
75
- * @param {Object<string, any>} [options={}] - Optional options to pass to the plugin.
76
- * @returns {Eleva} The Eleva instance (for chaining).
94
+ * @public
95
+ * @param {ElevaPlugin} plugin - The plugin object which must have an `install` function.
96
+ * @param {Object<string, any>} [options={}] - Optional configuration options for the plugin.
97
+ * @returns {Eleva} The Eleva instance (for method chaining).
98
+ * @example
99
+ * app.use(myPlugin, { option1: "value1" });
77
100
  */
78
101
  use(plugin, options = {}) {
79
- if (typeof plugin.install === "function") {
80
- plugin.install(this, options);
81
- }
82
- this._plugins.push(plugin);
102
+ plugin.install(this, options);
103
+ this._plugins.set(plugin.name, plugin);
104
+
83
105
  return this;
84
106
  }
85
107
 
86
108
  /**
87
- * Registers a component with the Eleva instance.
109
+ * Registers a new component with the Eleva instance.
110
+ * The component will be available for mounting using its registered name.
88
111
  *
89
- * @param {string} name - The name of the component.
112
+ * @public
113
+ * @param {string} name - The unique name of the component to register.
90
114
  * @param {ComponentDefinition} definition - The component definition including setup, template, style, and children.
91
- * @returns {Eleva} The Eleva instance (for chaining).
115
+ * @returns {Eleva} The Eleva instance (for method chaining).
116
+ * @throws {Error} If the component name is already registered.
117
+ * @example
118
+ * app.component("myButton", {
119
+ * template: (ctx) => `<button>${ctx.props.text}</button>`,
120
+ * style: () => "button { color: blue; }"
121
+ * });
92
122
  */
93
123
  component(name, definition) {
94
- this._components[name] = definition;
124
+ /** @type {Map<string, ComponentDefinition>} */
125
+ this._components.set(name, definition);
95
126
  return this;
96
127
  }
97
128
 
98
129
  /**
99
130
  * Mounts a registered component to a DOM element.
131
+ * This will initialize the component, set up its reactive state, and render it to the DOM.
100
132
  *
101
- * @param {HTMLElement} container - A DOM element where the component will be mounted.
102
- * @param {string|ComponentDefinition} compName - The name of the component to mount or a component definition.
133
+ * @public
134
+ * @param {HTMLElement} container - The DOM element where the component will be mounted.
135
+ * @param {string|ComponentDefinition} compName - The name of the registered component or a direct component definition.
103
136
  * @param {Object<string, any>} [props={}] - Optional properties to pass to the component.
104
- * @returns {object|Promise<object>} An object representing the mounted component instance, or a Promise that resolves to it for asynchronous setups.
105
- * @throws {Error} If the container is not found or if the component is not registered.
137
+ * @returns {Promise<MountResult>}
138
+ * A Promise that resolves to an object containing:
139
+ * - container: The mounted component's container element
140
+ * - data: The component's reactive state and context
141
+ * - unmount: Function to clean up and unmount the component
142
+ * @throws {Error} If the container is not found, or component is not registered.
143
+ * @example
144
+ * const instance = await app.mount(document.getElementById("app"), "myComponent", { text: "Click me" });
145
+ * // Later...
146
+ * instance.unmount();
106
147
  */
107
- mount(container, compName, props = {}) {
148
+ async mount(container, compName, props = {}) {
108
149
  if (!container) throw new Error(`Container not found: ${container}`);
109
150
 
151
+ /** @type {ComponentDefinition} */
110
152
  const definition =
111
- typeof compName === "string" ? this._components[compName] : compName;
153
+ typeof compName === "string" ? this._components.get(compName) : compName;
112
154
  if (!definition) throw new Error(`Component "${compName}" not registered.`);
113
155
 
114
156
  if (typeof definition.template !== "function")
@@ -135,20 +177,32 @@ export class Eleva {
135
177
  const context = {
136
178
  props,
137
179
  emitter: this.emitter,
180
+ /** @type {(v: any) => Signal} */
138
181
  signal: (v) => new this.signal(v),
139
182
  ...this._prepareLifecycleHooks(),
140
183
  };
141
184
 
142
185
  /**
143
186
  * Processes the mounting of the component.
187
+ * This function handles:
188
+ * 1. Merging setup data with the component context
189
+ * 2. Setting up reactive watchers
190
+ * 3. Rendering the component
191
+ * 4. Managing component lifecycle
144
192
  *
145
- * @param {Object<string, any>} data - Data returned from the component's setup function.
146
- * @returns {object} An object with the container, merged context data, and an unmount function.
193
+ * @param {Object<string, any>} data - Data returned from the component's setup function
194
+ * @returns {MountResult} An object containing:
195
+ * - container: The mounted component's container element
196
+ * - data: The component's reactive state and context
197
+ * - unmount: Function to clean up and unmount the component
147
198
  */
148
- const processMount = (data) => {
199
+ const processMount = async (data) => {
149
200
  const mergedContext = { ...context, ...data };
201
+ /** @type {Array<() => void>} */
150
202
  const watcherUnsubscribers = [];
203
+ /** @type {Array<MountResult>} */
151
204
  const childInstances = [];
205
+ /** @type {Array<() => void>} */
152
206
  const cleanupListeners = [];
153
207
 
154
208
  // Execute before hooks
@@ -162,7 +216,7 @@ export class Eleva {
162
216
  * Renders the component by parsing the template, patching the DOM,
163
217
  * processing events, injecting styles, and mounting child components.
164
218
  */
165
- const render = () => {
219
+ const render = async () => {
166
220
  const newHtml = TemplateEngine.parse(
167
221
  template(mergedContext),
168
222
  mergedContext
@@ -170,7 +224,7 @@ export class Eleva {
170
224
  this.renderer.patchDOM(container, newHtml);
171
225
  this._processEvents(container, mergedContext, cleanupListeners);
172
226
  this._injectStyles(container, compName, style, mergedContext);
173
- this._mountChildren(container, children, childInstances);
227
+ await this._mountComponents(container, children, childInstances);
174
228
 
175
229
  if (!this._isMounted) {
176
230
  mergedContext.onMount && mergedContext.onMount();
@@ -185,11 +239,11 @@ export class Eleva {
185
239
  * When a Signal's value changes, the component will re-render to reflect the updates.
186
240
  * Stores unsubscribe functions to clean up watchers when component unmounts.
187
241
  */
188
- Object.values(data).forEach((val) => {
242
+ for (const val of Object.values(data)) {
189
243
  if (val instanceof Signal) watcherUnsubscribers.push(val.watch(render));
190
- });
244
+ }
191
245
 
192
- render();
246
+ await render();
193
247
 
194
248
  return {
195
249
  container,
@@ -200,9 +254,9 @@ export class Eleva {
200
254
  * @returns {void}
201
255
  */
202
256
  unmount: () => {
203
- watcherUnsubscribers.forEach((fn) => fn());
204
- cleanupListeners.forEach((fn) => fn());
205
- childInstances.forEach((child) => child.unmount());
257
+ for (const fn of watcherUnsubscribers) fn();
258
+ for (const fn of cleanupListeners) fn();
259
+ for (const child of childInstances) child.unmount();
206
260
  mergedContext.onUnmount && mergedContext.onUnmount();
207
261
  container.innerHTML = "";
208
262
  },
@@ -216,26 +270,31 @@ export class Eleva {
216
270
  }
217
271
 
218
272
  /**
219
- * Prepares default no-operation lifecycle hook functions.
273
+ * Prepares default no-operation lifecycle hook functions for a component.
274
+ * These hooks will be called at various stages of the component's lifecycle.
220
275
  *
221
- * @returns {Object<string, function(): void>} An object with keys for lifecycle hooks mapped to empty functions.
222
276
  * @private
277
+ * @returns {Object<string, function(): void>} An object mapping lifecycle hook names to empty functions.
278
+ * The returned object will be merged with the component's context.
223
279
  */
224
280
  _prepareLifecycleHooks() {
225
- return this._lifecycleHooks.reduce((acc, hook) => {
226
- acc[hook] = () => {};
227
- return acc;
228
- }, {});
281
+ /** @type {Object<string, () => void>} */
282
+ const hooks = {};
283
+ for (const hook of this._lifecycleHooks) {
284
+ hooks[hook] = () => {};
285
+ }
286
+ return hooks;
229
287
  }
230
288
 
231
289
  /**
232
290
  * Processes DOM elements for event binding based on attributes starting with "@".
233
- * Tracks listeners for cleanup during unmount.
291
+ * This method handles the event delegation system and ensures proper cleanup of event listeners.
234
292
  *
235
- * @param {HTMLElement} container - The container element in which to search for events.
236
- * @param {Object<string, any>} context - The current context containing event handler definitions.
237
- * @param {Array<Function>} cleanupListeners - Array to collect cleanup functions for each event listener.
238
293
  * @private
294
+ * @param {HTMLElement} container - The container element in which to search for event attributes.
295
+ * @param {Object<string, any>} context - The current component context containing event handler definitions.
296
+ * @param {Array<Function>} cleanupListeners - Array to collect cleanup functions for each event listener.
297
+ * @returns {void}
239
298
  */
240
299
  _processEvents(container, context, cleanupListeners) {
241
300
  const elements = container.querySelectorAll("*");
@@ -258,12 +317,14 @@ export class Eleva {
258
317
 
259
318
  /**
260
319
  * Injects scoped styles into the component's container.
320
+ * The styles are automatically prefixed to prevent style leakage to other components.
261
321
  *
262
- * @param {HTMLElement} container - The container element.
263
- * @param {string} compName - The component name used to identify the style element.
264
- * @param {function(Object<string, any>): string} [styleFn] - A function that returns CSS styles as a string.
265
- * @param {Object<string, any>} context - The current context for style interpolation.
266
322
  * @private
323
+ * @param {HTMLElement} container - The container element where styles should be injected.
324
+ * @param {string} compName - The component name used to identify the style element.
325
+ * @param {function(Object<string, any>): string} [styleFn] - Optional function that returns CSS styles as a string.
326
+ * @param {Object<string, any>} context - The current component context for style interpolation.
327
+ * @returns {void}
267
328
  */
268
329
  _injectStyles(container, compName, styleFn, context) {
269
330
  if (!styleFn) return;
@@ -280,28 +341,118 @@ export class Eleva {
280
341
  }
281
342
 
282
343
  /**
283
- * Mounts child components within the parent component's container.
344
+ * Extracts props from an element's attributes that start with 'eleva-prop-'.
345
+ * This method is used to collect component properties from DOM elements.
346
+ *
347
+ * @private
348
+ * @param {HTMLElement} element - The DOM element to extract props from
349
+ * @returns {Object<string, any>} An object containing the extracted props
350
+ * @example
351
+ * // For an element with attributes:
352
+ * // <div eleva-prop-name="John" eleva-prop-age="25">
353
+ * // Returns: { name: "John", age: "25" }
354
+ */
355
+ _extractProps(element) {
356
+ const props = {};
357
+ for (const { name, value } of [...element.attributes]) {
358
+ if (name.startsWith("eleva-prop-")) {
359
+ props[name.replace("eleva-prop-", "")] = value;
360
+ }
361
+ }
362
+ return props;
363
+ }
364
+
365
+ /**
366
+ * Mounts a single component instance to a container element.
367
+ * This method handles the actual mounting of a component with its props.
368
+ *
369
+ * @private
370
+ * @param {HTMLElement} container - The container element to mount the component to
371
+ * @param {string|ComponentDefinition} component - The component to mount, either as a name or definition
372
+ * @param {Object<string, any>} props - The props to pass to the component
373
+ * @returns {Promise<MountResult>} A promise that resolves to the mounted component instance
374
+ * @throws {Error} If the container is not a valid HTMLElement
375
+ */
376
+ async _mountComponentInstance(container, component, props) {
377
+ if (!(container instanceof HTMLElement)) return null;
378
+ return await this.mount(container, component, props);
379
+ }
380
+
381
+ /**
382
+ * Mounts components found by a selector in the container.
383
+ * This method handles mounting multiple instances of the same component type.
384
+ *
385
+ * @private
386
+ * @param {HTMLElement} container - The container to search for components
387
+ * @param {string} selector - The CSS selector to find components
388
+ * @param {string|ComponentDefinition} component - The component to mount
389
+ * @param {Array<MountResult>} instances - Array to store the mounted component instances
390
+ * @returns {Promise<void>}
391
+ */
392
+ async _mountComponentsBySelector(container, selector, component, instances) {
393
+ for (const el of container.querySelectorAll(selector)) {
394
+ const props = this._extractProps(el);
395
+ const instance = await this._mountComponentInstance(el, component, props);
396
+ if (instance) instances.push(instance);
397
+ }
398
+ }
399
+
400
+ /**
401
+ * Mounts all components within the parent component's container.
402
+ * This method implements a dual mounting system that handles both:
403
+ * 1. Explicitly defined children components (passed through the children parameter)
404
+ * 2. Template-referenced components (found in the template using component names)
405
+ *
406
+ * The mounting process follows these steps:
407
+ * 1. Cleans up any existing component instances
408
+ * 2. Mounts explicitly defined children components
409
+ * 3. Mounts template-referenced components
284
410
  *
285
- * @param {HTMLElement} container - The parent container element.
286
- * @param {Object<string, ComponentDefinition>} [children] - An object mapping child component selectors to their definitions.
287
- * @param {Array<object>} childInstances - An array to store the mounted child component instances.
288
411
  * @private
412
+ * @param {HTMLElement} container - The container element to mount components in
413
+ * @param {Object<string, ComponentDefinition>} children - Map of selectors to component definitions for explicit children
414
+ * @param {Array<MountResult>} childInstances - Array to store all mounted component instances
415
+ * @returns {Promise<void>}
416
+ *
417
+ * @example
418
+ * // Explicit children mounting:
419
+ * const children = {
420
+ * '.user-profile': UserProfileComponent,
421
+ * '.settings-panel': SettingsComponent
422
+ * };
423
+ *
424
+ * // Template-referenced components:
425
+ * // <div>
426
+ * // <user-profile eleva-prop-name="John"></user-profile>
427
+ * // <settings-panel eleva-prop-theme="dark"></settings-panel>
428
+ * // </div>
289
429
  */
290
- _mountChildren(container, children, childInstances) {
291
- childInstances.forEach((child) => child.unmount());
430
+ async _mountComponents(container, children, childInstances) {
431
+ // Clean up existing instances
432
+ for (const child of childInstances) child.unmount();
292
433
  childInstances.length = 0;
293
434
 
294
- Object.keys(children || {}).forEach((childSelector) => {
295
- container.querySelectorAll(childSelector).forEach((childEl) => {
296
- const props = {};
297
- [...childEl.attributes].forEach(({ name, value }) => {
298
- if (name.startsWith("eleva-prop-")) {
299
- props[name.replace("eleva-prop-", "")] = value;
300
- }
301
- });
302
- const instance = this.mount(childEl, children[childSelector], props);
303
- childInstances.push(instance);
304
- });
305
- });
435
+ // Mount explicitly defined children components
436
+ if (children) {
437
+ for (const [selector, component] of Object.entries(children)) {
438
+ if (!selector) continue;
439
+ await this._mountComponentsBySelector(
440
+ container,
441
+ selector,
442
+ component,
443
+ childInstances
444
+ );
445
+ }
446
+ }
447
+
448
+ // Mount components referenced in the template
449
+ for (const [compName] of this._components) {
450
+ await this._mountComponentsBySelector(
451
+ container,
452
+ compName,
453
+ compName,
454
+ childInstances
455
+ );
456
+ }
306
457
  }
307
458
  }
@@ -1,49 +1,79 @@
1
1
  "use strict";
2
2
 
3
3
  /**
4
- * @class 🎙️ Emitter
5
- * @classdesc Robust inter-component communication with event bubbling.
6
- * Implements a basic publish-subscribe pattern for event handling, allowing components
7
- * to communicate through custom events.
4
+ * @class 📡 Emitter
5
+ * @classdesc A robust event emitter that enables inter-component communication through a publish-subscribe pattern.
6
+ * Components can emit events and listen for events from other components, facilitating loose coupling
7
+ * and reactive updates across the application.
8
+ *
9
+ * @example
10
+ * const emitter = new Emitter();
11
+ * emitter.on('user:login', (user) => console.log(`User logged in: ${user.name}`));
12
+ * emitter.emit('user:login', { name: 'John' }); // Logs: "User logged in: John"
8
13
  */
9
14
  export class Emitter {
10
15
  /**
11
16
  * Creates a new Emitter instance.
17
+ *
18
+ * @public
12
19
  */
13
20
  constructor() {
14
- /** @type {Object.<string, Function[]>} Storage for event handlers mapped by event name */
15
- this.events = {};
21
+ /** @private {Map<string, Set<function(any): void>>} Map of event names to their registered handler functions */
22
+ this._events = new Map();
16
23
  }
17
24
 
18
25
  /**
19
- * Registers an event handler for the specified event.
26
+ * Registers an event handler for the specified event name.
27
+ * The handler will be called with the event data when the event is emitted.
20
28
  *
21
- * @param {string} event - The name of the event.
22
- * @param {function(...any): void} handler - The function to call when the event is emitted.
29
+ * @public
30
+ * @param {string} event - The name of the event to listen for.
31
+ * @param {function(any): void} handler - The callback function to invoke when the event occurs.
32
+ * @returns {function(): boolean} A function to unsubscribe the event handler.
33
+ * @example
34
+ * const unsubscribe = emitter.on('user:login', (user) => console.log(user));
35
+ * // Later...
36
+ * unsubscribe(); // Stops listening for the event
23
37
  */
24
38
  on(event, handler) {
25
- (this.events[event] || (this.events[event] = [])).push(handler);
39
+ if (!this._events.has(event)) this._events.set(event, new Set());
40
+
41
+ this._events.get(event).add(handler);
42
+ return () => this.off(event, handler);
26
43
  }
27
44
 
28
45
  /**
29
- * Removes a previously registered event handler.
46
+ * Removes an event handler for the specified event name.
47
+ * If no handler is provided, all handlers for the event are removed.
30
48
  *
49
+ * @public
31
50
  * @param {string} event - The name of the event.
32
- * @param {function(...any): void} handler - The handler function to remove.
51
+ * @param {function(any): void} [handler] - The specific handler function to remove.
52
+ * @returns {void}
33
53
  */
34
54
  off(event, handler) {
35
- if (this.events[event]) {
36
- this.events[event] = this.events[event].filter((h) => h !== handler);
55
+ if (!this._events.has(event)) return;
56
+ if (handler) {
57
+ const handlers = this._events.get(event);
58
+ handlers.delete(handler);
59
+ // Remove the event if there are no handlers left
60
+ if (handlers.size === 0) this._events.delete(event);
61
+ } else {
62
+ this._events.delete(event);
37
63
  }
38
64
  }
39
65
 
40
66
  /**
41
- * Emits an event, invoking all handlers registered for that event.
67
+ * Emits an event with the specified data to all registered handlers.
68
+ * Handlers are called synchronously in the order they were registered.
42
69
  *
43
- * @param {string} event - The event name.
44
- * @param {...any} args - Additional arguments to pass to the event handlers.
70
+ * @public
71
+ * @param {string} event - The name of the event to emit.
72
+ * @param {...any} args - Optional arguments to pass to the event handlers.
73
+ * @returns {void}
45
74
  */
46
75
  emit(event, ...args) {
47
- (this.events[event] || []).forEach((handler) => handler(...args));
76
+ if (!this._events.has(event)) return;
77
+ this._events.get(event).forEach((handler) => handler(...args));
48
78
  }
49
79
  }
@@ -2,17 +2,27 @@
2
2
 
3
3
  /**
4
4
  * @class 🎨 Renderer
5
- * @classdesc Handles DOM patching, diffing, and attribute updates.
6
- * Provides methods for efficient DOM updates by diffing the new and old DOM structures
7
- * and applying only the necessary changes.
5
+ * @classdesc A DOM renderer that handles efficient DOM updates through patching and diffing.
6
+ * Provides methods for updating the DOM by comparing new and old structures and applying
7
+ * only the necessary changes, minimizing layout thrashing and improving performance.
8
+ *
9
+ * @example
10
+ * const renderer = new Renderer();
11
+ * const container = document.getElementById("app");
12
+ * const newHtml = "<div>Updated content</div>";
13
+ * renderer.patchDOM(container, newHtml);
8
14
  */
9
15
  export class Renderer {
10
16
  /**
11
17
  * Patches the DOM of a container element with new HTML content.
18
+ * This method efficiently updates the DOM by comparing the new content with the existing
19
+ * content and applying only the necessary changes.
12
20
  *
21
+ * @public
13
22
  * @param {HTMLElement} container - The container element to patch.
14
23
  * @param {string} newHtml - The new HTML content to apply.
15
- * @throws {Error} If container is not an HTMLElement or newHtml is not a string
24
+ * @returns {void}
25
+ * @throws {Error} If container is not an HTMLElement or newHtml is not a string.
16
26
  */
17
27
  patchDOM(container, newHtml) {
18
28
  if (!(container instanceof HTMLElement)) {
@@ -30,10 +40,14 @@ export class Renderer {
30
40
 
31
41
  /**
32
42
  * Diffs two DOM trees (old and new) and applies updates to the old DOM.
43
+ * This method recursively compares nodes and their attributes, applying only
44
+ * the necessary changes to minimize DOM operations.
33
45
  *
46
+ * @private
34
47
  * @param {HTMLElement} oldParent - The original DOM element.
35
48
  * @param {HTMLElement} newParent - The new DOM element.
36
- * @throws {Error} If either parent is not an HTMLElement
49
+ * @returns {void}
50
+ * @throws {Error} If either parent is not an HTMLElement.
37
51
  */
38
52
  diff(oldParent, newParent) {
39
53
  if (
@@ -102,10 +116,13 @@ export class Renderer {
102
116
 
103
117
  /**
104
118
  * Updates the attributes of an element to match those of a new element.
119
+ * Handles special cases for ARIA attributes, data attributes, and boolean properties.
105
120
  *
121
+ * @private
106
122
  * @param {HTMLElement} oldEl - The element to update.
107
123
  * @param {HTMLElement} newEl - The element providing the updated attributes.
108
- * @throws {Error} If either element is not an HTMLElement
124
+ * @returns {void}
125
+ * @throws {Error} If either element is not an HTMLElement.
109
126
  */
110
127
  updateAttributes(oldEl, newEl) {
111
128
  if (!(oldEl instanceof HTMLElement) || !(newEl instanceof HTMLElement)) {