eleva 0.1.0-alpha → 1.0.0-rc.1
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/LICENSE +1 -1
- package/README.md +467 -1
- package/dist/eleva.cjs.js +972 -0
- package/dist/eleva.cjs.js.map +1 -0
- package/dist/eleva.d.ts +591 -0
- package/dist/eleva.esm.js +970 -0
- package/dist/eleva.esm.js.map +1 -0
- package/dist/eleva.umd.js +978 -0
- package/dist/eleva.umd.js.map +1 -0
- package/dist/eleva.umd.min.js +3 -0
- package/dist/eleva.umd.min.js.map +1 -0
- package/package.json +195 -28
- package/src/core/Eleva.js +489 -0
- package/src/index.js +5 -0
- package/src/modules/Emitter.js +95 -0
- package/src/modules/Renderer.js +291 -0
- package/src/modules/Signal.js +93 -0
- package/src/modules/TemplateEngine.js +65 -0
- package/types/core/Eleva.d.ts +353 -0
- package/types/core/Eleva.d.ts.map +1 -0
- package/types/index.d.ts +3 -0
- package/types/index.d.ts.map +1 -0
- package/types/modules/Emitter.d.ts +66 -0
- package/types/modules/Emitter.d.ts.map +1 -0
- package/types/modules/Renderer.d.ts +104 -0
- package/types/modules/Renderer.d.ts.map +1 -0
- package/types/modules/Signal.d.ts +68 -0
- package/types/modules/Signal.d.ts.map +1 -0
- package/types/modules/TemplateEngine.d.ts +50 -0
- package/types/modules/TemplateEngine.d.ts.map +1 -0
|
@@ -0,0 +1,489 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
import { TemplateEngine } from "../modules/TemplateEngine.js";
|
|
4
|
+
import { Signal } from "../modules/Signal.js";
|
|
5
|
+
import { Emitter } from "../modules/Emitter.js";
|
|
6
|
+
import { Renderer } from "../modules/Renderer.js";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* @typedef {Object} ComponentDefinition
|
|
10
|
+
* @property {function(ComponentContext): (Record<string, unknown>|Promise<Record<string, unknown>>)} [setup]
|
|
11
|
+
* Optional setup function that initializes the component's state and returns reactive data
|
|
12
|
+
* @property {(function(ComponentContext): string|Promise<string>)} template
|
|
13
|
+
* Required function that defines the component's HTML structure
|
|
14
|
+
* @property {(function(ComponentContext): string)|string} [style]
|
|
15
|
+
* Optional function or string that provides component-scoped CSS styles
|
|
16
|
+
* @property {Record<string, ComponentDefinition>} [children]
|
|
17
|
+
* Optional object defining nested child components
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
/**
|
|
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
|
|
60
|
+
*/
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* @typedef {Object} MountResult
|
|
64
|
+
* @property {HTMLElement} container
|
|
65
|
+
* The DOM element where the component is mounted
|
|
66
|
+
* @property {ComponentContext} data
|
|
67
|
+
* The component's reactive state and context data
|
|
68
|
+
* @property {function(): Promise<void>} unmount
|
|
69
|
+
* Function to clean up and unmount the component
|
|
70
|
+
*/
|
|
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
|
+
|
|
80
|
+
/**
|
|
81
|
+
* @class 🧩 Eleva
|
|
82
|
+
* @classdesc A modern, signal-based component runtime framework that provides lifecycle hooks,
|
|
83
|
+
* scoped styles, and plugin support. Eleva manages component registration, plugin integration,
|
|
84
|
+
* event handling, and DOM rendering with a focus on performance and developer experience.
|
|
85
|
+
*
|
|
86
|
+
* @example
|
|
87
|
+
* // Basic component creation and mounting
|
|
88
|
+
* const app = new Eleva("myApp");
|
|
89
|
+
* app.component("myComponent", {
|
|
90
|
+
* setup: (ctx) => ({ count: ctx.signal(0) }),
|
|
91
|
+
* template: (ctx) => `<div>Hello ${ctx.props.name}</div>`
|
|
92
|
+
* });
|
|
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
|
+
* });
|
|
107
|
+
*/
|
|
108
|
+
export class Eleva {
|
|
109
|
+
/**
|
|
110
|
+
* Creates a new Eleva instance with the specified name and configuration.
|
|
111
|
+
*
|
|
112
|
+
* @public
|
|
113
|
+
* @param {string} name - The unique identifier name for this Eleva instance.
|
|
114
|
+
* @param {Record<string, unknown>} [config={}] - Optional configuration object for the instance.
|
|
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
|
+
*
|
|
127
|
+
*/
|
|
128
|
+
constructor(name, config = {}) {
|
|
129
|
+
/** @public {string} The unique identifier name for this Eleva instance */
|
|
130
|
+
this.name = name;
|
|
131
|
+
/** @public {Object<string, unknown>} Optional configuration object for the Eleva instance */
|
|
132
|
+
this.config = config;
|
|
133
|
+
/** @public {Emitter} Instance of the event emitter for handling component events */
|
|
134
|
+
this.emitter = new Emitter();
|
|
135
|
+
/** @public {typeof Signal} Static reference to the Signal class for creating reactive state */
|
|
136
|
+
this.signal = Signal;
|
|
137
|
+
/** @public {Renderer} Instance of the renderer for handling DOM updates and patching */
|
|
138
|
+
this.renderer = new Renderer();
|
|
139
|
+
|
|
140
|
+
/** @private {Map<string, ComponentDefinition>} Registry of all component definitions by name */
|
|
141
|
+
this._components = new Map();
|
|
142
|
+
/** @private {Map<string, ElevaPlugin>} Collection of installed plugin instances by name */
|
|
143
|
+
this._plugins = new Map();
|
|
144
|
+
/** @private {boolean} Flag indicating if the root component is currently mounted */
|
|
145
|
+
this._isMounted = false;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Integrates a plugin with the Eleva framework.
|
|
150
|
+
* The plugin's install function will be called with the Eleva instance and provided options.
|
|
151
|
+
* After installation, the plugin will be available for use by components.
|
|
152
|
+
*
|
|
153
|
+
* @public
|
|
154
|
+
* @param {ElevaPlugin} plugin - The plugin object which must have an `install` function.
|
|
155
|
+
* @param {Object<string, unknown>} [options={}] - Optional configuration options for the plugin.
|
|
156
|
+
* @returns {Eleva} The Eleva instance (for method chaining).
|
|
157
|
+
* @example
|
|
158
|
+
* app.use(myPlugin, { option1: "value1" });
|
|
159
|
+
*/
|
|
160
|
+
use(plugin, options = {}) {
|
|
161
|
+
plugin.install(this, options);
|
|
162
|
+
this._plugins.set(plugin.name, plugin);
|
|
163
|
+
|
|
164
|
+
return this;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Registers a new component with the Eleva instance.
|
|
169
|
+
* The component will be available for mounting using its registered name.
|
|
170
|
+
*
|
|
171
|
+
* @public
|
|
172
|
+
* @param {string} name - The unique name of the component to register.
|
|
173
|
+
* @param {ComponentDefinition} definition - The component definition including setup, template, style, and children.
|
|
174
|
+
* @returns {Eleva} The Eleva instance (for method chaining).
|
|
175
|
+
* @throws {Error} If the component name is already registered.
|
|
176
|
+
* @example
|
|
177
|
+
* app.component("myButton", {
|
|
178
|
+
* template: (ctx) => `<button>${ctx.props.text}</button>`,
|
|
179
|
+
* style: `button { color: blue; }`
|
|
180
|
+
* });
|
|
181
|
+
*/
|
|
182
|
+
component(name, definition) {
|
|
183
|
+
/** @type {Map<string, ComponentDefinition>} */
|
|
184
|
+
this._components.set(name, definition);
|
|
185
|
+
return this;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Mounts a registered component to a DOM element.
|
|
190
|
+
* This will initialize the component, set up its reactive state, and render it to the DOM.
|
|
191
|
+
*
|
|
192
|
+
* @public
|
|
193
|
+
* @param {HTMLElement} container - The DOM element where the component will be mounted.
|
|
194
|
+
* @param {string|ComponentDefinition} compName - The name of the registered component or a direct component definition.
|
|
195
|
+
* @param {Object<string, unknown>} [props={}] - Optional properties to pass to the component.
|
|
196
|
+
* @returns {Promise<MountResult>}
|
|
197
|
+
* A Promise that resolves to an object containing:
|
|
198
|
+
* - container: The mounted component's container element
|
|
199
|
+
* - data: The component's reactive state and context
|
|
200
|
+
* - unmount: Function to clean up and unmount the component
|
|
201
|
+
* @throws {Error} If the container is not found, or component is not registered.
|
|
202
|
+
* @example
|
|
203
|
+
* const instance = await app.mount(document.getElementById("app"), "myComponent", { text: "Click me" });
|
|
204
|
+
* // Later...
|
|
205
|
+
* instance.unmount();
|
|
206
|
+
*/
|
|
207
|
+
async mount(container, compName, props = {}) {
|
|
208
|
+
if (!container) throw new Error(`Container not found: ${container}`);
|
|
209
|
+
|
|
210
|
+
if (container._eleva_instance) return container._eleva_instance;
|
|
211
|
+
|
|
212
|
+
/** @type {ComponentDefinition} */
|
|
213
|
+
const definition =
|
|
214
|
+
typeof compName === "string" ? this._components.get(compName) : compName;
|
|
215
|
+
if (!definition) throw new Error(`Component "${compName}" not registered.`);
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Destructure the component definition to access core functionality.
|
|
219
|
+
* - setup: Optional function for component initialization and state management
|
|
220
|
+
* - template: Required function or string that returns the component's HTML structure
|
|
221
|
+
* - style: Optional function or string for component-scoped CSS styles
|
|
222
|
+
* - children: Optional object defining nested child components
|
|
223
|
+
*/
|
|
224
|
+
const { setup, template, style, children } = definition;
|
|
225
|
+
|
|
226
|
+
/** @type {ComponentContext} */
|
|
227
|
+
const context = {
|
|
228
|
+
props,
|
|
229
|
+
emitter: this.emitter,
|
|
230
|
+
/** @type {(v: unknown) => Signal<unknown>} */
|
|
231
|
+
signal: (v) => new this.signal(v),
|
|
232
|
+
};
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Processes the mounting of the component.
|
|
236
|
+
* This function handles:
|
|
237
|
+
* 1. Merging setup data with the component context
|
|
238
|
+
* 2. Setting up reactive watchers
|
|
239
|
+
* 3. Rendering the component
|
|
240
|
+
* 4. Managing component lifecycle
|
|
241
|
+
*
|
|
242
|
+
* @param {Object<string, unknown>} data - Data returned from the component's setup function
|
|
243
|
+
* @returns {Promise<MountResult>} An object containing:
|
|
244
|
+
* - container: The mounted component's container element
|
|
245
|
+
* - data: The component's reactive state and context
|
|
246
|
+
* - unmount: Function to clean up and unmount the component
|
|
247
|
+
*/
|
|
248
|
+
const processMount = async (data) => {
|
|
249
|
+
/** @type {ComponentContext} */
|
|
250
|
+
const mergedContext = { ...context, ...data };
|
|
251
|
+
/** @type {Array<() => void>} */
|
|
252
|
+
const watchers = [];
|
|
253
|
+
/** @type {Array<MountResult>} */
|
|
254
|
+
const childInstances = [];
|
|
255
|
+
/** @type {Array<() => void>} */
|
|
256
|
+
const listeners = [];
|
|
257
|
+
|
|
258
|
+
// Execute before hooks
|
|
259
|
+
if (!this._isMounted) {
|
|
260
|
+
/** @type {LifecycleHookContext} */
|
|
261
|
+
await mergedContext.onBeforeMount?.({
|
|
262
|
+
container,
|
|
263
|
+
context: mergedContext,
|
|
264
|
+
});
|
|
265
|
+
} else {
|
|
266
|
+
/** @type {LifecycleHookContext} */
|
|
267
|
+
await mergedContext.onBeforeUpdate?.({
|
|
268
|
+
container,
|
|
269
|
+
context: mergedContext,
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Renders the component by:
|
|
275
|
+
* 1. Processing the template
|
|
276
|
+
* 2. Updating the DOM
|
|
277
|
+
* 3. Processing events, injecting styles, and mounting child components.
|
|
278
|
+
*/
|
|
279
|
+
const render = async () => {
|
|
280
|
+
const templateResult =
|
|
281
|
+
typeof template === "function"
|
|
282
|
+
? await template(mergedContext)
|
|
283
|
+
: template;
|
|
284
|
+
const newHtml = TemplateEngine.parse(templateResult, mergedContext);
|
|
285
|
+
this.renderer.patchDOM(container, newHtml);
|
|
286
|
+
this._processEvents(container, mergedContext, listeners);
|
|
287
|
+
if (style)
|
|
288
|
+
this._injectStyles(container, compName, style, mergedContext);
|
|
289
|
+
if (children)
|
|
290
|
+
await this._mountComponents(container, children, childInstances);
|
|
291
|
+
|
|
292
|
+
if (!this._isMounted) {
|
|
293
|
+
/** @type {LifecycleHookContext} */
|
|
294
|
+
await mergedContext.onMount?.({
|
|
295
|
+
container,
|
|
296
|
+
context: mergedContext,
|
|
297
|
+
});
|
|
298
|
+
this._isMounted = true;
|
|
299
|
+
} else {
|
|
300
|
+
/** @type {LifecycleHookContext} */
|
|
301
|
+
await mergedContext.onUpdate?.({
|
|
302
|
+
container,
|
|
303
|
+
context: mergedContext,
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
};
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* Sets up reactive watchers for all Signal instances in the component's data.
|
|
310
|
+
* When a Signal's value changes, the component will re-render to reflect the updates.
|
|
311
|
+
* Stores unsubscribe functions to clean up watchers when component unmounts.
|
|
312
|
+
*/
|
|
313
|
+
for (const val of Object.values(data)) {
|
|
314
|
+
if (val instanceof Signal) watchers.push(val.watch(render));
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
await render();
|
|
318
|
+
|
|
319
|
+
const instance = {
|
|
320
|
+
container,
|
|
321
|
+
data: mergedContext,
|
|
322
|
+
/**
|
|
323
|
+
* Unmounts the component, cleaning up watchers and listeners, child components, and clearing the container.
|
|
324
|
+
*
|
|
325
|
+
* @returns {void}
|
|
326
|
+
*/
|
|
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();
|
|
341
|
+
container.innerHTML = "";
|
|
342
|
+
delete container._eleva_instance;
|
|
343
|
+
},
|
|
344
|
+
};
|
|
345
|
+
|
|
346
|
+
container._eleva_instance = instance;
|
|
347
|
+
return instance;
|
|
348
|
+
};
|
|
349
|
+
|
|
350
|
+
// Handle asynchronous setup.
|
|
351
|
+
const setupResult = typeof setup === "function" ? await setup(context) : {};
|
|
352
|
+
return await processMount(setupResult);
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/**
|
|
356
|
+
* Processes DOM elements for event binding based on attributes starting with "@".
|
|
357
|
+
* This method handles the event delegation system and ensures proper cleanup of event listeners.
|
|
358
|
+
*
|
|
359
|
+
* @private
|
|
360
|
+
* @param {HTMLElement} container - The container element in which to search for event attributes.
|
|
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.
|
|
363
|
+
* @returns {void}
|
|
364
|
+
*/
|
|
365
|
+
_processEvents(container, context, listeners) {
|
|
366
|
+
/** @type {NodeListOf<Element>} */
|
|
367
|
+
const elements = container.querySelectorAll("*");
|
|
368
|
+
for (const el of elements) {
|
|
369
|
+
/** @type {NamedNodeMap} */
|
|
370
|
+
const attrs = el.attributes;
|
|
371
|
+
for (let i = 0; i < attrs.length; i++) {
|
|
372
|
+
/** @type {Attr} */
|
|
373
|
+
const attr = attrs[i];
|
|
374
|
+
|
|
375
|
+
if (!attr.name.startsWith("@")) continue;
|
|
376
|
+
|
|
377
|
+
/** @type {keyof HTMLElementEventMap} */
|
|
378
|
+
const event = attr.name.slice(1);
|
|
379
|
+
/** @type {string} */
|
|
380
|
+
const handlerName = attr.value;
|
|
381
|
+
/** @type {(event: Event) => void} */
|
|
382
|
+
const handler =
|
|
383
|
+
context[handlerName] || TemplateEngine.evaluate(handlerName, context);
|
|
384
|
+
if (typeof handler === "function") {
|
|
385
|
+
el.addEventListener(event, handler);
|
|
386
|
+
el.removeAttribute(attr.name);
|
|
387
|
+
listeners.push(() => el.removeEventListener(event, handler));
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* Injects scoped styles into the component's container.
|
|
395
|
+
* The styles are automatically prefixed to prevent style leakage to other components.
|
|
396
|
+
*
|
|
397
|
+
* @private
|
|
398
|
+
* @param {HTMLElement} container - The container element where styles should be injected.
|
|
399
|
+
* @param {string} compName - The component name used to identify the style element.
|
|
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.
|
|
402
|
+
* @returns {void}
|
|
403
|
+
*/
|
|
404
|
+
_injectStyles(container, compName, styleDef, context) {
|
|
405
|
+
/** @type {string} */
|
|
406
|
+
const newStyle =
|
|
407
|
+
typeof styleDef === "function"
|
|
408
|
+
? TemplateEngine.parse(styleDef(context), context)
|
|
409
|
+
: styleDef;
|
|
410
|
+
/** @type {HTMLStyleElement|null} */
|
|
411
|
+
let styleEl = container.querySelector(`style[data-e-style="${compName}"]`);
|
|
412
|
+
|
|
413
|
+
if (styleEl && styleEl.textContent === newStyle) return;
|
|
414
|
+
if (!styleEl) {
|
|
415
|
+
styleEl = document.createElement("style");
|
|
416
|
+
styleEl.setAttribute("data-e-style", compName);
|
|
417
|
+
container.appendChild(styleEl);
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
styleEl.textContent = newStyle;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/**
|
|
424
|
+
* Extracts props from an element's attributes that start with the specified prefix.
|
|
425
|
+
* This method is used to collect component properties from DOM elements.
|
|
426
|
+
*
|
|
427
|
+
* @private
|
|
428
|
+
* @param {HTMLElement} element - The DOM element to extract props from
|
|
429
|
+
* @param {string} prefix - The prefix to look for in attributes
|
|
430
|
+
* @returns {Record<string, string>} An object containing the extracted props
|
|
431
|
+
* @example
|
|
432
|
+
* // For an element with attributes:
|
|
433
|
+
* // <div :name="John" :age="25">
|
|
434
|
+
* // Returns: { name: "John", age: "25" }
|
|
435
|
+
*/
|
|
436
|
+
_extractProps(element, prefix) {
|
|
437
|
+
if (!element.attributes) return {};
|
|
438
|
+
|
|
439
|
+
const props = {};
|
|
440
|
+
const attrs = element.attributes;
|
|
441
|
+
|
|
442
|
+
for (let i = attrs.length - 1; i >= 0; i--) {
|
|
443
|
+
const attr = attrs[i];
|
|
444
|
+
if (attr.name.startsWith(prefix)) {
|
|
445
|
+
const propName = attr.name.slice(prefix.length);
|
|
446
|
+
props[propName] = attr.value;
|
|
447
|
+
element.removeAttribute(attr.name);
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
return props;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* Mounts all components within the parent component's container.
|
|
455
|
+
* This method handles mounting of explicitly defined children components.
|
|
456
|
+
*
|
|
457
|
+
* The mounting process follows these steps:
|
|
458
|
+
* 1. Cleans up any existing component instances
|
|
459
|
+
* 2. Mounts explicitly defined children components
|
|
460
|
+
*
|
|
461
|
+
* @private
|
|
462
|
+
* @param {HTMLElement} container - The container element to mount components in
|
|
463
|
+
* @param {Object<string, ComponentDefinition>} children - Map of selectors to component definitions for explicit children
|
|
464
|
+
* @param {Array<MountResult>} childInstances - Array to store all mounted component instances
|
|
465
|
+
* @returns {Promise<void>}
|
|
466
|
+
*
|
|
467
|
+
* @example
|
|
468
|
+
* // Explicit children mounting:
|
|
469
|
+
* const children = {
|
|
470
|
+
* 'UserProfile': UserProfileComponent,
|
|
471
|
+
* '#settings-panel': "settings-panel"
|
|
472
|
+
* };
|
|
473
|
+
*/
|
|
474
|
+
async _mountComponents(container, children, childInstances) {
|
|
475
|
+
for (const [selector, component] of Object.entries(children)) {
|
|
476
|
+
if (!selector) continue;
|
|
477
|
+
for (const el of container.querySelectorAll(selector)) {
|
|
478
|
+
if (!(el instanceof HTMLElement)) continue;
|
|
479
|
+
/** @type {Record<string, string>} */
|
|
480
|
+
const props = this._extractProps(el, ":");
|
|
481
|
+
/** @type {MountResult} */
|
|
482
|
+
const instance = await this.mount(el, component, props);
|
|
483
|
+
if (instance && !childInstances.includes(instance)) {
|
|
484
|
+
childInstances.push(instance);
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
/**
|
|
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
|
+
* 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').
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* const emitter = new Emitter();
|
|
14
|
+
* emitter.on('user:login', (user) => console.log(`User logged in: ${user.name}`));
|
|
15
|
+
* emitter.emit('user:login', { name: 'John' }); // Logs: "User logged in: John"
|
|
16
|
+
*/
|
|
17
|
+
export class Emitter {
|
|
18
|
+
/**
|
|
19
|
+
* Creates a new Emitter instance.
|
|
20
|
+
*
|
|
21
|
+
* @public
|
|
22
|
+
*/
|
|
23
|
+
constructor() {
|
|
24
|
+
/** @private {Map<string, Set<(data: unknown) => void>>} Map of event names to their registered handler functions */
|
|
25
|
+
this._events = new Map();
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Registers an event handler for the specified event name.
|
|
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.
|
|
32
|
+
*
|
|
33
|
+
* @public
|
|
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.
|
|
37
|
+
* @example
|
|
38
|
+
* const unsubscribe = emitter.on('user:login', (user) => console.log(user));
|
|
39
|
+
* // Later...
|
|
40
|
+
* unsubscribe(); // Stops listening for the event
|
|
41
|
+
*/
|
|
42
|
+
on(event, handler) {
|
|
43
|
+
if (!this._events.has(event)) this._events.set(event, new Set());
|
|
44
|
+
|
|
45
|
+
this._events.get(event).add(handler);
|
|
46
|
+
return () => this.off(event, handler);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Removes an event handler for the specified event name.
|
|
51
|
+
* If no handler is provided, all handlers for the event are removed.
|
|
52
|
+
* Automatically cleans up empty event sets to prevent memory leaks.
|
|
53
|
+
*
|
|
54
|
+
* @public
|
|
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.
|
|
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');
|
|
63
|
+
*/
|
|
64
|
+
off(event, handler) {
|
|
65
|
+
if (!this._events.has(event)) return;
|
|
66
|
+
if (handler) {
|
|
67
|
+
const handlers = this._events.get(event);
|
|
68
|
+
handlers.delete(handler);
|
|
69
|
+
// Remove the event if there are no handlers left
|
|
70
|
+
if (handlers.size === 0) this._events.delete(event);
|
|
71
|
+
} else {
|
|
72
|
+
this._events.delete(event);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Emits an event with the specified data to all registered handlers.
|
|
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.
|
|
80
|
+
*
|
|
81
|
+
* @public
|
|
82
|
+
* @param {string} event - The name of the event to emit.
|
|
83
|
+
* @param {...unknown} args - Optional arguments to pass to the event handlers.
|
|
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 });
|
|
90
|
+
*/
|
|
91
|
+
emit(event, ...args) {
|
|
92
|
+
if (!this._events.has(event)) return;
|
|
93
|
+
this._events.get(event).forEach((handler) => handler(...args));
|
|
94
|
+
}
|
|
95
|
+
}
|