eleva 1.0.0-rc.1 → 1.0.0-rc.11

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.
Files changed (65) hide show
  1. package/README.md +505 -41
  2. package/dist/eleva-plugins.cjs.js +3397 -0
  3. package/dist/eleva-plugins.cjs.js.map +1 -0
  4. package/dist/eleva-plugins.esm.js +3392 -0
  5. package/dist/eleva-plugins.esm.js.map +1 -0
  6. package/dist/eleva-plugins.umd.js +3403 -0
  7. package/dist/eleva-plugins.umd.js.map +1 -0
  8. package/dist/eleva-plugins.umd.min.js +3 -0
  9. package/dist/eleva-plugins.umd.min.js.map +1 -0
  10. package/dist/eleva.cjs.js +617 -118
  11. package/dist/eleva.cjs.js.map +1 -1
  12. package/dist/eleva.d.ts +612 -75
  13. package/dist/eleva.esm.js +617 -118
  14. package/dist/eleva.esm.js.map +1 -1
  15. package/dist/eleva.umd.js +617 -118
  16. package/dist/eleva.umd.js.map +1 -1
  17. package/dist/eleva.umd.min.js +2 -2
  18. package/dist/eleva.umd.min.js.map +1 -1
  19. package/dist/plugins/attr.umd.js +232 -0
  20. package/dist/plugins/attr.umd.js.map +1 -0
  21. package/dist/plugins/attr.umd.min.js +3 -0
  22. package/dist/plugins/attr.umd.min.js.map +1 -0
  23. package/dist/plugins/props.umd.js +712 -0
  24. package/dist/plugins/props.umd.js.map +1 -0
  25. package/dist/plugins/props.umd.min.js +3 -0
  26. package/dist/plugins/props.umd.min.js.map +1 -0
  27. package/dist/plugins/router.umd.js +1808 -0
  28. package/dist/plugins/router.umd.js.map +1 -0
  29. package/dist/plugins/router.umd.min.js +3 -0
  30. package/dist/plugins/router.umd.min.js.map +1 -0
  31. package/dist/plugins/store.umd.js +685 -0
  32. package/dist/plugins/store.umd.js.map +1 -0
  33. package/dist/plugins/store.umd.min.js +3 -0
  34. package/dist/plugins/store.umd.min.js.map +1 -0
  35. package/package.json +107 -45
  36. package/src/core/Eleva.js +247 -63
  37. package/src/modules/Emitter.js +98 -8
  38. package/src/modules/Renderer.js +66 -36
  39. package/src/modules/Signal.js +85 -8
  40. package/src/modules/TemplateEngine.js +121 -13
  41. package/src/plugins/Attr.js +255 -0
  42. package/src/plugins/Props.js +593 -0
  43. package/src/plugins/Router.js +1922 -0
  44. package/src/plugins/Store.js +744 -0
  45. package/src/plugins/index.js +40 -0
  46. package/types/core/Eleva.d.ts +217 -50
  47. package/types/core/Eleva.d.ts.map +1 -1
  48. package/types/modules/Emitter.d.ts +111 -12
  49. package/types/modules/Emitter.d.ts.map +1 -1
  50. package/types/modules/Renderer.d.ts +68 -3
  51. package/types/modules/Renderer.d.ts.map +1 -1
  52. package/types/modules/Signal.d.ts +92 -10
  53. package/types/modules/Signal.d.ts.map +1 -1
  54. package/types/modules/TemplateEngine.d.ts +131 -15
  55. package/types/modules/TemplateEngine.d.ts.map +1 -1
  56. package/types/plugins/Attr.d.ts +29 -0
  57. package/types/plugins/Attr.d.ts.map +1 -0
  58. package/types/plugins/Props.d.ts +49 -0
  59. package/types/plugins/Props.d.ts.map +1 -0
  60. package/types/plugins/Router.d.ts +1000 -0
  61. package/types/plugins/Router.d.ts.map +1 -0
  62. package/types/plugins/Store.d.ts +87 -0
  63. package/types/plugins/Store.d.ts.map +1 -0
  64. package/types/plugins/index.d.ts +5 -0
  65. package/types/plugins/index.d.ts.map +1 -0
@@ -1 +1 @@
1
- {"version":3,"file":"eleva.umd.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 A secure template engine that handles interpolation and dynamic attribute parsing.\n * Provides a safe way to evaluate expressions in templates while preventing XSS attacks.\n * All methods are static and can be called directly on the class.\n *\n * @example\n * const template = \"Hello, {{name}}!\";\n * const data = { name: \"World\" };\n * const result = TemplateEngine.parse(template, data); // Returns: \"Hello, World!\"\n */\nexport class TemplateEngine {\n /**\n * @private {RegExp} Regular expression for matching template expressions in the format {{ expression }}\n * @type {RegExp}\n */\n static expressionPattern = /\\{\\{\\s*(.*?)\\s*\\}\\}/g;\n\n /**\n * Parses a template string, replacing expressions with their evaluated values.\n * Expressions are evaluated in the provided data context.\n *\n * @public\n * @static\n * @param {string} template - The template string to parse.\n * @param {Record<string, unknown>} data - The data context for evaluating expressions.\n * @returns {string} The parsed template with expressions replaced by their values.\n * @example\n * const result = TemplateEngine.parse(\"{{user.name}} is {{user.age}} years old\", {\n * user: { name: \"John\", age: 30 }\n * }); // Returns: \"John is 30 years old\"\n */\n static parse(template, data) {\n if (typeof template !== \"string\") return template;\n return template.replace(this.expressionPattern, (_, expression) =>\n this.evaluate(expression, data)\n );\n }\n\n /**\n * Evaluates an expression in the context of the provided data object.\n * Note: This does not provide a true sandbox and evaluated expressions may access global scope.\n * The use of the `with` statement is necessary for expression evaluation but has security implications.\n * Expressions should be carefully validated before evaluation.\n *\n * @public\n * @static\n * @param {string} expression - The expression to evaluate.\n * @param {Record<string, unknown>} data - The data context for evaluation.\n * @returns {unknown} The result of the evaluation, or an empty string if evaluation fails.\n * @example\n * const result = TemplateEngine.evaluate(\"user.name\", { user: { name: \"John\" } }); // Returns: \"John\"\n * const age = TemplateEngine.evaluate(\"user.age\", { user: { age: 30 } }); // Returns: 30\n */\n static evaluate(expression, data) {\n if (typeof expression !== \"string\") return expression;\n try {\n return new Function(\"data\", `with(data) { return ${expression}; }`)(data);\n } catch {\n return \"\";\n }\n }\n}\n","\"use strict\";\n\n/**\n * @class ⚡ Signal\n * @classdesc A reactive data holder that enables fine-grained reactivity in the Eleva framework.\n * Signals notify registered watchers when their value changes, enabling efficient DOM updates\n * through targeted patching rather than full re-renders.\n * Updates are batched using microtasks to prevent multiple synchronous notifications.\n * The class is generic, allowing type-safe handling of any value type T.\n *\n * @example\n * const count = new Signal(0);\n * count.watch((value) => console.log(`Count changed to: ${value}`));\n * count.value = 1; // Logs: \"Count changed to: 1\"\n * @template T\n */\nexport class Signal {\n /**\n * Creates a new Signal instance with the specified initial value.\n *\n * @public\n * @param {T} value - The initial value of the signal.\n */\n constructor(value) {\n /** @private {T} Internal storage for the signal's current value */\n this._value = value;\n /** @private {Set<(value: T) => void>} Collection of callback functions to be notified when value changes */\n this._watchers = new Set();\n /** @private {boolean} Flag to prevent multiple synchronous watcher notifications and batch updates into microtasks */\n this._pending = false;\n }\n\n /**\n * Gets the current value of the signal.\n *\n * @public\n * @returns {T} 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 * The notification is batched using microtasks to prevent multiple synchronous updates.\n *\n * @public\n * @param {T} newVal - The new value to set.\n * @returns {void}\n */\n set value(newVal) {\n if (this._value === newVal) return;\n\n this._value = newVal;\n this._notify();\n }\n\n /**\n * Registers a watcher function that will be called whenever the signal's value changes.\n * The watcher will receive the new value as its argument.\n *\n * @public\n * @param {(value: T) => void} fn - The callback function to invoke on value change.\n * @returns {() => boolean} A function to unsubscribe the watcher.\n * @example\n * const unsubscribe = signal.watch((value) => console.log(value));\n * // Later...\n * unsubscribe(); // Stops watching for changes\n */\n watch(fn) {\n this._watchers.add(fn);\n return () => this._watchers.delete(fn);\n }\n\n /**\n * Notifies all registered watchers of a value change using microtask scheduling.\n * Uses a pending flag to batch multiple synchronous updates into a single notification.\n * All watcher callbacks receive the current value when executed.\n *\n * @private\n * @returns {void}\n */\n _notify() {\n if (this._pending) return;\n\n this._pending = true;\n queueMicrotask(() => {\n /** @type {(fn: (value: T) => void) => void} */\n this._watchers.forEach((fn) => fn(this._value));\n this._pending = false;\n });\n }\n}\n","\"use strict\";\n\n/**\n * @class 📡 Emitter\n * @classdesc A robust event emitter that enables inter-component communication through a publish-subscribe pattern.\n * Components can emit events and listen for events from other components, facilitating loose coupling\n * and reactive updates across the application.\n * Events are handled synchronously in the order they were registered, with proper cleanup\n * of unsubscribed handlers.\n * Event names should follow the format 'namespace:action' (e.g., 'user:login', 'cart:update').\n *\n * @example\n * const emitter = new Emitter();\n * emitter.on('user:login', (user) => console.log(`User logged in: ${user.name}`));\n * emitter.emit('user:login', { name: 'John' }); // Logs: \"User logged in: John\"\n */\nexport class Emitter {\n /**\n * Creates a new Emitter instance.\n *\n * @public\n */\n constructor() {\n /** @private {Map<string, Set<(data: unknown) => void>>} Map of event names to their registered handler functions */\n this._events = new Map();\n }\n\n /**\n * Registers an event handler for the specified event name.\n * The handler will be called with the event data when the event is emitted.\n * Event names should follow the format 'namespace:action' for consistency.\n *\n * @public\n * @param {string} event - The name of the event to listen for (e.g., 'user:login').\n * @param {(data: unknown) => void} handler - The callback function to invoke when the event occurs.\n * @returns {() => void} A function to unsubscribe the event handler.\n * @example\n * const unsubscribe = emitter.on('user:login', (user) => console.log(user));\n * // Later...\n * unsubscribe(); // Stops listening for the event\n */\n on(event, handler) {\n if (!this._events.has(event)) this._events.set(event, new Set());\n\n this._events.get(event).add(handler);\n return () => this.off(event, handler);\n }\n\n /**\n * Removes an event handler for the specified event name.\n * If no handler is provided, all handlers for the event are removed.\n * Automatically cleans up empty event sets to prevent memory leaks.\n *\n * @public\n * @param {string} event - The name of the event to remove handlers from.\n * @param {(data: unknown) => void} [handler] - The specific handler function to remove.\n * @returns {void}\n * @example\n * // Remove a specific handler\n * emitter.off('user:login', loginHandler);\n * // Remove all handlers for an event\n * emitter.off('user:login');\n */\n off(event, handler) {\n if (!this._events.has(event)) return;\n if (handler) {\n const handlers = this._events.get(event);\n handlers.delete(handler);\n // Remove the event if there are no handlers left\n if (handlers.size === 0) this._events.delete(event);\n } else {\n this._events.delete(event);\n }\n }\n\n /**\n * Emits an event with the specified data to all registered handlers.\n * Handlers are called synchronously in the order they were registered.\n * If no handlers are registered for the event, the emission is silently ignored.\n *\n * @public\n * @param {string} event - The name of the event to emit.\n * @param {...unknown} args - Optional arguments to pass to the event handlers.\n * @returns {void}\n * @example\n * // Emit an event with data\n * emitter.emit('user:login', { name: 'John', role: 'admin' });\n * // Emit an event with multiple arguments\n * emitter.emit('cart:update', { items: [] }, { total: 0 });\n */\n emit(event, ...args) {\n if (!this._events.has(event)) return;\n this._events.get(event).forEach((handler) => handler(...args));\n }\n}\n","\"use strict\";\n\n/**\n * A regular expression to match hyphenated lowercase letters.\n * @private\n * @type {RegExp}\n */\nconst CAMEL_RE = /-([a-z])/g;\n\n/**\n * @class 🎨 Renderer\n * @classdesc A high-performance DOM renderer that implements an optimized direct DOM diffing algorithm.\n *\n * Key features:\n * - Single-pass diffing algorithm for efficient DOM updates\n * - Key-based node reconciliation for optimal performance\n * - Intelligent attribute handling for ARIA, data attributes, and boolean properties\n * - Preservation of special Eleva-managed instances and style elements\n * - Memory-efficient with reusable temporary containers\n *\n * The renderer is designed to minimize DOM operations while maintaining\n * exact attribute synchronization and proper node identity preservation.\n * It's particularly optimized for frequent updates and complex DOM structures.\n *\n * @example\n * const renderer = new Renderer();\n * const container = document.getElementById(\"app\");\n * const newHtml = \"<div>Updated content</div>\";\n * renderer.patchDOM(container, newHtml);\n */\nexport class Renderer {\n /**\n * Creates a new Renderer instance.\n * @public\n */\n constructor() {\n /**\n * A temporary container to hold the new HTML content while diffing.\n * @private\n * @type {HTMLElement}\n */\n this._tempContainer = document.createElement(\"div\");\n }\n\n /**\n * Patches the DOM of the given container with the provided HTML string.\n *\n * @public\n * @param {HTMLElement} container - The container element to patch.\n * @param {string} newHtml - The new HTML string.\n * @returns {void}\n * @throws {TypeError} If container is not an HTMLElement or newHtml is not a string.\n * @throws {Error} If DOM patching fails.\n */\n patchDOM(container, newHtml) {\n if (!(container instanceof HTMLElement)) {\n throw new TypeError(\"Container must be an HTMLElement\");\n }\n if (typeof newHtml !== \"string\") {\n throw new TypeError(\"newHtml must be a string\");\n }\n\n try {\n this._tempContainer.innerHTML = newHtml;\n this._diff(container, this._tempContainer);\n } catch (error) {\n throw new Error(`Failed to patch DOM: ${error.message}`);\n }\n }\n\n /**\n * Performs a diff between two DOM nodes and patches the old node to match the new node.\n *\n * @private\n * @param {HTMLElement} oldParent - The original DOM element.\n * @param {HTMLElement} newParent - The new DOM element.\n * @returns {void}\n */\n _diff(oldParent, newParent) {\n if (oldParent === newParent || oldParent.isEqualNode?.(newParent)) return;\n\n const oldChildren = Array.from(oldParent.childNodes);\n const newChildren = Array.from(newParent.childNodes);\n let oldStartIdx = 0,\n newStartIdx = 0;\n let oldEndIdx = oldChildren.length - 1;\n let newEndIdx = newChildren.length - 1;\n let oldKeyMap = null;\n\n while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {\n let oldStartNode = oldChildren[oldStartIdx];\n let newStartNode = newChildren[newStartIdx];\n\n if (!oldStartNode) {\n oldStartNode = oldChildren[++oldStartIdx];\n } else if (this._isSameNode(oldStartNode, newStartNode)) {\n this._patchNode(oldStartNode, newStartNode);\n oldStartIdx++;\n newStartIdx++;\n } else {\n if (!oldKeyMap) {\n oldKeyMap = this._createKeyMap(oldChildren, oldStartIdx, oldEndIdx);\n }\n const key = this._getNodeKey(newStartNode);\n const oldNodeToMove = key ? oldKeyMap.get(key) : null;\n\n if (oldNodeToMove) {\n this._patchNode(oldNodeToMove, newStartNode);\n oldParent.insertBefore(oldNodeToMove, oldStartNode);\n oldChildren[oldChildren.indexOf(oldNodeToMove)] = null;\n } else {\n oldParent.insertBefore(newStartNode.cloneNode(true), oldStartNode);\n }\n newStartIdx++;\n }\n }\n\n if (oldStartIdx > oldEndIdx) {\n const refNode = newChildren[newEndIdx + 1]\n ? oldChildren[oldStartIdx]\n : null;\n for (let i = newStartIdx; i <= newEndIdx; i++) {\n if (newChildren[i])\n oldParent.insertBefore(newChildren[i].cloneNode(true), refNode);\n }\n } else if (newStartIdx > newEndIdx) {\n for (let i = oldStartIdx; i <= oldEndIdx; i++) {\n if (oldChildren[i]) this._removeNode(oldParent, oldChildren[i]);\n }\n }\n }\n\n /**\n * Patches a single node.\n *\n * @private\n * @param {Node} oldNode - The original DOM node.\n * @param {Node} newNode - The new DOM node.\n * @returns {void}\n */\n _patchNode(oldNode, newNode) {\n if (oldNode?._eleva_instance) return;\n\n if (!this._isSameNode(oldNode, newNode)) {\n oldNode.replaceWith(newNode.cloneNode(true));\n return;\n }\n\n if (oldNode.nodeType === Node.ELEMENT_NODE) {\n this._updateAttributes(oldNode, newNode);\n this._diff(oldNode, newNode);\n } else if (\n oldNode.nodeType === Node.TEXT_NODE &&\n oldNode.nodeValue !== newNode.nodeValue\n ) {\n oldNode.nodeValue = newNode.nodeValue;\n }\n }\n\n /**\n * Removes a node from its parent.\n *\n * @private\n * @param {HTMLElement} parent - The parent element containing the node to remove.\n * @param {Node} node - The node to remove.\n * @returns {void}\n */\n _removeNode(parent, node) {\n if (node.nodeName === \"STYLE\" && node.hasAttribute(\"data-e-style\")) return;\n\n parent.removeChild(node);\n }\n\n /**\n * Updates the attributes of an element to match a new element's attributes.\n *\n * @private\n * @param {HTMLElement} oldEl - The original element to update.\n * @param {HTMLElement} newEl - The new element to update.\n * @returns {void}\n */\n _updateAttributes(oldEl, newEl) {\n const oldAttrs = oldEl.attributes;\n const newAttrs = newEl.attributes;\n\n // Single pass for new/updated attributes\n for (let i = 0; i < newAttrs.length; i++) {\n const { name, value } = newAttrs[i];\n if (name.startsWith(\"@\")) continue;\n if (oldEl.getAttribute(name) === value) continue;\n oldEl.setAttribute(name, value);\n\n if (name.startsWith(\"aria-\")) {\n const prop =\n \"aria\" + name.slice(5).replace(CAMEL_RE, (_, l) => l.toUpperCase());\n oldEl[prop] = value;\n } else if (name.startsWith(\"data-\")) {\n oldEl.dataset[name.slice(5)] = value;\n } else {\n const prop = name.replace(CAMEL_RE, (_, l) => l.toUpperCase());\n if (prop in oldEl) {\n const descriptor = Object.getOwnPropertyDescriptor(\n Object.getPrototypeOf(oldEl),\n prop\n );\n const isBoolean =\n typeof oldEl[prop] === \"boolean\" ||\n (descriptor?.get &&\n typeof descriptor.get.call(oldEl) === \"boolean\");\n if (isBoolean) {\n oldEl[prop] =\n value !== \"false\" &&\n (value === \"\" || value === prop || value === \"true\");\n } else {\n oldEl[prop] = value;\n }\n }\n }\n }\n\n // Remove any attributes no longer present\n for (let i = oldAttrs.length - 1; i >= 0; i--) {\n const name = oldAttrs[i].name;\n if (!newEl.hasAttribute(name)) {\n oldEl.removeAttribute(name);\n }\n }\n }\n\n /**\n * Determines if two nodes are the same based on their type, name, and key attributes.\n *\n * @private\n * @param {Node} oldNode - The first node to compare.\n * @param {Node} newNode - The second node to compare.\n * @returns {boolean} True if the nodes are considered the same, false otherwise.\n */\n _isSameNode(oldNode, newNode) {\n if (!oldNode || !newNode) return false;\n\n const oldKey =\n oldNode.nodeType === Node.ELEMENT_NODE\n ? oldNode.getAttribute(\"key\")\n : null;\n const newKey =\n newNode.nodeType === Node.ELEMENT_NODE\n ? newNode.getAttribute(\"key\")\n : null;\n\n if (oldKey && newKey) return oldKey === newKey;\n\n return (\n !oldKey &&\n !newKey &&\n oldNode.nodeType === newNode.nodeType &&\n oldNode.nodeName === newNode.nodeName\n );\n }\n\n /**\n * Creates a key map for the children of a parent node.\n *\n * @private\n * @param {Array<Node>} children - The children of the parent node.\n * @param {number} start - The start index of the children.\n * @param {number} end - The end index of the children.\n * @returns {Map<string, Node>} A key map for the children.\n */\n _createKeyMap(children, start, end) {\n const map = new Map();\n for (let i = start; i <= end; i++) {\n const child = children[i];\n const key = this._getNodeKey(child);\n if (key) map.set(key, child);\n }\n return map;\n }\n\n /**\n * Extracts the key attribute from a node if it exists.\n *\n * @private\n * @param {Node} node - The node to extract the key from.\n * @returns {string|null} The key attribute value or null if not found.\n */\n _getNodeKey(node) {\n return node?.nodeType === Node.ELEMENT_NODE\n ? node.getAttribute(\"key\")\n : null;\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 * @typedef {Object} ComponentDefinition\n * @property {function(ComponentContext): (Record<string, unknown>|Promise<Record<string, unknown>>)} [setup]\n * Optional setup function that initializes the component's state and returns reactive data\n * @property {(function(ComponentContext): string|Promise<string>)} template\n * Required function that defines the component's HTML structure\n * @property {(function(ComponentContext): string)|string} [style]\n * Optional function or string that provides component-scoped CSS styles\n * @property {Record<string, ComponentDefinition>} [children]\n * Optional object defining nested child components\n */\n\n/**\n * @typedef {Object} ComponentContext\n * @property {Record<string, unknown>} props\n * Component properties passed during mounting\n * @property {Emitter} emitter\n * Event emitter instance for component event handling\n * @property {function<T>(value: T): Signal<T>} signal\n * Factory function to create reactive Signal instances\n * @property {function(LifecycleHookContext): Promise<void>} [onBeforeMount]\n * Hook called before component mounting\n * @property {function(LifecycleHookContext): Promise<void>} [onMount]\n * Hook called after component mounting\n * @property {function(LifecycleHookContext): Promise<void>} [onBeforeUpdate]\n * Hook called before component update\n * @property {function(LifecycleHookContext): Promise<void>} [onUpdate]\n * Hook called after component update\n * @property {function(UnmountHookContext): Promise<void>} [onUnmount]\n * Hook called during component unmounting\n */\n\n/**\n * @typedef {Object} LifecycleHookContext\n * @property {HTMLElement} container\n * The DOM element where the component is mounted\n * @property {ComponentContext} context\n * The component's reactive state and context data\n */\n\n/**\n * @typedef {Object} UnmountHookContext\n * @property {HTMLElement} container\n * The DOM element where the component is mounted\n * @property {ComponentContext} context\n * The component's reactive state and context data\n * @property {{\n * watchers: Array<() => void>, // Signal watcher cleanup functions\n * listeners: Array<() => void>, // Event listener cleanup functions\n * children: Array<MountResult> // Child component instances\n * }} cleanup\n * Object containing cleanup functions and instances\n */\n\n/**\n * @typedef {Object} MountResult\n * @property {HTMLElement} container\n * The DOM element where the component is mounted\n * @property {ComponentContext} data\n * The component's reactive state and context data\n * @property {function(): Promise<void>} unmount\n * Function to clean up and unmount the component\n */\n\n/**\n * @typedef {Object} ElevaPlugin\n * @property {function(Eleva, Record<string, unknown>): void} install\n * Function that installs the plugin into the Eleva instance\n * @property {string} name\n * Unique identifier name for the plugin\n */\n\n/**\n * @class 🧩 Eleva\n * @classdesc A modern, signal-based component runtime framework that provides lifecycle hooks,\n * scoped styles, and plugin support. Eleva manages component registration, plugin integration,\n * event handling, and DOM rendering with a focus on performance and developer experience.\n *\n * @example\n * // Basic component creation and mounting\n * const app = new Eleva(\"myApp\");\n * app.component(\"myComponent\", {\n * setup: (ctx) => ({ count: ctx.signal(0) }),\n * template: (ctx) => `<div>Hello ${ctx.props.name}</div>`\n * });\n * app.mount(document.getElementById(\"app\"), \"myComponent\", { name: \"World\" });\n *\n * @example\n * // Using lifecycle hooks\n * app.component(\"lifecycleDemo\", {\n * setup: () => {\n * return {\n * onMount: ({ container, context }) => {\n * console.log('Component mounted!');\n * }\n * };\n * },\n * template: `<div>Lifecycle Demo</div>`\n * });\n */\nexport class Eleva {\n /**\n * Creates a new Eleva instance with the specified name and configuration.\n *\n * @public\n * @param {string} name - The unique identifier name for this Eleva instance.\n * @param {Record<string, unknown>} [config={}] - Optional configuration object for the instance.\n * May include framework-wide settings and default behaviors.\n * @throws {Error} If the name is not provided or is not a string.\n * @returns {Eleva} A new Eleva instance.\n *\n * @example\n * const app = new Eleva(\"myApp\");\n * app.component(\"myComponent\", {\n * setup: (ctx) => ({ count: ctx.signal(0) }),\n * template: (ctx) => `<div>Hello ${ctx.props.name}!</div>`\n * });\n * app.mount(document.getElementById(\"app\"), \"myComponent\", { name: \"World\" });\n *\n */\n constructor(name, config = {}) {\n /** @public {string} The unique identifier name for this Eleva instance */\n this.name = name;\n /** @public {Object<string, unknown>} Optional configuration object for the Eleva instance */\n this.config = config;\n /** @public {Emitter} Instance of the event emitter for handling component events */\n this.emitter = new Emitter();\n /** @public {typeof Signal} Static reference to the Signal class for creating reactive state */\n this.signal = Signal;\n /** @public {Renderer} Instance of the renderer for handling DOM updates and patching */\n this.renderer = new Renderer();\n\n /** @private {Map<string, ComponentDefinition>} Registry of all component definitions by name */\n this._components = new Map();\n /** @private {Map<string, ElevaPlugin>} Collection of installed plugin instances by name */\n this._plugins = new Map();\n /** @private {boolean} Flag indicating if the root component is currently mounted */\n this._isMounted = false;\n }\n\n /**\n * Integrates a plugin with the Eleva framework.\n * The plugin's install function will be called with the Eleva instance and provided options.\n * After installation, the plugin will be available for use by components.\n *\n * @public\n * @param {ElevaPlugin} plugin - The plugin object which must have an `install` function.\n * @param {Object<string, unknown>} [options={}] - Optional configuration options for the plugin.\n * @returns {Eleva} The Eleva instance (for method chaining).\n * @example\n * app.use(myPlugin, { option1: \"value1\" });\n */\n use(plugin, options = {}) {\n plugin.install(this, options);\n this._plugins.set(plugin.name, plugin);\n\n return this;\n }\n\n /**\n * Registers a new component with the Eleva instance.\n * The component will be available for mounting using its registered name.\n *\n * @public\n * @param {string} name - The unique name of the component to register.\n * @param {ComponentDefinition} definition - The component definition including setup, template, style, and children.\n * @returns {Eleva} The Eleva instance (for method chaining).\n * @throws {Error} If the component name is already registered.\n * @example\n * app.component(\"myButton\", {\n * template: (ctx) => `<button>${ctx.props.text}</button>`,\n * style: `button { color: blue; }`\n * });\n */\n component(name, definition) {\n /** @type {Map<string, ComponentDefinition>} */\n this._components.set(name, definition);\n return this;\n }\n\n /**\n * Mounts a registered component to a DOM element.\n * This will initialize the component, set up its reactive state, and render it to the DOM.\n *\n * @public\n * @param {HTMLElement} container - The DOM element where the component will be mounted.\n * @param {string|ComponentDefinition} compName - The name of the registered component or a direct component definition.\n * @param {Object<string, unknown>} [props={}] - Optional properties to pass to the component.\n * @returns {Promise<MountResult>}\n * A Promise that resolves to an object containing:\n * - container: The mounted component's container element\n * - data: The component's reactive state and context\n * - unmount: Function to clean up and unmount the component\n * @throws {Error} If the container is not found, or component is not registered.\n * @example\n * const instance = await app.mount(document.getElementById(\"app\"), \"myComponent\", { text: \"Click me\" });\n * // Later...\n * instance.unmount();\n */\n async mount(container, compName, props = {}) {\n if (!container) throw new Error(`Container not found: ${container}`);\n\n if (container._eleva_instance) return container._eleva_instance;\n\n /** @type {ComponentDefinition} */\n const definition =\n typeof compName === \"string\" ? this._components.get(compName) : compName;\n if (!definition) throw new Error(`Component \"${compName}\" not registered.`);\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 or string that returns the component's HTML structure\n * - style: Optional function or string for component-scoped CSS styles\n * - children: Optional object defining nested child components\n */\n const { setup, template, style, children } = definition;\n\n /** @type {ComponentContext} */\n const context = {\n props,\n emitter: this.emitter,\n /** @type {(v: unknown) => Signal<unknown>} */\n signal: (v) => new this.signal(v),\n };\n\n /**\n * Processes the mounting of the component.\n * This function handles:\n * 1. Merging setup data with the component context\n * 2. Setting up reactive watchers\n * 3. Rendering the component\n * 4. Managing component lifecycle\n *\n * @param {Object<string, unknown>} data - Data returned from the component's setup function\n * @returns {Promise<MountResult>} An object containing:\n * - container: The mounted component's container element\n * - data: The component's reactive state and context\n * - unmount: Function to clean up and unmount the component\n */\n const processMount = async (data) => {\n /** @type {ComponentContext} */\n const mergedContext = { ...context, ...data };\n /** @type {Array<() => void>} */\n const watchers = [];\n /** @type {Array<MountResult>} */\n const childInstances = [];\n /** @type {Array<() => void>} */\n const listeners = [];\n\n // Execute before hooks\n if (!this._isMounted) {\n /** @type {LifecycleHookContext} */\n await mergedContext.onBeforeMount?.({\n container,\n context: mergedContext,\n });\n } else {\n /** @type {LifecycleHookContext} */\n await mergedContext.onBeforeUpdate?.({\n container,\n context: mergedContext,\n });\n }\n\n /**\n * Renders the component by:\n * 1. Processing the template\n * 2. Updating the DOM\n * 3. Processing events, injecting styles, and mounting child components.\n */\n const render = async () => {\n const templateResult =\n typeof template === \"function\"\n ? await template(mergedContext)\n : template;\n const newHtml = TemplateEngine.parse(templateResult, mergedContext);\n this.renderer.patchDOM(container, newHtml);\n this._processEvents(container, mergedContext, listeners);\n if (style)\n this._injectStyles(container, compName, style, mergedContext);\n if (children)\n await this._mountComponents(container, children, childInstances);\n\n if (!this._isMounted) {\n /** @type {LifecycleHookContext} */\n await mergedContext.onMount?.({\n container,\n context: mergedContext,\n });\n this._isMounted = true;\n } else {\n /** @type {LifecycleHookContext} */\n await mergedContext.onUpdate?.({\n container,\n context: mergedContext,\n });\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 for (const val of Object.values(data)) {\n if (val instanceof Signal) watchers.push(val.watch(render));\n }\n\n await render();\n\n const instance = {\n container,\n data: mergedContext,\n /**\n * Unmounts the component, cleaning up watchers and listeners, child components, and clearing the container.\n *\n * @returns {void}\n */\n unmount: async () => {\n /** @type {UnmountHookContext} */\n await mergedContext.onUnmount?.({\n container,\n context: mergedContext,\n cleanup: {\n watchers: watchers,\n listeners: listeners,\n children: childInstances,\n },\n });\n for (const fn of watchers) fn();\n for (const fn of listeners) fn();\n for (const child of childInstances) await child.unmount();\n container.innerHTML = \"\";\n delete container._eleva_instance;\n },\n };\n\n container._eleva_instance = instance;\n return instance;\n };\n\n // Handle asynchronous setup.\n const setupResult = typeof setup === \"function\" ? await setup(context) : {};\n return await processMount(setupResult);\n }\n\n /**\n * Processes DOM elements for event binding based on attributes starting with \"@\".\n * This method handles the event delegation system and ensures proper cleanup of event listeners.\n *\n * @private\n * @param {HTMLElement} container - The container element in which to search for event attributes.\n * @param {ComponentContext} context - The current component context containing event handler definitions.\n * @param {Array<() => void>} listeners - Array to collect cleanup functions for each event listener.\n * @returns {void}\n */\n _processEvents(container, context, listeners) {\n /** @type {NodeListOf<Element>} */\n const elements = container.querySelectorAll(\"*\");\n for (const el of elements) {\n /** @type {NamedNodeMap} */\n const attrs = el.attributes;\n for (let i = 0; i < attrs.length; i++) {\n /** @type {Attr} */\n const attr = attrs[i];\n\n if (!attr.name.startsWith(\"@\")) continue;\n\n /** @type {keyof HTMLElementEventMap} */\n const event = attr.name.slice(1);\n /** @type {string} */\n const handlerName = attr.value;\n /** @type {(event: Event) => void} */\n const handler =\n context[handlerName] || TemplateEngine.evaluate(handlerName, context);\n if (typeof handler === \"function\") {\n el.addEventListener(event, handler);\n el.removeAttribute(attr.name);\n listeners.push(() => el.removeEventListener(event, handler));\n }\n }\n }\n }\n\n /**\n * Injects scoped styles into the component's container.\n * The styles are automatically prefixed to prevent style leakage to other components.\n *\n * @private\n * @param {HTMLElement} container - The container element where styles should be injected.\n * @param {string} compName - The component name used to identify the style element.\n * @param {(function(ComponentContext): string)|string} styleDef - The component's style definition (function or string).\n * @param {ComponentContext} context - The current component context for style interpolation.\n * @returns {void}\n */\n _injectStyles(container, compName, styleDef, context) {\n /** @type {string} */\n const newStyle =\n typeof styleDef === \"function\"\n ? TemplateEngine.parse(styleDef(context), context)\n : styleDef;\n /** @type {HTMLStyleElement|null} */\n let styleEl = container.querySelector(`style[data-e-style=\"${compName}\"]`);\n\n if (styleEl && styleEl.textContent === newStyle) return;\n if (!styleEl) {\n styleEl = document.createElement(\"style\");\n styleEl.setAttribute(\"data-e-style\", compName);\n container.appendChild(styleEl);\n }\n\n styleEl.textContent = newStyle;\n }\n\n /**\n * Extracts props from an element's attributes that start with the specified prefix.\n * This method is used to collect component properties from DOM elements.\n *\n * @private\n * @param {HTMLElement} element - The DOM element to extract props from\n * @param {string} prefix - The prefix to look for in attributes\n * @returns {Record<string, string>} An object containing the extracted props\n * @example\n * // For an element with attributes:\n * // <div :name=\"John\" :age=\"25\">\n * // Returns: { name: \"John\", age: \"25\" }\n */\n _extractProps(element, prefix) {\n if (!element.attributes) return {};\n\n const props = {};\n const attrs = element.attributes;\n\n for (let i = attrs.length - 1; i >= 0; i--) {\n const attr = attrs[i];\n if (attr.name.startsWith(prefix)) {\n const propName = attr.name.slice(prefix.length);\n props[propName] = attr.value;\n element.removeAttribute(attr.name);\n }\n }\n return props;\n }\n\n /**\n * Mounts all components within the parent component's container.\n * This method handles mounting of explicitly defined children components.\n *\n * The mounting process follows these steps:\n * 1. Cleans up any existing component instances\n * 2. Mounts explicitly defined children components\n *\n * @private\n * @param {HTMLElement} container - The container element to mount components in\n * @param {Object<string, ComponentDefinition>} children - Map of selectors to component definitions for explicit children\n * @param {Array<MountResult>} childInstances - Array to store all mounted component instances\n * @returns {Promise<void>}\n *\n * @example\n * // Explicit children mounting:\n * const children = {\n * 'UserProfile': UserProfileComponent,\n * '#settings-panel': \"settings-panel\"\n * };\n */\n async _mountComponents(container, children, childInstances) {\n for (const [selector, component] of Object.entries(children)) {\n if (!selector) continue;\n for (const el of container.querySelectorAll(selector)) {\n if (!(el instanceof HTMLElement)) continue;\n /** @type {Record<string, string>} */\n const props = this._extractProps(el, \":\");\n /** @type {MountResult} */\n const instance = await this.mount(el, component, props);\n if (instance && !childInstances.includes(instance)) {\n childInstances.push(instance);\n }\n }\n }\n }\n}\n"],"names":["TemplateEngine","static","parse","template","data","replace","this","expressionPattern","_","expression","evaluate","Function","Signal","constructor","value","_value","_watchers","Set","_pending","newVal","_notify","watch","fn","add","delete","queueMicrotask","forEach","Emitter","_events","Map","on","event","handler","has","set","get","off","handlers","size","emit","args","CAMEL_RE","Renderer","_tempContainer","document","createElement","patchDOM","container","newHtml","HTMLElement","TypeError","innerHTML","_diff","error","Error","message","oldParent","newParent","isEqualNode","oldChildren","Array","from","childNodes","newChildren","oldStartIdx","newStartIdx","oldEndIdx","length","newEndIdx","oldKeyMap","oldStartNode","newStartNode","_isSameNode","_patchNode","_createKeyMap","key","_getNodeKey","oldNodeToMove","insertBefore","indexOf","cloneNode","refNode","i","_removeNode","oldNode","newNode","_eleva_instance","nodeType","Node","ELEMENT_NODE","_updateAttributes","TEXT_NODE","nodeValue","replaceWith","parent","node","nodeName","hasAttribute","removeChild","oldEl","newEl","oldAttrs","attributes","newAttrs","name","startsWith","getAttribute","setAttribute","slice","l","toUpperCase","dataset","prop","descriptor","Object","getOwnPropertyDescriptor","getPrototypeOf","isBoolean","call","removeAttribute","oldKey","newKey","children","start","end","map","child","config","emitter","signal","renderer","_components","_plugins","_isMounted","use","plugin","options","install","component","definition","mount","compName","props","setup","style","context","v","setupResult","async","mergedContext","watchers","childInstances","listeners","onBeforeUpdate","onBeforeMount","render","templateResult","_processEvents","_injectStyles","_mountComponents","onUpdate","onMount","val","values","push","instance","unmount","onUnmount","cleanup","processMount","elements","querySelectorAll","el","attrs","attr","handlerName","addEventListener","removeEventListener","styleDef","newStyle","styleEl","querySelector","textContent","appendChild","_extractProps","element","prefix","selector","entries","includes"],"mappings":";yCAaO,MAAMA,EAKXC,yBAA2B,uBAgB3B,YAAOC,CAAMC,EAAUC,GACrB,MAAwB,iBAAbD,EAA8BA,EAClCA,EAASE,QAAQC,KAAKC,kBAAmB,CAACC,EAAGC,IAClDH,KAAKI,SAASD,EAAYL,GAE9B,CAiBA,eAAOM,CAASD,EAAYL,GAC1B,GAA0B,iBAAfK,EAAyB,OAAOA,EAC3C,IACE,OAAO,IAAIE,SAAS,OAAQ,uBAAuBF,OAA5C,CAA6DL,EACtE,CAAE,MACA,MAAO,EACT,CACF,EC/CK,MAAMQ,EAOXC,WAAAA,CAAYC,GAEVR,KAAKS,OAASD,EAEdR,KAAKU,UAAY,IAAIC,IAErBX,KAAKY,UAAW,CAClB,CAQA,SAAIJ,GACF,OAAOR,KAAKS,MACd,CAUA,SAAID,CAAMK,GACJb,KAAKS,SAAWI,IAEpBb,KAAKS,OAASI,EACdb,KAAKc,UACP,CAcAC,KAAAA,CAAMC,GAEJ,OADAhB,KAAKU,UAAUO,IAAID,GACZ,IAAMhB,KAAKU,UAAUQ,OAAOF,EACrC,CAUAF,OAAAA,GACMd,KAAKY,WAETZ,KAAKY,UAAW,EAChBO,eAAe,KAEbnB,KAAKU,UAAUU,QAASJ,GAAOA,EAAGhB,KAAKS,SACvCT,KAAKY,UAAW,IAEpB,EC3EK,MAAMS,EAMXd,WAAAA,GAEEP,KAAKsB,QAAU,IAAIC,GACrB,CAgBAC,EAAAA,CAAGC,EAAOC,GAIR,OAHK1B,KAAKsB,QAAQK,IAAIF,IAAQzB,KAAKsB,QAAQM,IAAIH,EAAO,IAAId,KAE1DX,KAAKsB,QAAQO,IAAIJ,GAAOR,IAAIS,GACrB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,CAAiBhH,EAAW2E,EAAU6B,GAC1C,IAAK,MAAOoC,EAAUjD,KAAcxB,OAAO0E,QAAQlE,GACjD,GAAKiE,EACL,IAAK,MAAMf,KAAM7H,EAAU4H,iBAAiBgB,GAAW,CACrD,KAAMf,aAAc3H,aAAc,SAElC,MAAM6F,EAAQxI,KAAKkL,cAAcZ,EAAI,KAE/BP,QAAiB/J,KAAKsI,MAAMgC,EAAIlC,EAAWI,GAC7CuB,IAAad,EAAesC,SAASxB,IACvCd,EAAea,KAAKC,EAExB,CAEJ"}
1
+ {"version":3,"file":"eleva.umd.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// TYPE DEFINITIONS - TypeScript-friendly JSDoc types for IDE support\n// ============================================================================\n\n/**\n * @typedef {Record<string, unknown>} TemplateData\n * Data context for template interpolation\n */\n\n/**\n * @typedef {string} TemplateString\n * A string containing {{ expression }} interpolation markers\n */\n\n/**\n * @typedef {string} Expression\n * A JavaScript expression to be evaluated in the data context\n */\n\n/**\n * @typedef {unknown} EvaluationResult\n * The result of evaluating an expression (string, number, boolean, object, etc.)\n */\n\n/**\n * @class 🔒 TemplateEngine\n * @classdesc A secure template engine that handles interpolation and dynamic attribute parsing.\n * Provides a way to evaluate expressions in templates.\n * All methods are static and can be called directly on the class.\n *\n * Template Syntax:\n * - `{{ expression }}` - Interpolate any JavaScript expression\n * - `{{ variable }}` - Access data properties directly\n * - `{{ object.property }}` - Access nested properties\n * - `{{ condition ? a : b }}` - Ternary expressions\n * - `{{ func(arg) }}` - Call functions from data context\n *\n * @example\n * // Basic interpolation\n * const template = \"Hello, {{name}}!\";\n * const data = { name: \"World\" };\n * const result = TemplateEngine.parse(template, data);\n * // Result: \"Hello, World!\"\n *\n * @example\n * // Nested properties\n * const template = \"Welcome, {{user.name}}!\";\n * const data = { user: { name: \"John\" } };\n * const result = TemplateEngine.parse(template, data);\n * // Result: \"Welcome, John!\"\n *\n * @example\n * // Expressions\n * const template = \"Status: {{active ? 'Online' : 'Offline'}}\";\n * const data = { active: true };\n * const result = TemplateEngine.parse(template, data);\n * // Result: \"Status: Online\"\n *\n * @example\n * // With Signal values\n * const template = \"Count: {{count.value}}\";\n * const data = { count: { value: 42 } };\n * const result = TemplateEngine.parse(template, data);\n * // Result: \"Count: 42\"\n */\nexport class TemplateEngine {\n /**\n * Regular expression for matching template expressions in the format {{ expression }}\n * Matches: {{ anything }} with optional whitespace inside braces\n *\n * @static\n * @private\n * @type {RegExp}\n */\n static expressionPattern = /\\{\\{\\s*(.*?)\\s*\\}\\}/g;\n\n /**\n * Parses a template string, replacing expressions with their evaluated values.\n * Expressions are evaluated in the provided data context.\n *\n * @public\n * @static\n * @param {TemplateString|unknown} template - The template string to parse.\n * @param {TemplateData} data - The data context for evaluating expressions.\n * @returns {string} The parsed template with expressions replaced by their values.\n *\n * @example\n * // Simple variables\n * TemplateEngine.parse(\"Hello, {{name}}!\", { name: \"World\" });\n * // Result: \"Hello, World!\"\n *\n * @example\n * // Nested properties\n * TemplateEngine.parse(\"{{user.name}} is {{user.age}} years old\", {\n * user: { name: \"John\", age: 30 }\n * });\n * // Result: \"John is 30 years old\"\n *\n * @example\n * // Multiple expressions\n * TemplateEngine.parse(\"{{greeting}}, {{name}}! You have {{count}} messages.\", {\n * greeting: \"Hello\",\n * name: \"User\",\n * count: 5\n * });\n * // Result: \"Hello, User! You have 5 messages.\"\n *\n * @example\n * // With conditionals\n * TemplateEngine.parse(\"Status: {{online ? 'Active' : 'Inactive'}}\", {\n * online: true\n * });\n * // Result: \"Status: Active\"\n */\n static parse(template, data) {\n if (typeof template !== \"string\") return template;\n return template.replace(this.expressionPattern, (_, expression) =>\n this.evaluate(expression, data)\n );\n }\n\n /**\n * Evaluates an expression in the context of the provided data object.\n *\n * Note: This does not provide a true sandbox and evaluated expressions may access global scope.\n * The use of the `with` statement is necessary for expression evaluation but has security implications.\n * Only use with trusted templates. User input should never be directly interpolated.\n *\n * @public\n * @static\n * @param {Expression|unknown} expression - The expression to evaluate.\n * @param {TemplateData} data - The data context for evaluation.\n * @returns {EvaluationResult} The result of the evaluation, or an empty string if evaluation fails.\n *\n * @example\n * // Property access\n * TemplateEngine.evaluate(\"user.name\", { user: { name: \"John\" } });\n * // Result: \"John\"\n *\n * @example\n * // Numeric values\n * TemplateEngine.evaluate(\"user.age\", { user: { age: 30 } });\n * // Result: 30\n *\n * @example\n * // Expressions\n * TemplateEngine.evaluate(\"items.length > 0\", { items: [1, 2, 3] });\n * // Result: true\n *\n * @example\n * // Function calls\n * TemplateEngine.evaluate(\"formatDate(date)\", {\n * date: new Date(),\n * formatDate: (d) => d.toISOString()\n * });\n * // Result: \"2024-01-01T00:00:00.000Z\"\n *\n * @example\n * // Failed evaluation returns empty string\n * TemplateEngine.evaluate(\"nonexistent.property\", {});\n * // Result: \"\"\n */\n static evaluate(expression, data) {\n if (typeof expression !== \"string\") return expression;\n try {\n return new Function(\"data\", `with(data) { return ${expression}; }`)(data);\n } catch {\n return \"\";\n }\n }\n}\n","\"use strict\";\n\n// ============================================================================\n// TYPE DEFINITIONS - TypeScript-friendly JSDoc types for IDE support\n// ============================================================================\n\n/**\n * @template T\n * @callback SignalWatcher\n * @param {T} value - The new value of the signal\n * @returns {void}\n */\n\n/**\n * @callback SignalUnsubscribe\n * @returns {boolean} True if the watcher was successfully removed\n */\n\n/**\n * @template T\n * @typedef {Object} SignalLike\n * @property {T} value - The current value\n * @property {function(SignalWatcher<T>): SignalUnsubscribe} watch - Subscribe to changes\n */\n\n/**\n * @class ⚡ Signal\n * @classdesc A reactive data holder that enables fine-grained reactivity in the Eleva framework.\n * Signals notify registered watchers when their value changes, enabling efficient DOM updates\n * through targeted patching rather than full re-renders.\n * Updates are batched using microtasks to prevent multiple synchronous notifications.\n * The class is generic, allowing type-safe handling of any value type T.\n *\n * @template T The type of value held by this signal\n *\n * @example\n * // Basic usage\n * const count = new Signal(0);\n * count.watch((value) => console.log(`Count changed to: ${value}`));\n * count.value = 1; // Logs: \"Count changed to: 1\"\n *\n * @example\n * // With unsubscribe\n * const name = new Signal(\"John\");\n * const unsubscribe = name.watch((value) => console.log(value));\n * name.value = \"Jane\"; // Logs: \"Jane\"\n * unsubscribe(); // Stop watching\n * name.value = \"Bob\"; // No log output\n *\n * @example\n * // With objects\n * /** @type {Signal<{x: number, y: number}>} *\\/\n * const position = new Signal({ x: 0, y: 0 });\n * position.value = { x: 10, y: 20 }; // Triggers watchers\n *\n * @implements {SignalLike<T>}\n */\nexport class Signal {\n /**\n * Creates a new Signal instance with the specified initial value.\n *\n * @public\n * @param {T} value - The initial value of the signal.\n *\n * @example\n * // Primitive types\n * const count = new Signal(0); // Signal<number>\n * const name = new Signal(\"John\"); // Signal<string>\n * const active = new Signal(true); // Signal<boolean>\n *\n * @example\n * // Complex types (use JSDoc for type inference)\n * /** @type {Signal<string[]>} *\\/\n * const items = new Signal([]);\n *\n * /** @type {Signal<{id: number, name: string} | null>} *\\/\n * const user = new Signal(null);\n */\n constructor(value) {\n /**\n * Internal storage for the signal's current value\n * @private\n * @type {T}\n */\n this._value = value;\n /**\n * Collection of callback functions to be notified when value changes\n * @private\n * @type {Set<SignalWatcher<T>>}\n */\n this._watchers = new Set();\n /**\n * Flag to prevent multiple synchronous watcher notifications\n * @private\n * @type {boolean}\n */\n this._pending = false;\n }\n\n /**\n * Gets the current value of the signal.\n *\n * @public\n * @returns {T} 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 * The notification is batched using microtasks to prevent multiple synchronous updates.\n *\n * @public\n * @param {T} newVal - The new value to set.\n * @returns {void}\n */\n set value(newVal) {\n if (this._value === newVal) return;\n\n this._value = newVal;\n this._notify();\n }\n\n /**\n * Registers a watcher function that will be called whenever the signal's value changes.\n * The watcher will receive the new value as its argument.\n *\n * @public\n * @param {SignalWatcher<T>} fn - The callback function to invoke on value change.\n * @returns {SignalUnsubscribe} A function to unsubscribe the watcher.\n *\n * @example\n * // Basic watching\n * const unsubscribe = signal.watch((value) => console.log(value));\n *\n * @example\n * // Stop watching\n * unsubscribe(); // Returns true if watcher was removed\n *\n * @example\n * // Multiple watchers\n * const unsub1 = signal.watch((v) => console.log(\"Watcher 1:\", v));\n * const unsub2 = signal.watch((v) => console.log(\"Watcher 2:\", v));\n * signal.value = \"test\"; // Both watchers are called\n */\n watch(fn) {\n this._watchers.add(fn);\n return () => this._watchers.delete(fn);\n }\n\n /**\n * Notifies all registered watchers of a value change using microtask scheduling.\n * Uses a pending flag to batch multiple synchronous updates into a single notification.\n * All watcher callbacks receive the current value when executed.\n *\n * @private\n * @returns {void}\n */\n _notify() {\n if (this._pending) return;\n\n this._pending = true;\n queueMicrotask(() => {\n /** @type {(fn: (value: T) => void) => void} */\n this._watchers.forEach((fn) => fn(this._value));\n this._pending = false;\n });\n }\n}\n","\"use strict\";\n\n// ============================================================================\n// TYPE DEFINITIONS - TypeScript-friendly JSDoc types for IDE support\n// ============================================================================\n\n/**\n * @template T\n * @callback EventHandler\n * @param {...T} args - Event arguments\n * @returns {void|Promise<void>}\n */\n\n/**\n * @callback EventUnsubscribe\n * @returns {void}\n */\n\n/**\n * @typedef {`${string}:${string}`} EventName\n * Event names follow the format 'namespace:action' (e.g., 'user:login', 'cart:update')\n */\n\n/**\n * @typedef {Object} EmitterLike\n * @property {function(string, EventHandler<unknown>): EventUnsubscribe} on - Subscribe to an event\n * @property {function(string, EventHandler<unknown>=): void} off - Unsubscribe from an event\n * @property {function(string, ...unknown): void} emit - Emit an event\n */\n\n/**\n * @class 📡 Emitter\n * @classdesc A robust event emitter that enables inter-component communication through a publish-subscribe pattern.\n * Components can emit events and listen for events from other components, facilitating loose coupling\n * and reactive updates across the application.\n * Events are handled synchronously in the order they were registered, with proper cleanup\n * of unsubscribed handlers.\n *\n * Event names should follow the format 'namespace:action' for consistency and organization.\n *\n * @example\n * // Basic usage\n * const emitter = new Emitter();\n * emitter.on('user:login', (user) => console.log(`User logged in: ${user.name}`));\n * emitter.emit('user:login', { name: 'John' }); // Logs: \"User logged in: John\"\n *\n * @example\n * // With unsubscribe\n * const unsub = emitter.on('cart:update', (items) => {\n * console.log(`Cart has ${items.length} items`);\n * });\n * emitter.emit('cart:update', [{ id: 1, name: 'Book' }]); // Logs: \"Cart has 1 items\"\n * unsub(); // Stop listening\n * emitter.emit('cart:update', []); // No log output\n *\n * @example\n * // Multiple arguments\n * emitter.on('order:placed', (orderId, amount, currency) => {\n * console.log(`Order ${orderId}: ${amount} ${currency}`);\n * });\n * emitter.emit('order:placed', 'ORD-123', 99.99, 'USD');\n *\n * @example\n * // Common event patterns\n * // Lifecycle events\n * emitter.on('component:mount', (component) => {});\n * emitter.on('component:unmount', (component) => {});\n * // State events\n * emitter.on('state:change', (newState, oldState) => {});\n * // Navigation events\n * emitter.on('router:navigate', (to, from) => {});\n *\n * @implements {EmitterLike}\n */\nexport class Emitter {\n /**\n * Creates a new Emitter instance.\n *\n * @public\n *\n * @example\n * const emitter = new Emitter();\n */\n constructor() {\n /**\n * Map of event names to their registered handler functions\n * @private\n * @type {Map<string, Set<EventHandler<unknown>>>}\n */\n this._events = new Map();\n }\n\n /**\n * Registers an event handler for the specified event name.\n * The handler will be called with the event data when the event is emitted.\n * Event names should follow the format 'namespace:action' for consistency.\n *\n * @public\n * @template T\n * @param {string} event - The name of the event to listen for (e.g., 'user:login').\n * @param {EventHandler<T>} handler - The callback function to invoke when the event occurs.\n * @returns {EventUnsubscribe} A function to unsubscribe the event handler.\n *\n * @example\n * // Basic subscription\n * const unsubscribe = emitter.on('user:login', (user) => console.log(user));\n *\n * @example\n * // Typed handler\n * emitter.on('user:update', (/** @type {{id: number, name: string}} *\\/ user) => {\n * console.log(`User ${user.id}: ${user.name}`);\n * });\n *\n * @example\n * // Cleanup\n * unsubscribe(); // Stops listening for the event\n */\n on(event, handler) {\n if (!this._events.has(event)) this._events.set(event, new Set());\n\n this._events.get(event).add(handler);\n return () => this.off(event, handler);\n }\n\n /**\n * Removes an event handler for the specified event name.\n * If no handler is provided, all handlers for the event are removed.\n * Automatically cleans up empty event sets to prevent memory leaks.\n *\n * @public\n * @template T\n * @param {string} event - The name of the event to remove handlers from.\n * @param {EventHandler<T>} [handler] - The specific handler function to remove.\n * @returns {void}\n *\n * @example\n * // Remove a specific handler\n * const loginHandler = (user) => console.log(user);\n * emitter.on('user:login', loginHandler);\n * emitter.off('user:login', loginHandler);\n *\n * @example\n * // Remove all handlers for an event\n * emitter.off('user:login');\n */\n off(event, handler) {\n if (!this._events.has(event)) return;\n if (handler) {\n const handlers = this._events.get(event);\n handlers.delete(handler);\n // Remove the event if there are no handlers left\n if (handlers.size === 0) this._events.delete(event);\n } else {\n this._events.delete(event);\n }\n }\n\n /**\n * Emits an event with the specified data to all registered handlers.\n * Handlers are called synchronously in the order they were registered.\n * If no handlers are registered for the event, the emission is silently ignored.\n *\n * @public\n * @template T\n * @param {string} event - The name of the event to emit.\n * @param {...T} args - Optional arguments to pass to the event handlers.\n * @returns {void}\n *\n * @example\n * // Emit an event with data\n * emitter.emit('user:login', { name: 'John', role: 'admin' });\n *\n * @example\n * // Emit an event with multiple arguments\n * emitter.emit('order:placed', 'ORD-123', 99.99, 'USD');\n *\n * @example\n * // Emit without data\n * emitter.emit('app:ready');\n */\n emit(event, ...args) {\n if (!this._events.has(event)) return;\n this._events.get(event).forEach((handler) => handler(...args));\n }\n}\n","\"use strict\";\n\n// ============================================================================\n// TYPE DEFINITIONS - TypeScript-friendly JSDoc types for IDE support\n// ============================================================================\n\n/**\n * @typedef {Object} PatchOptions\n * @property {boolean} [preserveStyles=true]\n * Whether to preserve style elements with data-e-style attribute\n * @property {boolean} [preserveInstances=true]\n * Whether to preserve elements with _eleva_instance property\n */\n\n/**\n * @typedef {Map<string, Node>} KeyMap\n * Map of key attribute values to their corresponding DOM nodes\n */\n\n/**\n * @typedef {'ELEMENT_NODE'|'TEXT_NODE'|'COMMENT_NODE'|'DOCUMENT_FRAGMENT_NODE'} NodeTypeName\n * Common DOM node type names\n */\n\n/**\n * @class 🎨 Renderer\n * @classdesc A high-performance DOM renderer that implements an optimized direct DOM diffing algorithm.\n *\n * Key features:\n * - Single-pass diffing algorithm for efficient DOM updates\n * - Key-based node reconciliation for optimal performance\n * - Intelligent attribute handling for ARIA, data attributes, and boolean properties\n * - Preservation of special Eleva-managed instances and style elements\n * - Memory-efficient with reusable temporary containers\n *\n * The renderer is designed to minimize DOM operations while maintaining\n * exact attribute synchronization and proper node identity preservation.\n * It's particularly optimized for frequent updates and complex DOM structures.\n *\n * @example\n * // Basic usage\n * const renderer = new Renderer();\n * const container = document.getElementById(\"app\");\n * const newHtml = \"<div>Updated content</div>\";\n * renderer.patchDOM(container, newHtml);\n *\n * @example\n * // With keyed elements for optimal list updates\n * const listHtml = `\n * <ul>\n * <li key=\"item-1\">First</li>\n * <li key=\"item-2\">Second</li>\n * <li key=\"item-3\">Third</li>\n * </ul>\n * `;\n * renderer.patchDOM(container, listHtml);\n *\n * @example\n * // The renderer preserves Eleva-managed elements\n * // Elements with _eleva_instance are not replaced during diffing\n * // Style elements with data-e-style are preserved\n */\nexport class Renderer {\n /**\n * Creates a new Renderer instance.\n *\n * @public\n *\n * @example\n * const renderer = new Renderer();\n */\n constructor() {\n /**\n * A temporary container to hold the new HTML content while diffing.\n * Reused across patch operations to minimize memory allocation.\n * @private\n * @type {HTMLDivElement}\n */\n this._tempContainer = document.createElement(\"div\");\n }\n\n /**\n * Patches the DOM of the given container with the provided HTML string.\n * Uses an optimized diffing algorithm to minimize DOM operations.\n *\n * @public\n * @param {HTMLElement} container - The container element to patch.\n * @param {string} newHtml - The new HTML string.\n * @returns {void}\n * @throws {TypeError} If container is not an HTMLElement or newHtml is not a string.\n * @throws {Error} If DOM patching fails.\n *\n * @example\n * // Update container content\n * renderer.patchDOM(container, '<div class=\"updated\">New content</div>');\n *\n * @example\n * // Update list with keys for optimal diffing\n * const items = ['a', 'b', 'c'];\n * const html = items.map(item =>\n * `<li key=\"${item}\">${item}</li>`\n * ).join('');\n * renderer.patchDOM(listContainer, `<ul>${html}</ul>`);\n */\n patchDOM(container, newHtml) {\n if (!(container instanceof HTMLElement)) {\n throw new TypeError(\"Container must be an HTMLElement\");\n }\n if (typeof newHtml !== \"string\") {\n throw new TypeError(\"newHtml must be a string\");\n }\n\n try {\n this._tempContainer.innerHTML = newHtml;\n this._diff(container, this._tempContainer);\n } catch (error) {\n throw new Error(`Failed to patch DOM: ${error.message}`);\n }\n }\n\n /**\n * Performs a diff between two DOM nodes and patches the old node to match the new node.\n *\n * @private\n * @param {HTMLElement} oldParent - The original DOM element.\n * @param {HTMLElement} newParent - The new DOM element.\n * @returns {void}\n */\n _diff(oldParent, newParent) {\n if (oldParent === newParent || oldParent.isEqualNode?.(newParent)) return;\n\n const oldChildren = Array.from(oldParent.childNodes);\n const newChildren = Array.from(newParent.childNodes);\n let oldStartIdx = 0,\n newStartIdx = 0;\n let oldEndIdx = oldChildren.length - 1;\n let newEndIdx = newChildren.length - 1;\n let oldKeyMap = null;\n\n while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {\n let oldStartNode = oldChildren[oldStartIdx];\n let newStartNode = newChildren[newStartIdx];\n\n if (!oldStartNode) {\n oldStartNode = oldChildren[++oldStartIdx];\n } else if (this._isSameNode(oldStartNode, newStartNode)) {\n this._patchNode(oldStartNode, newStartNode);\n oldStartIdx++;\n newStartIdx++;\n } else {\n if (!oldKeyMap) {\n oldKeyMap = this._createKeyMap(oldChildren, oldStartIdx, oldEndIdx);\n }\n const key = this._getNodeKey(newStartNode);\n const oldNodeToMove = key ? oldKeyMap.get(key) : null;\n\n if (oldNodeToMove) {\n this._patchNode(oldNodeToMove, newStartNode);\n oldParent.insertBefore(oldNodeToMove, oldStartNode);\n oldChildren[oldChildren.indexOf(oldNodeToMove)] = null;\n } else {\n oldParent.insertBefore(newStartNode.cloneNode(true), oldStartNode);\n }\n newStartIdx++;\n }\n }\n\n if (oldStartIdx > oldEndIdx) {\n const refNode = newChildren[newEndIdx + 1]\n ? oldChildren[oldStartIdx]\n : null;\n for (let i = newStartIdx; i <= newEndIdx; i++) {\n if (newChildren[i])\n oldParent.insertBefore(newChildren[i].cloneNode(true), refNode);\n }\n } else if (newStartIdx > newEndIdx) {\n for (let i = oldStartIdx; i <= oldEndIdx; i++) {\n if (oldChildren[i]) this._removeNode(oldParent, oldChildren[i]);\n }\n }\n }\n\n /**\n * Patches a single node.\n *\n * @private\n * @param {Node} oldNode - The original DOM node.\n * @param {Node} newNode - The new DOM node.\n * @returns {void}\n */\n _patchNode(oldNode, newNode) {\n if (oldNode?._eleva_instance) return;\n\n if (!this._isSameNode(oldNode, newNode)) {\n oldNode.replaceWith(newNode.cloneNode(true));\n return;\n }\n\n if (oldNode.nodeType === Node.ELEMENT_NODE) {\n this._updateAttributes(oldNode, newNode);\n this._diff(oldNode, newNode);\n } else if (\n oldNode.nodeType === Node.TEXT_NODE &&\n oldNode.nodeValue !== newNode.nodeValue\n ) {\n oldNode.nodeValue = newNode.nodeValue;\n }\n }\n\n /**\n * Removes a node from its parent.\n *\n * @private\n * @param {HTMLElement} parent - The parent element containing the node to remove.\n * @param {Node} node - The node to remove.\n * @returns {void}\n */\n _removeNode(parent, node) {\n if (node.nodeName === \"STYLE\" && node.hasAttribute(\"data-e-style\")) return;\n\n parent.removeChild(node);\n }\n\n /**\n * Updates the attributes of an element to match a new element's attributes.\n *\n * @private\n * @param {HTMLElement} oldEl - The original element to update.\n * @param {HTMLElement} newEl - The new element to update.\n * @returns {void}\n */\n _updateAttributes(oldEl, newEl) {\n const oldAttrs = oldEl.attributes;\n const newAttrs = newEl.attributes;\n\n // Process new attributes\n for (let i = 0; i < newAttrs.length; i++) {\n const { name, value } = newAttrs[i];\n\n // Skip event attributes (handled by event system)\n if (name.startsWith(\"@\")) continue;\n\n // Skip if attribute hasn't changed\n if (oldEl.getAttribute(name) === value) continue;\n\n // Basic attribute setting\n oldEl.setAttribute(name, value);\n }\n\n // Remove old attributes that are no longer present\n for (let i = oldAttrs.length - 1; i >= 0; i--) {\n const name = oldAttrs[i].name;\n if (!newEl.hasAttribute(name)) {\n oldEl.removeAttribute(name);\n }\n }\n }\n\n /**\n * Determines if two nodes are the same based on their type, name, and key attributes.\n *\n * @private\n * @param {Node} oldNode - The first node to compare.\n * @param {Node} newNode - The second node to compare.\n * @returns {boolean} True if the nodes are considered the same, false otherwise.\n */\n _isSameNode(oldNode, newNode) {\n if (!oldNode || !newNode) return false;\n\n const oldKey =\n oldNode.nodeType === Node.ELEMENT_NODE\n ? oldNode.getAttribute(\"key\")\n : null;\n const newKey =\n newNode.nodeType === Node.ELEMENT_NODE\n ? newNode.getAttribute(\"key\")\n : null;\n\n if (oldKey && newKey) return oldKey === newKey;\n\n return (\n !oldKey &&\n !newKey &&\n oldNode.nodeType === newNode.nodeType &&\n oldNode.nodeName === newNode.nodeName\n );\n }\n\n /**\n * Creates a key map for the children of a parent node.\n * Used for efficient O(1) lookup of keyed elements during diffing.\n *\n * @private\n * @param {Array<ChildNode>} children - The children of the parent node.\n * @param {number} start - The start index of the children.\n * @param {number} end - The end index of the children.\n * @returns {KeyMap} A key map for the children.\n */\n _createKeyMap(children, start, end) {\n const map = new Map();\n for (let i = start; i <= end; i++) {\n const child = children[i];\n const key = this._getNodeKey(child);\n if (key) map.set(key, child);\n }\n return map;\n }\n\n /**\n * Extracts the key attribute from a node if it exists.\n *\n * @private\n * @param {Node} node - The node to extract the key from.\n * @returns {string|null} The key attribute value or null if not found.\n */\n _getNodeKey(node) {\n return node?.nodeType === Node.ELEMENT_NODE\n ? node.getAttribute(\"key\")\n : null;\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// TYPE DEFINITIONS - TypeScript-friendly JSDoc types for IDE support\n// ============================================================================\n\n// -----------------------------------------------------------------------------\n// Configuration Types\n// -----------------------------------------------------------------------------\n\n/**\n * @typedef {Object} ElevaConfig\n * @property {boolean} [debug=false]\n * Enable debug mode for verbose logging\n * @property {string} [prefix='e']\n * Prefix for component style scoping\n * @property {boolean} [async=true]\n * Enable async component setup\n */\n\n// -----------------------------------------------------------------------------\n// Component Types\n// -----------------------------------------------------------------------------\n\n/**\n * @typedef {Object} ComponentDefinition\n * @property {SetupFunction} [setup]\n * Optional setup function that initializes the component's state and returns reactive data\n * @property {TemplateFunction|string} template\n * Required function or string that defines the component's HTML structure\n * @property {StyleFunction|string} [style]\n * Optional function or string that provides component-scoped CSS styles\n * @property {ChildrenMap} [children]\n * Optional object defining nested child components\n */\n\n/**\n * @callback SetupFunction\n * @param {ComponentContext} ctx - The component context with props, emitter, and signal factory\n * @returns {SetupResult|Promise<SetupResult>} Reactive data and lifecycle hooks\n */\n\n/**\n * @typedef {Record<string, unknown> & LifecycleHooks} SetupResult\n * Data returned from setup function, may include lifecycle hooks\n */\n\n/**\n * @callback TemplateFunction\n * @param {ComponentContext} ctx - The component context\n * @returns {string|Promise<string>} HTML template string\n */\n\n/**\n * @callback StyleFunction\n * @param {ComponentContext} ctx - The component context\n * @returns {string} CSS styles string\n */\n\n/**\n * @typedef {Record<string, ComponentDefinition|string>} ChildrenMap\n * Map of CSS selectors to component definitions or registered component names\n */\n\n// -----------------------------------------------------------------------------\n// Context Types\n// -----------------------------------------------------------------------------\n\n/**\n * @typedef {Object} ComponentContext\n * @property {ComponentProps} props\n * Component properties passed during mounting\n * @property {Emitter} emitter\n * Event emitter instance for component event handling\n * @property {SignalFactory} signal\n * Factory function to create reactive Signal instances\n */\n\n/**\n * @typedef {Record<string, unknown>} ComponentProps\n * Properties passed to a component during mounting\n */\n\n/**\n * @callback SignalFactory\n * @template T\n * @param {T} initialValue - The initial value for the signal\n * @returns {Signal<T>} A new Signal instance\n */\n\n// -----------------------------------------------------------------------------\n// Lifecycle Hook Types\n// -----------------------------------------------------------------------------\n\n/**\n * @typedef {Object} LifecycleHooks\n * @property {LifecycleHook} [onBeforeMount]\n * Hook called before component mounting\n * @property {LifecycleHook} [onMount]\n * Hook called after component mounting\n * @property {LifecycleHook} [onBeforeUpdate]\n * Hook called before component update\n * @property {LifecycleHook} [onUpdate]\n * Hook called after component update\n * @property {UnmountHook} [onUnmount]\n * Hook called during component unmounting\n */\n\n/**\n * @callback LifecycleHook\n * @param {LifecycleHookContext} ctx - Context with container and component data\n * @returns {void|Promise<void>}\n */\n\n/**\n * @callback UnmountHook\n * @param {UnmountHookContext} ctx - Context with cleanup resources\n * @returns {void|Promise<void>}\n */\n\n/**\n * @typedef {Object} LifecycleHookContext\n * @property {HTMLElement} container\n * The DOM element where the component is mounted\n * @property {ComponentContext & SetupResult} context\n * The component's reactive state and context data\n */\n\n/**\n * @typedef {Object} UnmountHookContext\n * @property {HTMLElement} container\n * The DOM element where the component is mounted\n * @property {ComponentContext & SetupResult} context\n * The component's reactive state and context data\n * @property {CleanupResources} cleanup\n * Object containing cleanup functions and instances\n */\n\n/**\n * @typedef {Object} CleanupResources\n * @property {Array<UnsubscribeFunction>} watchers\n * Signal watcher cleanup functions\n * @property {Array<UnsubscribeFunction>} listeners\n * Event listener cleanup functions\n * @property {Array<MountResult>} children\n * Child component instances\n */\n\n// -----------------------------------------------------------------------------\n// Mount Result Types\n// -----------------------------------------------------------------------------\n\n/**\n * @typedef {Object} MountResult\n * @property {HTMLElement} container\n * The DOM element where the component is mounted\n * @property {ComponentContext & SetupResult} data\n * The component's reactive state and context data\n * @property {UnmountFunction} unmount\n * Function to clean up and unmount the component\n */\n\n/**\n * @callback UnmountFunction\n * @returns {Promise<void>}\n */\n\n/**\n * @callback UnsubscribeFunction\n * @returns {void|boolean}\n */\n\n// -----------------------------------------------------------------------------\n// Plugin Types\n// -----------------------------------------------------------------------------\n\n/**\n * @typedef {Object} ElevaPlugin\n * @property {PluginInstallFunction} install\n * Function that installs the plugin into the Eleva instance\n * @property {string} name\n * Unique identifier name for the plugin\n * @property {PluginUninstallFunction} [uninstall]\n * Optional function to uninstall the plugin\n */\n\n/**\n * @callback PluginInstallFunction\n * @param {Eleva} eleva - The Eleva instance\n * @param {PluginOptions} options - Plugin configuration options\n * @returns {void|Eleva|unknown} Optionally returns the Eleva instance or plugin result\n */\n\n/**\n * @callback PluginUninstallFunction\n * @param {Eleva} eleva - The Eleva instance\n * @returns {void}\n */\n\n/**\n * @typedef {Record<string, unknown>} PluginOptions\n * Configuration options passed to a plugin during installation\n */\n\n// -----------------------------------------------------------------------------\n// Event Types\n// -----------------------------------------------------------------------------\n\n/**\n * @callback EventHandler\n * @param {Event} event - The DOM event object\n * @returns {void}\n */\n\n/**\n * @typedef {'click'|'submit'|'input'|'change'|'focus'|'blur'|'keydown'|'keyup'|'keypress'|'mouseenter'|'mouseleave'|'mouseover'|'mouseout'|'mousedown'|'mouseup'|'touchstart'|'touchend'|'touchmove'|'scroll'|'resize'|'load'|'error'|string} DOMEventName\n * Common DOM event names (prefixed with @ in templates)\n */\n\n/**\n * @class 🧩 Eleva\n * @classdesc A modern, signal-based component runtime framework that provides lifecycle hooks,\n * scoped styles, and plugin support. Eleva manages component registration, plugin integration,\n * event handling, and DOM rendering with a focus on performance and developer experience.\n *\n * @example\n * // Basic component creation and mounting\n * const app = new Eleva(\"myApp\");\n * app.component(\"myComponent\", {\n * setup: (ctx) => ({ count: ctx.signal(0) }),\n * template: (ctx) => `<div>Hello ${ctx.props.name}</div>`\n * });\n * app.mount(document.getElementById(\"app\"), \"myComponent\", { name: \"World\" });\n *\n * @example\n * // Using lifecycle hooks\n * app.component(\"lifecycleDemo\", {\n * setup: () => {\n * return {\n * onMount: ({ container, context }) => {\n * console.log('Component mounted!');\n * }\n * };\n * },\n * template: `<div>Lifecycle Demo</div>`\n * });\n */\nexport class Eleva {\n /**\n * Creates a new Eleva instance with the specified name and configuration.\n *\n * @public\n * @param {string} name - The unique identifier name for this Eleva instance.\n * @param {Record<string, unknown>} [config={}] - Optional configuration object for the instance.\n * May include framework-wide settings and default behaviors.\n * @throws {Error} If the name is not provided or is not a string.\n * @returns {Eleva} A new Eleva instance.\n *\n * @example\n * const app = new Eleva(\"myApp\");\n * app.component(\"myComponent\", {\n * setup: (ctx) => ({ count: ctx.signal(0) }),\n * template: (ctx) => `<div>Hello ${ctx.props.name}!</div>`\n * });\n * app.mount(document.getElementById(\"app\"), \"myComponent\", { name: \"World\" });\n *\n */\n constructor(name, config = {}) {\n /** @public {string} The unique identifier name for this Eleva instance */\n this.name = name;\n /** @public {Object<string, unknown>} Optional configuration object for the Eleva instance */\n this.config = config;\n /** @public {Emitter} Instance of the event emitter for handling component events */\n this.emitter = new Emitter();\n /** @public {typeof Signal} Static reference to the Signal class for creating reactive state */\n this.signal = Signal;\n /** @public {typeof TemplateEngine} Static reference to the TemplateEngine class for template parsing */\n this.templateEngine = TemplateEngine;\n /** @public {Renderer} Instance of the renderer for handling DOM updates and patching */\n this.renderer = new Renderer();\n\n /** @private {Map<string, ComponentDefinition>} Registry of all component definitions by name */\n this._components = new Map();\n /** @private {Map<string, ElevaPlugin>} Collection of installed plugin instances by name */\n this._plugins = new Map();\n /** @private {number} Counter for generating unique component IDs */\n this._componentCounter = 0;\n }\n\n /**\n * Integrates a plugin with the Eleva framework.\n * The plugin's install function will be called with the Eleva instance and provided options.\n * After installation, the plugin will be available for use by components.\n *\n * Note: Plugins that wrap core methods (e.g., mount) must be uninstalled in reverse order\n * of installation (LIFO - Last In, First Out) to avoid conflicts.\n *\n * @public\n * @param {ElevaPlugin} plugin - The plugin object which must have an `install` function.\n * @param {Object<string, unknown>} [options={}] - Optional configuration options for the plugin.\n * @returns {Eleva} The Eleva instance (for method chaining).\n * @example\n * app.use(myPlugin, { option1: \"value1\" });\n *\n * @example\n * // Correct uninstall order (LIFO)\n * app.use(PluginA);\n * app.use(PluginB);\n * // Uninstall in reverse order:\n * PluginB.uninstall(app);\n * PluginA.uninstall(app);\n */\n use(plugin, options = {}) {\n this._plugins.set(plugin.name, plugin);\n const result = plugin.install(this, options);\n\n return result !== undefined ? result : this;\n }\n\n /**\n * Registers a new component with the Eleva instance.\n * The component will be available for mounting using its registered name.\n *\n * @public\n * @param {string} name - The unique name of the component to register.\n * @param {ComponentDefinition} definition - The component definition including setup, template, style, and children.\n * @returns {Eleva} The Eleva instance (for method chaining).\n * @throws {Error} If the component name is already registered.\n * @example\n * app.component(\"myButton\", {\n * template: (ctx) => `<button>${ctx.props.text}</button>`,\n * style: `button { color: blue; }`\n * });\n */\n component(name, definition) {\n /** @type {Map<string, ComponentDefinition>} */\n this._components.set(name, definition);\n return this;\n }\n\n /**\n * Mounts a registered component to a DOM element.\n * This will initialize the component, set up its reactive state, and render it to the DOM.\n *\n * @public\n * @param {HTMLElement} container - The DOM element where the component will be mounted.\n * @param {string|ComponentDefinition} compName - The name of the registered component or a direct component definition.\n * @param {Object<string, unknown>} [props={}] - Optional properties to pass to the component.\n * @returns {Promise<MountResult>}\n * A Promise that resolves to an object containing:\n * - container: The mounted component's container element\n * - data: The component's reactive state and context\n * - unmount: Function to clean up and unmount the component\n * @throws {Error} If the container is not found, or component is not registered.\n * @example\n * const instance = await app.mount(document.getElementById(\"app\"), \"myComponent\", { text: \"Click me\" });\n * // Later...\n * instance.unmount();\n */\n async mount(container, compName, props = {}) {\n if (!container) throw new Error(`Container not found: ${container}`);\n\n if (container._eleva_instance) return container._eleva_instance;\n\n /** @type {ComponentDefinition} */\n const definition =\n typeof compName === \"string\" ? this._components.get(compName) : compName;\n if (!definition) throw new Error(`Component \"${compName}\" not registered.`);\n\n /** @type {string} */\n const compId = `c${++this._componentCounter}`;\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 or string that returns the component's HTML structure\n * - style: Optional function or string for component-scoped CSS styles\n * - children: Optional object defining nested child components\n */\n const { setup, template, style, children } = definition;\n\n /** @type {ComponentContext} */\n const context = {\n props,\n emitter: this.emitter,\n /** @type {(v: unknown) => Signal<unknown>} */\n signal: (v) => new this.signal(v),\n };\n\n /**\n * Processes the mounting of the component.\n * This function handles:\n * 1. Merging setup data with the component context\n * 2. Setting up reactive watchers\n * 3. Rendering the component\n * 4. Managing component lifecycle\n *\n * @param {Object<string, unknown>} data - Data returned from the component's setup function\n * @returns {Promise<MountResult>} An object containing:\n * - container: The mounted component's container element\n * - data: The component's reactive state and context\n * - unmount: Function to clean up and unmount the component\n */\n const processMount = async (data) => {\n /** @type {ComponentContext} */\n const mergedContext = { ...context, ...data };\n /** @type {Array<() => void>} */\n const watchers = [];\n /** @type {Array<MountResult>} */\n const childInstances = [];\n /** @type {Array<() => void>} */\n const listeners = [];\n /** @private {boolean} Local mounted state for this component instance */\n let isMounted = false;\n\n // ========================================================================\n // Render Batching\n // ========================================================================\n\n /** @private {boolean} Flag to prevent multiple queued renders */\n let renderScheduled = false;\n\n /**\n * Schedules a batched render on the next microtask.\n * Multiple signal changes within the same synchronous block are collapsed into one render.\n * @private\n */\n const scheduleRender = () => {\n if (renderScheduled) return;\n renderScheduled = true;\n queueMicrotask(async () => {\n renderScheduled = false;\n await render();\n });\n };\n\n /**\n * Renders the component by:\n * 1. Executing lifecycle hooks\n * 2. Processing the template\n * 3. Updating the DOM\n * 4. Processing events, injecting styles, and mounting child components.\n */\n const render = async () => {\n const templateResult =\n typeof template === \"function\"\n ? await template(mergedContext)\n : template;\n const html = this.templateEngine.parse(templateResult, mergedContext);\n\n // Execute before hooks\n if (!isMounted) {\n await mergedContext.onBeforeMount?.({\n container,\n context: mergedContext,\n });\n } else {\n await mergedContext.onBeforeUpdate?.({\n container,\n context: mergedContext,\n });\n }\n\n this.renderer.patchDOM(container, html);\n this._processEvents(container, mergedContext, listeners);\n if (style) this._injectStyles(container, compId, style, mergedContext);\n if (children)\n await this._mountComponents(container, children, childInstances);\n\n // Execute after hooks\n if (!isMounted) {\n await mergedContext.onMount?.({\n container,\n context: mergedContext,\n });\n isMounted = true;\n } else {\n await mergedContext.onUpdate?.({\n container,\n context: mergedContext,\n });\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, a batched render is scheduled.\n * Multiple changes within the same frame are collapsed into one render.\n * Stores unsubscribe functions to clean up watchers when component unmounts.\n */\n for (const val of Object.values(data)) {\n if (val instanceof Signal) watchers.push(val.watch(scheduleRender));\n }\n\n await render();\n\n const instance = {\n container,\n data: mergedContext,\n /**\n * Unmounts the component, cleaning up watchers and listeners, child components, and clearing the container.\n *\n * @returns {void}\n */\n unmount: async () => {\n /** @type {UnmountHookContext} */\n await mergedContext.onUnmount?.({\n container,\n context: mergedContext,\n cleanup: {\n watchers: watchers,\n listeners: listeners,\n children: childInstances,\n },\n });\n for (const fn of watchers) fn();\n for (const fn of listeners) fn();\n for (const child of childInstances) await child.unmount();\n container.innerHTML = \"\";\n delete container._eleva_instance;\n },\n };\n\n container._eleva_instance = instance;\n return instance;\n };\n\n // Handle asynchronous setup.\n const setupResult = typeof setup === \"function\" ? await setup(context) : {};\n return await processMount(setupResult);\n }\n\n /**\n * Processes DOM elements for event binding based on attributes starting with \"@\".\n * This method handles the event delegation system and ensures proper cleanup of event listeners.\n *\n * @private\n * @param {HTMLElement} container - The container element in which to search for event attributes.\n * @param {ComponentContext} context - The current component context containing event handler definitions.\n * @param {Array<() => void>} listeners - Array to collect cleanup functions for each event listener.\n * @returns {void}\n */\n _processEvents(container, context, listeners) {\n /** @type {NodeListOf<Element>} */\n const elements = container.querySelectorAll(\"*\");\n for (const el of elements) {\n /** @type {NamedNodeMap} */\n const attrs = el.attributes;\n for (let i = 0; i < attrs.length; i++) {\n /** @type {Attr} */\n const attr = attrs[i];\n\n if (!attr.name.startsWith(\"@\")) continue;\n\n /** @type {keyof HTMLElementEventMap} */\n const event = attr.name.slice(1);\n /** @type {string} */\n const handlerName = attr.value;\n /** @type {(event: Event) => void} */\n const handler =\n context[handlerName] ||\n this.templateEngine.evaluate(handlerName, context);\n if (typeof handler === \"function\") {\n el.addEventListener(event, handler);\n el.removeAttribute(attr.name);\n listeners.push(() => el.removeEventListener(event, handler));\n }\n }\n }\n }\n\n /**\n * Injects scoped styles into the component's container.\n * The styles are automatically prefixed to prevent style leakage to other components.\n *\n * @private\n * @param {HTMLElement} container - The container element where styles should be injected.\n * @param {string} compId - The component ID used to identify the style element.\n * @param {(function(ComponentContext): string)|string} styleDef - The component's style definition (function or string).\n * @param {ComponentContext} context - The current component context for style interpolation.\n * @returns {void}\n */\n _injectStyles(container, compId, styleDef, context) {\n /** @type {string} */\n const newStyle =\n typeof styleDef === \"function\"\n ? this.templateEngine.parse(styleDef(context), context)\n : styleDef;\n\n /** @type {HTMLStyleElement|null} */\n let styleEl = container.querySelector(`style[data-e-style=\"${compId}\"]`);\n\n if (styleEl && styleEl.textContent === newStyle) return;\n if (!styleEl) {\n styleEl = document.createElement(\"style\");\n styleEl.setAttribute(\"data-e-style\", compId);\n container.appendChild(styleEl);\n }\n\n styleEl.textContent = newStyle;\n }\n\n /**\n * Extracts props from an element's attributes that start with the specified prefix.\n * This method is used to collect component properties from DOM elements.\n *\n * @private\n * @param {HTMLElement} element - The DOM element to extract props from\n * @returns {Record<string, string>} An object containing the extracted props\n * @example\n * // For an element with attributes:\n * // <div :name=\"John\" :age=\"25\">\n * // Returns: { name: \"John\", age: \"25\" }\n */\n _extractProps(element) {\n if (!element.attributes) return {};\n\n const props = {};\n const attrs = element.attributes;\n\n for (let i = attrs.length - 1; i >= 0; i--) {\n const attr = attrs[i];\n if (attr.name.startsWith(\":\")) {\n const propName = attr.name.slice(1);\n props[propName] = attr.value;\n element.removeAttribute(attr.name);\n }\n }\n return props;\n }\n\n /**\n * Mounts all components within the parent component's container.\n * This method handles mounting of explicitly defined children components.\n *\n * The mounting process follows these steps:\n * 1. Cleans up any existing component instances\n * 2. Mounts explicitly defined children components\n *\n * @private\n * @param {HTMLElement} container - The container element to mount components in\n * @param {Object<string, ComponentDefinition>} children - Map of selectors to component definitions for explicit children\n * @param {Array<MountResult>} childInstances - Array to store all mounted component instances\n * @returns {Promise<void>}\n *\n * @example\n * // Explicit children mounting:\n * const children = {\n * 'UserProfile': UserProfileComponent,\n * '#settings-panel': \"settings-panel\"\n * };\n */\n async _mountComponents(container, children, childInstances) {\n for (const [selector, component] of Object.entries(children)) {\n if (!selector) continue;\n for (const el of container.querySelectorAll(selector)) {\n if (!(el instanceof HTMLElement)) continue;\n /** @type {Record<string, string>} */\n const props = this._extractProps(el);\n /** @type {MountResult} */\n const instance = await this.mount(el, component, props);\n if (instance && !childInstances.includes(instance)) {\n childInstances.push(instance);\n }\n }\n }\n }\n}\n"],"names":["TemplateEngine","static","parse","template","data","replace","this","expressionPattern","_","expression","evaluate","Function","Signal","constructor","value","_value","_watchers","Set","_pending","newVal","_notify","watch","fn","add","delete","queueMicrotask","forEach","Emitter","_events","Map","on","event","handler","has","set","get","off","handlers","size","emit","args","Renderer","_tempContainer","document","createElement","patchDOM","container","newHtml","HTMLElement","TypeError","innerHTML","_diff","error","Error","message","oldParent","newParent","isEqualNode","oldChildren","Array","from","childNodes","newChildren","oldStartIdx","newStartIdx","oldEndIdx","length","newEndIdx","oldKeyMap","oldStartNode","newStartNode","_isSameNode","_patchNode","_createKeyMap","key","_getNodeKey","oldNodeToMove","insertBefore","indexOf","cloneNode","refNode","i","_removeNode","oldNode","newNode","_eleva_instance","nodeType","Node","ELEMENT_NODE","_updateAttributes","TEXT_NODE","nodeValue","replaceWith","parent","node","nodeName","hasAttribute","removeChild","oldEl","newEl","oldAttrs","attributes","newAttrs","name","startsWith","getAttribute","setAttribute","removeAttribute","oldKey","newKey","children","start","end","map","child","config","emitter","signal","templateEngine","renderer","_components","_plugins","_componentCounter","use","plugin","options","result","install","undefined","component","definition","mount","compName","props","compId","setup","style","context","v","setupResult","async","mergedContext","watchers","childInstances","listeners","isMounted","renderScheduled","scheduleRender","render","templateResult","html","onBeforeUpdate","onBeforeMount","_processEvents","_injectStyles","_mountComponents","onUpdate","onMount","val","Object","values","push","instance","unmount","onUnmount","cleanup","processMount","elements","querySelectorAll","el","attrs","attr","slice","handlerName","addEventListener","removeEventListener","styleDef","newStyle","styleEl","querySelector","textContent","appendChild","_extractProps","element","selector","entries","includes"],"mappings":";yCAmEO,MAAMA,EASXC,yBAA2B,uBAwC3B,YAAOC,CAAMC,EAAUC,GACrB,MAAwB,iBAAbD,EAA8BA,EAClCA,EAASE,QAAQC,KAAKC,kBAAmB,CAACC,EAAGC,IAClDH,KAAKI,SAASD,EAAYL,GAE9B,CA2CA,eAAOM,CAASD,EAAYL,GAC1B,GAA0B,iBAAfK,EAAyB,OAAOA,EAC3C,IACE,OAAO,IAAIE,SAAS,OAAQ,uBAAuBF,OAA5C,CAA6DL,EACtE,CAAE,MACA,MAAO,EACT,CACF,EClHK,MAAMQ,EAqBXC,WAAAA,CAAYC,GAMVR,KAAKS,OAASD,EAMdR,KAAKU,UAAY,IAAIC,IAMrBX,KAAKY,UAAW,CAClB,CAQA,SAAIJ,GACF,OAAOR,KAAKS,MACd,CAUA,SAAID,CAAMK,GACJb,KAAKS,SAAWI,IAEpBb,KAAKS,OAASI,EACdb,KAAKc,UACP,CAwBAC,KAAAA,CAAMC,GAEJ,OADAhB,KAAKU,UAAUO,IAAID,GACZ,IAAMhB,KAAKU,UAAUQ,OAAOF,EACrC,CAUAF,OAAAA,GACMd,KAAKY,WAETZ,KAAKY,UAAW,EAChBO,eAAe,KAEbnB,KAAKU,UAAUU,QAASJ,GAAOA,EAAGhB,KAAKS,SACvCT,KAAKY,UAAW,IAEpB,EC9FK,MAAMS,EASXd,WAAAA,GAMEP,KAAKsB,QAAU,IAAIC,GACrB,CA2BAC,EAAAA,CAAGC,EAAOC,GAIR,OAHK1B,KAAKsB,QAAQK,IAAIF,IAAQzB,KAAKsB,QAAQM,IAAIH,EAAO,IAAId,KAE1DX,KAAKsB,QAAQO,IAAIJ,GAAOR,IAAIS,GACrB,IAAM1B,KAAK8B,IAAIL,EAAOC,EAC/B,CAuBAI,GAA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exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
4
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
5
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ElevaAttrPlugin = {}));
6
+ })(this, (function (exports) { 'use strict';
7
+
8
+ /**
9
+ * A regular expression to match hyphenated lowercase letters.
10
+ * @private
11
+ * @type {RegExp}
12
+ */
13
+ const CAMEL_RE = /-([a-z])/g;
14
+
15
+ /**
16
+ * @class 🎯 AttrPlugin
17
+ * @classdesc A plugin that provides advanced attribute handling for Eleva components.
18
+ * This plugin extends the renderer with sophisticated attribute processing including:
19
+ * - ARIA attribute handling with proper property mapping
20
+ * - Data attribute management
21
+ * - Boolean attribute processing
22
+ * - Dynamic property detection and mapping
23
+ * - Attribute cleanup and removal
24
+ *
25
+ * @example
26
+ * // Install the plugin
27
+ * const app = new Eleva("myApp");
28
+ * app.use(AttrPlugin);
29
+ *
30
+ * // Use advanced attributes in components
31
+ * app.component("myComponent", {
32
+ * template: (ctx) => `
33
+ * <button
34
+ * aria-expanded="${ctx.isExpanded.value}"
35
+ * data-user-id="${ctx.userId.value}"
36
+ * disabled="${ctx.isLoading.value}"
37
+ * class="btn ${ctx.variant.value}"
38
+ * >
39
+ * ${ctx.text.value}
40
+ * </button>
41
+ * `
42
+ * });
43
+ */
44
+ const AttrPlugin = {
45
+ /**
46
+ * Unique identifier for the plugin
47
+ * @type {string}
48
+ */
49
+ name: "attr",
50
+ /**
51
+ * Plugin version
52
+ * @type {string}
53
+ */
54
+ version: "1.0.0-rc.11",
55
+ /**
56
+ * Plugin description
57
+ * @type {string}
58
+ */
59
+ description: "Advanced attribute handling for Eleva components",
60
+ /**
61
+ * Installs the plugin into the Eleva instance
62
+ *
63
+ * @param {Object} eleva - The Eleva instance
64
+ * @param {Object} options - Plugin configuration options
65
+ * @param {boolean} [options.enableAria=true] - Enable ARIA attribute handling
66
+ * @param {boolean} [options.enableData=true] - Enable data attribute handling
67
+ * @param {boolean} [options.enableBoolean=true] - Enable boolean attribute handling
68
+ * @param {boolean} [options.enableDynamic=true] - Enable dynamic property detection
69
+ */
70
+ install(eleva, options = {}) {
71
+ const {
72
+ enableAria = true,
73
+ enableData = true,
74
+ enableBoolean = true,
75
+ enableDynamic = true
76
+ } = options;
77
+
78
+ /**
79
+ * Updates the attributes of an element to match a new element's attributes.
80
+ * This method provides sophisticated attribute processing including:
81
+ * - ARIA attribute handling with proper property mapping
82
+ * - Data attribute management
83
+ * - Boolean attribute processing
84
+ * - Dynamic property detection and mapping
85
+ * - Attribute cleanup and removal
86
+ *
87
+ * @param {HTMLElement} oldEl - The original element to update
88
+ * @param {HTMLElement} newEl - The new element to update
89
+ * @returns {void}
90
+ */
91
+ const updateAttributes = (oldEl, newEl) => {
92
+ const oldAttrs = oldEl.attributes;
93
+ const newAttrs = newEl.attributes;
94
+
95
+ // Process new attributes
96
+ for (let i = 0; i < newAttrs.length; i++) {
97
+ const {
98
+ name,
99
+ value
100
+ } = newAttrs[i];
101
+
102
+ // Skip event attributes (handled by event system)
103
+ if (name.startsWith("@")) continue;
104
+
105
+ // Skip if attribute hasn't changed
106
+ if (oldEl.getAttribute(name) === value) continue;
107
+
108
+ // Handle ARIA attributes
109
+ if (enableAria && name.startsWith("aria-")) {
110
+ const prop = "aria" + name.slice(5).replace(CAMEL_RE, (_, l) => l.toUpperCase());
111
+ oldEl[prop] = value;
112
+ oldEl.setAttribute(name, value);
113
+ }
114
+ // Handle data attributes
115
+ else if (enableData && name.startsWith("data-")) {
116
+ oldEl.dataset[name.slice(5)] = value;
117
+ oldEl.setAttribute(name, value);
118
+ }
119
+ // Handle other attributes
120
+ else {
121
+ let prop = name.replace(CAMEL_RE, (_, l) => l.toUpperCase());
122
+
123
+ // Dynamic property detection
124
+ if (enableDynamic && !(prop in oldEl) && !Object.getOwnPropertyDescriptor(Object.getPrototypeOf(oldEl), prop)) {
125
+ const elementProps = Object.getOwnPropertyNames(Object.getPrototypeOf(oldEl));
126
+ const matchingProp = elementProps.find(p => p.toLowerCase() === name.toLowerCase() || p.toLowerCase().includes(name.toLowerCase()) || name.toLowerCase().includes(p.toLowerCase()));
127
+ if (matchingProp) {
128
+ prop = matchingProp;
129
+ }
130
+ }
131
+ const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(oldEl), prop);
132
+ const hasProperty = prop in oldEl || descriptor;
133
+ if (hasProperty) {
134
+ // Boolean attribute handling
135
+ if (enableBoolean) {
136
+ const isBoolean = typeof oldEl[prop] === "boolean" || descriptor?.get && typeof descriptor.get.call(oldEl) === "boolean";
137
+ if (isBoolean) {
138
+ const boolValue = value !== "false" && (value === "" || value === prop || value === "true");
139
+ oldEl[prop] = boolValue;
140
+ if (boolValue) {
141
+ oldEl.setAttribute(name, "");
142
+ } else {
143
+ oldEl.removeAttribute(name);
144
+ }
145
+ } else {
146
+ oldEl[prop] = value;
147
+ oldEl.setAttribute(name, value);
148
+ }
149
+ } else {
150
+ oldEl[prop] = value;
151
+ oldEl.setAttribute(name, value);
152
+ }
153
+ } else {
154
+ oldEl.setAttribute(name, value);
155
+ }
156
+ }
157
+ }
158
+
159
+ // Remove old attributes that are no longer present
160
+ for (let i = oldAttrs.length - 1; i >= 0; i--) {
161
+ const name = oldAttrs[i].name;
162
+ if (!newEl.hasAttribute(name)) {
163
+ oldEl.removeAttribute(name);
164
+ }
165
+ }
166
+ };
167
+
168
+ // Extend the renderer with the advanced attribute handler
169
+ if (eleva.renderer) {
170
+ eleva.renderer.updateAttributes = updateAttributes;
171
+
172
+ // Store the original _patchNode method
173
+ const originalPatchNode = eleva.renderer._patchNode;
174
+ eleva.renderer._originalPatchNode = originalPatchNode;
175
+
176
+ // Override the _patchNode method to use our attribute handler
177
+ eleva.renderer._patchNode = function (oldNode, newNode) {
178
+ if (oldNode?._eleva_instance) return;
179
+ if (!this._isSameNode(oldNode, newNode)) {
180
+ oldNode.replaceWith(newNode.cloneNode(true));
181
+ return;
182
+ }
183
+ if (oldNode.nodeType === Node.ELEMENT_NODE) {
184
+ updateAttributes(oldNode, newNode);
185
+ this._diff(oldNode, newNode);
186
+ } else if (oldNode.nodeType === Node.TEXT_NODE && oldNode.nodeValue !== newNode.nodeValue) {
187
+ oldNode.nodeValue = newNode.nodeValue;
188
+ }
189
+ };
190
+ }
191
+
192
+ // Add plugin metadata to the Eleva instance
193
+ if (!eleva.plugins) {
194
+ eleva.plugins = new Map();
195
+ }
196
+ eleva.plugins.set(this.name, {
197
+ name: this.name,
198
+ version: this.version,
199
+ description: this.description,
200
+ options
201
+ });
202
+
203
+ // Add utility methods for manual attribute updates
204
+ eleva.updateElementAttributes = updateAttributes;
205
+ },
206
+ /**
207
+ * Uninstalls the plugin from the Eleva instance
208
+ *
209
+ * @param {Object} eleva - The Eleva instance
210
+ */
211
+ uninstall(eleva) {
212
+ // Restore original _patchNode method if it exists
213
+ if (eleva.renderer && eleva.renderer._originalPatchNode) {
214
+ eleva.renderer._patchNode = eleva.renderer._originalPatchNode;
215
+ delete eleva.renderer._originalPatchNode;
216
+ }
217
+
218
+ // Remove plugin metadata
219
+ if (eleva.plugins) {
220
+ eleva.plugins.delete(this.name);
221
+ }
222
+
223
+ // Remove utility methods
224
+ delete eleva.updateElementAttributes;
225
+ }
226
+ };
227
+
228
+ exports.Attr = AttrPlugin;
229
+ exports.AttrPlugin = AttrPlugin;
230
+
231
+ }));
232
+ //# sourceMappingURL=attr.umd.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"attr.umd.js","sources":["../../src/plugins/Attr.js"],"sourcesContent":["\"use strict\";\n\n/**\n * A regular expression to match hyphenated lowercase letters.\n * @private\n * @type {RegExp}\n */\nconst CAMEL_RE = /-([a-z])/g;\n\n/**\n * @class 🎯 AttrPlugin\n * @classdesc A plugin that provides advanced attribute handling for Eleva components.\n * This plugin extends the renderer with sophisticated attribute processing including:\n * - ARIA attribute handling with proper property mapping\n * - Data attribute management\n * - Boolean attribute processing\n * - Dynamic property detection and mapping\n * - Attribute cleanup and removal\n *\n * @example\n * // Install the plugin\n * const app = new Eleva(\"myApp\");\n * app.use(AttrPlugin);\n *\n * // Use advanced attributes in components\n * app.component(\"myComponent\", {\n * template: (ctx) => `\n * <button\n * aria-expanded=\"${ctx.isExpanded.value}\"\n * data-user-id=\"${ctx.userId.value}\"\n * disabled=\"${ctx.isLoading.value}\"\n * class=\"btn ${ctx.variant.value}\"\n * >\n * ${ctx.text.value}\n * </button>\n * `\n * });\n */\nexport const AttrPlugin = {\n /**\n * Unique identifier for the plugin\n * @type {string}\n */\n name: \"attr\",\n\n /**\n * Plugin version\n * @type {string}\n */\n version: \"1.0.0-rc.11\",\n\n /**\n * Plugin description\n * @type {string}\n */\n description: \"Advanced attribute handling for Eleva components\",\n\n /**\n * Installs the plugin into the Eleva instance\n *\n * @param {Object} eleva - The Eleva instance\n * @param {Object} options - Plugin configuration options\n * @param {boolean} [options.enableAria=true] - Enable ARIA attribute handling\n * @param {boolean} [options.enableData=true] - Enable data attribute handling\n * @param {boolean} [options.enableBoolean=true] - Enable boolean attribute handling\n * @param {boolean} [options.enableDynamic=true] - Enable dynamic property detection\n */\n install(eleva, options = {}) {\n const {\n enableAria = true,\n enableData = true,\n enableBoolean = true,\n enableDynamic = true,\n } = options;\n\n /**\n * Updates the attributes of an element to match a new element's attributes.\n * This method provides sophisticated attribute processing including:\n * - ARIA attribute handling with proper property mapping\n * - Data attribute management\n * - Boolean attribute processing\n * - Dynamic property detection and mapping\n * - Attribute cleanup and removal\n *\n * @param {HTMLElement} oldEl - The original element to update\n * @param {HTMLElement} newEl - The new element to update\n * @returns {void}\n */\n const updateAttributes = (oldEl, newEl) => {\n const oldAttrs = oldEl.attributes;\n const newAttrs = newEl.attributes;\n\n // Process new attributes\n for (let i = 0; i < newAttrs.length; i++) {\n const { name, value } = newAttrs[i];\n\n // Skip event attributes (handled by event system)\n if (name.startsWith(\"@\")) continue;\n\n // Skip if attribute hasn't changed\n if (oldEl.getAttribute(name) === value) continue;\n\n // Handle ARIA attributes\n if (enableAria && name.startsWith(\"aria-\")) {\n const prop =\n \"aria\" + name.slice(5).replace(CAMEL_RE, (_, l) => l.toUpperCase());\n oldEl[prop] = value;\n oldEl.setAttribute(name, value);\n }\n // Handle data attributes\n else if (enableData && name.startsWith(\"data-\")) {\n oldEl.dataset[name.slice(5)] = value;\n oldEl.setAttribute(name, value);\n }\n // Handle other attributes\n else {\n let prop = name.replace(CAMEL_RE, (_, l) => l.toUpperCase());\n\n // Dynamic property detection\n if (\n enableDynamic &&\n !(prop in oldEl) &&\n !Object.getOwnPropertyDescriptor(Object.getPrototypeOf(oldEl), prop)\n ) {\n const elementProps = Object.getOwnPropertyNames(\n Object.getPrototypeOf(oldEl)\n );\n const matchingProp = elementProps.find(\n (p) =>\n p.toLowerCase() === name.toLowerCase() ||\n p.toLowerCase().includes(name.toLowerCase()) ||\n name.toLowerCase().includes(p.toLowerCase())\n );\n\n if (matchingProp) {\n prop = matchingProp;\n }\n }\n\n const descriptor = Object.getOwnPropertyDescriptor(\n Object.getPrototypeOf(oldEl),\n prop\n );\n const hasProperty = prop in oldEl || descriptor;\n\n if (hasProperty) {\n // Boolean attribute handling\n if (enableBoolean) {\n const isBoolean =\n typeof oldEl[prop] === \"boolean\" ||\n (descriptor?.get &&\n typeof descriptor.get.call(oldEl) === \"boolean\");\n\n if (isBoolean) {\n const boolValue =\n value !== \"false\" &&\n (value === \"\" || value === prop || value === \"true\");\n oldEl[prop] = boolValue;\n\n if (boolValue) {\n oldEl.setAttribute(name, \"\");\n } else {\n oldEl.removeAttribute(name);\n }\n } else {\n oldEl[prop] = value;\n oldEl.setAttribute(name, value);\n }\n } else {\n oldEl[prop] = value;\n oldEl.setAttribute(name, value);\n }\n } else {\n oldEl.setAttribute(name, value);\n }\n }\n }\n\n // Remove old attributes that are no longer present\n for (let i = oldAttrs.length - 1; i >= 0; i--) {\n const name = oldAttrs[i].name;\n if (!newEl.hasAttribute(name)) {\n oldEl.removeAttribute(name);\n }\n }\n };\n\n // Extend the renderer with the advanced attribute handler\n if (eleva.renderer) {\n eleva.renderer.updateAttributes = updateAttributes;\n\n // Store the original _patchNode method\n const originalPatchNode = eleva.renderer._patchNode;\n eleva.renderer._originalPatchNode = originalPatchNode;\n\n // Override the _patchNode method to use our attribute handler\n eleva.renderer._patchNode = function (oldNode, newNode) {\n if (oldNode?._eleva_instance) return;\n\n if (!this._isSameNode(oldNode, newNode)) {\n oldNode.replaceWith(newNode.cloneNode(true));\n return;\n }\n\n if (oldNode.nodeType === Node.ELEMENT_NODE) {\n updateAttributes(oldNode, newNode);\n this._diff(oldNode, newNode);\n } else if (\n oldNode.nodeType === Node.TEXT_NODE &&\n oldNode.nodeValue !== newNode.nodeValue\n ) {\n oldNode.nodeValue = newNode.nodeValue;\n }\n };\n }\n\n // Add plugin metadata to the Eleva instance\n if (!eleva.plugins) {\n eleva.plugins = new Map();\n }\n eleva.plugins.set(this.name, {\n name: this.name,\n version: this.version,\n description: this.description,\n options,\n });\n\n // Add utility methods for manual attribute updates\n eleva.updateElementAttributes = updateAttributes;\n },\n\n /**\n * Uninstalls the plugin from the Eleva instance\n *\n * @param {Object} eleva - The Eleva instance\n */\n uninstall(eleva) {\n // Restore original _patchNode method if it exists\n if (eleva.renderer && eleva.renderer._originalPatchNode) {\n eleva.renderer._patchNode = eleva.renderer._originalPatchNode;\n delete eleva.renderer._originalPatchNode;\n }\n\n // Remove plugin metadata\n if (eleva.plugins) {\n eleva.plugins.delete(this.name);\n }\n\n // Remove utility methods\n delete eleva.updateElementAttributes;\n },\n};\n\n// Short name export for convenience\nexport { AttrPlugin as Attr };\n"],"names":["CAMEL_RE","AttrPlugin","name","version","description","install","eleva","options","enableAria","enableData","enableBoolean","enableDynamic","updateAttributes","oldEl","newEl","oldAttrs","attributes","newAttrs","i","length","value","startsWith","getAttribute","prop","slice","replace","_","l","toUpperCase","setAttribute","dataset","Object","getOwnPropertyDescriptor","getPrototypeOf","elementProps","getOwnPropertyNames","matchingProp","find","p","toLowerCase","includes","descriptor","hasProperty","isBoolean","get","call","boolValue","removeAttribute","hasAttribute","renderer","originalPatchNode","_patchNode","_originalPatchNode","oldNode","newNode","_eleva_instance","_isSameNode","replaceWith","cloneNode","nodeType","Node","ELEMENT_NODE","_diff","TEXT_NODE","nodeValue","plugins","Map","set","updateElementAttributes","uninstall","delete"],"mappings":";;;;;;;EAEA;EACA;EACA;EACA;EACA;EACA,MAAMA,QAAQ,GAAG,WAAW;;EAE5B;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;AACO,QAAMC,UAAU,GAAG;EACxB;EACF;EACA;EACA;EACEC,EAAAA,IAAI,EAAE,MAAM;EAEZ;EACF;EACA;EACA;EACEC,EAAAA,OAAO,EAAE,aAAa;EAEtB;EACF;EACA;EACA;EACEC,EAAAA,WAAW,EAAE,kDAAkD;EAE/D;EACF;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACEC,EAAAA,OAAOA,CAACC,KAAK,EAAEC,OAAO,GAAG,EAAE,EAAE;MAC3B,MAAM;EACJC,MAAAA,UAAU,GAAG,IAAI;EACjBC,MAAAA,UAAU,GAAG,IAAI;EACjBC,MAAAA,aAAa,GAAG,IAAI;EACpBC,MAAAA,aAAa,GAAG;EAClB,KAAC,GAAGJ,OAAO;;EAEX;EACJ;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACI,IAAA,MAAMK,gBAAgB,GAAGA,CAACC,KAAK,EAAEC,KAAK,KAAK;EACzC,MAAA,MAAMC,QAAQ,GAAGF,KAAK,CAACG,UAAU;EACjC,MAAA,MAAMC,QAAQ,GAAGH,KAAK,CAACE,UAAU;;EAEjC;EACA,MAAA,KAAK,IAAIE,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGD,QAAQ,CAACE,MAAM,EAAED,CAAC,EAAE,EAAE;UACxC,MAAM;YAAEhB,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AC2C,QAAQ,CAACG,kBAAkB;EAC1C,IAAA;;EAEA;MACA,IAAI9C,KAAK,CAAC2D,OAAO,EAAE;QACjB3D,KAAK,CAAC2D,OAAO,CAACK,MAAM,CAAC,IAAI,CAACpE,IAAI,CAAC;EACjC,IAAA;;EAEA;MACA,OAAOI,KAAK,CAAC8D,uBAAuB;EACtC,EAAA;EACF;;;;;;;;;"}
@@ -0,0 +1,3 @@
1
+ /*! Eleva Attr Plugin v1.0.0-rc.11 | MIT License | https://elevajs.com */
2
+ var e,t;e=this,t=function(e){"use strict";const t=/-([a-z])/g,r={name:"attr",version:"1.0.0-rc.11",description:"Advanced attribute handling for Eleva components",install(e,r={}){const{enableAria:n=!0,enableData:o=!0,enableBoolean:i=!0,enableDynamic:a=!0}=r,s=(e,r)=>{const s=e.attributes,l=r.attributes;for(let r=0;r<l.length;r++){const{name:s,value:d}=l[r];if(!s.startsWith("@")&&e.getAttribute(s)!==d)if(n&&s.startsWith("aria-"))e["aria"+s.slice(5).replace(t,(e,t)=>t.toUpperCase())]=d,e.setAttribute(s,d);else if(o&&s.startsWith("data-"))e.dataset[s.slice(5)]=d,e.setAttribute(s,d);else{let r=s.replace(t,(e,t)=>t.toUpperCase());if(a&&!(r in e)&&!Object.getOwnPropertyDescriptor(Object.getPrototypeOf(e),r)){const t=Object.getOwnPropertyNames(Object.getPrototypeOf(e)).find(e=>e.toLowerCase()===s.toLowerCase()||e.toLowerCase().includes(s.toLowerCase())||s.toLowerCase().includes(e.toLowerCase()));t&&(r=t)}const n=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(e),r);if(r in e||n)if(i)if("boolean"==typeof e[r]||n?.get&&"boolean"==typeof n.get.call(e)){const t="false"!==d&&(""===d||d===r||"true"===d);e[r]=t,t?e.setAttribute(s,""):e.removeAttribute(s)}else e[r]=d,e.setAttribute(s,d);else e[r]=d,e.setAttribute(s,d);else e.setAttribute(s,d)}}for(let t=s.length-1;t>=0;t--){const n=s[t].name;r.hasAttribute(n)||e.removeAttribute(n)}};e.renderer&&(e.renderer.updateAttributes=s,e.renderer._originalPatchNode=e.renderer._patchNode,e.renderer._patchNode=function(e,t){e?._eleva_instance||(this._isSameNode(e,t)?e.nodeType===Node.ELEMENT_NODE?(s(e,t),this._diff(e,t)):e.nodeType===Node.TEXT_NODE&&e.nodeValue!==t.nodeValue&&(e.nodeValue=t.nodeValue):e.replaceWith(t.cloneNode(!0)))}),e.plugins||(e.plugins=new Map),e.plugins.set(this.name,{name:this.name,version:this.version,description:this.description,options:r}),e.updateElementAttributes=s},uninstall(e){e.renderer&&e.renderer._originalPatchNode&&(e.renderer._patchNode=e.renderer._originalPatchNode,delete e.renderer._originalPatchNode),e.plugins&&e.plugins.delete(this.name),delete e.updateElementAttributes}};e.Attr=r,e.AttrPlugin=r},"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).ElevaAttrPlugin={});
3
+ //# sourceMappingURL=attr.umd.min.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"attr.umd.min.js","sources":["../../src/plugins/Attr.js"],"sourcesContent":["\"use strict\";\n\n/**\n * A regular expression to match hyphenated lowercase letters.\n * @private\n * @type {RegExp}\n */\nconst CAMEL_RE = /-([a-z])/g;\n\n/**\n * @class 🎯 AttrPlugin\n * @classdesc A plugin that provides advanced attribute handling for Eleva components.\n * This plugin extends the renderer with sophisticated attribute processing including:\n * - ARIA attribute handling with proper property mapping\n * - Data attribute management\n * - Boolean attribute processing\n * - Dynamic property detection and mapping\n * - Attribute cleanup and removal\n *\n * @example\n * // Install the plugin\n * const app = new Eleva(\"myApp\");\n * app.use(AttrPlugin);\n *\n * // Use advanced attributes in components\n * app.component(\"myComponent\", {\n * template: (ctx) => `\n * <button\n * aria-expanded=\"${ctx.isExpanded.value}\"\n * data-user-id=\"${ctx.userId.value}\"\n * disabled=\"${ctx.isLoading.value}\"\n * class=\"btn ${ctx.variant.value}\"\n * >\n * ${ctx.text.value}\n * </button>\n * `\n * });\n */\nexport const AttrPlugin = {\n /**\n * Unique identifier for the plugin\n * @type {string}\n */\n name: \"attr\",\n\n /**\n * Plugin version\n * @type {string}\n */\n version: \"1.0.0-rc.11\",\n\n /**\n * Plugin description\n * @type {string}\n */\n description: \"Advanced attribute handling for Eleva components\",\n\n /**\n * Installs the plugin into the Eleva instance\n *\n * @param {Object} eleva - The Eleva instance\n * @param {Object} options - Plugin configuration options\n * @param {boolean} [options.enableAria=true] - Enable ARIA attribute handling\n * @param {boolean} [options.enableData=true] - Enable data attribute handling\n * @param {boolean} [options.enableBoolean=true] - Enable boolean attribute handling\n * @param {boolean} [options.enableDynamic=true] - Enable dynamic property detection\n */\n install(eleva, options = {}) {\n const {\n enableAria = true,\n enableData = true,\n enableBoolean = true,\n enableDynamic = true,\n } = options;\n\n /**\n * Updates the attributes of an element to match a new element's attributes.\n * This method provides sophisticated attribute processing including:\n * - ARIA attribute handling with proper property mapping\n * - Data attribute management\n * - Boolean attribute processing\n * - Dynamic property detection and mapping\n * - Attribute cleanup and removal\n *\n * @param {HTMLElement} oldEl - The original element to update\n * @param {HTMLElement} newEl - The new element to update\n * @returns {void}\n */\n const updateAttributes = (oldEl, newEl) => {\n const oldAttrs = oldEl.attributes;\n const newAttrs = newEl.attributes;\n\n // Process new attributes\n for (let i = 0; i < newAttrs.length; i++) {\n const { name, value } = newAttrs[i];\n\n // Skip event attributes (handled by event system)\n if (name.startsWith(\"@\")) continue;\n\n // Skip if attribute hasn't changed\n if (oldEl.getAttribute(name) === value) continue;\n\n // Handle ARIA attributes\n if (enableAria && name.startsWith(\"aria-\")) {\n const prop =\n \"aria\" + name.slice(5).replace(CAMEL_RE, (_, l) => l.toUpperCase());\n oldEl[prop] = value;\n oldEl.setAttribute(name, value);\n }\n // Handle data attributes\n else if (enableData && name.startsWith(\"data-\")) {\n oldEl.dataset[name.slice(5)] = value;\n oldEl.setAttribute(name, value);\n }\n // Handle other attributes\n else {\n let prop = name.replace(CAMEL_RE, (_, l) => l.toUpperCase());\n\n // Dynamic property detection\n if (\n enableDynamic &&\n !(prop in oldEl) &&\n !Object.getOwnPropertyDescriptor(Object.getPrototypeOf(oldEl), prop)\n ) {\n const elementProps = Object.getOwnPropertyNames(\n Object.getPrototypeOf(oldEl)\n );\n const matchingProp = elementProps.find(\n (p) =>\n p.toLowerCase() === name.toLowerCase() ||\n p.toLowerCase().includes(name.toLowerCase()) ||\n name.toLowerCase().includes(p.toLowerCase())\n );\n\n if (matchingProp) {\n prop = matchingProp;\n }\n }\n\n const descriptor = Object.getOwnPropertyDescriptor(\n Object.getPrototypeOf(oldEl),\n prop\n );\n const hasProperty = prop in oldEl || descriptor;\n\n if (hasProperty) {\n // Boolean attribute handling\n if (enableBoolean) {\n const isBoolean =\n typeof oldEl[prop] === \"boolean\" ||\n (descriptor?.get &&\n typeof descriptor.get.call(oldEl) === \"boolean\");\n\n if (isBoolean) {\n const boolValue =\n value !== \"false\" &&\n (value === \"\" || value === prop || value === \"true\");\n oldEl[prop] = boolValue;\n\n if (boolValue) {\n oldEl.setAttribute(name, \"\");\n } else {\n oldEl.removeAttribute(name);\n }\n } else {\n oldEl[prop] = value;\n oldEl.setAttribute(name, value);\n }\n } else {\n oldEl[prop] = value;\n oldEl.setAttribute(name, value);\n }\n } else {\n oldEl.setAttribute(name, value);\n }\n }\n }\n\n // Remove old attributes that are no longer present\n for (let i = oldAttrs.length - 1; i >= 0; i--) {\n const name = oldAttrs[i].name;\n if (!newEl.hasAttribute(name)) {\n oldEl.removeAttribute(name);\n }\n }\n };\n\n // Extend the renderer with the advanced attribute handler\n if (eleva.renderer) {\n eleva.renderer.updateAttributes = updateAttributes;\n\n // Store the original _patchNode method\n const originalPatchNode = eleva.renderer._patchNode;\n eleva.renderer._originalPatchNode = originalPatchNode;\n\n // Override the _patchNode method to use our attribute handler\n eleva.renderer._patchNode = function (oldNode, newNode) {\n if (oldNode?._eleva_instance) return;\n\n if (!this._isSameNode(oldNode, newNode)) {\n oldNode.replaceWith(newNode.cloneNode(true));\n return;\n }\n\n if (oldNode.nodeType === Node.ELEMENT_NODE) {\n updateAttributes(oldNode, newNode);\n this._diff(oldNode, newNode);\n } else if (\n oldNode.nodeType === Node.TEXT_NODE &&\n oldNode.nodeValue !== newNode.nodeValue\n ) {\n oldNode.nodeValue = newNode.nodeValue;\n }\n };\n }\n\n // Add plugin metadata to the Eleva instance\n if (!eleva.plugins) {\n eleva.plugins = new Map();\n }\n eleva.plugins.set(this.name, {\n name: this.name,\n version: this.version,\n description: this.description,\n options,\n });\n\n // Add utility methods for manual attribute updates\n eleva.updateElementAttributes = updateAttributes;\n },\n\n /**\n * Uninstalls the plugin from the Eleva instance\n *\n * @param {Object} eleva - The Eleva instance\n */\n uninstall(eleva) {\n // Restore original _patchNode method if it exists\n if (eleva.renderer && eleva.renderer._originalPatchNode) {\n eleva.renderer._patchNode = eleva.renderer._originalPatchNode;\n delete eleva.renderer._originalPatchNode;\n }\n\n // Remove plugin metadata\n if (eleva.plugins) {\n eleva.plugins.delete(this.name);\n }\n\n // Remove utility methods\n delete eleva.updateElementAttributes;\n },\n};\n\n// Short name export for convenience\nexport { AttrPlugin as Attr };\n"],"names":["CAMEL_RE","AttrPlugin","name","version","description","install","eleva","options","enableAria","enableData","enableBoolean","enableDynamic","updateAttributes","oldEl","newEl","oldAttrs","attributes","newAttrs","i","length","value","startsWith","getAttribute","slice","replace","_","l","toUpperCase","setAttribute","dataset","prop","Object","getOwnPropertyDescriptor","getPrototypeOf","matchingProp","getOwnPropertyNames","find","p","toLowerCase","includes","descriptor","get","call","boolValue","removeAttribute","hasAttribute","renderer","_originalPatchNode","_patchNode","oldNode","newNode","_eleva_instance","this","_isSameNode","nodeType","Node","ELEMENT_NODE","_diff","TEXT_NODE","nodeValue","replaceWith","cloneNode","plugins","Map","set","updateElementAttributes","uninstall","delete"],"mappings":";0CAOA,MAAMA,EAAW,YA+BJC,EAAa,CAKxBC,KAAM,OAMNC,QAAS,c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