rasti 4.0.0-alpha.9 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/es/View.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"View.js","sources":["../src/View.js"],"sourcesContent":["import Emitter from './Emitter.js';\nimport getResult from './utils/getResult.js';\nimport validateListener from './utils/validateListener.js';\n\n/*\n * These option keys will be extended on the view instance.\n */\nconst viewOptions = ['el', 'tag', 'attributes', 'events', 'model', 'template', 'onDestroy'];\n\n/**\n * - Listens for changes and renders the UI.\n * - Handles user input and interactivity.\n * - Sends captured input to the model.\n *\n * A `View` is an atomic unit of the user interface that can render data from a specific model or multiple models.\n * However, views can also be independent and have no associated data. \n * Models must be unaware of views. Views, on the other hand, may render model data and listen to the change events \n * emitted by the models to re-render themselves based on changes. \n * Each `View` has a root element, `this.el`, which is used for event delegation. \n * All element lookups are scoped to this element, and any rendering or DOM manipulations should be done inside it. \n * If `this.el` is not present, an element will be created using `this.tag` (defaulting to `div`) and `this.attributes`.\n * @module\n * @extends Emitter\n * @param {object} options Object containing options. The following keys will be merged into the view instance: `el`, `tag`, `attributes`, `events`, `model`, `template`, `onDestroy`.\n * @property {node|Function} el Every view has a root DOM element stored at `this.el`. If not present, it will be created. If `this.el` is a function, it will be called to get the element at `this.ensureElement`, bound to the view instance. See {@link module_view__ensureelement View.ensureElement}.\n * @property {string|Function} tag If `this.el` is not present, an element will be created using `this.tag` and `this.attributes`. Default is `div`. If it is a function, it will be called to get the tag, bound to the view instance. See {@link module_view__ensureelement View.ensureElement}.\n * @property {object|Function} attributes If `this.el` is not present, an element will be created using `this.tag` and `this.attributes`. If it is a function, it will be called to get the attributes object, bound to the view instance. See {@link module_view__ensureelement View.ensureElement}.\n * @property {object|Function} events Object in the format `{'event selector' : 'listener'}`. It will be used to bind delegated event listeners to the root element. If it is a function, it will be called to get the events object, bound to the view instance. See {@link module_view_delegateevents View.delegateEvents}.\n * @property {object} model A model or any object containing data and business logic.\n * @property {Function} template A function that returns a string with the view's inner HTML. See {@link module_view__render View.render}. \n * @property {number} uid Unique identifier for the view instance. This can be used to generate unique IDs for elements within the view. It is automatically generated and should not be set manually.\n * @example\n * import { View, Model } from 'rasti';\n * \n * class Timer extends View {\n * constructor(options) {\n * super(options);\n * // Create model to store internal state. Set `seconds` attribute to 0.\n * this.model = new Model({ seconds : 0 });\n * // Listen to changes in model `seconds` attribute and re-render.\n * this.model.on('change:seconds', this.render.bind(this));\n * // Increment model `seconds` attribute every 1000 milliseconds.\n * this.interval = setInterval(() => this.model.seconds++, 1000);\n * }\n *\n * template(model) {\n * return `Seconds: <span>${model.seconds}</span>`;\n * }\n * }\n * // Render view and append view's element into the body.\n * document.body.appendChild(new Timer().render().el);\n */\nexport default class View extends Emitter {\n constructor(options = {}) {\n super();\n // Call preinitialize.\n this.preinitialize.apply(this, arguments);\n // Store delegated event listeners,\n // so they can be unbound later.\n this.delegatedEventListeners = [];\n // Store child views,\n // so they can be destroyed.\n this.children = [];\n // Mutable array to store handlers to be called on destroy.\n this.destroyQueue = [];\n this.viewOptions = [];\n // Extend \"this\" with options.\n viewOptions.forEach(key => {\n if (key in options) {\n this[key] = options[key];\n this.viewOptions.push(key);\n }\n });\n // Ensure that the view has a unique id at `this.uid`.\n this.ensureUid();\n // Ensure that the view has a root element at `this.el`.\n this.ensureElement();\n }\n\n /**\n * If you define a preinitialize method, it will be invoked when the view is first created, before any instantiation logic is run.\n * @param {object} options The view options.\n */\n preinitialize() {}\n\n /**\n * Returns the first element that matches the selector, \n * scoped to DOM elements within the current view's root element (`this.el`).\n * @param {string} selector CSS selector.\n * @return {node} Element matching selector within the view's root element (`this.el`).\n */\n $(selector) {\n return this.el.querySelector(selector);\n }\n\n /**\n * Returns a list of elements that match the selector, \n * scoped to DOM elements within the current view's root element (`this.el`).\n * @param {string} selector CSS selector.\n * @return {node[]} List of elements matching selector within the view's root element (`this.el`).\n */\n $$(selector) {\n return this.el.querySelectorAll(selector);\n }\n\n /**\n * Destroy the view.\n * Destroy children views if any, undelegate events, stop listening to events, call `onDestroy` lifecycle method.\n * @param {object} options Options object or any arguments passed to `destroy` method will be passed to `onDestroy` method.\n * @return {View} Return `this` for chaining.\n */\n destroy() {\n // Call destroy on children.\n this.destroyChildren();\n // Undelegate `this.el` event listeners\n this.undelegateEvents();\n // Stop listening to events.\n this.stopListening();\n // Unbind `this` events.\n this.off();\n // Call destroy queue.\n this.destroyQueue.forEach(fn => fn());\n this.destroyQueue = [];\n // Call onDestroy lifecycle method\n this.onDestroy.apply(this, arguments);\n // Set destroyed flag.\n this.destroyed = true;\n // Return `this` for chaining.\n return this;\n }\n\n /**\n * `onDestroy` lifecycle method is called after the view is destroyed.\n * Override with your code. Useful to stop listening to model's events.\n * @param {object} options Options object or any arguments passed to `destroy` method.\n */\n onDestroy() {}\n\n /**\n * Add a view as a child.\n * Children views are stored at `this.children`, and destroyed when the parent is destroyed.\n * Returns the child for chaining.\n * @param {View} child\n * @return {View}\n */\n addChild(child) {\n this.children.push(child);\n return child;\n }\n\n /**\n * Call destroy method on children views.\n */\n destroyChildren() {\n this.children.forEach(child => child.destroy());\n this.children = [];\n }\n\n /**\n * Ensure that the view has a unique id at `this.uid`.\n */\n ensureUid() {\n if (!this.uid) this.uid = `r${++View.uid}`;\n }\n\n /**\n * Ensure that the view has a root element at `this.el`.\n * You shouldn't call this method directly. It's called from the constructor.\n * You may override it if you want to use a different logic or to \n * postpone element creation.\n */\n ensureElement() {\n // Element is already present.\n if (this.el) {\n // If \"this.el\" is a function, call it to get the element.\n this.el = getResult(this.el, this);\n } else {\n // If \"this.el\" is not present,\n // create a new element according \"this.tag\"\n // and \"this.attributes\".\n const tag = getResult(this.tag, this);\n const attrs = getResult(this.attributes, this);\n this.el = this.createElement(tag, attrs);\n }\n // Delegate events on element.\n this.delegateEvents();\n }\n\n /**\n * Create an element.\n * Called from the constructor if `this.el` is undefined, to ensure\n * the view has a root element.\n * @param {string} tag Tag for the element. Default to `div`\n * @param {object} attributes Attributes for the element.\n * @return {node} The created element.\n */\n createElement(tag = 'div', attributes = {}) {\n // Create DOM element.\n let el = document.createElement(tag);\n // Add element attributes.\n Object.keys(attributes)\n .forEach(key => el.setAttribute(key, attributes[key]));\n\n return el;\n }\n\n /**\n * Remove `this.el` from the DOM.\n * @return {View} Return `this` for chaining.\n */\n removeElement() {\n this.el.parentNode.removeChild(this.el);\n // Return `this` for chaining.\n return this;\n }\n\n /**\n * Provide declarative listeners for DOM events within a view. If an events object is not provided, \n * it defaults to using `this.events`. If `this.events` is a function, it will be called to get the events object.\n * \n * The events object should follow the format `{'event selector': 'listener'}`:\n * - `event`: The type of event (e.g., 'click').\n * - `selector`: A CSS selector to match the event target. If omitted, the event is bound to the root element.\n * - `listener`: A function or a string representing a method name on the view. The method will be called with `this` bound to the view instance.\n * \n * By default, `delegateEvents` is called within the View's constructor. If you have a simple events object, \n * all of your DOM events will be connected automatically, and you will not need to call this function manually.\n * \n * All attached listeners are bound to the view, ensuring that `this` refers to the view object when the listeners are invoked.\n * When `delegateEvents` is called again, possibly with a different events object, all previous listeners are removed and delegated afresh.\n * \n * **Listener signature:** `(event, view, matched)`\n * - `event`: The native DOM event object.\n * - `view`: The current view instance (`this`).\n * - `matched`: The element that satisfies the selector. If no selector is provided, it will be the view's root element (`this.el`).\n *\n * If more than one ancestor between `event.target` and the view's root element matches the selector, the listener will be\n * invoked **once for each matched element** (from inner to outer).\n *\n * @param {object} [events] Object in the format `{'event selector' : 'listener'}`. Used to bind delegated event listeners to the root element.\n * @return {View} Returns `this` for chaining.\n * @example\n * // Using prototype (recommended for static events)\n * class Modal extends View {\n * onClickOk(event, view, matched) {\n * // matched === the button.ok element that was clicked\n * this.close();\n * }\n * \n * onClickCancel() {\n * this.destroy();\n * }\n * }\n * Modal.prototype.events = {\n * 'click button.ok': 'onClickOk',\n * 'click button.cancel': 'onClickCancel',\n * 'submit form': 'onSubmit'\n * };\n * \n * // Using a function for dynamic events\n * class DynamicView extends View {\n * events() {\n * return {\n * [`click .${this.model.buttonClass}`]: 'onButtonClick',\n * 'click': 'onRootClick'\n * };\n * }\n * }\n */\n delegateEvents(events) {\n if (!events) events = getResult(this.events, this);\n if (!events) return this;\n\n if (this.delegatedEventListeners.length) this.undelegateEvents();\n\n // Store events by type i.e.: \"click\", \"submit\", etc.\n let eventTypes = {};\n\n Object.keys(events).forEach(key => {\n const keyParts = key.split(' ');\n const type = keyParts.shift();\n const selector = keyParts.join(' ');\n\n let listener = events[key];\n // Listener may be a string representing a method name on the view, or a function.\n if (typeof listener === 'string') listener = this[listener];\n // Validate listener is a function.\n validateListener(listener);\n\n if (!eventTypes[type]) eventTypes[type] = [];\n\n eventTypes[type].push({ selector, listener });\n });\n\n Object.keys(eventTypes).forEach(type => {\n // Listener for the type of event.\n const typeListener = (event) => {\n // Iterate and run every individual listener if the selector matches.\n eventTypes[type].forEach(({ selector, listener }) => {\n // No selector provided: invoke listener once with root element.\n if (!selector) {\n listener.call(this, event, this, this.el);\n return;\n }\n\n let node = event.target;\n // Traverse ancestors until reaching the view root (`this.el`).\n while (node && node !== this.el) {\n if (node.matches && node.matches(selector)) {\n listener.call(this, event, this, node);\n }\n node = node.parentElement;\n }\n });\n };\n\n this.delegatedEventListeners.push({ type, listener : typeListener });\n this.el.addEventListener(type, typeListener);\n });\n // Return `this` for chaining.\n return this;\n }\n\n /**\n * Removes all of the view's delegated events. \n * Useful if you want to disable or remove a view from the DOM temporarily. \n * Called automatically when the view is destroyed and when `delegateEvents` is called again.\n * @return {View} Return `this` for chaining.\n */\n undelegateEvents() {\n this.delegatedEventListeners.forEach(({ type, listener }) => {\n this.el.removeEventListener(type, listener);\n });\n\n this.delegatedEventListeners = [];\n // Return `this` for chaining.\n return this;\n }\n\n /**\n * Renders the view. \n * This method should be overridden with custom logic.\n * The only convention is to manipulate the DOM within the scope of `this.el`,\n * and to return `this` for chaining. \n * If you add any child views, you should call `this.destroyChildren` before re-rendering. \n * The default implementation updates `this.el`'s innerHTML with the result\n * of calling `this.template`, passing `this.model` as the argument.\n * <br><br> &#9888; **Security Notice:** The default implementation utilizes `innerHTML`, which may introduce Cross-Site Scripting (XSS) risks. \n * Ensure that any user-generated content is properly sanitized before inserting it into the DOM. \n * You can use the {@link #module_view_sanitize View.sanitize} static method to escape HTML entities in a string. \n * For best practices on secure data handling, refer to the \n * [OWASP's XSS Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html).<br><br>\n * @return {View} Returns `this` for chaining.\n */\n render() {\n if (this.template) this.el.innerHTML = this.template(this.model);\n // Return `this` for chaining.\n return this;\n }\n\n /**\n * Escape HTML entities in a string.\n * Use this method to sanitize user-generated content before inserting it into the DOM.\n * Override this method to provide a custom escape function.\n * This method is inherited by {@link #module_component Component} and used to escape template interpolations.\n * @static\n * @param {string} value String to escape.\n * @return {string} Escaped string.\n */\n static sanitize(value) {\n return `${value}`.replace(/[&<>\"']/g, match => ({\n '&' : '&amp;',\n '<' : '&lt;',\n '>' : '&gt;',\n '\"' : '&quot;',\n '\\'' : '&#039;'\n }[match]));\n }\n\n /**\n * Reset the unique ID counter to 0.\n * This is useful for server-side rendering scenarios where you want to ensure that\n * the generated unique IDs match those on the client, enabling seamless hydration of components.\n * This method is inherited by {@link #module_component Component}.\n * @static\n */\n static resetUid() {\n View.uid = 0;\n }\n}\n\n/**\n * Counter for generating unique IDs for view instances. \n * This is primarily used to assign unique identifiers to each view instance (`this.uid`), which can be helpful for tasks like \n * generating element IDs. \n * {@link #module_component Component}s use `this.uid` to generate data attributes for their elements, to be looked up on hydration. \n * For server-side rendering, this counter should be reset to `0` on every request to ensure that the generated \n * unique IDs match those on the client, enabling seamless hydration of components. \n * @static\n * @type {number}\n * @default 0\n */\nView.uid = 0;\n"],"names":[],"mappings":";;;;;;;;;AAIA;AACA;AACA;AACA,MAAM,WAAW,GAAG,CAAC,IAAI,EAAE,KAAK,EAAE,YAAY,EAAE,QA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D,QAAQ,CAAC,CAAC;;AAEV,QAAQ,IAAI,CAAC,uBAAuB,GAAG,EAAE;AACzC;AACA,QAAQ,OAAO,IAAI;AACnB,IAAI;;AAEJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,MAAM,GAAG;AACb,QAAQ,IAAI,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,EAAE,CAAC,SAAS,GAAG,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC;AACxE;AACA,QAAQ,OAAO,IAAI;AACnB,IAAI;;AAEJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,OAAO,QAAQ,CAAC,KAAK,EAAE;AAC3B,QAAQ,OAAO,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,UAAU,EAAE,KAAK,KAAK;AACxD,YAAY,GAAG,GAAG,OAAO;AACzB,YAAY,GAAG,GAAG,MAAM;AACxB,YAAY,GAAG,GAAG,MAAM;AACxB,YAAY,GAAG,GAAG,QAAQ;AAC1B,YAAY,IAAI,GAAG;AACnB,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC;AAClB,IAAI;;AAEJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,OAAO,QAAQ,GAAG;AACtB,QAAQ,IAAI,CAAC,GAAG,GAAG,CAAC;AACpB,IAAI;AACJ;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,CAAC,GAAG,GAAG,CAAC;;;;"}
1
+ {"version":3,"file":"View.js","sources":["../src/View.js"],"sourcesContent":["import Emitter from './Emitter.js';\nimport getResult from './utils/getResult.js';\nimport validateListener from './utils/validateListener.js';\n\n/*\n * These option keys will be extended on the view instance.\n */\nconst viewOptions = ['el', 'tag', 'attributes', 'events', 'model', 'template', 'onDestroy'];\n\n/**\n * - Listens for changes and renders the UI.\n * - Handles user input and interactivity.\n * - Sends captured input to the model.\n *\n * A `View` is an atomic unit of the user interface that can render data from a specific model or multiple models.\n * However, views can also be independent and have no associated data. \n * Models must be unaware of views. Views, on the other hand, may render model data and listen to the change events \n * emitted by the models to re-render themselves based on changes. \n * Each `View` has a root element, `this.el`, which is used for event delegation. \n * All element lookups are scoped to this element, and any rendering or DOM manipulations should be done inside it. \n * If `this.el` is not present, an element will be created using `this.tag` (defaulting to `div`) and `this.attributes`.\n * @module\n * @extends Emitter\n * @param {object} options Object containing options. The following keys will be merged into the view instance: `el`, `tag`, `attributes`, `events`, `model`, `template`, `onDestroy`.\n * @property {node|Function} el Every view has a root DOM element stored at `this.el`. If not present, it will be created. If `this.el` is a function, it will be called to get the element at `this.ensureElement`, bound to the view instance. See {@link module_view__ensureelement View.ensureElement}.\n * @property {string|Function} tag If `this.el` is not present, an element will be created using `this.tag` and `this.attributes`. Default is `div`. If it is a function, it will be called to get the tag, bound to the view instance. See {@link module_view__ensureelement View.ensureElement}.\n * @property {object|Function} attributes If `this.el` is not present, an element will be created using `this.tag` and `this.attributes`. If it is a function, it will be called to get the attributes object, bound to the view instance. See {@link module_view__ensureelement View.ensureElement}.\n * @property {object|Function} events Object in the format `{'event selector' : 'listener'}`. It will be used to bind delegated event listeners to the root element. If it is a function, it will be called to get the events object, bound to the view instance. See {@link module_view_delegateevents View.delegateEvents}.\n * @property {object} model A model or any object containing data and business logic.\n * @property {Function} template A function that returns a string with the view's inner HTML. See {@link module_view__render View.render}. \n * @property {number} uid Unique identifier for the view instance. This can be used to generate unique IDs for elements within the view. It is automatically generated and should not be set manually.\n * @example\n * import { View, Model } from 'rasti';\n * \n * class Timer extends View {\n * constructor(options) {\n * super(options);\n * // Create model to store internal state. Set `seconds` attribute to 0.\n * this.model = new Model({ seconds : 0 });\n * // Listen to changes in model `seconds` attribute and re-render.\n * this.model.on('change:seconds', this.render.bind(this));\n * // Increment model `seconds` attribute every 1000 milliseconds.\n * this.interval = setInterval(() => this.model.seconds++, 1000);\n * }\n *\n * template(model) {\n * return `Seconds: <span>${View.sanitize(model.seconds)}</span>`;\n * }\n *\n * render() {\n * if (this.template) {\n * this.el.innerHTML = this.template(this.model);\n * }\n * return this;\n * }\n * }\n * // Render view and append view's element into the body.\n * document.body.appendChild(new Timer().render().el);\n */\nexport default class View extends Emitter {\n constructor(options = {}) {\n super();\n // Call preinitialize.\n this.preinitialize.apply(this, arguments);\n // Store delegated event listeners,\n // so they can be unbound later.\n this.delegatedEventListeners = [];\n // Store child views,\n // so they can be destroyed.\n this.children = [];\n // Mutable array to store handlers to be called on destroy.\n this.destroyQueue = [];\n this.viewOptions = [];\n // Extend \"this\" with options.\n viewOptions.forEach(key => {\n if (key in options) {\n this[key] = options[key];\n this.viewOptions.push(key);\n }\n });\n // Ensure that the view has a unique id at `this.uid`.\n this.ensureUid();\n // Ensure that the view has a root element at `this.el`.\n this.ensureElement();\n }\n\n /**\n * If you define a preinitialize method, it will be invoked when the view is first created, before any instantiation logic is run.\n * @param {object} options The view options.\n */\n preinitialize() {}\n\n /**\n * Returns the first element that matches the selector, \n * scoped to DOM elements within the current view's root element (`this.el`).\n * @param {string} selector CSS selector.\n * @return {node} Element matching selector within the view's root element (`this.el`).\n */\n $(selector) {\n return this.el.querySelector(selector);\n }\n\n /**\n * Returns a list of elements that match the selector, \n * scoped to DOM elements within the current view's root element (`this.el`).\n * @param {string} selector CSS selector.\n * @return {node[]} List of elements matching selector within the view's root element (`this.el`).\n */\n $$(selector) {\n return this.el.querySelectorAll(selector);\n }\n\n /**\n * Destroy the view.\n * Destroy children views if any, undelegate events, stop listening to events, call `onDestroy` lifecycle method.\n * @param {object} options Options object or any arguments passed to `destroy` method will be passed to `onDestroy` method.\n * @return {View} Return `this` for chaining.\n */\n destroy() {\n // Call destroy on children.\n this.destroyChildren();\n // Undelegate `this.el` event listeners\n this.undelegateEvents();\n // Stop listening to events.\n this.stopListening();\n // Unbind `this` events.\n this.off();\n // Call destroy queue.\n this.destroyQueue.forEach(fn => fn());\n this.destroyQueue = [];\n // Call onDestroy lifecycle method\n this.onDestroy.apply(this, arguments);\n // Set destroyed flag.\n this.destroyed = true;\n // Return `this` for chaining.\n return this;\n }\n\n /**\n * `onDestroy` lifecycle method is called after the view is destroyed.\n * Override with your code. Useful to stop listening to model's events.\n * @param {object} options Options object or any arguments passed to `destroy` method.\n */\n onDestroy() {}\n\n /**\n * Add a view as a child.\n * Children views are stored at `this.children`, and destroyed when the parent is destroyed.\n * Returns the child for chaining.\n * @param {View} child\n * @return {View}\n */\n addChild(child) {\n this.children.push(child);\n return child;\n }\n\n /**\n * Call destroy method on children views.\n */\n destroyChildren() {\n this.children.forEach(child => child.destroy());\n this.children = [];\n }\n\n /**\n * Ensure that the view has a unique id at `this.uid`.\n */\n ensureUid() {\n if (!this.uid) this.uid = `r${++View.uid}`;\n }\n\n /**\n * Ensure that the view has a root element at `this.el`.\n * You shouldn't call this method directly. It's called from the constructor.\n * You may override it if you want to use a different logic or to \n * postpone element creation.\n */\n ensureElement() {\n // Element is already present.\n if (this.el) {\n // If \"this.el\" is a function, call it to get the element.\n this.el = getResult(this.el, this);\n } else {\n // If \"this.el\" is not present,\n // create a new element according \"this.tag\"\n // and \"this.attributes\".\n const tag = getResult(this.tag, this);\n const attrs = getResult(this.attributes, this);\n this.el = this.createElement(tag, attrs);\n }\n // Delegate events on element.\n this.delegateEvents();\n }\n\n /**\n * Create an element.\n * Called from the constructor if `this.el` is undefined, to ensure\n * the view has a root element.\n * @param {string} tag Tag for the element. Default to `div`\n * @param {object} attributes Attributes for the element.\n * @return {node} The created element.\n */\n createElement(tag = 'div', attributes = {}) {\n // Create DOM element.\n let el = document.createElement(tag);\n // Add element attributes.\n Object.keys(attributes)\n .forEach(key => el.setAttribute(key, attributes[key]));\n\n return el;\n }\n\n /**\n * Remove `this.el` from the DOM.\n * @return {View} Return `this` for chaining.\n */\n removeElement() {\n this.el.parentNode.removeChild(this.el);\n // Return `this` for chaining.\n return this;\n }\n\n /**\n * Provide declarative listeners for DOM events within a view. If an events object is not provided, \n * it defaults to using `this.events`. If `this.events` is a function, it will be called to get the events object.\n * \n * The events object should follow the format `{'event selector': 'listener'}`:\n * - `event`: The type of event (e.g., 'click').\n * - `selector`: A CSS selector to match the event target. If omitted, the event is bound to the root element.\n * - `listener`: A function or a string representing a method name on the view. The method will be called with `this` bound to the view instance.\n * \n * By default, `delegateEvents` is called within the View's constructor. If you have a simple events object, \n * all of your DOM events will be connected automatically, and you will not need to call this function manually.\n * \n * All attached listeners are bound to the view, ensuring that `this` refers to the view object when the listeners are invoked.\n * When `delegateEvents` is called again, possibly with a different events object, all previous listeners are removed and delegated afresh.\n * \n * **Listener signature:** `(event, view, matched)`\n * - `event`: The native DOM event object.\n * - `view`: The current view instance (`this`).\n * - `matched`: The element that satisfies the selector. If no selector is provided, it will be the view's root element (`this.el`).\n *\n * If more than one ancestor between `event.target` and the view's root element matches the selector, the listener will be\n * invoked **once for each matched element** (from inner to outer).\n *\n * @param {object} [events] Object in the format `{'event selector' : 'listener'}`. Used to bind delegated event listeners to the root element.\n * @return {View} Returns `this` for chaining.\n * @example\n * // Using prototype (recommended for static events)\n * class Modal extends View {\n * onClickOk(event, view, matched) {\n * // matched === the button.ok element that was clicked\n * this.close();\n * }\n * \n * onClickCancel() {\n * this.destroy();\n * }\n * }\n * Modal.prototype.events = {\n * 'click button.ok': 'onClickOk',\n * 'click button.cancel': 'onClickCancel',\n * 'submit form': 'onSubmit'\n * };\n * \n * // Using a function for dynamic events\n * class DynamicView extends View {\n * events() {\n * return {\n * [`click .${this.model.buttonClass}`]: 'onButtonClick',\n * 'click': 'onRootClick'\n * };\n * }\n * }\n */\n delegateEvents(events) {\n if (!events) events = getResult(this.events, this);\n if (!events) return this;\n\n if (this.delegatedEventListeners.length) this.undelegateEvents();\n\n // Store events by type i.e.: \"click\", \"submit\", etc.\n let eventTypes = {};\n\n Object.keys(events).forEach(key => {\n const keyParts = key.split(' ');\n const type = keyParts.shift();\n const selector = keyParts.join(' ');\n\n let listener = events[key];\n // Listener may be a string representing a method name on the view, or a function.\n if (typeof listener === 'string') listener = this[listener];\n // Validate listener is a function.\n validateListener(listener);\n\n if (!eventTypes[type]) eventTypes[type] = [];\n\n eventTypes[type].push({ selector, listener });\n });\n\n Object.keys(eventTypes).forEach(type => {\n // Listener for the type of event.\n const typeListener = (event) => {\n // Iterate and run every individual listener if the selector matches.\n eventTypes[type].forEach(({ selector, listener }) => {\n // No selector provided: invoke listener once with root element.\n if (!selector) {\n listener.call(this, event, this, this.el);\n return;\n }\n\n let node = event.target;\n // Traverse ancestors until reaching the view root (`this.el`).\n while (node && node !== this.el) {\n if (node.matches && node.matches(selector)) {\n listener.call(this, event, this, node);\n }\n node = node.parentElement;\n }\n });\n };\n\n this.delegatedEventListeners.push({ type, listener : typeListener });\n this.el.addEventListener(type, typeListener);\n });\n // Return `this` for chaining.\n return this;\n }\n\n /**\n * Removes all of the view's delegated events. \n * Useful if you want to disable or remove a view from the DOM temporarily. \n * Called automatically when the view is destroyed and when `delegateEvents` is called again.\n * @return {View} Return `this` for chaining.\n */\n undelegateEvents() {\n this.delegatedEventListeners.forEach(({ type, listener }) => {\n this.el.removeEventListener(type, listener);\n });\n\n this.delegatedEventListeners = [];\n // Return `this` for chaining.\n return this;\n }\n\n /**\n * `render` is the core function that your view should override, in order to populate its element (`this.el`), with the appropriate HTML. The convention is for `render` to always return `this`. \n * Views are low-level building blocks for creating user interfaces. For most use cases, we recommend using {@link #module_component Component} instead, which provides a more declarative template syntax, automatic DOM updates, and a more efficient render pipeline. \n * If you add any child views, you should call `this.destroyChildren` before re-rendering.\n * \n * @return {View} Returns `this` for chaining.\n * @example\n * class UserView extends View {\n * render() {\n * if (this.template) {\n * const model = this.model;\n * // Sanitize model attributes to prevent XSS attacks.\n * const safeData = {\n * name : View.sanitize(model.name),\n * email : View.sanitize(model.email),\n * bio : View.sanitize(model.bio)\n * };\n * this.el.innerHTML = this.template(safeData);\n * }\n * return this;\n * }\n * }\n */\n render() {\n return this;\n }\n\n /**\n * Escape HTML entities in a string.\n * Use this method to sanitize user-generated content before inserting it into the DOM.\n * Override this method to provide a custom escape function.\n * This method is inherited by {@link #module_component Component} and used to escape template interpolations.\n * @static\n * @param {string} value String to escape.\n * @return {string} Escaped string.\n */\n static sanitize(value) {\n return `${value}`.replace(/[&<>\"']/g, match => ({\n '&' : '&amp;',\n '<' : '&lt;',\n '>' : '&gt;',\n '\"' : '&quot;',\n '\\'' : '&#039;'\n }[match]));\n }\n\n /**\n * Reset the unique ID counter to 0.\n * This is useful for server-side rendering scenarios where you want to ensure that\n * the generated unique IDs match those on the client, enabling seamless hydration of components.\n * This method is inherited by {@link #module_component Component}.\n * @static\n */\n static resetUid() {\n View.uid = 0;\n }\n}\n\n/**\n * Counter for generating unique IDs for view instances. \n * This is primarily used to assign unique identifiers to each view instance (`this.uid`), which can be helpful for tasks like \n * generating element IDs. \n * {@link #module_component Component}s use `this.uid` to generate data attributes for their elements, to be looked up on hydration. \n * For server-side rendering, this counter should be reset to `0` on every request to ensure that the generated \n * unique IDs match those on the client, enabling seamless hydration of components. \n * @static\n * @type {number}\n * @default 0\n */\nView.uid = 0;\n"],"names":[],"mappings":";;;;;;;;;AAIA;AACA;AACA;AACA,MAAM,WAAW,GAAG,CAAC,IAAI,EAAE,KAAK,EAAE,YAAY,EAAE,QAAQ,EAAE,OAAO,EAAE,UAAU,EAAE,WAAW,CAAC;;AAE3F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,MAAM,IAAI,SAAS,OAAO,CAAC;AAC1C,IAAI,WAAW,CAAC,OAAO,GAAG,EAAE,EAAE;AAC9B,QAAQ,KAAK,EAAE;AACf;AACA,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B,QAAQ,OAAO,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,UAAU,EAAE,KAAK,KAAK;AACxD,YAAY,GAAG,GAAG,OAAO;AACzB,YAAY,GAAG,GAAG,MAAM;AACxB,YAAY,GAAG,GAAG,MAAM;AACxB,YAAY,GAAG,GAAG,QAAQ;AAC1B,YAAY,IAAI,GAAG;AACnB,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC;AAClB,IAAI;;AAEJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,OAAO,QAAQ,GAAG;AACtB,QAAQ,IAAI,CAAC,GAAG,GAAG,CAAC;AACpB,IAAI;AACJ;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,CAAC,GAAG,GAAG,CAAC;;;;"}
package/es/utils/dev.js CHANGED
@@ -5,6 +5,7 @@
5
5
  * - UMD dev: replaced with true
6
6
  * - UMD prod: replaced with false
7
7
  * @type {boolean}
8
+ * @module
8
9
  * @private
9
10
  */
10
11
  const __DEV__ = process.env.NODE_ENV !== 'production';
@@ -1 +1 @@
1
- {"version":3,"file":"dev.js","sources":["../../src/utils/dev.js"],"sourcesContent":["/**\n * Development mode flag.\n * This will be replaced during build:\n * - ESM/CJS: replaced with process.env.NODE_ENV !== 'production'\n * - UMD dev: replaced with true\n * - UMD prod: replaced with false\n * @type {boolean}\n * @private\n */\nconst __DEV__ = true;\n\nexport default __DEV__;\n"],"names":[],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAA,OAAA,GAAA,OAAA,CAAA,GAAA,CAAA,QAAA,KAAA;;;;"}
1
+ {"version":3,"file":"dev.js","sources":["../../src/utils/dev.js"],"sourcesContent":["/**\n * Development mode flag.\n * This will be replaced during build:\n * - ESM/CJS: replaced with process.env.NODE_ENV !== 'production'\n * - UMD dev: replaced with true\n * - UMD prod: replaced with false\n * @type {boolean}\n * @module\n * @private\n */\nconst __DEV__ = true;\n\nexport default __DEV__;\n"],"names":[],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAA,OAAA,GAAA,OAAA,CAAA,GAAA,CAAA,QAAA,KAAA;;;;"}
@@ -99,7 +99,7 @@ function formatTemplateSource(source, errorExpression) {
99
99
  // If error expression is multi-line, show full details.
100
100
  if (typeof errorExpression === 'function') {
101
101
  const fullSource = errorExpression.toString();
102
- if (fullSource.includes('\n')) {
102
+ if (fullSource.match(/\n/)) {
103
103
  formattedLines.push('');
104
104
  formattedLines.push(' | Expression details:');
105
105
  fullSource.split('\n').forEach(line => {
@@ -1 +1 @@
1
- {"version":3,"file":"formatTemplateSource.js","sources":["../../src/utils/formatTemplateSource.js"],"sourcesContent":["import repeat from './repeat.js';\nimport padStart from './padStart.js';\n\n/**\n * Converts an expression to its string representation for display.\n * @param {any} expr The expression to convert.\n * @return {string} String representation of the expression.\n * @private\n */\nfunction expressionToString(expr) {\n if (typeof expr.toString === 'function') {\n const source = expr.toString();\n // Keep single line or show first line for multi-line.\n return '${' + (source.includes('\\n') ? source.split('\\n')[0] + '...' : source) + '}';\n }\n return '${' + String(expr) + '}';\n}\n\n/**\n * Formats the template source with line numbers and highlights the specific error expression.\n * @param {Object} source The original template source object with strings and expressions.\n * @param {any} errorExpression The expression that caused the error.\n * @return {string} Formatted template source.\n * @module\n * @private\n */\nexport default function formatTemplateSource(source, errorExpression) {\n if (!source || !source.strings || !source.expressions || !errorExpression) return '';\n\n const { strings, expressions } = source;\n\n // Find the index of the error expression in the expressions array.\n const expressionIndex = expressions.indexOf(errorExpression);\n if (expressionIndex === -1) return '';\n\n // Build the template source and calculate the error position directly.\n let templateSource = '';\n let errorPosition = -1;\n\n for (let i = 0; i < strings.length; i++) {\n templateSource += strings[i];\n\n if (i < expressions.length) {\n // Mark the position before adding the error expression.\n if (i === expressionIndex) {\n errorPosition = templateSource.length;\n }\n templateSource += expressionToString(expressions[i]);\n }\n }\n\n if (errorPosition === -1) return '';\n\n // Find the line and column of the error position.\n const lines = templateSource.split('\\n');\n const formattedLines = [];\n const maxLineNumWidth = String(lines.length).length;\n\n let errorLineNum = -1;\n let errorStartCol = -1;\n let charCount = 0;\n\n for (let i = 0; i < lines.length; i++) {\n const lineLength = lines[i].length + 1; // +1 for newline character.\n if (charCount + lineLength > errorPosition) {\n errorLineNum = i;\n errorStartCol = errorPosition - charCount;\n break;\n }\n charCount += lineLength;\n }\n\n if (errorLineNum === -1) return '';\n\n // Get the expression string to determine marker length.\n const expressionStr = expressionToString(errorExpression);\n\n // Format output with context.\n const contextStart = Math.max(0, errorLineNum - 2);\n const contextEnd = Math.min(lines.length - 1, errorLineNum + 2);\n\n for (let i = contextStart; i <= contextEnd; i++) {\n const lineNum = i + 1;\n const lineNumStr = padStart(String(lineNum), maxLineNumWidth, ' ');\n const isErrorLine = i === errorLineNum;\n const linePrefix = isErrorLine ? ` ${lineNumStr} > ` : ` ${lineNumStr} | `;\n\n formattedLines.push(linePrefix + lines[i]);\n\n // Add pointer on error line.\n if (isErrorLine) {\n const markerPos = linePrefix.length + errorStartCol;\n const markerLen = expressionStr.length;\n const pointerLine = repeat(' ', markerPos) + repeat('^', markerLen) + ' <-- Error here!';\n formattedLines.push(pointerLine);\n }\n }\n\n // If error expression is multi-line, show full details.\n if (typeof errorExpression === 'function') {\n const fullSource = errorExpression.toString();\n if (fullSource.includes('\\n')) {\n formattedLines.push('');\n formattedLines.push(' | Expression details:');\n fullSource.split('\\n').forEach(line => {\n formattedLines.push(' | ' + line);\n });\n }\n }\n\n return formattedLines.join('\\n');\n}\n"],"names":[],"mappings":";;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,kBAAkB,CAAC,IAAI,EAAE;AAClC,IAAI,IAAI,OAAO,IAAI,CAAC,QAAQ,KAAK,UAAU,EAAE;AAC7C,QAAQ,MAAM,MAAM,GAAG,IAAI,CAAC,QAAQ,EAAE;AACtC;AACA,QAAQ,OAAO,IAAI,IAA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WAAW,GAAG,CAAC,KAAK,YAAY;AAC9C,QAAQ,MAAM,UAAU,GAAG,WAAW,GAAG,CAAC,CAAC,EAAE,UAAU,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,EAAE,UAAU,CAAC,GAAG,CAAC;;AAElF,QAAQ,cAAc,CAAC,IAAI,CAAC,UAAU,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;;AAElD;AACA,QAAQ,IAAI,WAAW,EAAE;AACzB,YAAY,MAAM,SAAS,GAAG,UAAU,CAAC,MAAM,GAAG,aAAa;AAC/D,YAAY,MAAM,SAAS,GAAG,aAAa,CAAC,MAAM;AAClD,YAAY,MAAM,WAAW,GAAG,MAAM,CAAC,GAAG,EAAE,SAAS,CAAC,GAAG,MAAM,CAAC,GAAG,EAAE,SAAS,CAAC,GAAG,kBAAkB;AACpG,YAAY,cAAc,CAAC,IAAI,CAAC,WAAW,CAAC;AAC5C,QAAQ;AACR,IAAI;;AAEJ;AACA,IAAI,IAAI,OAAO,eAAe,KAAK,UAAU,EAAE;AAC/C,QAAQ,MAAM,UAAU,GAAG,eAAe,CAAC,QAAQ,EAAE;AACrD,QAAQ,IAAI,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE;AACvC,YAAY,cAAc,CAAC,IAAI,CAAC,EAAE,CAAC;AACnC,YAAY,cAAc,CAAC,IAAI,CAAC,4BAA4B,CAAC;AAC7D,YAAY,UAAU,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,IAAI,IAAI;AACnD,gBAAgB,cAAc,CAAC,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC;AACzD,YAAY,CAAC,CAAC;AACd,QAAQ;AACR,IAAI;;AAEJ,IAAI,OAAO,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC;AACpC;;;;"}
1
+ {"version":3,"file":"formatTemplateSource.js","sources":["../../src/utils/formatTemplateSource.js"],"sourcesContent":["import repeat from './repeat.js';\nimport padStart from './padStart.js';\n\n/**\n * Converts an expression to its string representation for display.\n * @param {any} expr The expression to convert.\n * @return {string} String representation of the expression.\n * @private\n */\nfunction expressionToString(expr) {\n if (typeof expr.toString === 'function') {\n const source = expr.toString();\n // Keep single line or show first line for multi-line.\n return '${' + (source.includes('\\n') ? source.split('\\n')[0] + '...' : source) + '}';\n }\n return '${' + String(expr) + '}';\n}\n\n/**\n * Formats the template source with line numbers and highlights the specific error expression.\n * @param {Object} source The original template source object with strings and expressions.\n * @param {any} errorExpression The expression that caused the error.\n * @return {string} Formatted template source.\n * @module\n * @private\n */\nexport default function formatTemplateSource(source, errorExpression) {\n if (!source || !source.strings || !source.expressions || !errorExpression) return '';\n\n const { strings, expressions } = source;\n\n // Find the index of the error expression in the expressions array.\n const expressionIndex = expressions.indexOf(errorExpression);\n if (expressionIndex === -1) return '';\n\n // Build the template source and calculate the error position directly.\n let templateSource = '';\n let errorPosition = -1;\n\n for (let i = 0; i < strings.length; i++) {\n templateSource += strings[i];\n\n if (i < expressions.length) {\n // Mark the position before adding the error expression.\n if (i === expressionIndex) {\n errorPosition = templateSource.length;\n }\n templateSource += expressionToString(expressions[i]);\n }\n }\n\n if (errorPosition === -1) return '';\n\n // Find the line and column of the error position.\n const lines = templateSource.split('\\n');\n const formattedLines = [];\n const maxLineNumWidth = String(lines.length).length;\n\n let errorLineNum = -1;\n let errorStartCol = -1;\n let charCount = 0;\n\n for (let i = 0; i < lines.length; i++) {\n const lineLength = lines[i].length + 1; // +1 for newline character.\n if (charCount + lineLength > errorPosition) {\n errorLineNum = i;\n errorStartCol = errorPosition - charCount;\n break;\n }\n charCount += lineLength;\n }\n\n if (errorLineNum === -1) return '';\n\n // Get the expression string to determine marker length.\n const expressionStr = expressionToString(errorExpression);\n\n // Format output with context.\n const contextStart = Math.max(0, errorLineNum - 2);\n const contextEnd = Math.min(lines.length - 1, errorLineNum + 2);\n\n for (let i = contextStart; i <= contextEnd; i++) {\n const lineNum = i + 1;\n const lineNumStr = padStart(String(lineNum), maxLineNumWidth, ' ');\n const isErrorLine = i === errorLineNum;\n const linePrefix = isErrorLine ? ` ${lineNumStr} > ` : ` ${lineNumStr} | `;\n\n formattedLines.push(linePrefix + lines[i]);\n\n // Add pointer on error line.\n if (isErrorLine) {\n const markerPos = linePrefix.length + errorStartCol;\n const markerLen = expressionStr.length;\n const pointerLine = repeat(' ', markerPos) + repeat('^', markerLen) + ' <-- Error here!';\n formattedLines.push(pointerLine);\n }\n }\n\n // If error expression is multi-line, show full details.\n if (typeof errorExpression === 'function') {\n const fullSource = errorExpression.toString();\n if (fullSource.match(/\\n/)) {\n formattedLines.push('');\n formattedLines.push(' | Expression details:');\n fullSource.split('\\n').forEach(line => {\n formattedLines.push(' | ' + line);\n });\n }\n }\n\n return formattedLines.join('\\n');\n}\n"],"names":[],"mappings":";;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,kBAAkB,CAAC,IAAI,EAAE;AAClC,IAAI,IAAI,OAAO,IAAI,CAAC,QAAQ,KAAK,UAAU,EAAE;AAC7C,QAAQ,MAAM,MAAM,GAAG,IAAI,CAAC,QAAQ,EAAE;AACtC;AACA,QAAQ,OAAO,IAAI,IAAI,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,KAAK,GAAG,MAAM,CAAC,GAAG,GAAG;AAC5F,IAAI;AACJ,IAAI,OAAO,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,GAAG;AACpC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAAS,oBAAoB,CAAC,MAAM,EAAE,eAAe,EAAE;AACtE,IAAI,IAAI,CAAC,MAAM,IAAI,CAAC,MAAM,CAAC,OAAO,IAAI,CAAC,MAAM,CAAC,WAAW,IAAI,CAAC,eAAe,EAAE,OAAO,EAAE;;AAExF,IAAI,MAAM,EAAE,OAAO,EAAE,WAAW,EAAE,GAAG,MAAM;;AAE3C;AACA,I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,YAAY,cAAc,CAAC,IAAI,CAAC,WAAW,CAAC;AAC5C,QAAQ;AACR,IAAI;;AAEJ;AACA,IAAI,IAAI,OAAO,eAAe,KAAK,UAAU,EAAE;AAC/C,QAAQ,MAAM,UAAU,GAAG,eAAe,CAAC,QAAQ,EAAE;AACrD,QAAQ,IAAI,UAAU,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE;AACpC,YAAY,cAAc,CAAC,IAAI,CAAC,EAAE,CAAC;AACnC,YAAY,cAAc,CAAC,IAAI,CAAC,4BAA4B,CAAC;AAC7D,YAAY,UAAU,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,IAAI,IAAI;AACnD,gBAAgB,cAAc,CAAC,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC;AACzD,YAAY,CAAC,CAAC;AACd,QAAQ;AACR,IAAI;;AAEJ,IAAI,OAAO,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC;AACpC;;;;"}
@@ -1,6 +1,21 @@
1
+ let isChrome, moveBeforeSupported, preserveFocus, resetFocus;
2
+
3
+ // Browser compatibility notes (as of 2025):
4
+ // - Safari: Does not support moveBefore.
5
+ // - Firefox: moveBefore preserves focus but loses scroll position.
6
+ // - Chrome: moveBefore preserves scroll position but loses focus.
7
+ if (typeof document !== 'undefined') {
8
+ isChrome = !!navigator.userAgent.match(/Chrome/);
9
+ moveBeforeSupported = !!Element.prototype.moveBefore;
10
+ preserveFocus = !moveBeforeSupported || isChrome;
11
+ // When using moveBefore, Chrome resets the focus but preserves the active element.
12
+ // So we need to blur the active element before setting the focus again.
13
+ resetFocus = moveBeforeSupported && isChrome;
14
+ }
15
+
1
16
  /**
2
17
  * Replaces an existing DOM node with a new node, preserving internal DOM state.
3
- * Uses moveBefore if available, otherwise falls back to before.
18
+ * Uses moveBefore if available, otherwise falls back to insertBefore.
4
19
  *
5
20
  * @param {Node} oldNode The existing DOM node to replace.
6
21
  * @param {Node} newNode The new DOM node to replace the old node with.
@@ -8,16 +23,18 @@
8
23
  * @private
9
24
  */
10
25
  function replaceNode(oldNode, newNode) {
11
- if (Element.prototype.moveBefore) {
12
- oldNode.parentNode.moveBefore(newNode, oldNode);
13
- oldNode.parentNode.removeChild(oldNode);
14
- } else {
15
- const activeElement = document.activeElement;
16
- oldNode.parentNode.insertBefore(newNode, oldNode);
17
- oldNode.parentNode.removeChild(oldNode);
18
- if (activeElement && activeElement !== document.activeElement && newNode.contains(activeElement)) {
19
- activeElement.focus();
20
- }
26
+ const activeElement = preserveFocus &&
27
+ document.activeElement &&
28
+ newNode.contains(document.activeElement) ?
29
+ document.activeElement : null;
30
+
31
+ if (activeElement && resetFocus) activeElement.blur();
32
+
33
+ oldNode.parentNode[moveBeforeSupported ? 'moveBefore' : 'insertBefore'](newNode, oldNode);
34
+ oldNode.parentNode.removeChild(oldNode);
35
+
36
+ if (activeElement && activeElement !== document.activeElement && newNode.contains(activeElement)) {
37
+ activeElement.focus();
21
38
  }
22
39
  }
23
40
 
@@ -1 +1 @@
1
- {"version":3,"file":"replaceNode.js","sources":["../../src/utils/replaceNode.js"],"sourcesContent":["/**\n * Replaces an existing DOM node with a new node, preserving internal DOM state.\n * Uses moveBefore if available, otherwise falls back to before.\n * \n * @param {Node} oldNode The existing DOM node to replace.\n * @param {Node} newNode The new DOM node to replace the old node with.\n * @module\n * @private\n */\nexport default function replaceNode(oldNode, newNode) {\n if (Element.prototype.moveBefore) {\n oldNode.parentNode.moveBefore(newNode, oldNode);\n oldNode.parentNode.removeChild(oldNode);\n } else {\n const activeElement = document.activeElement;\n oldNode.parentNode.insertBefore(newNode, oldNode);\n oldNode.parentNode.removeChild(oldNode);\n if (activeElement && activeElement !== document.activeElement && newNode.contains(activeElement)) {\n activeElement.focus();\n }\n }\n}\n"],"names":[],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAAS,WAAW,CAAC,OAAO,EAAE,OAAO,EAAE;AACtD,IAAI,IAAI,OAAO,CAAC,SAAS,CAAC,UAAU,EAAE;AACtC,QAAQ,OAAO,CAAC,UAAU,CAAC,UAAU,CAAC,OAAO,EAAE,OAAO,CAAC;AACvD,QAAQ,OAAO,CAAC,UAAU,CAAC,WAAW,CAAC,OAAO,CAAC;AAC/C,IAAI,CAAC,MAAM;AACX,QAAQ,MAAM,aAAa,GAAG,QAAQ,CAAC,aAAa;AACpD,QAAQ,OAAO,CAAC,UAAU,CAAC,YAAY,CAAC,OAAO,EAAE,OAAO,CAAC;AACzD,QAAQ,OAAO,CAAC,UAAU,CAAC,WAAW,CAAC,OAAO,CAAC;AAC/C,QAAQ,IAAI,aAAa,IAAI,aAAa,KAAK,QAAQ,CAAC,aAAa,IAAI,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAC,EAAE;AAC1G,YAAY,aAAa,CAAC,KAAK,EAAE;AACjC,QAAQ;AACR,IAAI;AACJ;;;;"}
1
+ {"version":3,"file":"replaceNode.js","sources":["../../src/utils/replaceNode.js"],"sourcesContent":["let isChrome, moveBeforeSupported, preserveFocus, resetFocus;\n\n// Browser compatibility notes (as of 2025):\n// - Safari: Does not support moveBefore.\n// - Firefox: moveBefore preserves focus but loses scroll position.\n// - Chrome: moveBefore preserves scroll position but loses focus.\nif (typeof document !== 'undefined') {\n isChrome = !!navigator.userAgent.match(/Chrome/);\n moveBeforeSupported = !!Element.prototype.moveBefore;\n preserveFocus = !moveBeforeSupported || isChrome;\n // When using moveBefore, Chrome resets the focus but preserves the active element.\n // So we need to blur the active element before setting the focus again.\n resetFocus = moveBeforeSupported && isChrome;\n}\n\n/**\n * Replaces an existing DOM node with a new node, preserving internal DOM state.\n * Uses moveBefore if available, otherwise falls back to insertBefore.\n * \n * @param {Node} oldNode The existing DOM node to replace.\n * @param {Node} newNode The new DOM node to replace the old node with.\n * @module\n * @private\n */\nexport default function replaceNode(oldNode, newNode) {\n const activeElement = preserveFocus &&\n document.activeElement &&\n newNode.contains(document.activeElement) ?\n document.activeElement : null;\n\n if (activeElement && resetFocus) activeElement.blur();\n\n oldNode.parentNode[moveBeforeSupported ? 'moveBefore' : 'insertBefore'](newNode, oldNode);\n oldNode.parentNode.removeChild(oldNode);\n\n if (activeElement && activeElement !== document.activeElement && newNode.contains(activeElement)) {\n activeElement.focus();\n }\n}\n"],"names":[],"mappings":"AAAA,IAAI,QAAQ,EAAE,mBAAmB,EAAE,aAAa,EAAE,UAAU;;AAE5D;AACA;AACA;AACA;AACA,IAAI,OAAO,QAAQ,KAAK,WAAW,EAAE;AACrC,IAAI,QAAQ,GAAG,CAAC,CAAC,SAAS,CAAC,SAAS,CAAC,KAAK,CAAC,QAAQ,CAAC;AACpD,IAAI,mBAAmB,GAAG,CAAC,CAAC,OAAO,CAAC,SAAS,CAAC,UAAU;AACxD,IAAI,aAAa,GAAG,CAAC,mBAAmB,IAAI,QAAQ;AACpD;AACA;AACA,IAAI,UAAU,GAAG,mBAAmB,IAAI,QAAQ;AAChD;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAAS,WAAW,CAAC,OAAO,EAAE,OAAO,EAAE;AACtD,IAAI,MAAM,aAAa,GAAG,aAAa;AACvC,QAAQ,QAAQ,CAAC,aAAa;AAC9B,QAAQ,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAC,aAAa,CAAC;AAChD,QAAQ,QAAQ,CAAC,aAAa,GAAG,IAAI;;AAErC,IAAI,IAAI,aAAa,IAAI,UAAU,EAAE,aAAa,CAAC,IAAI,EAAE;;AAEzD,IAAI,OAAO,CAAC,UAAU,CAAC,mBAAmB,GAAG,YAAY,GAAG,cAAc,CAAC,CAAC,OAAO,EAAE,OAAO,CAAC;AAC7F,IAAI,OAAO,CAAC,UAAU,CAAC,WAAW,CAAC,OAAO,CAAC;;AAE3C,IAAI,IAAI,aAAa,IAAI,aAAa,KAAK,QAAQ,CAAC,aAAa,IAAI,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAC,EAAE;AACtG,QAAQ,aAAa,CAAC,KAAK,EAAE;AAC7B,IAAI;AACJ;;;;"}
package/lib/Component.cjs CHANGED
@@ -37,21 +37,37 @@ require('./utils/padStart.cjs');
37
37
  */
38
38
  const getExpressionResult = (expression, context, meta) => {
39
39
  try {
40
- return utils_getResult(expression, context, context);
40
+ if (typeof expression !== 'function') return expression;
41
+ // In development, detect uninstantiated Component classes and provide a helpful error.
42
+ // This typically happens when a component tag is malformed and not properly expanded.
43
+ if (utils_dev && expression.prototype instanceof Component) {
44
+ throw new Error(
45
+ `Received uninstantiated Component class "${expression.name || 'Anonymous'}". ` +
46
+ 'This usually happens when a component tag is malformed (e.g., missing closing tag or typo). ' +
47
+ 'If that\'s not the case, make sure to instantiate child components using a component tag, mount(), or new.'
48
+ );
49
+ }
50
+
51
+ return expression.call(context, context);
41
52
  } catch (error) {
42
- if (meta && !error.cause) {
53
+ if (meta && !error._rasti) {
43
54
  let message;
44
55
 
45
56
  if (utils_dev) {
46
57
  const formattedSource = utils_formatTemplateSource(context.source, expression);
47
- message = utils_createDevelopmentErrorMessage(`Error in ${context.constructor.name}#${context.uid} (${meta})\n${error.message}\n\nTemplate source:\n\n${formattedSource}`);
58
+ message = utils_createDevelopmentErrorMessage(
59
+ `Error in ${context.constructor.name}#${context.uid} (${meta})\n${error.message}\n\nTemplate source:\n\n${formattedSource}`
60
+ );
48
61
  } else {
49
62
  message = utils_createProductionErrorMessage(`Error in ${context.constructor.name}#${context.uid} expression`);
50
63
  }
64
+
51
65
  const enhancedError = new Error(message, { cause : error });
52
- enhancedError.stack = error.stack;
66
+ enhancedError._rasti = true;
67
+
53
68
  throw enhancedError;
54
69
  }
70
+
55
71
  throw error;
56
72
  }
57
73
  };
@@ -72,7 +88,9 @@ const isComponent = (el) => !!(el && el.dataset && el.dataset[Component.DATASET_
72
88
  * @return {boolean} True if the element contains a component.
73
89
  * @private
74
90
  */
75
- const containsElement = (el) => !!(el && el.dataset && el.dataset[Component.DATASET_ELEMENT]) || !!el.querySelector(`[${Component.ATTRIBUTE_ELEMENT}]`);
91
+ const containsElement = (el) => !!(
92
+ el && ((el.dataset && el.dataset[Component.DATASET_ELEMENT]) || (el.querySelector && el.querySelector(`[${Component.ATTRIBUTE_ELEMENT}]`)))
93
+ );
76
94
 
77
95
  /**
78
96
  * Generate string with placeholders for interpolated expressions.
@@ -215,8 +233,8 @@ const expandComponents = (main, expressions, skipNormalization = false) => {
215
233
  }
216
234
  // Match component tags with backreference to ensure correct pairing.
217
235
  return main.replace(
218
- new RegExp(`<(${PH})([^>]*)>([\\s\\S]*?)</\\1>|<(${PH})([^>]*)/>`,'g'),
219
- (match, openTag, openIdx, nonVoidAttrs, inner, selfClosingTag, selfClosingIdx, selfClosingAttrs) => {
236
+ new RegExp(`<(${PH})([^>]*)/>|<(${PH})([^>]*)>([\\s\\S]*?)</\\4>`,'g'),
237
+ (match, selfClosingTag, selfClosingIdx, selfClosingAttrs, openTag, openIdx, nonVoidAttrs, inner) => {
220
238
  let tag, attributesStr, innerList;
221
239
 
222
240
  if (openTag) {
@@ -246,7 +264,7 @@ const expandComponents = (main, expressions, skipNormalization = false) => {
246
264
  // Add `renderChildren` function to options.
247
265
  if (innerList) {
248
266
  // Evaluate items in parent context and create Partial.
249
- options.renderChildren = () => new core_Partial(innerList.map(item => getExpressionResult(item, this)));
267
+ options.renderChildren = () => new core_Partial(innerList.map(item => getExpressionResult(item, this, 'children')));
250
268
  }
251
269
  // Mount component.
252
270
  return tag.mount(options);
@@ -463,7 +481,7 @@ const parseAttributes = (attributesStr, expressions) => {
463
481
  const PH = Component.PLACEHOLDER('(\\d+)');
464
482
  const attributes = [];
465
483
  // Parse attributes string with support for placeholders in both names and values.
466
- const regExp = new RegExp(`(?:${PH}|([\\w-]+))(?:=(["']?)(?:${PH}|((?:.?(?!["']?\\s+(?:\\S+)=|\\s*/?[>"']))+.))?\\3)?`, 'g');
484
+ const regExp = new RegExp(`(?:${PH}|([\\w-]+))(?:=(["']?)(?:${PH}|((?:.?(?!["']?\\s+(?:\\S+)=|\\s*/>|\\s*[>"']))+.))?\\3)?`, 'g');
467
485
 
468
486
  let attributeMatch;
469
487
  while ((attributeMatch = regExp.exec(attributesStr)) !== null) {
@@ -491,7 +509,7 @@ const parseAttributes = (attributesStr, expressions) => {
491
509
  /*
492
510
  * These option keys will be extended on the component instance.
493
511
  */
494
- const componentOptions = ['key', 'state', 'onCreate', 'onChange', 'onHydrate', 'onRecycle', 'onUpdate'];
512
+ const componentOptions = ['key', 'state', 'onCreate', 'onChange', 'onHydrate', 'onBeforeRecycle', 'onRecycle', 'onBeforeUpdate', 'onUpdate'];
495
513
 
496
514
  /**
497
515
  * @lends module:Component
@@ -664,22 +682,34 @@ class Component extends View {
664
682
  /**
665
683
  * Used internally on the render process.
666
684
  * Reuse a `Component` by replacing the placeholder comment with the real nodes.
667
- * Call `onRecycle` lifecycle method.
668
- * @param parent {node} The parent node.
669
- * @param props {object} The props to set on the recycled component.
685
+ * Calls `onBeforeRecycle` lifecycle method at the beginning, before any recycling operations occur.
686
+ * @param parent {node} The parent node. If not provided, the node is already in the correct position and won't be moved.
670
687
  * @return {Component} The component instance.
671
688
  * @private
672
689
  */
673
- recycle(parent, props) {
690
+ recycle(parent) {
691
+ // Call `onBeforeRecycle` lifecycle method.
692
+ this.onBeforeRecycle.call(this);
693
+ // No parent means the node is already in the correct position. So we don't need to replace it.
674
694
  if (parent) {
675
695
  // Locate the placeholder comment and replace it with the real nodes
676
696
  const placeholder = utils_findComment(parent, Component.MARKER_RECYCLED(this.uid), isComponent);
677
697
  utils_replaceNode(placeholder, this.el);
678
698
  }
679
- // Update props.
680
- if (props) {
681
- this.props.set(props);
682
- }
699
+ // Return `this` for chaining.
700
+ return this;
701
+ }
702
+
703
+ /**
704
+ * Update the component's props.
705
+ * Sets the props and calls the `onRecycle` lifecycle method.
706
+ * @param props {object} The props to set on the component.
707
+ * @return {Component} The component instance.
708
+ * @private
709
+ */
710
+ updateProps(props) {
711
+ // Set the props.
712
+ this.props.set(props);
683
713
  // Call `onRecycle` lifecycle method.
684
714
  this.onRecycle.call(this);
685
715
  // Return `this` for chaining.
@@ -710,7 +740,7 @@ class Component extends View {
710
740
  * import { Component } from 'rasti';
711
741
  * // Create a Title component.
712
742
  * const Title = Component.create`
713
- * <h1>${({ props }) => props.children}</h1>
743
+ * <h1>${({ props }) => props.renderChildren()}</h1>
714
744
  * `;
715
745
  * // Create Main component.
716
746
  * const Main = Component.create`
@@ -844,14 +874,42 @@ class Component extends View {
844
874
  }
845
875
 
846
876
  /**
847
- * Render the `Component`.
848
- * - If `this.el` is not present, the `Component` will be rendered as a string inside a `DocumentFragment` and hydrated, making `this.el` available. The `onHydrate` lifecycle method will be called.
849
- * - If `this.el` is present, the method will update the attributes and inner HTML of the element, or recreate its child component in the case of a container. The `onUpdate` lifecycle method will be called.
850
- * - When rendering child components, recycling happens in two ways:
851
- * - Components with a `key` are recycled if a previous child with the same key exists.
852
- * - Unkeyed components are recycled if they have the same type and position in the template or partial.
853
- * A recycled `Component` will call the `onRecycle` lifecycle method.
854
- * - If the active element is inside the component, it will retain focus after the render.
877
+ * Render the `Component`.
878
+ *
879
+ * **First render (when `this.el` is not present):**
880
+ * This is the initial render call. The component will be rendered as a string inside a `DocumentFragment` and hydrated,
881
+ * making `this.el` available. `this.el` is the root DOM element of the component that can be applied to the DOM.
882
+ * The `onHydrate` lifecycle method will be called.
883
+ *
884
+ * **Note:** Typically, you don't need to call `render()` directly for the first render. The static method `Component.mount()`
885
+ * handles this process automatically, creating the component instance, rendering it, and appending it to the DOM.
886
+ *
887
+ * **Update render (when `this.el` is present):**
888
+ * This indicates the component is being updated. The method will:
889
+ * - Update only the attributes of the root element and child elements
890
+ * - Update only the content of interpolations (the dynamic parts of the template)
891
+ * - For container components (components that render a single child component), update the single interpolation
892
+ *
893
+ * The `onBeforeUpdate` lifecycle method will be called at the beginning, followed by the `onUpdate` lifecycle method at the end.
894
+ *
895
+ * **Child component handling:**
896
+ * When rendering child components, they can be either recreated or recycled:
897
+ *
898
+ * - **Recreation:** A new component instance is created, running the constructor again. This happens when no matching component
899
+ * is found for recycling.
900
+ *
901
+ * - **Recycling:** The same component instance is reused. Recycling happens in two ways:
902
+ * - Components with a `key` are recycled if a previous child with the same key exists
903
+ * - Unkeyed components are recycled if they have the same type and position in the template or partial
904
+ *
905
+ * When a component is recycled:
906
+ * - The `onBeforeRecycle` lifecycle method is called when recycling starts
907
+ * - The component's `this.props` is updated with the new props from the parent
908
+ * - The `onRecycle` lifecycle method is called after props are updated
909
+ *
910
+ * A recycled component may not use props at all and remain unchanged, or it may be subscribed to a different model
911
+ * (or even the same model as the parent) and update independently in subsequent render cycles.
912
+ *
855
913
  * @return {Component} The component instance.
856
914
  */
857
915
  render() {
@@ -863,14 +921,16 @@ class Component extends View {
863
921
  this.hydrate(fragment);
864
922
  return this;
865
923
  }
924
+ // Call `onBeforeUpdate` lifecycle method.
925
+ this.onBeforeUpdate.call(this);
866
926
  // Clear event listeners.
867
927
  this.eventsManager.reset();
868
- // Update elements.
869
- this.template.elements.forEach(element => element.update());
870
928
  // Store previous children.
871
929
  const previousChildren = this.children;
872
930
  // Clear current children.
873
931
  this.children = [];
932
+ // Store props to update.
933
+ const propsQueue = [];
874
934
  // Update interpolations.
875
935
  this.template.interpolations.forEach(interpolation => {
876
936
  // Reset the tracker.
@@ -914,8 +974,10 @@ class Component extends View {
914
974
  const rendered = this.renderTemplatePart(interpolation.expression, addChild, tracker);
915
975
 
916
976
  const recycle = ([recycled, discarded], fragment) => {
917
- // Add child, update props and recycle (move to new position if needed).
918
- this.addChild(recycled).recycle(fragment, discarded.props.toJSON());
977
+ // Store props to update.
978
+ propsQueue.push([recycled, discarded.props.toJSON()]);
979
+ // Add child and recycle (move to new position if needed).
980
+ this.addChild(recycled).recycle(fragment);
919
981
  // Destroy discarded component.
920
982
  discarded.destroy();
921
983
  };
@@ -944,10 +1006,17 @@ class Component extends View {
944
1006
  previousChildren.forEach(prev => {
945
1007
  if (this.children.indexOf(prev) < 0) prev.destroy();
946
1008
  });
947
- // If container, set el to the child element.
1009
+ // Update recycled children props.
1010
+ propsQueue.forEach(([recycled, props]) => {
1011
+ recycled.updateProps(props);
1012
+ });
1013
+ // If this component is a container, set el to the child element.
1014
+ // Otherwise, update elements attributes and delegate events.
948
1015
  if (this.isContainer()) {
949
1016
  this.el = this.children[0].el;
950
1017
  } else {
1018
+ // Update elements attributes.
1019
+ this.template.elements.forEach(element => element.update());
951
1020
  // If there are pending event types, delegate events again.
952
1021
  if (this.eventsManager.hasPendingTypes()) {
953
1022
  this.delegateEvents();
@@ -989,6 +1058,19 @@ class Component extends View {
989
1058
  */
990
1059
  onHydrate() {}
991
1060
 
1061
+ /**
1062
+ * Lifecycle method. Called before the component is recycled and reused between renders.
1063
+ * This method is called at the beginning of the `recycle` method, before any recycling operations occur.
1064
+ *
1065
+ * A component is recycled when:
1066
+ * - It has a `key` and a previous child with the same key exists
1067
+ * - It doesn't have a `key` but has the same type and position in the template or partial
1068
+ *
1069
+ * Use this method to perform operations that need to happen before the component is recycled,
1070
+ * such as storing previous state or preparing for the recycling.
1071
+ */
1072
+ onBeforeRecycle() {}
1073
+
992
1074
  /**
993
1075
  * Lifecycle method. Called when the component is recycled and reused between renders.
994
1076
  *
@@ -1001,6 +1083,14 @@ class Component extends View {
1001
1083
  */
1002
1084
  onRecycle() {}
1003
1085
 
1086
+ /**
1087
+ * Lifecycle method. Called before the component is updated or re-rendered.
1088
+ * This method is called at the beginning of the `render` method when the component's state, model, or props change and trigger a re-render.
1089
+ * Use this method to perform operations that need to happen before the component is updated,
1090
+ * such as saving previous state or preparing for the update.
1091
+ */
1092
+ onBeforeUpdate() {}
1093
+
1004
1094
  /**
1005
1095
  * Lifecycle method. Called when the component is updated or re-rendered.
1006
1096
  * This method is called when the component's state, model, or props change and trigger a re-render.
@@ -1122,7 +1212,7 @@ class Component extends View {
1122
1212
  * ```javascript
1123
1213
  * const Button = Component.create`
1124
1214
  * <button class="${({ props }) => props.className}">
1125
- * ${({ props }) => props.children}
1215
+ * ${({ props }) => props.renderChildren()}
1126
1216
  * </button>
1127
1217
  * `;
1128
1218
  * ```
@@ -1168,14 +1258,14 @@ class Component extends View {
1168
1258
  * // Create a button component.
1169
1259
  * const Button = Component.create`
1170
1260
  * <button class="button">
1171
- * ${({ props }) => props.children}
1261
+ * ${({ props }) => props.renderChildren()}
1172
1262
  * </button>
1173
1263
  * `;
1174
1264
  * // Create a navigation component. Add buttons as children. Iterate over items.
1175
1265
  * const Navigation = Component.create`
1176
1266
  * <nav>
1177
1267
  * ${({ props }) => props.items.map(
1178
- * item => Button.mount({ children : item.label })
1268
+ * item => Button.mount({ renderChildren : () => item.label })
1179
1269
  * )}
1180
1270
  * </nav>
1181
1271
  * `;
@@ -1191,7 +1281,7 @@ class Component extends View {
1191
1281
  * // Create a button component.
1192
1282
  * const Button = Component.create`
1193
1283
  * <button class="button">
1194
- * ${({ props }) => props.children}
1284
+ * ${({ props }) => props.renderChildren()}
1195
1285
  * </button>
1196
1286
  * `;
1197
1287
  * // Create a navigation component. Add buttons as children. Iterate over items.
@@ -1214,7 +1304,7 @@ class Component extends View {
1214
1304
  * // Create a button component.
1215
1305
  * const Button = Component.create`
1216
1306
  * <button class="${({ props }) => props.className}">
1217
- * ${({ props }) => props.children}
1307
+ * ${({ props }) => props.renderChildren()}
1218
1308
  * </button>
1219
1309
  * `;
1220
1310
  * // Create a container that renders a Button component.
@@ -1224,7 +1314,7 @@ class Component extends View {
1224
1314
  * // Create a container that renders a Button component, using a function.
1225
1315
  * const ButtonCancel = Component.create(() => Button.mount({
1226
1316
  * className : 'cancel',
1227
- * children : 'Cancel'
1317
+ * renderChildren : () => 'Cancel'
1228
1318
  * }));
1229
1319
  * ```
1230
1320
  * @static
@@ -1314,7 +1404,7 @@ Component.MARKER_END = (uid) => `rst-e-${uid}`;
1314
1404
  * Components are defined with the {@link #module_component_create Component.create} static method, which takes a tagged template string or a function that returns another component.
1315
1405
  * @module
1316
1406
  * @extends View
1317
- * @param {object} options Object containing options. The following keys will be merged to `this`: model, state, key, onDestroy, onHydrate, onRecycle, onUpdate, onCreate, onChange. Any additional options not in the component or view options list will be automatically extracted as props and stored as `this.props`.
1407
+ * @param {object} options Object containing options. The following keys will be merged to `this`: model, state, key, onDestroy, onHydrate, onBeforeRecycle, onRecycle, onBeforeUpdate, onUpdate, onCreate, onChange. Any additional options not in the component or view options list will be automatically extracted as props and stored as `this.props`.
1318
1408
  * @property {string} [key] A unique key to identify the component. Components with keys are recycled when the same key is found in the previous render. Unkeyed components are recycled based on type and position.
1319
1409
  * @property {Model} [model] A `Model` or any emitter object containing data and business logic. The component will listen to `change` events and call `onChange` lifecycle method.
1320
1410
  * @property {Model} [state] A `Model` or any emitter object containing data and business logic, to be used as internal state. The component will listen to `change` events and call `onChange` lifecycle method.