eleva 1.2.16-beta → 1.2.18-beta

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,26 @@
1
1
  "use strict";
2
2
 
3
+ /**
4
+ * A regular expression to match hyphenated lowercase letters.
5
+ * @private
6
+ * @type {RegExp}
7
+ */
8
+ const CAMEL_RE = /-([a-z])/g;
9
+
3
10
  /**
4
11
  * @class 🎨 Renderer
5
- * @classdesc A DOM renderer that handles efficient DOM updates through patching and diffing.
6
- * Provides methods for updating the DOM by comparing new and old structures and applying
7
- * only the necessary changes, minimizing layout thrashing and improving performance.
12
+ * @classdesc A high-performance DOM renderer that implements an optimized direct DOM diffing algorithm.
13
+ *
14
+ * Key features:
15
+ * - Single-pass diffing algorithm for efficient DOM updates
16
+ * - Key-based node reconciliation for optimal performance
17
+ * - Intelligent attribute handling for ARIA, data attributes, and boolean properties
18
+ * - Preservation of special Eleva-managed instances and style elements
19
+ * - Memory-efficient with reusable temporary containers
20
+ *
21
+ * The renderer is designed to minimize DOM operations while maintaining
22
+ * exact attribute synchronization and proper node identity preservation.
23
+ * It's particularly optimized for frequent updates and complex DOM structures.
8
24
  *
9
25
  * @example
10
26
  * const renderer = new Renderer();
@@ -14,144 +30,201 @@
14
30
  */
15
31
  export class Renderer {
16
32
  /**
17
- * Creates a new Renderer instance with a reusable temporary container for parsing HTML.
33
+ * Creates a new Renderer instance.
18
34
  * @public
19
35
  */
20
36
  constructor() {
21
- /** @private {HTMLElement} Reusable temporary container for parsing new HTML */
37
+ /**
38
+ * A temporary container to hold the new HTML content while diffing.
39
+ * @private
40
+ * @type {HTMLElement}
41
+ */
22
42
  this._tempContainer = document.createElement("div");
23
43
  }
24
44
 
25
45
  /**
26
- * Patches the DOM of a container element with new HTML content.
27
- * Efficiently updates the DOM by parsing new HTML into a reusable container
28
- * and applying only the necessary changes.
46
+ * Patches the DOM of the given container with the provided HTML string.
29
47
  *
30
48
  * @public
31
- * @param {HTMLElement} container - The container element to patch.
32
- * @param {string} newHtml - The new HTML content to apply.
49
+ * @param {HTMLElement} container - The container whose DOM will be patched.
50
+ * @param {string} newHtml - The new HTML string.
51
+ * @throws {TypeError} If the container is not an HTMLElement or newHtml is not a string.
52
+ * @throws {Error} If the DOM patching fails.
33
53
  * @returns {void}
34
- * @throws {Error} If container is not an HTMLElement, newHtml is not a string, or patching fails.
35
54
  */
36
55
  patchDOM(container, newHtml) {
37
56
  if (!(container instanceof HTMLElement)) {
38
- throw new Error("Container must be an HTMLElement");
57
+ throw new TypeError("Container must be an HTMLElement");
39
58
  }
40
59
  if (typeof newHtml !== "string") {
41
- throw new Error("newHtml must be a string");
60
+ throw new TypeError("newHtml must be a string");
42
61
  }
43
62
 
44
63
  try {
45
- // Directly set new HTML, replacing any existing content
46
64
  this._tempContainer.innerHTML = newHtml;
47
-
48
65
  this._diff(container, this._tempContainer);
49
- } catch {
50
- throw new Error("Failed to patch DOM");
66
+ } catch (error) {
67
+ throw new Error(`Failed to patch DOM: ${error.message}`);
51
68
  }
52
69
  }
53
70
 
54
71
  /**
55
- * Diffs two DOM trees (old and new) and applies updates to the old DOM.
56
- * This method recursively compares nodes and their attributes, applying only
57
- * the necessary changes to minimize DOM operations.
72
+ * Performs a diff between two DOM nodes and patches the old node to match the new node.
58
73
  *
59
74
  * @private
60
- * @param {HTMLElement} oldParent - The original DOM element.
61
- * @param {HTMLElement} newParent - The new DOM element.
75
+ * @param {Node} oldParent - The old parent node to be patched.
76
+ * @param {Node} newParent - The new parent node to compare.
62
77
  * @returns {void}
63
78
  */
64
79
  _diff(oldParent, newParent) {
65
- if (oldParent.isEqualNode(newParent)) return;
66
-
67
- const oldChildren = oldParent.childNodes;
68
- const newChildren = newParent.childNodes;
69
- const maxLength = Math.max(oldChildren.length, newChildren.length);
80
+ if (oldParent === newParent || oldParent.isEqualNode?.(newParent)) return;
70
81
 
71
- for (let i = 0; i < maxLength; i++) {
72
- const oldNode = oldChildren[i];
73
- const newNode = newChildren[i];
82
+ const oldChildren = Array.from(oldParent.childNodes);
83
+ const newChildren = Array.from(newParent.childNodes);
84
+ let oldStartIdx = 0,
85
+ newStartIdx = 0;
86
+ let oldEndIdx = oldChildren.length - 1;
87
+ let newEndIdx = newChildren.length - 1;
88
+ let oldKeyMap = null;
74
89
 
75
- if (oldNode?._eleva_instance) {
76
- continue;
77
- }
90
+ while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
91
+ let oldStartNode = oldChildren[oldStartIdx];
92
+ let newStartNode = newChildren[newStartIdx];
78
93
 
79
- if (!oldNode && newNode) {
80
- oldParent.appendChild(newNode.cloneNode(true));
94
+ if (!oldStartNode) {
95
+ oldStartIdx++;
81
96
  continue;
82
97
  }
83
- if (oldNode && !newNode) {
84
- oldParent.removeChild(oldNode);
98
+ if (!newStartNode) {
99
+ newStartIdx++;
85
100
  continue;
86
101
  }
87
102
 
88
- const isSameType =
89
- oldNode.nodeType === newNode.nodeType &&
90
- oldNode.nodeName === newNode.nodeName;
103
+ if (this._keysMatch(oldStartNode, newStartNode)) {
104
+ this._patchNode(oldStartNode, newStartNode);
105
+ oldStartIdx++;
106
+ newStartIdx++;
107
+ } else {
108
+ oldKeyMap ??= this._createKeyMap(oldChildren, oldStartIdx, oldEndIdx);
91
109
 
92
- if (!isSameType) {
93
- oldParent.replaceChild(newNode.cloneNode(true), oldNode);
94
- continue;
95
- }
110
+ const newKey =
111
+ newStartNode.nodeType === Node.ELEMENT_NODE
112
+ ? newStartNode.getAttribute("key")
113
+ : null;
114
+ const moveIndex = newKey ? oldKeyMap.get(newKey) : undefined;
115
+ const oldNodeToMove =
116
+ moveIndex !== undefined ? oldChildren[moveIndex] : null;
96
117
 
97
- if (oldNode.nodeType === Node.ELEMENT_NODE) {
98
- const oldKey = oldNode.getAttribute("key");
99
- const newKey = newNode.getAttribute("key");
118
+ if (oldNodeToMove) {
119
+ this._patchNode(oldNodeToMove, newStartNode);
120
+ oldParent.insertBefore(oldNodeToMove, oldStartNode);
100
121
 
101
- if (oldKey !== newKey && (oldKey || newKey)) {
102
- oldParent.replaceChild(newNode.cloneNode(true), oldNode);
103
- continue;
122
+ if (moveIndex !== undefined) oldChildren[moveIndex] = null;
123
+ } else {
124
+ oldParent.insertBefore(newStartNode.cloneNode(true), oldStartNode);
104
125
  }
126
+ newStartIdx++;
127
+ }
128
+ }
105
129
 
106
- this._updateAttributes(oldNode, newNode);
107
- this._diff(oldNode, newNode);
108
- } else if (
109
- oldNode.nodeType === Node.TEXT_NODE &&
110
- oldNode.nodeValue !== newNode.nodeValue
111
- ) {
112
- oldNode.nodeValue = newNode.nodeValue;
130
+ // Cleanup
131
+ if (oldStartIdx > oldEndIdx) {
132
+ const refNode = newChildren[newEndIdx + 1]
133
+ ? oldChildren[oldStartIdx]
134
+ : null;
135
+ for (let i = newStartIdx; i <= newEndIdx; i++) {
136
+ if (newChildren[i])
137
+ oldParent.insertBefore(newChildren[i].cloneNode(true), refNode);
138
+ }
139
+ } else if (newStartIdx > newEndIdx) {
140
+ for (let i = oldStartIdx; i <= oldEndIdx; i++) {
141
+ const node = oldChildren[i];
142
+ if (
143
+ node &&
144
+ !(node.nodeName === "STYLE" && node.hasAttribute("data-e-style"))
145
+ ) {
146
+ oldParent.removeChild(node);
147
+ }
113
148
  }
114
149
  }
115
150
  }
116
151
 
117
152
  /**
118
- * Updates the attributes of an element to match those of a new element.
119
- * Handles special cases for ARIA attributes, data attributes, and boolean properties.
153
+ * Checks if the node types match.
120
154
  *
121
155
  * @private
122
- * @param {HTMLElement} oldEl - The element to update.
123
- * @param {HTMLElement} newEl - The element providing the updated attributes.
156
+ * @param {Node} oldNode - The old node.
157
+ * @param {Node} newNode - The new node.
158
+ * @returns {boolean} True if the nodes match, false otherwise.
159
+ */
160
+ _keysMatch(oldNode, newNode) {
161
+ if (oldNode.nodeType !== Node.ELEMENT_NODE) return true;
162
+ const oldKey = oldNode.getAttribute("key");
163
+ const newKey = newNode.getAttribute("key");
164
+ return oldKey === newKey;
165
+ }
166
+
167
+ /**
168
+ * Patches a node.
169
+ *
170
+ * @private
171
+ * @param {Node} oldNode - The old node to patch.
172
+ * @param {Node} newNode - The new node to patch.
124
173
  * @returns {void}
125
174
  */
126
- _updateAttributes(oldEl, newEl) {
127
- const oldAttrs = oldEl.attributes;
128
- const newAttrs = newEl.attributes;
175
+ _patchNode(oldNode, newNode) {
176
+ if (oldNode?._eleva_instance) return;
129
177
 
130
- // Remove old attributes
131
- for (const { name } of oldAttrs) {
132
- if (!newEl.hasAttribute(name)) {
133
- oldEl.removeAttribute(name);
134
- }
178
+ if (
179
+ oldNode.nodeType !== newNode.nodeType ||
180
+ oldNode.nodeName !== newNode.nodeName
181
+ ) {
182
+ oldNode.replaceWith(newNode.cloneNode(true));
183
+ return;
184
+ }
185
+
186
+ if (oldNode.nodeType === Node.ELEMENT_NODE) {
187
+ const oldEl = oldNode;
188
+ const newEl = newNode;
189
+ this._updateAttributes(oldEl, newEl);
190
+ this._diff(oldEl, newEl);
191
+ } else if (
192
+ oldNode.nodeType === Node.TEXT_NODE &&
193
+ oldNode.nodeValue !== newNode.nodeValue
194
+ ) {
195
+ oldNode.nodeValue = newNode.nodeValue;
135
196
  }
197
+ }
136
198
 
137
- // Update/add new attributes
138
- for (const attr of newAttrs) {
139
- const { name, value } = attr;
140
- if (name.startsWith("@")) continue;
199
+ /**
200
+ * Updates the attributes of an element.
201
+ *
202
+ * @private
203
+ * @param {HTMLElement} oldEl - The old element to update.
204
+ * @param {HTMLElement} newEl - The new element to update.
205
+ * @returns {void}
206
+ */
207
+ _updateAttributes(oldEl, newEl) {
208
+ const oldAttrs = oldEl.attributes;
209
+ const newAttrs = newEl.attributes;
141
210
 
142
- if (oldEl.getAttribute(name) === value) continue;
211
+ // Single pass for new/updated attributes
212
+ for (let i = 0; i < newAttrs.length; i++) {
213
+ const { name, value } = newAttrs[i];
214
+ if (name[0] === "@" || oldEl.getAttribute(name) === value) continue;
143
215
 
144
216
  oldEl.setAttribute(name, value);
145
217
 
146
- if (name.startsWith("aria-")) {
147
- const prop =
148
- "aria" +
149
- name.slice(5).replace(/-([a-z])/g, (_, l) => l.toUpperCase());
150
- oldEl[prop] = value;
151
- } else if (name.startsWith("data-")) {
218
+ if (name[0] === "a" && name[4] === "-") {
219
+ const s = name.slice(5);
220
+ oldEl["aria" + s.replace(CAMEL_RE, (_, l) => l.toUpperCase())] = value;
221
+ } else if (name[0] === "d" && name[3] === "-") {
152
222
  oldEl.dataset[name.slice(5)] = value;
153
223
  } else {
154
- const prop = name.replace(/-([a-z])/g, (_, l) => l.toUpperCase());
224
+ const prop = name.includes("-")
225
+ ? name.replace(CAMEL_RE, (_, l) => l.toUpperCase())
226
+ : name;
227
+
155
228
  if (prop in oldEl) {
156
229
  const descriptor = Object.getOwnPropertyDescriptor(
157
230
  Object.getPrototypeOf(oldEl),
@@ -161,7 +234,6 @@ export class Renderer {
161
234
  typeof oldEl[prop] === "boolean" ||
162
235
  (descriptor?.get &&
163
236
  typeof descriptor.get.call(oldEl) === "boolean");
164
-
165
237
  if (isBoolean) {
166
238
  oldEl[prop] =
167
239
  value !== "false" &&
@@ -172,5 +244,34 @@ export class Renderer {
172
244
  }
173
245
  }
174
246
  }
247
+
248
+ // Remove any attributes no longer present
249
+ for (let i = oldAttrs.length - 1; i >= 0; i--) {
250
+ const name = oldAttrs[i].name;
251
+ if (!newEl.hasAttribute(name)) {
252
+ oldEl.removeAttribute(name);
253
+ }
254
+ }
255
+ }
256
+
257
+ /**
258
+ * Creates a key map for the children of a parent node.
259
+ *
260
+ * @private
261
+ * @param {Array<Node>} children - The children of the parent node.
262
+ * @param {number} start - The start index of the children.
263
+ * @param {number} end - The end index of the children.
264
+ * @returns {Map<string, number>} A map of key to child index.
265
+ */
266
+ _createKeyMap(children, start, end) {
267
+ const map = new Map();
268
+ for (let i = start; i <= end; i++) {
269
+ const child = children[i];
270
+ if (child?.nodeType === Node.ELEMENT_NODE) {
271
+ const key = child.getAttribute("key");
272
+ if (key) map.set(key, i);
273
+ }
274
+ }
275
+ return map;
175
276
  }
176
277
  }
@@ -5,6 +5,8 @@
5
5
  * @classdesc A reactive data holder that enables fine-grained reactivity in the Eleva framework.
6
6
  * Signals notify registered watchers when their value changes, enabling efficient DOM updates
7
7
  * through targeted patching rather than full re-renders.
8
+ * Updates are batched using microtasks to prevent multiple synchronous notifications.
9
+ * The class is generic, allowing type-safe handling of any value type T.
8
10
  *
9
11
  * @example
10
12
  * const count = new Signal(0);
@@ -17,12 +19,12 @@ export class Signal {
17
19
  * Creates a new Signal instance with the specified initial value.
18
20
  *
19
21
  * @public
20
- * @param {*} value - The initial value of the signal.
22
+ * @param {T} value - The initial value of the signal.
21
23
  */
22
24
  constructor(value) {
23
- /** @private {T} Internal storage for the signal's current value, where T is the type of the initial value */
25
+ /** @private {T} Internal storage for the signal's current value */
24
26
  this._value = value;
25
- /** @private {Set<function(T): void>} Collection of callback functions to be notified when value changes, where T is the value type */
27
+ /** @private {Set<(value: T) => void>} Collection of callback functions to be notified when value changes */
26
28
  this._watchers = new Set();
27
29
  /** @private {boolean} Flag to prevent multiple synchronous watcher notifications and batch updates into microtasks */
28
30
  this._pending = false;
@@ -32,7 +34,7 @@ export class Signal {
32
34
  * Gets the current value of the signal.
33
35
  *
34
36
  * @public
35
- * @returns {T} The current value, where T is the type of the initial value.
37
+ * @returns {T} The current value.
36
38
  */
37
39
  get value() {
38
40
  return this._value;
@@ -43,7 +45,7 @@ export class Signal {
43
45
  * The notification is batched using microtasks to prevent multiple synchronous updates.
44
46
  *
45
47
  * @public
46
- * @param {T} newVal - The new value to set, where T is the type of the initial value.
48
+ * @param {T} newVal - The new value to set.
47
49
  * @returns {void}
48
50
  */
49
51
  set value(newVal) {
@@ -58,8 +60,8 @@ export class Signal {
58
60
  * The watcher will receive the new value as its argument.
59
61
  *
60
62
  * @public
61
- * @param {function(T): void} fn - The callback function to invoke on value change, where T is the value type.
62
- * @returns {function(): boolean} A function to unsubscribe the watcher.
63
+ * @param {(value: T) => void} fn - The callback function to invoke on value change.
64
+ * @returns {() => boolean} A function to unsubscribe the watcher.
63
65
  * @example
64
66
  * const unsubscribe = signal.watch((value) => console.log(value));
65
67
  * // Later...
@@ -83,6 +85,7 @@ export class Signal {
83
85
 
84
86
  this._pending = true;
85
87
  queueMicrotask(() => {
88
+ /** @type {(fn: (value: T) => void) => void} */
86
89
  this._watchers.forEach((fn) => fn(this._value));
87
90
  this._pending = false;
88
91
  });
@@ -14,6 +14,7 @@
14
14
  export class TemplateEngine {
15
15
  /**
16
16
  * @private {RegExp} Regular expression for matching template expressions in the format {{ expression }}
17
+ * @type {RegExp}
17
18
  */
18
19
  static expressionPattern = /\{\{\s*(.*?)\s*\}\}/g;
19
20
 
@@ -24,7 +25,7 @@ export class TemplateEngine {
24
25
  * @public
25
26
  * @static
26
27
  * @param {string} template - The template string to parse.
27
- * @param {Object} data - The data context for evaluating expressions.
28
+ * @param {Record<string, unknown>} data - The data context for evaluating expressions.
28
29
  * @returns {string} The parsed template with expressions replaced by their values.
29
30
  * @example
30
31
  * const result = TemplateEngine.parse("{{user.name}} is {{user.age}} years old", {
@@ -41,12 +42,14 @@ export class TemplateEngine {
41
42
  /**
42
43
  * Evaluates an expression in the context of the provided data object.
43
44
  * Note: This does not provide a true sandbox and evaluated expressions may access global scope.
45
+ * The use of the `with` statement is necessary for expression evaluation but has security implications.
46
+ * Expressions should be carefully validated before evaluation.
44
47
  *
45
48
  * @public
46
49
  * @static
47
50
  * @param {string} expression - The expression to evaluate.
48
- * @param {Object} data - The data context for evaluation.
49
- * @returns {*} The result of the evaluation, or an empty string if evaluation fails.
51
+ * @param {Record<string, unknown>} data - The data context for evaluation.
52
+ * @returns {unknown} The result of the evaluation, or an empty string if evaluation fails.
50
53
  * @example
51
54
  * const result = TemplateEngine.evaluate("user.name", { user: { name: "John" } }); // Returns: "John"
52
55
  * const age = TemplateEngine.evaluate("user.age", { user: { age: 30 } }); // Returns: 30