eleva 1.0.0-alpha → 1.2.0-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/README.md +108 -105
- package/dist/eleva.d.ts +106 -89
- package/dist/eleva.esm.js +125 -68
- package/dist/eleva.esm.js.map +1 -1
- package/dist/eleva.min.js +1 -1
- package/dist/eleva.min.js.map +1 -1
- package/dist/eleva.umd.js +125 -68
- package/dist/eleva.umd.js.map +1 -1
- package/package.json +2 -1
- package/src/core/Eleva.js +93 -40
- package/src/modules/Emitter.js +8 -8
- package/src/modules/Renderer.js +8 -8
- package/src/modules/Signal.js +7 -5
- package/src/modules/TemplateEngine.js +10 -11
- package/types/core/Eleva.d.ts +109 -30
- package/types/core/Eleva.d.ts.map +1 -1
- package/types/modules/Emitter.d.ts +10 -10
- package/types/modules/Emitter.d.ts.map +1 -1
- package/types/modules/Renderer.d.ts +2 -2
- package/types/modules/Signal.d.ts +10 -8
- package/types/modules/Signal.d.ts.map +1 -1
- package/types/modules/TemplateEngine.d.ts +15 -12
- package/types/modules/TemplateEngine.d.ts.map +1 -1
package/dist/eleva.min.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"eleva.min.js","sources":["../src/modules/TemplateEngine.js","../src/modules/Signal.js","../src/modules/Emitter.js","../src/modules/Renderer.js","../src/core/Eleva.js"],"sourcesContent":["\"use strict\";\n\n/**\n * 🔒 TemplateEngine: Secure interpolation & dynamic attribute parsing.\n *\n * This class provides methods to parse template strings by replacing\n * interpolation expressions with dynamic data values and to evaluate expressions\n * within a given data context.\n */\nexport class TemplateEngine {\n /**\n * Parses a template string and replaces interpolation expressions with corresponding values.\n *\n * @param {string} template - The template string containing expressions in the format {{ expression }}.\n * @param {object} data - The data object to use for evaluating expressions.\n * @returns {string} The resulting string with evaluated values.\n */\n static parse(template, data) {\n return template.replace(/\\{\\{\\s*(.*?)\\s*\\}\\}/g, (_, expr) => {\n const value = this.evaluate(expr, data);\n return value === undefined ? \"\" : value;\n });\n }\n\n /**\n * Evaluates an expression using the provided data context.\n *\n * @param {string} expr - The JavaScript expression to evaluate.\n * @param {object} data - The data context for evaluating the expression.\n * @returns {*} The result of the evaluated expression, or an empty string if undefined or on error.\n */\n static evaluate(expr, data) {\n try {\n const keys = Object.keys(data);\n const values = keys.map((k) => data[k]);\n const result = new Function(...keys, `return ${expr}`)(...values);\n return result === undefined ? \"\" : result;\n } catch (error) {\n console.error(`Template evaluation error:`, {\n expression: expr,\n data,\n error: error.message,\n });\n return \"\";\n }\n }\n}\n","\"use strict\";\n\n/**\n * ⚡ Signal: Fine-grained reactivity.\n *\n * A reactive data holder that notifies registered watchers when its value changes,\n * allowing for fine-grained DOM patching rather than full re-renders.\n */\nexport class Signal {\n /**\n * Creates a new Signal instance.\n *\n * @param {*} value - The initial value of the signal.\n */\n constructor(value) {\n this._value = value;\n this._watchers = new Set();\n }\n\n /**\n * Gets the current value of the signal.\n *\n * @returns {*} The current value.\n */\n get value() {\n return this._value;\n }\n\n /**\n * Sets a new value for the signal and notifies all registered watchers if the value has changed.\n *\n * @param {*} newVal - The new value to set.\n */\n set value(newVal) {\n if (newVal !== this._value) {\n this._value = newVal;\n this._watchers.forEach((fn) => fn(newVal));\n }\n }\n\n /**\n * Registers a watcher function that will be called whenever the signal's value changes.\n *\n * @param {Function} fn - The callback function to invoke on value change.\n * @returns {Function} A function to unsubscribe the watcher.\n */\n watch(fn) {\n this._watchers.add(fn);\n return () => this._watchers.delete(fn);\n }\n}\n","\"use strict\";\n\n/**\n * 🎙️ Emitter: Robust inter-component communication with event bubbling.\n *\n * Implements a basic publish-subscribe pattern for event handling,\n * allowing components to communicate through custom events.\n */\nexport class Emitter {\n /**\n * Creates a new Emitter instance.\n */\n constructor() {\n /** @type {Object.<string, Function[]>} */\n this.events = {};\n }\n\n /**\n * Registers an event handler for the specified event.\n *\n * @param {string} event - The name of the event.\n * @param {Function} handler - The function to call when the event is emitted.\n */\n on(event, handler) {\n (this.events[event] || (this.events[event] = [])).push(handler);\n }\n\n /**\n * Removes a previously registered event handler.\n *\n * @param {string} event - The name of the event.\n * @param {Function} handler - The handler function to remove.\n */\n off(event, handler) {\n if (this.events[event]) {\n this.events[event] = this.events[event].filter((h) => h !== handler);\n }\n }\n\n /**\n * Emits an event, invoking all handlers registered for that event.\n *\n * @param {string} event - The event name.\n * @param {...*} args - Additional arguments to pass to the event handlers.\n */\n emit(event, ...args) {\n (this.events[event] || []).forEach((handler) => handler(...args));\n }\n}\n","\"use strict\";\n\n/**\n * 🎨 Renderer: Handles DOM patching, diffing, and attribute updates.\n *\n * Provides methods for efficient DOM updates by diffing the new and old DOM structures\n * and applying only the necessary changes.\n */\nexport class Renderer {\n /**\n * Patches the DOM of a container element with new HTML content.\n *\n * @param {HTMLElement} container - The container element to patch.\n * @param {string} newHtml - The new HTML content to apply.\n */\n patchDOM(container, newHtml) {\n const tempContainer = document.createElement(\"div\");\n tempContainer.innerHTML = newHtml;\n this.diff(container, tempContainer);\n }\n\n /**\n * Diffs two DOM trees (old and new) and applies updates to the old DOM.\n *\n * @param {HTMLElement} oldParent - The original DOM element.\n * @param {HTMLElement} newParent - The new DOM element.\n */\n diff(oldParent, newParent) {\n const oldNodes = Array.from(oldParent.childNodes);\n const newNodes = Array.from(newParent.childNodes);\n const max = Math.max(oldNodes.length, newNodes.length);\n for (let i = 0; i < max; i++) {\n const oldNode = oldNodes[i];\n const newNode = newNodes[i];\n\n // Append new nodes that don't exist in the old tree.\n if (!oldNode && newNode) {\n oldParent.appendChild(newNode.cloneNode(true));\n continue;\n }\n // Remove old nodes not present in the new tree.\n if (oldNode && !newNode) {\n oldParent.removeChild(oldNode);\n continue;\n }\n\n // For element nodes, compare keys if available.\n if (\n oldNode.nodeType === Node.ELEMENT_NODE &&\n newNode.nodeType === Node.ELEMENT_NODE\n ) {\n const oldKey = oldNode.getAttribute(\"key\");\n const newKey = newNode.getAttribute(\"key\");\n if (oldKey || newKey) {\n if (oldKey !== newKey) {\n oldParent.replaceChild(newNode.cloneNode(true), oldNode);\n continue;\n }\n }\n }\n\n // Replace nodes if types or tag names differ.\n if (\n oldNode.nodeType !== newNode.nodeType ||\n oldNode.nodeName !== newNode.nodeName\n ) {\n oldParent.replaceChild(newNode.cloneNode(true), oldNode);\n continue;\n }\n // For text nodes, update content if different.\n if (oldNode.nodeType === Node.TEXT_NODE) {\n if (oldNode.nodeValue !== newNode.nodeValue) {\n oldNode.nodeValue = newNode.nodeValue;\n }\n continue;\n }\n // For element nodes, update attributes and then diff children.\n if (oldNode.nodeType === Node.ELEMENT_NODE) {\n this.updateAttributes(oldNode, newNode);\n this.diff(oldNode, newNode);\n }\n }\n }\n\n /**\n * Updates the attributes of an element to match those of a new element.\n *\n * @param {HTMLElement} oldEl - The element to update.\n * @param {HTMLElement} newEl - The element providing the updated attributes.\n */\n updateAttributes(oldEl, newEl) {\n const attributeToPropertyMap = {\n value: \"value\",\n checked: \"checked\",\n selected: \"selected\",\n disabled: \"disabled\",\n };\n\n // Remove old attributes that no longer exist.\n Array.from(oldEl.attributes).forEach((attr) => {\n if (attr.name.startsWith(\"@\")) return;\n if (!newEl.hasAttribute(attr.name)) {\n oldEl.removeAttribute(attr.name);\n }\n });\n // Add or update attributes from newEl.\n Array.from(newEl.attributes).forEach((attr) => {\n if (attr.name.startsWith(\"@\")) return;\n if (oldEl.getAttribute(attr.name) !== attr.value) {\n oldEl.setAttribute(attr.name, attr.value);\n if (attributeToPropertyMap[attr.name]) {\n oldEl[attributeToPropertyMap[attr.name]] = attr.value;\n } else if (attr.name in oldEl) {\n oldEl[attr.name] = attr.value;\n }\n }\n });\n }\n}\n","\"use strict\";\n\nimport { TemplateEngine } from \"../modules/TemplateEngine.js\";\nimport { Signal } from \"../modules/Signal.js\";\nimport { Emitter } from \"../modules/Emitter.js\";\nimport { Renderer } from \"../modules/Renderer.js\";\n\n/**\n * 🧩 Eleva Core: Signal-based component runtime framework with lifecycle, scoped styles, and plugins.\n *\n * The Eleva class is the core of the framework. It manages component registration,\n * plugin integration, lifecycle hooks, event handling, and DOM rendering.\n */\nexport class Eleva {\n /**\n * Creates a new Eleva instance.\n *\n * @param {string} name - The name of the Eleva instance.\n * @param {object} [config={}] - Optional configuration for the instance.\n */\n constructor(name, config = {}) {\n this.name = name;\n this.config = config;\n this._components = {};\n this._plugins = [];\n this._lifecycleHooks = [\n \"onBeforeMount\",\n \"onMount\",\n \"onBeforeUpdate\",\n \"onUpdate\",\n \"onUnmount\",\n ];\n this._isMounted = false;\n this.emitter = new Emitter();\n this.renderer = new Renderer();\n }\n\n /**\n * Integrates a plugin with the Eleva framework.\n *\n * @param {object} [plugin] - The plugin object which should have an install function.\n * @param {object} [options={}] - Optional options to pass to the plugin.\n * @returns {Eleva} The Eleva instance (for chaining).\n */\n use(plugin, options = {}) {\n if (typeof plugin.install === \"function\") {\n plugin.install(this, options);\n }\n this._plugins.push(plugin);\n return this;\n }\n\n /**\n * Registers a component with the Eleva instance.\n *\n * @param {string} name - The name of the component.\n * @param {object} definition - The component definition including setup, template, style, and children.\n * @returns {Eleva} The Eleva instance (for chaining).\n */\n component(name, definition) {\n this._components[name] = definition;\n return this;\n }\n\n /**\n * Mounts a registered component to a DOM element.\n *\n * @param {string|HTMLElement} selectorOrElement - A CSS selector string or DOM element where the component will be mounted.\n * @param {string} compName - The name of the component to mount.\n * @param {object} [props={}] - Optional properties to pass to the component.\n * @returns {object|Promise<object>} An object representing the mounted component instance, or a Promise that resolves to it for asynchronous setups.\n * @throws Will throw an error if the container or component is not found.\n */\n mount(selectorOrElement, compName, props = {}) {\n const container =\n typeof selectorOrElement === \"string\"\n ? document.querySelector(selectorOrElement)\n : selectorOrElement;\n if (!container)\n throw new Error(`Container not found: ${selectorOrElement}`);\n\n const definition = this._components[compName];\n if (!definition) throw new Error(`Component \"${compName}\" not registered.`);\n\n const { setup, template, style, children } = definition;\n const context = {\n props,\n emit: this.emitter.emit.bind(this.emitter),\n on: this.emitter.on.bind(this.emitter),\n signal: (v) => new Signal(v),\n ...this._prepareLifecycleHooks(),\n };\n\n /**\n * Processes the mounting of the component.\n *\n * @param {object} data - Data returned from the component's setup function.\n * @returns {object} An object with the container, merged context data, and an unmount function.\n */\n const processMount = (data) => {\n const mergedContext = { ...context, ...data };\n const watcherUnsubscribers = [];\n const childInstances = [];\n\n if (!this._isMounted) {\n mergedContext.onBeforeMount && mergedContext.onBeforeMount();\n } else {\n mergedContext.onBeforeUpdate && mergedContext.onBeforeUpdate();\n }\n\n /**\n * Renders the component by parsing the template, patching the DOM,\n * processing events, injecting styles, and mounting child components.\n */\n const render = () => {\n const newHtml = TemplateEngine.parse(\n template(mergedContext),\n mergedContext\n );\n this.renderer.patchDOM(container, newHtml);\n this._processEvents(container, mergedContext);\n this._injectStyles(container, compName, style, mergedContext);\n this._mountChildren(container, children, childInstances);\n if (!this._isMounted) {\n mergedContext.onMount && mergedContext.onMount();\n this._isMounted = true;\n } else {\n mergedContext.onUpdate && mergedContext.onUpdate();\n }\n };\n\n Object.values(data).forEach((val) => {\n if (val instanceof Signal) watcherUnsubscribers.push(val.watch(render));\n });\n\n render();\n\n return {\n container,\n data: mergedContext,\n /**\n * Unmounts the component, cleaning up watchers, child components, and clearing the container.\n */\n unmount: () => {\n watcherUnsubscribers.forEach((fn) => fn());\n childInstances.forEach((child) => child.unmount());\n mergedContext.onUnmount && mergedContext.onUnmount();\n container.innerHTML = \"\";\n },\n };\n };\n\n // Handle asynchronous setup if needed.\n const setupResult = setup(context);\n if (setupResult && typeof setupResult.then === \"function\") {\n return setupResult.then((data) => processMount(data));\n } else {\n const data = setupResult || {};\n return processMount(data);\n }\n }\n\n /**\n * Prepares default no-operation lifecycle hook functions.\n *\n * @returns {object} An object with keys for lifecycle hooks mapped to empty functions.\n * @private\n */\n _prepareLifecycleHooks() {\n return this._lifecycleHooks.reduce((acc, hook) => {\n acc[hook] = () => {};\n return acc;\n }, {});\n }\n\n /**\n * Processes DOM elements for event binding based on attributes starting with \"@\".\n *\n * @param {HTMLElement} container - The container element in which to search for events.\n * @param {object} context - The current context containing event handler definitions.\n * @private\n */\n _processEvents(container, context) {\n container.querySelectorAll(\"*\").forEach((el) => {\n [...el.attributes].forEach(({ name, value }) => {\n if (name.startsWith(\"@\")) {\n const event = name.slice(1);\n const handler = TemplateEngine.evaluate(value, context);\n if (typeof handler === \"function\") {\n el.addEventListener(event, handler);\n el.removeAttribute(name);\n }\n }\n });\n });\n }\n\n /**\n * Injects scoped styles into the component's container.\n *\n * @param {HTMLElement} container - The container element.\n * @param {string} compName - The component name used to identify the style element.\n * @param {Function} styleFn - A function that returns CSS styles as a string.\n * @param {object} context - The current context for style interpolation.\n * @private\n */\n _injectStyles(container, compName, styleFn, context) {\n if (styleFn) {\n let styleEl = container.querySelector(\n `style[data-eleva-style=\"${compName}\"]`\n );\n if (!styleEl) {\n styleEl = document.createElement(\"style\");\n styleEl.setAttribute(\"data-eleva-style\", compName);\n container.appendChild(styleEl);\n }\n styleEl.textContent = TemplateEngine.parse(styleFn(context), context);\n }\n }\n\n /**\n * Mounts child components within the parent component's container.\n *\n * @param {HTMLElement} container - The parent container element.\n * @param {object} children - An object mapping child component selectors to their definitions.\n * @param {Array} childInstances - An array to store the mounted child component instances.\n * @private\n */\n _mountChildren(container, children, childInstances) {\n childInstances.forEach((child) => child.unmount());\n childInstances.length = 0;\n\n Object.keys(children || {}).forEach((childName) => {\n container.querySelectorAll(childName).forEach((childEl) => {\n const props = {};\n [...childEl.attributes].forEach(({ name, value }) => {\n if (name.startsWith(\"eleva-prop-\")) {\n props[name.slice(\"eleva-prop-\".length)] = value;\n }\n });\n const instance = this.mount(childEl, childName, props);\n childInstances.push(instance);\n });\n });\n }\n}\n"],"names":["TemplateEngine","parse","template","data","replace","_","expr","value","this","evaluate","undefined","keys","Object","values","map","k","result","Function","error","console","expression","message","Signal","constructor","_value","_watchers","Set","newVal","forEach","fn","watch","add","delete","Emitter","events","on","event","handler","push","off","filter","h","emit","args","Renderer","patchDOM","container","newHtml","tempContainer","document","createElement","innerHTML","diff","oldParent","newParent","oldNodes","Array","from","childNodes","newNodes","max","Math","length","i","oldNode","newNode","nodeType","Node","ELEMENT_NODE","oldKey","getAttribute","newKey","replaceChild","cloneNode","nodeName","TEXT_NODE","updateAttributes","nodeValue","removeChild","appendChild","oldEl","newEl","attributeToPropertyMap","checked","selected","disabled","attributes","attr","name","startsWith","hasAttribute","removeAttribute","setAttribute","config","_components","_plugins","_lifecycleHooks","_isMounted","emitter","renderer","use","plugin","options","install","component","definition","mount","selectorOrElement","compName","props","querySelector","Error","setup","style","children","context","bind","signal","v","_prepareLifecycleHooks","processMount","mergedContext","watcherUnsubscribers","childInstances","onBeforeUpdate","onBeforeMount","render","_processEvents","_injectStyles","_mountChildren","onUpdate","onMount","val","unmount","child","onUnmount","setupResult","then","reduce","acc","hook","querySelectorAll","el","slice","addEventListener","styleFn","styleEl","textContent","childName","childEl","instance"],"mappings":"sOASO,MAAMA,EAQX,YAAOC,CAAMC,EAAUC,GACrB,OAAOD,EAASE,QAAQ,wBAAwB,CAACC,EAAGC,KAClD,MAAMC,EAAQC,KAAKC,SAASH,EAAMH,GAClC,YAAiBO,IAAVH,EAAsB,GAAKA,CAAK,GAE3C,CASA,eAAOE,CAASH,EAAMH,GACpB,IACE,MAAMQ,EAAOC,OAAOD,KAAKR,GACnBU,EAASF,EAAKG,KAAKC,GAAMZ,EAAKY,KAC9BC,EAAS,IAAIC,YAAYN,EAAM,UAAUL,IAAhC,IAA2CO,GAC1D,YAAkBH,IAAXM,EAAuB,GAAKA,CACpC,CAAC,MAAOE,GAMP,OALAC,QAAQD,MAAM,6BAA8B,CAC1CE,WAAYd,EACZH,OACAe,MAAOA,EAAMG,UAER,EACT,CACF,ECrCK,MAAMC,EAMXC,WAAAA,CAAYhB,GACVC,KAAKgB,OAASjB,EACdC,KAAKiB,UAAY,IAAIC,GACvB,CAOA,SAAInB,GACF,OAAOC,KAAKgB,MACd,CAOA,SAAIjB,CAAMoB,GACJA,IAA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Ae/F,SAAS0G,GAAUA,EAAMD,YACxCV,EAAe7D,OAAS,EAExBlD,OAAOD,KAAKuG,GAAY,CAAE,GAAEtF,SAASwH,IACnCtG,EAAU+F,iBAAiBO,GAAWxH,SAASyH,IAC7C,MAAMxC,EAAQ,CAAE,EAChB,IAAIwC,EAAQ/D,YAAY1D,SAAQ,EAAG4D,OAAMjF,YACnCiF,EAAKC,WAAW,iBAClBoB,EAAMrB,EAAKuD,MAAM,KAAyBxI,EAC5C,IAEF,MAAM+I,EAAW9I,KAAKkG,MAAM2C,EAASD,EAAWvC,GAChDc,EAAerF,KAAKgH,EAAS,GAC7B,GAEN"}
|
|
1
|
+
{"version":3,"file":"eleva.min.js","sources":["../src/modules/TemplateEngine.js","../src/modules/Signal.js","../src/modules/Emitter.js","../src/modules/Renderer.js","../src/core/Eleva.js"],"sourcesContent":["\"use strict\";\n\n/**\n * @class 🔒 TemplateEngine\n * @classdesc Secure interpolation & dynamic attribute parsing.\n * Provides methods to parse template strings by replacing interpolation expressions\n * with dynamic data values and to evaluate expressions within a given data context.\n */\nexport class TemplateEngine {\n /**\n * Parses a template string and replaces interpolation expressions with corresponding values.\n *\n * @param {string} template - The template string containing expressions in the format `{{ expression }}`.\n * @param {Object<string, any>} data - The data object to use for evaluating expressions.\n * @returns {string} The resulting string with evaluated values.\n */\n static parse(template, data) {\n return template.replace(/\\{\\{\\s*(.*?)\\s*\\}\\}/g, (_, expr) => {\n const value = this.evaluate(expr, data);\n return value === undefined ? \"\" : value;\n });\n }\n\n /**\n * Evaluates a JavaScript expression using the provided data context.\n *\n * @param {string} expr - The JavaScript expression to evaluate.\n * @param {Object<string, any>} data - The data context for evaluating the expression.\n * @returns {any} The result of the evaluated expression, or an empty string if undefined or on error.\n */\n static evaluate(expr, data) {\n try {\n const keys = Object.keys(data);\n const values = Object.values(data);\n const result = new Function(...keys, `return ${expr}`)(...values);\n return result === undefined ? \"\" : result;\n } catch (error) {\n console.error(`Template evaluation error:`, {\n expression: expr,\n data,\n error: error.message,\n });\n return \"\";\n }\n }\n}\n","\"use strict\";\n\n/**\n * @class ⚡ Signal\n * @classdesc Fine-grained reactivity.\n * A reactive data holder that notifies registered watchers when its value changes,\n * enabling fine-grained DOM patching rather than full re-renders.\n */\nexport class Signal {\n /**\n * Creates a new Signal instance.\n *\n * @param {*} value - The initial value of the signal.\n */\n constructor(value) {\n /** @private {*} Internal storage for the signal's current value */\n this._value = value;\n /** @private {Set<function>} Collection of callback functions to be notified when value changes */\n this._watchers = new Set();\n }\n\n /**\n * Gets the current value of the signal.\n *\n * @returns {*} The current value.\n */\n get value() {\n return this._value;\n }\n\n /**\n * Sets a new value for the signal and notifies all registered watchers if the value has changed.\n *\n * @param {*} newVal - The new value to set.\n */\n set value(newVal) {\n if (newVal !== this._value) {\n this._value = newVal;\n this._watchers.forEach((fn) => fn(newVal));\n }\n }\n\n /**\n * Registers a watcher function that will be called whenever the signal's value changes.\n *\n * @param {function(any): void} fn - The callback function to invoke on value change.\n * @returns {function(): boolean} A function to unsubscribe the watcher.\n */\n watch(fn) {\n this._watchers.add(fn);\n return () => this._watchers.delete(fn);\n }\n}\n","\"use strict\";\n\n/**\n * @class 🎙️ Emitter\n * @classdesc Robust inter-component communication with event bubbling.\n * Implements a basic publish-subscribe pattern for event handling, allowing components\n * to communicate through custom events.\n */\nexport class Emitter {\n /**\n * Creates a new Emitter instance.\n */\n constructor() {\n /** @type {Object.<string, Function[]>} Storage for event handlers mapped by event name */\n this.events = {};\n }\n\n /**\n * Registers an event handler for the specified event.\n *\n * @param {string} event - The name of the event.\n * @param {function(...any): void} handler - The function to call when the event is emitted.\n */\n on(event, handler) {\n (this.events[event] || (this.events[event] = [])).push(handler);\n }\n\n /**\n * Removes a previously registered event handler.\n *\n * @param {string} event - The name of the event.\n * @param {function(...any): void} handler - The handler function to remove.\n */\n off(event, handler) {\n if (this.events[event]) {\n this.events[event] = this.events[event].filter((h) => h !== handler);\n }\n }\n\n /**\n * Emits an event, invoking all handlers registered for that event.\n *\n * @param {string} event - The event name.\n * @param {...any} args - Additional arguments to pass to the event handlers.\n */\n emit(event, ...args) {\n (this.events[event] || []).forEach((handler) => handler(...args));\n }\n}\n","\"use strict\";\n\n/**\n * @class 🎨 Renderer\n * @classdesc Handles DOM patching, diffing, and attribute updates.\n * Provides methods for efficient DOM updates by diffing the new and old DOM structures\n * and applying only the necessary changes.\n */\nexport class Renderer {\n /**\n * Patches the DOM of a container element with new HTML content.\n *\n * @param {HTMLElement} container - The container element to patch.\n * @param {string} newHtml - The new HTML content to apply.\n */\n patchDOM(container, newHtml) {\n const tempContainer = document.createElement(\"div\");\n tempContainer.innerHTML = newHtml;\n this.diff(container, tempContainer);\n }\n\n /**\n * Diffs two DOM trees (old and new) and applies updates to the old DOM.\n *\n * @param {HTMLElement} oldParent - The original DOM element.\n * @param {HTMLElement} newParent - The new DOM element.\n */\n diff(oldParent, newParent) {\n const oldNodes = Array.from(oldParent.childNodes);\n const newNodes = Array.from(newParent.childNodes);\n const max = Math.max(oldNodes.length, newNodes.length);\n for (let i = 0; i < max; i++) {\n const oldNode = oldNodes[i];\n const newNode = newNodes[i];\n\n // Case 1: Append new nodes that don't exist in the old tree.\n if (!oldNode && newNode) {\n oldParent.appendChild(newNode.cloneNode(true));\n continue;\n }\n // Case 2: Remove old nodes not present in the new tree.\n if (oldNode && !newNode) {\n oldParent.removeChild(oldNode);\n continue;\n }\n\n // Case 3: For element nodes, compare keys if available.\n if (\n oldNode.nodeType === Node.ELEMENT_NODE &&\n newNode.nodeType === Node.ELEMENT_NODE\n ) {\n const oldKey = oldNode.getAttribute(\"key\");\n const newKey = newNode.getAttribute(\"key\");\n if (oldKey || newKey) {\n if (oldKey !== newKey) {\n oldParent.replaceChild(newNode.cloneNode(true), oldNode);\n continue;\n }\n }\n }\n\n // Case 4: Replace nodes if types or tag names differ.\n if (\n oldNode.nodeType !== newNode.nodeType ||\n oldNode.nodeName !== newNode.nodeName\n ) {\n oldParent.replaceChild(newNode.cloneNode(true), oldNode);\n continue;\n }\n // Case 5: For text nodes, update content if different.\n if (oldNode.nodeType === Node.TEXT_NODE) {\n if (oldNode.nodeValue !== newNode.nodeValue) {\n oldNode.nodeValue = newNode.nodeValue;\n }\n continue;\n }\n // Case 6: For element nodes, update attributes and then diff children.\n if (oldNode.nodeType === Node.ELEMENT_NODE) {\n this.updateAttributes(oldNode, newNode);\n this.diff(oldNode, newNode);\n }\n }\n }\n\n /**\n * Updates the attributes of an element to match those of a new element.\n *\n * @param {HTMLElement} oldEl - The element to update.\n * @param {HTMLElement} newEl - The element providing the updated attributes.\n */\n updateAttributes(oldEl, newEl) {\n const attributeToPropertyMap = {\n value: \"value\",\n checked: \"checked\",\n selected: \"selected\",\n disabled: \"disabled\",\n };\n\n // Remove old attributes that no longer exist.\n Array.from(oldEl.attributes).forEach((attr) => {\n if (attr.name.startsWith(\"@\")) return;\n if (!newEl.hasAttribute(attr.name)) {\n oldEl.removeAttribute(attr.name);\n }\n });\n // Add or update attributes from newEl.\n Array.from(newEl.attributes).forEach((attr) => {\n if (attr.name.startsWith(\"@\")) return;\n if (oldEl.getAttribute(attr.name) !== attr.value) {\n oldEl.setAttribute(attr.name, attr.value);\n if (attributeToPropertyMap[attr.name]) {\n oldEl[attributeToPropertyMap[attr.name]] = attr.value;\n } else if (attr.name in oldEl) {\n oldEl[attr.name] = attr.value;\n }\n }\n });\n }\n}\n","\"use strict\";\n\nimport { TemplateEngine } from \"../modules/TemplateEngine.js\";\nimport { Signal } from \"../modules/Signal.js\";\nimport { Emitter } from \"../modules/Emitter.js\";\nimport { Renderer } from \"../modules/Renderer.js\";\n\n/**\n * Defines the structure and behavior of a component.\n * @typedef {Object} ComponentDefinition\n * @property {function(Object<string, any>): (Object<string, any>|Promise<Object<string, any>>)} [setup]\n * Optional setup function that initializes the component's reactive state and lifecycle.\n * Receives props and context as an argument and should return an object containing the component's state.\n * Can return either a synchronous object or a Promise that resolves to an object for async initialization.\n *\n * @property {function(Object<string, any>): string} template\n * Required function that defines the component's HTML structure.\n * Receives the merged context (props + setup data) and must return an HTML template string.\n * Supports dynamic expressions using {{ }} syntax for reactive data binding.\n *\n * @property {function(Object<string, any>): string} [style]\n * Optional function that defines component-scoped CSS styles.\n * Receives the merged context and returns a CSS string that will be automatically scoped to the component.\n * Styles are injected into the component's container and only affect elements within it.\n *\n * @property {Object<string, ComponentDefinition>} [children]\n * Optional object that defines nested child components.\n * Keys are CSS selectors that match elements in the template where child components should be mounted.\n * Values are ComponentDefinition objects that define the structure and behavior of each child component.\n */\n\n/**\n * @class 🧩 Eleva\n * @classdesc Signal-based component runtime framework with lifecycle hooks, scoped styles, and plugin support.\n * Manages component registration, plugin integration, event handling, and DOM rendering.\n */\nexport class Eleva {\n /**\n * Creates a new Eleva instance.\n *\n * @param {string} name - The name of the Eleva instance.\n * @param {Object<string, any>} [config={}] - Optional configuration for the instance.\n */\n constructor(name, config = {}) {\n /** @type {string} The unique identifier name for this Eleva instance */\n this.name = name;\n /** @type {Object<string, any>} Optional configuration object for the Eleva instance */\n this.config = config;\n /** @type {Object<string, ComponentDefinition>} Object storing registered component definitions by name */\n this._components = {};\n /** @private {Array<Object>} Collection of installed plugin instances */\n this._plugins = [];\n /** @private {string[]} Array of lifecycle hook names supported by the component */\n this._lifecycleHooks = [\n \"onBeforeMount\",\n \"onMount\",\n \"onBeforeUpdate\",\n \"onUpdate\",\n \"onUnmount\",\n ];\n /** @private {boolean} Flag indicating if component is currently mounted */\n this._isMounted = false;\n /** @private {Emitter} Instance of the event emitter for handling component events */\n this.emitter = new Emitter();\n /** @private {Renderer} Instance of the renderer for handling DOM updates and patching */\n this.renderer = new Renderer();\n }\n\n /**\n * Integrates a plugin with the Eleva framework.\n *\n * @param {Object} plugin - The plugin object which should have an `install` function.\n * @param {Object<string, any>} [options={}] - Optional options to pass to the plugin.\n * @returns {Eleva} The Eleva instance (for chaining).\n */\n use(plugin, options = {}) {\n if (typeof plugin.install === \"function\") {\n plugin.install(this, options);\n }\n this._plugins.push(plugin);\n return this;\n }\n\n /**\n * Registers a component with the Eleva instance.\n *\n * @param {string} name - The name of the component.\n * @param {ComponentDefinition} definition - The component definition including setup, template, style, and children.\n * @returns {Eleva} The Eleva instance (for chaining).\n */\n component(name, definition) {\n this._components[name] = definition;\n return this;\n }\n\n /**\n * Mounts a registered component to a DOM element.\n *\n * @param {HTMLElement} container - A DOM element where the component will be mounted.\n * @param {string|ComponentDefinition} compName - The name of the component to mount or a component definition.\n * @param {Object<string, any>} [props={}] - Optional properties to pass to the component.\n * @returns {object|Promise<object>} An object representing the mounted component instance, or a Promise that resolves to it for asynchronous setups.\n * @throws {Error} If the container is not found or if the component is not registered.\n */\n mount(container, compName, props = {}) {\n if (!container) throw new Error(`Container not found: ${container}`);\n\n let definition;\n if (typeof compName === \"string\") {\n definition = this._components[compName];\n if (!definition)\n throw new Error(`Component \"${compName}\" not registered.`);\n } else if (typeof compName === \"object\") {\n definition = compName;\n } else {\n throw new Error(\"Invalid component parameter.\");\n }\n\n /**\n * Destructure the component definition to access core functionality.\n * - setup: Optional function for component initialization and state management\n * - template: Required function that returns the component's HTML structure\n * - style: Optional function for component-scoped CSS styles\n * - children: Optional object defining nested child components\n */\n const { setup, template, style, children } = definition;\n\n /**\n * Creates the initial context object for the component instance.\n * This context provides core functionality and will be merged with setup data.\n * @type {Object<string, any>}\n * @property {Object<string, any>} props - Component properties passed during mounting\n * @property {Emitter} emitter - Event emitter instance for component event handling\n * @property {function(any): Signal} signal - Factory function to create reactive Signal instances\n * @property {Object<string, function(): void>} ...lifecycleHooks - Prepared lifecycle hook functions\n */\n const context = {\n props,\n emitter: this.emitter,\n signal: (v) => new Signal(v),\n ...this._prepareLifecycleHooks(),\n };\n\n /**\n * Processes the mounting of the component.\n *\n * @param {Object<string, any>} data - Data returned from the component's setup function.\n * @returns {object} An object with the container, merged context data, and an unmount function.\n */\n const processMount = (data) => {\n const mergedContext = { ...context, ...data };\n const watcherUnsubscribers = [];\n const childInstances = [];\n\n if (!this._isMounted) {\n mergedContext.onBeforeMount && mergedContext.onBeforeMount();\n } else {\n mergedContext.onBeforeUpdate && mergedContext.onBeforeUpdate();\n }\n\n /**\n * Renders the component by parsing the template, patching the DOM,\n * processing events, injecting styles, and mounting child components.\n */\n const render = () => {\n const newHtml = TemplateEngine.parse(\n template(mergedContext),\n mergedContext\n );\n this.renderer.patchDOM(container, newHtml);\n this._processEvents(container, mergedContext);\n this._injectStyles(container, compName, style, mergedContext);\n this._mountChildren(container, children, childInstances);\n if (!this._isMounted) {\n mergedContext.onMount && mergedContext.onMount();\n this._isMounted = true;\n } else {\n mergedContext.onUpdate && mergedContext.onUpdate();\n }\n };\n\n /**\n * Sets up reactive watchers for all Signal instances in the component's data.\n * When a Signal's value changes, the component will re-render to reflect the updates.\n * Stores unsubscribe functions to clean up watchers when component unmounts.\n */\n Object.values(data).forEach((val) => {\n if (val instanceof Signal) watcherUnsubscribers.push(val.watch(render));\n });\n\n render();\n\n return {\n container,\n data: mergedContext,\n /**\n * Unmounts the component, cleaning up watchers, child components, and clearing the container.\n *\n * @returns {void}\n */\n unmount: () => {\n watcherUnsubscribers.forEach((fn) => fn());\n childInstances.forEach((child) => child.unmount());\n mergedContext.onUnmount && mergedContext.onUnmount();\n container.innerHTML = \"\";\n },\n };\n };\n\n // Handle asynchronous setup.\n return Promise.resolve(\n typeof setup === \"function\" ? setup(context) : {}\n ).then((data) => processMount(data));\n }\n\n /**\n * Prepares default no-operation lifecycle hook functions.\n *\n * @returns {Object<string, function(): void>} An object with keys for lifecycle hooks mapped to empty functions.\n * @private\n */\n _prepareLifecycleHooks() {\n return this._lifecycleHooks.reduce((acc, hook) => {\n acc[hook] = () => {};\n return acc;\n }, {});\n }\n\n /**\n * Processes DOM elements for event binding based on attributes starting with \"@\".\n *\n * @param {HTMLElement} container - The container element in which to search for events.\n * @param {Object<string, any>} context - The current context containing event handler definitions.\n * @private\n */\n _processEvents(container, context) {\n container.querySelectorAll(\"*\").forEach((el) => {\n [...el.attributes].forEach(({ name, value }) => {\n if (name.startsWith(\"@\")) {\n const event = name.slice(1);\n const handler = TemplateEngine.evaluate(value, context);\n if (typeof handler === \"function\") {\n el.addEventListener(event, handler);\n el.removeAttribute(name);\n }\n }\n });\n });\n }\n\n /**\n * Injects scoped styles into the component's container.\n *\n * @param {HTMLElement} container - The container element.\n * @param {string} compName - The component name used to identify the style element.\n * @param {function(Object<string, any>): string} [styleFn] - A function that returns CSS styles as a string.\n * @param {Object<string, any>} context - The current context for style interpolation.\n * @private\n */\n _injectStyles(container, compName, styleFn, context) {\n if (styleFn) {\n let styleEl = container.querySelector(\n `style[data-eleva-style=\"${compName}\"]`\n );\n if (!styleEl) {\n styleEl = document.createElement(\"style\");\n styleEl.setAttribute(\"data-eleva-style\", compName);\n container.appendChild(styleEl);\n }\n styleEl.textContent = TemplateEngine.parse(styleFn(context), context);\n }\n }\n\n /**\n * Mounts child components within the parent component's container.\n *\n * @param {HTMLElement} container - The parent container element.\n * @param {Object<string, ComponentDefinition>} [children] - An object mapping child component selectors to their definitions.\n * @param {Array<object>} childInstances - An array to store the mounted child component instances.\n * @private\n */\n _mountChildren(container, children, childInstances) {\n childInstances.forEach((child) => child.unmount());\n childInstances.length = 0;\n\n Object.keys(children || {}).forEach((childSelector) => {\n container.querySelectorAll(childSelector).forEach((childEl) => {\n const props = {};\n [...childEl.attributes].forEach(({ name, value }) => {\n if (name.startsWith(\"eleva-prop-\")) {\n props[name.slice(\"eleva-prop-\".length)] = value;\n }\n });\n const instance = this.mount(childEl, children[childSelector], props);\n childInstances.push(instance);\n });\n });\n }\n}\n"],"names":["TemplateEngine","parse","template","data","replace","_","expr","value","this","evaluate","undefined","keys","Object","values","result","Function","error","console","expression","message","Signal","constructor","_value","_watchers","Set","newVal","forEach","fn","watch","add","delete","Emitter","events","on","event","handler","push","off","filter","h","emit","args","Renderer","patchDOM","container","newHtml","tempContainer","document","createElement","innerHTML","diff","oldParent","newParent","oldNodes","Array","from","childNodes","newNodes","max","Math","length","i","oldNode","newNode","nodeType","Node","ELEMENT_NODE","oldKey","getAttribute","newKey","replaceChild","cloneNode","nodeName","TEXT_NODE","updateAttributes","nodeValue","removeChild","appendChild","oldEl","newEl","attributeToPropertyMap","checked","selected","disabled","attributes","attr","name","startsWith","hasAttribute","removeAttribute","setAttribute","config","_components","_plugins","_lifecycleHooks","_isMounted","emitter","renderer","use","plugin","options","install","component","definition","mount","compName","props","Error","setup","style","children","context","signal","v","_prepareLifecycleHooks","processMount","mergedContext","watcherUnsubscribers","childInstances","onBeforeUpdate","onBeforeMount","render","_processEvents","_injectStyles","_mountChildren","onUpdate","onMount","val","unmount","child","onUnmount","Promise","resolve","then","reduce","acc","hook","querySelectorAll","el","slice","addEventListener","styleFn","styleEl","querySelector","textContent","childSelector","childEl","instance"],"mappings":"sOAQO,MAAMA,EAQX,YAAOC,CAAMC,EAAUC,GACrB,OAAOD,EAASE,QAAQ,wBAAwB,CAACC,EAAGC,KAClD,MAAMC,EAAQC,KAAKC,SAASH,EAAMH,GAClC,YAAiBO,IAAVH,EAAsB,GAAKA,CAAK,GAE3C,CASA,eAAOE,CAASH,EAAMH,GACpB,IACE,MAAMQ,EAAOC,OAAOD,KAAKR,GACnBU,EAASD,OAAOC,OAAOV,GACvBW,EAAS,IAAIC,YAAYJ,EAAM,UAAUL,IAAhC,IAA2CO,GAC1D,YAAkBH,IAAXI,EAAuB,GAAKA,CACpC,CAAC,MAAOE,GAMP,OALAC,QAAQD,MAAM,6BAA8B,CAC1CE,WAAYZ,EACZH,OACAa,MAAOA,EAAMG,UAER,EACT,CACF,ECpCK,MAAMC,EAMXC,WAAAA,CAAYd,GAEVC,KAAKc,OAASf,EAEdC,KAAKe,UAAY,IAAIC,GACvB,CAOA,SAAIjB,GACF,OAAOC,KAAKc,MACd,CAOA,SAAIf,CAAMkB,GACJA,IAAWjB,KAAKc,SAClBd,KAAKc,OAASG,EACdjB,KAAKe,UAAUG,SAASC,GAAOA,EAAGF,KAEtC,CAQAG,KAAAA,CAAMD,GAEJ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,EAAG4D,OAAM/E,YACnC+E,EAAKC,WAAW,iBAClBmB,EAAMpB,EAAKqD,MAAM,KAAyBpI,EAC5C,IAEF,MAAM4I,EAAW3I,KAAKgG,MAAM0C,EAASpC,EAASmC,GAAgBvC,GAC9DY,EAAelF,KAAK+G,EAAS,GAC7B,GAEN"}
|
package/dist/eleva.umd.js
CHANGED
|
@@ -5,18 +5,17 @@
|
|
|
5
5
|
})(this, (function () { 'use strict';
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
|
-
* 🔒 TemplateEngine
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
* within a given data context.
|
|
8
|
+
* @class 🔒 TemplateEngine
|
|
9
|
+
* @classdesc Secure interpolation & dynamic attribute parsing.
|
|
10
|
+
* Provides methods to parse template strings by replacing interpolation expressions
|
|
11
|
+
* with dynamic data values and to evaluate expressions within a given data context.
|
|
13
12
|
*/
|
|
14
13
|
class TemplateEngine {
|
|
15
14
|
/**
|
|
16
15
|
* Parses a template string and replaces interpolation expressions with corresponding values.
|
|
17
16
|
*
|
|
18
|
-
* @param {string} template - The template string containing expressions in the format {{ expression }}
|
|
19
|
-
* @param {
|
|
17
|
+
* @param {string} template - The template string containing expressions in the format `{{ expression }}`.
|
|
18
|
+
* @param {Object<string, any>} data - The data object to use for evaluating expressions.
|
|
20
19
|
* @returns {string} The resulting string with evaluated values.
|
|
21
20
|
*/
|
|
22
21
|
static parse(template, data) {
|
|
@@ -27,16 +26,16 @@
|
|
|
27
26
|
}
|
|
28
27
|
|
|
29
28
|
/**
|
|
30
|
-
* Evaluates
|
|
29
|
+
* Evaluates a JavaScript expression using the provided data context.
|
|
31
30
|
*
|
|
32
31
|
* @param {string} expr - The JavaScript expression to evaluate.
|
|
33
|
-
* @param {
|
|
34
|
-
* @returns {
|
|
32
|
+
* @param {Object<string, any>} data - The data context for evaluating the expression.
|
|
33
|
+
* @returns {any} The result of the evaluated expression, or an empty string if undefined or on error.
|
|
35
34
|
*/
|
|
36
35
|
static evaluate(expr, data) {
|
|
37
36
|
try {
|
|
38
37
|
const keys = Object.keys(data);
|
|
39
|
-
const values =
|
|
38
|
+
const values = Object.values(data);
|
|
40
39
|
const result = new Function(...keys, `return ${expr}`)(...values);
|
|
41
40
|
return result === undefined ? "" : result;
|
|
42
41
|
} catch (error) {
|
|
@@ -51,10 +50,10 @@
|
|
|
51
50
|
}
|
|
52
51
|
|
|
53
52
|
/**
|
|
54
|
-
* ⚡ Signal
|
|
55
|
-
*
|
|
53
|
+
* @class ⚡ Signal
|
|
54
|
+
* @classdesc Fine-grained reactivity.
|
|
56
55
|
* A reactive data holder that notifies registered watchers when its value changes,
|
|
57
|
-
*
|
|
56
|
+
* enabling fine-grained DOM patching rather than full re-renders.
|
|
58
57
|
*/
|
|
59
58
|
class Signal {
|
|
60
59
|
/**
|
|
@@ -63,7 +62,9 @@
|
|
|
63
62
|
* @param {*} value - The initial value of the signal.
|
|
64
63
|
*/
|
|
65
64
|
constructor(value) {
|
|
65
|
+
/** @private {*} Internal storage for the signal's current value */
|
|
66
66
|
this._value = value;
|
|
67
|
+
/** @private {Set<function>} Collection of callback functions to be notified when value changes */
|
|
67
68
|
this._watchers = new Set();
|
|
68
69
|
}
|
|
69
70
|
|
|
@@ -91,8 +92,8 @@
|
|
|
91
92
|
/**
|
|
92
93
|
* Registers a watcher function that will be called whenever the signal's value changes.
|
|
93
94
|
*
|
|
94
|
-
* @param {
|
|
95
|
-
* @returns {
|
|
95
|
+
* @param {function(any): void} fn - The callback function to invoke on value change.
|
|
96
|
+
* @returns {function(): boolean} A function to unsubscribe the watcher.
|
|
96
97
|
*/
|
|
97
98
|
watch(fn) {
|
|
98
99
|
this._watchers.add(fn);
|
|
@@ -101,17 +102,17 @@
|
|
|
101
102
|
}
|
|
102
103
|
|
|
103
104
|
/**
|
|
104
|
-
* 🎙️ Emitter
|
|
105
|
-
*
|
|
106
|
-
* Implements a basic publish-subscribe pattern for event handling,
|
|
107
|
-
*
|
|
105
|
+
* @class 🎙️ Emitter
|
|
106
|
+
* @classdesc Robust inter-component communication with event bubbling.
|
|
107
|
+
* Implements a basic publish-subscribe pattern for event handling, allowing components
|
|
108
|
+
* to communicate through custom events.
|
|
108
109
|
*/
|
|
109
110
|
class Emitter {
|
|
110
111
|
/**
|
|
111
112
|
* Creates a new Emitter instance.
|
|
112
113
|
*/
|
|
113
114
|
constructor() {
|
|
114
|
-
/** @type {Object.<string, Function[]>} */
|
|
115
|
+
/** @type {Object.<string, Function[]>} Storage for event handlers mapped by event name */
|
|
115
116
|
this.events = {};
|
|
116
117
|
}
|
|
117
118
|
|
|
@@ -119,7 +120,7 @@
|
|
|
119
120
|
* Registers an event handler for the specified event.
|
|
120
121
|
*
|
|
121
122
|
* @param {string} event - The name of the event.
|
|
122
|
-
* @param {
|
|
123
|
+
* @param {function(...any): void} handler - The function to call when the event is emitted.
|
|
123
124
|
*/
|
|
124
125
|
on(event, handler) {
|
|
125
126
|
(this.events[event] || (this.events[event] = [])).push(handler);
|
|
@@ -129,7 +130,7 @@
|
|
|
129
130
|
* Removes a previously registered event handler.
|
|
130
131
|
*
|
|
131
132
|
* @param {string} event - The name of the event.
|
|
132
|
-
* @param {
|
|
133
|
+
* @param {function(...any): void} handler - The handler function to remove.
|
|
133
134
|
*/
|
|
134
135
|
off(event, handler) {
|
|
135
136
|
if (this.events[event]) {
|
|
@@ -141,7 +142,7 @@
|
|
|
141
142
|
* Emits an event, invoking all handlers registered for that event.
|
|
142
143
|
*
|
|
143
144
|
* @param {string} event - The event name.
|
|
144
|
-
* @param {
|
|
145
|
+
* @param {...any} args - Additional arguments to pass to the event handlers.
|
|
145
146
|
*/
|
|
146
147
|
emit(event, ...args) {
|
|
147
148
|
(this.events[event] || []).forEach(handler => handler(...args));
|
|
@@ -149,8 +150,8 @@
|
|
|
149
150
|
}
|
|
150
151
|
|
|
151
152
|
/**
|
|
152
|
-
* 🎨 Renderer
|
|
153
|
-
*
|
|
153
|
+
* @class 🎨 Renderer
|
|
154
|
+
* @classdesc Handles DOM patching, diffing, and attribute updates.
|
|
154
155
|
* Provides methods for efficient DOM updates by diffing the new and old DOM structures
|
|
155
156
|
* and applying only the necessary changes.
|
|
156
157
|
*/
|
|
@@ -181,18 +182,18 @@
|
|
|
181
182
|
const oldNode = oldNodes[i];
|
|
182
183
|
const newNode = newNodes[i];
|
|
183
184
|
|
|
184
|
-
// Append new nodes that don't exist in the old tree.
|
|
185
|
+
// Case 1: Append new nodes that don't exist in the old tree.
|
|
185
186
|
if (!oldNode && newNode) {
|
|
186
187
|
oldParent.appendChild(newNode.cloneNode(true));
|
|
187
188
|
continue;
|
|
188
189
|
}
|
|
189
|
-
// Remove old nodes not present in the new tree.
|
|
190
|
+
// Case 2: Remove old nodes not present in the new tree.
|
|
190
191
|
if (oldNode && !newNode) {
|
|
191
192
|
oldParent.removeChild(oldNode);
|
|
192
193
|
continue;
|
|
193
194
|
}
|
|
194
195
|
|
|
195
|
-
// For element nodes, compare keys if available.
|
|
196
|
+
// Case 3: For element nodes, compare keys if available.
|
|
196
197
|
if (oldNode.nodeType === Node.ELEMENT_NODE && newNode.nodeType === Node.ELEMENT_NODE) {
|
|
197
198
|
const oldKey = oldNode.getAttribute("key");
|
|
198
199
|
const newKey = newNode.getAttribute("key");
|
|
@@ -204,19 +205,19 @@
|
|
|
204
205
|
}
|
|
205
206
|
}
|
|
206
207
|
|
|
207
|
-
// Replace nodes if types or tag names differ.
|
|
208
|
+
// Case 4: Replace nodes if types or tag names differ.
|
|
208
209
|
if (oldNode.nodeType !== newNode.nodeType || oldNode.nodeName !== newNode.nodeName) {
|
|
209
210
|
oldParent.replaceChild(newNode.cloneNode(true), oldNode);
|
|
210
211
|
continue;
|
|
211
212
|
}
|
|
212
|
-
// For text nodes, update content if different.
|
|
213
|
+
// Case 5: For text nodes, update content if different.
|
|
213
214
|
if (oldNode.nodeType === Node.TEXT_NODE) {
|
|
214
215
|
if (oldNode.nodeValue !== newNode.nodeValue) {
|
|
215
216
|
oldNode.nodeValue = newNode.nodeValue;
|
|
216
217
|
}
|
|
217
218
|
continue;
|
|
218
219
|
}
|
|
219
|
-
// For element nodes, update attributes and then diff children.
|
|
220
|
+
// Case 6: For element nodes, update attributes and then diff children.
|
|
220
221
|
if (oldNode.nodeType === Node.ELEMENT_NODE) {
|
|
221
222
|
this.updateAttributes(oldNode, newNode);
|
|
222
223
|
this.diff(oldNode, newNode);
|
|
@@ -261,34 +262,65 @@
|
|
|
261
262
|
}
|
|
262
263
|
|
|
263
264
|
/**
|
|
264
|
-
*
|
|
265
|
+
* Defines the structure and behavior of a component.
|
|
266
|
+
* @typedef {Object} ComponentDefinition
|
|
267
|
+
* @property {function(Object<string, any>): (Object<string, any>|Promise<Object<string, any>>)} [setup]
|
|
268
|
+
* Optional setup function that initializes the component's reactive state and lifecycle.
|
|
269
|
+
* Receives props and context as an argument and should return an object containing the component's state.
|
|
270
|
+
* Can return either a synchronous object or a Promise that resolves to an object for async initialization.
|
|
271
|
+
*
|
|
272
|
+
* @property {function(Object<string, any>): string} template
|
|
273
|
+
* Required function that defines the component's HTML structure.
|
|
274
|
+
* Receives the merged context (props + setup data) and must return an HTML template string.
|
|
275
|
+
* Supports dynamic expressions using {{ }} syntax for reactive data binding.
|
|
276
|
+
*
|
|
277
|
+
* @property {function(Object<string, any>): string} [style]
|
|
278
|
+
* Optional function that defines component-scoped CSS styles.
|
|
279
|
+
* Receives the merged context and returns a CSS string that will be automatically scoped to the component.
|
|
280
|
+
* Styles are injected into the component's container and only affect elements within it.
|
|
265
281
|
*
|
|
266
|
-
*
|
|
267
|
-
*
|
|
282
|
+
* @property {Object<string, ComponentDefinition>} [children]
|
|
283
|
+
* Optional object that defines nested child components.
|
|
284
|
+
* Keys are CSS selectors that match elements in the template where child components should be mounted.
|
|
285
|
+
* Values are ComponentDefinition objects that define the structure and behavior of each child component.
|
|
286
|
+
*/
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* @class 🧩 Eleva
|
|
290
|
+
* @classdesc Signal-based component runtime framework with lifecycle hooks, scoped styles, and plugin support.
|
|
291
|
+
* Manages component registration, plugin integration, event handling, and DOM rendering.
|
|
268
292
|
*/
|
|
269
293
|
class Eleva {
|
|
270
294
|
/**
|
|
271
295
|
* Creates a new Eleva instance.
|
|
272
296
|
*
|
|
273
297
|
* @param {string} name - The name of the Eleva instance.
|
|
274
|
-
* @param {
|
|
298
|
+
* @param {Object<string, any>} [config={}] - Optional configuration for the instance.
|
|
275
299
|
*/
|
|
276
300
|
constructor(name, config = {}) {
|
|
301
|
+
/** @type {string} The unique identifier name for this Eleva instance */
|
|
277
302
|
this.name = name;
|
|
303
|
+
/** @type {Object<string, any>} Optional configuration object for the Eleva instance */
|
|
278
304
|
this.config = config;
|
|
305
|
+
/** @type {Object<string, ComponentDefinition>} Object storing registered component definitions by name */
|
|
279
306
|
this._components = {};
|
|
307
|
+
/** @private {Array<Object>} Collection of installed plugin instances */
|
|
280
308
|
this._plugins = [];
|
|
309
|
+
/** @private {string[]} Array of lifecycle hook names supported by the component */
|
|
281
310
|
this._lifecycleHooks = ["onBeforeMount", "onMount", "onBeforeUpdate", "onUpdate", "onUnmount"];
|
|
311
|
+
/** @private {boolean} Flag indicating if component is currently mounted */
|
|
282
312
|
this._isMounted = false;
|
|
313
|
+
/** @private {Emitter} Instance of the event emitter for handling component events */
|
|
283
314
|
this.emitter = new Emitter();
|
|
315
|
+
/** @private {Renderer} Instance of the renderer for handling DOM updates and patching */
|
|
284
316
|
this.renderer = new Renderer();
|
|
285
317
|
}
|
|
286
318
|
|
|
287
319
|
/**
|
|
288
320
|
* Integrates a plugin with the Eleva framework.
|
|
289
321
|
*
|
|
290
|
-
* @param {
|
|
291
|
-
* @param {
|
|
322
|
+
* @param {Object} plugin - The plugin object which should have an `install` function.
|
|
323
|
+
* @param {Object<string, any>} [options={}] - Optional options to pass to the plugin.
|
|
292
324
|
* @returns {Eleva} The Eleva instance (for chaining).
|
|
293
325
|
*/
|
|
294
326
|
use(plugin, options = {}) {
|
|
@@ -303,7 +335,7 @@
|
|
|
303
335
|
* Registers a component with the Eleva instance.
|
|
304
336
|
*
|
|
305
337
|
* @param {string} name - The name of the component.
|
|
306
|
-
* @param {
|
|
338
|
+
* @param {ComponentDefinition} definition - The component definition including setup, template, style, and children.
|
|
307
339
|
* @returns {Eleva} The Eleva instance (for chaining).
|
|
308
340
|
*/
|
|
309
341
|
component(name, definition) {
|
|
@@ -314,27 +346,50 @@
|
|
|
314
346
|
/**
|
|
315
347
|
* Mounts a registered component to a DOM element.
|
|
316
348
|
*
|
|
317
|
-
* @param {
|
|
318
|
-
* @param {string} compName - The name of the component to mount.
|
|
319
|
-
* @param {
|
|
349
|
+
* @param {HTMLElement} container - A DOM element where the component will be mounted.
|
|
350
|
+
* @param {string|ComponentDefinition} compName - The name of the component to mount or a component definition.
|
|
351
|
+
* @param {Object<string, any>} [props={}] - Optional properties to pass to the component.
|
|
320
352
|
* @returns {object|Promise<object>} An object representing the mounted component instance, or a Promise that resolves to it for asynchronous setups.
|
|
321
|
-
* @throws
|
|
353
|
+
* @throws {Error} If the container is not found or if the component is not registered.
|
|
322
354
|
*/
|
|
323
|
-
mount(
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
355
|
+
mount(container, compName, props = {}) {
|
|
356
|
+
if (!container) throw new Error(`Container not found: ${container}`);
|
|
357
|
+
let definition;
|
|
358
|
+
if (typeof compName === "string") {
|
|
359
|
+
definition = this._components[compName];
|
|
360
|
+
if (!definition) throw new Error(`Component "${compName}" not registered.`);
|
|
361
|
+
} else if (typeof compName === "object") {
|
|
362
|
+
definition = compName;
|
|
363
|
+
} else {
|
|
364
|
+
throw new Error("Invalid component parameter.");
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* Destructure the component definition to access core functionality.
|
|
369
|
+
* - setup: Optional function for component initialization and state management
|
|
370
|
+
* - template: Required function that returns the component's HTML structure
|
|
371
|
+
* - style: Optional function for component-scoped CSS styles
|
|
372
|
+
* - children: Optional object defining nested child components
|
|
373
|
+
*/
|
|
328
374
|
const {
|
|
329
375
|
setup,
|
|
330
376
|
template,
|
|
331
377
|
style,
|
|
332
378
|
children
|
|
333
379
|
} = definition;
|
|
380
|
+
|
|
381
|
+
/**
|
|
382
|
+
* Creates the initial context object for the component instance.
|
|
383
|
+
* This context provides core functionality and will be merged with setup data.
|
|
384
|
+
* @type {Object<string, any>}
|
|
385
|
+
* @property {Object<string, any>} props - Component properties passed during mounting
|
|
386
|
+
* @property {Emitter} emitter - Event emitter instance for component event handling
|
|
387
|
+
* @property {function(any): Signal} signal - Factory function to create reactive Signal instances
|
|
388
|
+
* @property {Object<string, function(): void>} ...lifecycleHooks - Prepared lifecycle hook functions
|
|
389
|
+
*/
|
|
334
390
|
const context = {
|
|
335
391
|
props,
|
|
336
|
-
|
|
337
|
-
on: this.emitter.on.bind(this.emitter),
|
|
392
|
+
emitter: this.emitter,
|
|
338
393
|
signal: v => new Signal(v),
|
|
339
394
|
...this._prepareLifecycleHooks()
|
|
340
395
|
};
|
|
@@ -342,7 +397,7 @@
|
|
|
342
397
|
/**
|
|
343
398
|
* Processes the mounting of the component.
|
|
344
399
|
*
|
|
345
|
-
* @param {
|
|
400
|
+
* @param {Object<string, any>} data - Data returned from the component's setup function.
|
|
346
401
|
* @returns {object} An object with the container, merged context data, and an unmount function.
|
|
347
402
|
*/
|
|
348
403
|
const processMount = data => {
|
|
@@ -375,6 +430,12 @@
|
|
|
375
430
|
mergedContext.onUpdate && mergedContext.onUpdate();
|
|
376
431
|
}
|
|
377
432
|
};
|
|
433
|
+
|
|
434
|
+
/**
|
|
435
|
+
* Sets up reactive watchers for all Signal instances in the component's data.
|
|
436
|
+
* When a Signal's value changes, the component will re-render to reflect the updates.
|
|
437
|
+
* Stores unsubscribe functions to clean up watchers when component unmounts.
|
|
438
|
+
*/
|
|
378
439
|
Object.values(data).forEach(val => {
|
|
379
440
|
if (val instanceof Signal) watcherUnsubscribers.push(val.watch(render));
|
|
380
441
|
});
|
|
@@ -384,6 +445,8 @@
|
|
|
384
445
|
data: mergedContext,
|
|
385
446
|
/**
|
|
386
447
|
* Unmounts the component, cleaning up watchers, child components, and clearing the container.
|
|
448
|
+
*
|
|
449
|
+
* @returns {void}
|
|
387
450
|
*/
|
|
388
451
|
unmount: () => {
|
|
389
452
|
watcherUnsubscribers.forEach(fn => fn());
|
|
@@ -394,20 +457,14 @@
|
|
|
394
457
|
};
|
|
395
458
|
};
|
|
396
459
|
|
|
397
|
-
// Handle asynchronous setup
|
|
398
|
-
|
|
399
|
-
if (setupResult && typeof setupResult.then === "function") {
|
|
400
|
-
return setupResult.then(data => processMount(data));
|
|
401
|
-
} else {
|
|
402
|
-
const data = setupResult || {};
|
|
403
|
-
return processMount(data);
|
|
404
|
-
}
|
|
460
|
+
// Handle asynchronous setup.
|
|
461
|
+
return Promise.resolve(typeof setup === "function" ? setup(context) : {}).then(data => processMount(data));
|
|
405
462
|
}
|
|
406
463
|
|
|
407
464
|
/**
|
|
408
465
|
* Prepares default no-operation lifecycle hook functions.
|
|
409
466
|
*
|
|
410
|
-
* @returns {
|
|
467
|
+
* @returns {Object<string, function(): void>} An object with keys for lifecycle hooks mapped to empty functions.
|
|
411
468
|
* @private
|
|
412
469
|
*/
|
|
413
470
|
_prepareLifecycleHooks() {
|
|
@@ -421,7 +478,7 @@
|
|
|
421
478
|
* Processes DOM elements for event binding based on attributes starting with "@".
|
|
422
479
|
*
|
|
423
480
|
* @param {HTMLElement} container - The container element in which to search for events.
|
|
424
|
-
* @param {
|
|
481
|
+
* @param {Object<string, any>} context - The current context containing event handler definitions.
|
|
425
482
|
* @private
|
|
426
483
|
*/
|
|
427
484
|
_processEvents(container, context) {
|
|
@@ -447,8 +504,8 @@
|
|
|
447
504
|
*
|
|
448
505
|
* @param {HTMLElement} container - The container element.
|
|
449
506
|
* @param {string} compName - The component name used to identify the style element.
|
|
450
|
-
* @param {
|
|
451
|
-
* @param {
|
|
507
|
+
* @param {function(Object<string, any>): string} [styleFn] - A function that returns CSS styles as a string.
|
|
508
|
+
* @param {Object<string, any>} context - The current context for style interpolation.
|
|
452
509
|
* @private
|
|
453
510
|
*/
|
|
454
511
|
_injectStyles(container, compName, styleFn, context) {
|
|
@@ -467,15 +524,15 @@
|
|
|
467
524
|
* Mounts child components within the parent component's container.
|
|
468
525
|
*
|
|
469
526
|
* @param {HTMLElement} container - The parent container element.
|
|
470
|
-
* @param {
|
|
471
|
-
* @param {Array} childInstances - An array to store the mounted child component instances.
|
|
527
|
+
* @param {Object<string, ComponentDefinition>} [children] - An object mapping child component selectors to their definitions.
|
|
528
|
+
* @param {Array<object>} childInstances - An array to store the mounted child component instances.
|
|
472
529
|
* @private
|
|
473
530
|
*/
|
|
474
531
|
_mountChildren(container, children, childInstances) {
|
|
475
532
|
childInstances.forEach(child => child.unmount());
|
|
476
533
|
childInstances.length = 0;
|
|
477
|
-
Object.keys(children || {}).forEach(
|
|
478
|
-
container.querySelectorAll(
|
|
534
|
+
Object.keys(children || {}).forEach(childSelector => {
|
|
535
|
+
container.querySelectorAll(childSelector).forEach(childEl => {
|
|
479
536
|
const props = {};
|
|
480
537
|
[...childEl.attributes].forEach(({
|
|
481
538
|
name,
|
|
@@ -485,7 +542,7 @@
|
|
|
485
542
|
props[name.slice("eleva-prop-".length)] = value;
|
|
486
543
|
}
|
|
487
544
|
});
|
|
488
|
-
const instance = this.mount(childEl,
|
|
545
|
+
const instance = this.mount(childEl, children[childSelector], props);
|
|
489
546
|
childInstances.push(instance);
|
|
490
547
|
});
|
|
491
548
|
});
|