eleva 1.2.17-beta → 1.2.18-beta

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/core/Eleva.js CHANGED
@@ -7,34 +7,76 @@ import { Renderer } from "../modules/Renderer.js";
7
7
 
8
8
  /**
9
9
  * @typedef {Object} ComponentDefinition
10
- * @property {function(Object<string, any>): (Object<string, any>|Promise<Object<string, any>>)} [setup]
10
+ * @property {function(ComponentContext): (Record<string, unknown>|Promise<Record<string, unknown>>)} [setup]
11
11
  * Optional setup function that initializes the component's state and returns reactive data
12
- * @property {(function(Object<string, any>): string|Promise<string>|string)} template
12
+ * @property {(function(ComponentContext): string|Promise<string>)} template
13
13
  * Required function that defines the component's HTML structure
14
- * @property {(function(Object<string, any>): string)|string} [style]
14
+ * @property {(function(ComponentContext): string)|string} [style]
15
15
  * Optional function or string that provides component-scoped CSS styles
16
- * @property {Object<string, ComponentDefinition>} [children]
16
+ * @property {Record<string, ComponentDefinition>} [children]
17
17
  * Optional object defining nested child components
18
18
  */
19
19
 
20
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
21
+ * @typedef {Object} ComponentContext
22
+ * @property {Record<string, unknown>} props
23
+ * Component properties passed during mounting
24
+ * @property {Emitter} emitter
25
+ * Event emitter instance for component event handling
26
+ * @property {function<T>(value: T): Signal<T>} signal
27
+ * Factory function to create reactive Signal instances
28
+ * @property {function(LifecycleHookContext): Promise<void>} [onBeforeMount]
29
+ * Hook called before component mounting
30
+ * @property {function(LifecycleHookContext): Promise<void>} [onMount]
31
+ * Hook called after component mounting
32
+ * @property {function(LifecycleHookContext): Promise<void>} [onBeforeUpdate]
33
+ * Hook called before component update
34
+ * @property {function(LifecycleHookContext): Promise<void>} [onUpdate]
35
+ * Hook called after component update
36
+ * @property {function(UnmountHookContext): Promise<void>} [onUnmount]
37
+ * Hook called during component unmounting
38
+ */
39
+
40
+ /**
41
+ * @typedef {Object} LifecycleHookContext
42
+ * @property {HTMLElement} container
43
+ * The DOM element where the component is mounted
44
+ * @property {ComponentContext} context
45
+ * The component's reactive state and context data
46
+ */
47
+
48
+ /**
49
+ * @typedef {Object} UnmountHookContext
50
+ * @property {HTMLElement} container
51
+ * The DOM element where the component is mounted
52
+ * @property {ComponentContext} context
53
+ * The component's reactive state and context data
54
+ * @property {{
55
+ * watchers: Array<() => void>, // Signal watcher cleanup functions
56
+ * listeners: Array<() => void>, // Event listener cleanup functions
57
+ * children: Array<MountResult> // Child component instances
58
+ * }} cleanup
59
+ * Object containing cleanup functions and instances
26
60
  */
27
61
 
28
62
  /**
29
63
  * @typedef {Object} MountResult
30
64
  * @property {HTMLElement} container
31
65
  * The DOM element where the component is mounted
32
- * @property {Object<string, any>} data
66
+ * @property {ComponentContext} data
33
67
  * The component's reactive state and context data
34
- * @property {function(): void} unmount
68
+ * @property {function(): Promise<void>} unmount
35
69
  * Function to clean up and unmount the component
36
70
  */
37
71
 
72
+ /**
73
+ * @typedef {Object} ElevaPlugin
74
+ * @property {function(Eleva, Record<string, unknown>): void} install
75
+ * Function that installs the plugin into the Eleva instance
76
+ * @property {string} name
77
+ * Unique identifier name for the plugin
78
+ */
79
+
38
80
  /**
39
81
  * @class 🧩 Eleva
40
82
  * @classdesc A modern, signal-based component runtime framework that provides lifecycle hooks,
@@ -42,12 +84,26 @@ import { Renderer } from "../modules/Renderer.js";
42
84
  * event handling, and DOM rendering with a focus on performance and developer experience.
43
85
  *
44
86
  * @example
87
+ * // Basic component creation and mounting
45
88
  * const app = new Eleva("myApp");
46
89
  * app.component("myComponent", {
47
- * template: (ctx) => `<div>Hello ${ctx.props.name}</div>`,
48
- * setup: (ctx) => ({ count: new Signal(0) })
90
+ * setup: (ctx) => ({ count: ctx.signal(0) }),
91
+ * template: (ctx) => `<div>Hello ${ctx.props.name}</div>`
49
92
  * });
50
93
  * app.mount(document.getElementById("app"), "myComponent", { name: "World" });
94
+ *
95
+ * @example
96
+ * // Using lifecycle hooks
97
+ * app.component("lifecycleDemo", {
98
+ * setup: () => {
99
+ * return {
100
+ * onMount: ({ container, context }) => {
101
+ * console.log('Component mounted!');
102
+ * }
103
+ * };
104
+ * },
105
+ * template: `<div>Lifecycle Demo</div>`
106
+ * });
51
107
  */
52
108
  export class Eleva {
53
109
  /**
@@ -55,13 +111,24 @@ export class Eleva {
55
111
  *
56
112
  * @public
57
113
  * @param {string} name - The unique identifier name for this Eleva instance.
58
- * @param {Object<string, any>} [config={}] - Optional configuration object for the instance.
114
+ * @param {Record<string, unknown>} [config={}] - Optional configuration object for the instance.
59
115
  * May include framework-wide settings and default behaviors.
116
+ * @throws {Error} If the name is not provided or is not a string.
117
+ * @returns {Eleva} A new Eleva instance.
118
+ *
119
+ * @example
120
+ * const app = new Eleva("myApp");
121
+ * app.component("myComponent", {
122
+ * setup: (ctx) => ({ count: ctx.signal(0) }),
123
+ * template: (ctx) => `<div>Hello ${ctx.props.name}!</div>`
124
+ * });
125
+ * app.mount(document.getElementById("app"), "myComponent", { name: "World" });
126
+ *
60
127
  */
61
128
  constructor(name, config = {}) {
62
129
  /** @public {string} The unique identifier name for this Eleva instance */
63
130
  this.name = name;
64
- /** @public {Object<string, any>} Optional configuration object for the Eleva instance */
131
+ /** @public {Object<string, unknown>} Optional configuration object for the Eleva instance */
65
132
  this.config = config;
66
133
  /** @public {Emitter} Instance of the event emitter for handling component events */
67
134
  this.emitter = new Emitter();
@@ -74,14 +141,6 @@ export class Eleva {
74
141
  this._components = new Map();
75
142
  /** @private {Map<string, ElevaPlugin>} Collection of installed plugin instances by name */
76
143
  this._plugins = new Map();
77
- /** @private {string[]} Array of lifecycle hook names supported by components */
78
- this._lifecycleHooks = [
79
- "onBeforeMount",
80
- "onMount",
81
- "onBeforeUpdate",
82
- "onUpdate",
83
- "onUnmount",
84
- ];
85
144
  /** @private {boolean} Flag indicating if the root component is currently mounted */
86
145
  this._isMounted = false;
87
146
  }
@@ -93,7 +152,7 @@ export class Eleva {
93
152
  *
94
153
  * @public
95
154
  * @param {ElevaPlugin} plugin - The plugin object which must have an `install` function.
96
- * @param {Object<string, any>} [options={}] - Optional configuration options for the plugin.
155
+ * @param {Object<string, unknown>} [options={}] - Optional configuration options for the plugin.
97
156
  * @returns {Eleva} The Eleva instance (for method chaining).
98
157
  * @example
99
158
  * app.use(myPlugin, { option1: "value1" });
@@ -133,7 +192,7 @@ export class Eleva {
133
192
  * @public
134
193
  * @param {HTMLElement} container - The DOM element where the component will be mounted.
135
194
  * @param {string|ComponentDefinition} compName - The name of the registered component or a direct component definition.
136
- * @param {Object<string, any>} [props={}] - Optional properties to pass to the component.
195
+ * @param {Object<string, unknown>} [props={}] - Optional properties to pass to the component.
137
196
  * @returns {Promise<MountResult>}
138
197
  * A Promise that resolves to an object containing:
139
198
  * - container: The mounted component's container element
@@ -164,21 +223,12 @@ export class Eleva {
164
223
  */
165
224
  const { setup, template, style, children } = definition;
166
225
 
167
- /**
168
- * Creates the initial context object for the component instance.
169
- * This context provides core functionality and will be merged with setup data.
170
- * @type {Object<string, any>}
171
- * @property {Object<string, any>} props - Component properties passed during mounting
172
- * @property {Emitter} emitter - Event emitter instance for component event handling
173
- * @property {function(any): Signal} signal - Factory function to create reactive Signal instances
174
- * @property {Object<string, function(): void>} ...lifecycleHooks - Prepared lifecycle hook functions
175
- */
226
+ /** @type {ComponentContext} */
176
227
  const context = {
177
228
  props,
178
229
  emitter: this.emitter,
179
- /** @type {(v: any) => Signal<any>} */
230
+ /** @type {(v: unknown) => Signal<unknown>} */
180
231
  signal: (v) => new this.signal(v),
181
- ...this._prepareLifecycleHooks(),
182
232
  };
183
233
 
184
234
  /**
@@ -189,27 +239,35 @@ export class Eleva {
189
239
  * 3. Rendering the component
190
240
  * 4. Managing component lifecycle
191
241
  *
192
- * @param {Object<string, any>} data - Data returned from the component's setup function
242
+ * @param {Object<string, unknown>} data - Data returned from the component's setup function
193
243
  * @returns {Promise<MountResult>} An object containing:
194
244
  * - container: The mounted component's container element
195
245
  * - data: The component's reactive state and context
196
246
  * - unmount: Function to clean up and unmount the component
197
247
  */
198
248
  const processMount = async (data) => {
199
- /** @type {Object<string, any>} */
249
+ /** @type {ComponentContext} */
200
250
  const mergedContext = { ...context, ...data };
201
251
  /** @type {Array<() => void>} */
202
- const watcherUnsubscribers = [];
252
+ const watchers = [];
203
253
  /** @type {Array<MountResult>} */
204
254
  const childInstances = [];
205
255
  /** @type {Array<() => void>} */
206
- const cleanupListeners = [];
256
+ const listeners = [];
207
257
 
208
258
  // Execute before hooks
209
259
  if (!this._isMounted) {
210
- mergedContext.onBeforeMount && mergedContext.onBeforeMount();
260
+ /** @type {LifecycleHookContext} */
261
+ await mergedContext.onBeforeMount?.({
262
+ container,
263
+ context: mergedContext,
264
+ });
211
265
  } else {
212
- mergedContext.onBeforeUpdate && mergedContext.onBeforeUpdate();
266
+ /** @type {LifecycleHookContext} */
267
+ await mergedContext.onBeforeUpdate?.({
268
+ container,
269
+ context: mergedContext,
270
+ });
213
271
  }
214
272
 
215
273
  /**
@@ -225,17 +283,25 @@ export class Eleva {
225
283
  : template;
226
284
  const newHtml = TemplateEngine.parse(templateResult, mergedContext);
227
285
  this.renderer.patchDOM(container, newHtml);
228
- this._processEvents(container, mergedContext, cleanupListeners);
286
+ this._processEvents(container, mergedContext, listeners);
229
287
  if (style)
230
288
  this._injectStyles(container, compName, style, mergedContext);
231
289
  if (children)
232
290
  await this._mountComponents(container, children, childInstances);
233
291
 
234
292
  if (!this._isMounted) {
235
- mergedContext.onMount && mergedContext.onMount();
293
+ /** @type {LifecycleHookContext} */
294
+ await mergedContext.onMount?.({
295
+ container,
296
+ context: mergedContext,
297
+ });
236
298
  this._isMounted = true;
237
299
  } else {
238
- mergedContext.onUpdate && mergedContext.onUpdate();
300
+ /** @type {LifecycleHookContext} */
301
+ await mergedContext.onUpdate?.({
302
+ container,
303
+ context: mergedContext,
304
+ });
239
305
  }
240
306
  };
241
307
 
@@ -245,7 +311,7 @@ export class Eleva {
245
311
  * Stores unsubscribe functions to clean up watchers when component unmounts.
246
312
  */
247
313
  for (const val of Object.values(data)) {
248
- if (val instanceof Signal) watcherUnsubscribers.push(val.watch(render));
314
+ if (val instanceof Signal) watchers.push(val.watch(render));
249
315
  }
250
316
 
251
317
  await render();
@@ -258,11 +324,20 @@ export class Eleva {
258
324
  *
259
325
  * @returns {void}
260
326
  */
261
- unmount: () => {
262
- for (const fn of watcherUnsubscribers) fn();
263
- for (const fn of cleanupListeners) fn();
264
- for (const child of childInstances) child.unmount();
265
- mergedContext.onUnmount && mergedContext.onUnmount();
327
+ unmount: async () => {
328
+ /** @type {UnmountHookContext} */
329
+ await mergedContext.onUnmount?.({
330
+ container,
331
+ context: mergedContext,
332
+ cleanup: {
333
+ watchers: watchers,
334
+ listeners: listeners,
335
+ children: childInstances,
336
+ },
337
+ });
338
+ for (const fn of watchers) fn();
339
+ for (const fn of listeners) fn();
340
+ for (const child of childInstances) await child.unmount();
266
341
  container.innerHTML = "";
267
342
  delete container._eleva_instance;
268
343
  },
@@ -277,50 +352,39 @@ export class Eleva {
277
352
  return await processMount(setupResult);
278
353
  }
279
354
 
280
- /**
281
- * Prepares default no-operation lifecycle hook functions for a component.
282
- * These hooks will be called at various stages of the component's lifecycle.
283
- *
284
- * @private
285
- * @returns {Object<string, function(): void>} An object mapping lifecycle hook names to empty functions.
286
- * The returned object will be merged with the component's context.
287
- */
288
- _prepareLifecycleHooks() {
289
- /** @type {Object<string, () => void>} */
290
- const hooks = {};
291
- for (const hook of this._lifecycleHooks) {
292
- hooks[hook] = () => {};
293
- }
294
- return hooks;
295
- }
296
-
297
355
  /**
298
356
  * Processes DOM elements for event binding based on attributes starting with "@".
299
357
  * This method handles the event delegation system and ensures proper cleanup of event listeners.
300
358
  *
301
359
  * @private
302
360
  * @param {HTMLElement} container - The container element in which to search for event attributes.
303
- * @param {Object<string, any>} context - The current component context containing event handler definitions.
304
- * @param {Array<Function>} cleanupListeners - Array to collect cleanup functions for each event listener.
361
+ * @param {ComponentContext} context - The current component context containing event handler definitions.
362
+ * @param {Array<() => void>} listeners - Array to collect cleanup functions for each event listener.
305
363
  * @returns {void}
306
364
  */
307
- _processEvents(container, context, cleanupListeners) {
365
+ _processEvents(container, context, listeners) {
366
+ /** @type {NodeListOf<Element>} */
308
367
  const elements = container.querySelectorAll("*");
309
368
  for (const el of elements) {
369
+ /** @type {NamedNodeMap} */
310
370
  const attrs = el.attributes;
311
371
  for (let i = 0; i < attrs.length; i++) {
372
+ /** @type {Attr} */
312
373
  const attr = attrs[i];
313
374
 
314
375
  if (!attr.name.startsWith("@")) continue;
315
376
 
377
+ /** @type {keyof HTMLElementEventMap} */
316
378
  const event = attr.name.slice(1);
379
+ /** @type {string} */
317
380
  const handlerName = attr.value;
381
+ /** @type {(event: Event) => void} */
318
382
  const handler =
319
383
  context[handlerName] || TemplateEngine.evaluate(handlerName, context);
320
384
  if (typeof handler === "function") {
321
385
  el.addEventListener(event, handler);
322
386
  el.removeAttribute(attr.name);
323
- cleanupListeners.push(() => el.removeEventListener(event, handler));
387
+ listeners.push(() => el.removeEventListener(event, handler));
324
388
  }
325
389
  }
326
390
  }
@@ -333,15 +397,17 @@ export class Eleva {
333
397
  * @private
334
398
  * @param {HTMLElement} container - The container element where styles should be injected.
335
399
  * @param {string} compName - The component name used to identify the style element.
336
- * @param {(function(Object<string, any>): string)|string} styleDef - The component's style definition (function or string).
337
- * @param {Object<string, any>} context - The current component context for style interpolation.
400
+ * @param {(function(ComponentContext): string)|string} styleDef - The component's style definition (function or string).
401
+ * @param {ComponentContext} context - The current component context for style interpolation.
338
402
  * @returns {void}
339
403
  */
340
404
  _injectStyles(container, compName, styleDef, context) {
405
+ /** @type {string} */
341
406
  const newStyle =
342
407
  typeof styleDef === "function"
343
408
  ? TemplateEngine.parse(styleDef(context), context)
344
409
  : styleDef;
410
+ /** @type {HTMLStyleElement|null} */
345
411
  let styleEl = container.querySelector(`style[data-e-style="${compName}"]`);
346
412
 
347
413
  if (styleEl && styleEl.textContent === newStyle) return;
@@ -361,7 +427,7 @@ export class Eleva {
361
427
  * @private
362
428
  * @param {HTMLElement} element - The DOM element to extract props from
363
429
  * @param {string} prefix - The prefix to look for in attributes
364
- * @returns {Object<string, any>} An object containing the extracted props
430
+ * @returns {Record<string, string>} An object containing the extracted props
365
431
  * @example
366
432
  * // For an element with attributes:
367
433
  * // <div :name="John" :age="25">
@@ -404,7 +470,9 @@ export class Eleva {
404
470
  if (!selector) continue;
405
471
  for (const el of container.querySelectorAll(selector)) {
406
472
  if (!(el instanceof HTMLElement)) continue;
473
+ /** @type {Record<string, string>} */
407
474
  const props = this._extractProps(el, ":");
475
+ /** @type {MountResult} */
408
476
  const instance = await this.mount(el, component, props);
409
477
  if (instance && !childInstances.includes(instance)) {
410
478
  childInstances.push(instance);
@@ -5,6 +5,9 @@
5
5
  * @classdesc A robust event emitter that enables inter-component communication through a publish-subscribe pattern.
6
6
  * Components can emit events and listen for events from other components, facilitating loose coupling
7
7
  * and reactive updates across the application.
8
+ * Events are handled synchronously in the order they were registered, with proper cleanup
9
+ * of unsubscribed handlers.
10
+ * Event names should follow the format 'namespace:action' (e.g., 'user:login', 'cart:update').
8
11
  *
9
12
  * @example
10
13
  * const emitter = new Emitter();
@@ -18,18 +21,19 @@ export class Emitter {
18
21
  * @public
19
22
  */
20
23
  constructor() {
21
- /** @private {Map<string, Set<function(any): void>>} Map of event names to their registered handler functions */
24
+ /** @private {Map<string, Set<(data: unknown) => void>>} Map of event names to their registered handler functions */
22
25
  this._events = new Map();
23
26
  }
24
27
 
25
28
  /**
26
29
  * Registers an event handler for the specified event name.
27
30
  * The handler will be called with the event data when the event is emitted.
31
+ * Event names should follow the format 'namespace:action' for consistency.
28
32
  *
29
33
  * @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(): void} A function to unsubscribe the event handler.
34
+ * @param {string} event - The name of the event to listen for (e.g., 'user:login').
35
+ * @param {(data: unknown) => void} handler - The callback function to invoke when the event occurs.
36
+ * @returns {() => void} A function to unsubscribe the event handler.
33
37
  * @example
34
38
  * const unsubscribe = emitter.on('user:login', (user) => console.log(user));
35
39
  * // Later...
@@ -45,11 +49,17 @@ export class Emitter {
45
49
  /**
46
50
  * Removes an event handler for the specified event name.
47
51
  * If no handler is provided, all handlers for the event are removed.
52
+ * Automatically cleans up empty event sets to prevent memory leaks.
48
53
  *
49
54
  * @public
50
- * @param {string} event - The name of the event.
51
- * @param {function(any): void} [handler] - The specific handler function to remove.
55
+ * @param {string} event - The name of the event to remove handlers from.
56
+ * @param {(data: unknown) => void} [handler] - The specific handler function to remove.
52
57
  * @returns {void}
58
+ * @example
59
+ * // Remove a specific handler
60
+ * emitter.off('user:login', loginHandler);
61
+ * // Remove all handlers for an event
62
+ * emitter.off('user:login');
53
63
  */
54
64
  off(event, handler) {
55
65
  if (!this._events.has(event)) return;
@@ -66,11 +76,17 @@ export class Emitter {
66
76
  /**
67
77
  * Emits an event with the specified data to all registered handlers.
68
78
  * Handlers are called synchronously in the order they were registered.
79
+ * If no handlers are registered for the event, the emission is silently ignored.
69
80
  *
70
81
  * @public
71
82
  * @param {string} event - The name of the event to emit.
72
- * @param {...any} args - Optional arguments to pass to the event handlers.
83
+ * @param {...unknown} args - Optional arguments to pass to the event handlers.
73
84
  * @returns {void}
85
+ * @example
86
+ * // Emit an event with data
87
+ * emitter.emit('user:login', { name: 'John', role: 'admin' });
88
+ * // Emit an event with multiple arguments
89
+ * emitter.emit('cart:update', { items: [] }, { total: 0 });
74
90
  */
75
91
  emit(event, ...args) {
76
92
  if (!this._events.has(event)) return;