rasti 3.0.1 → 4.0.0-alpha.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.
Files changed (64) hide show
  1. package/README.md +42 -11
  2. package/dist/rasti.js +1767 -622
  3. package/dist/rasti.min.js +1 -1
  4. package/es/Component.js +728 -467
  5. package/es/Emitter.js +182 -28
  6. package/es/Model.js +237 -51
  7. package/es/View.js +73 -31
  8. package/es/core/Element.js +55 -0
  9. package/es/core/EventsManager.js +41 -0
  10. package/es/core/Interpolation.js +70 -0
  11. package/es/core/InterpolationWrapper.js +14 -0
  12. package/es/core/Partial.js +12 -0
  13. package/es/core/PathManager.js +88 -0
  14. package/es/core/SafeHTML.js +17 -0
  15. package/es/index.js +13 -0
  16. package/es/utils/deepFlat.js +4 -2
  17. package/es/utils/findComment.js +42 -0
  18. package/es/utils/getAttributesDiff.js +33 -0
  19. package/es/utils/getAttributesHTML.js +25 -0
  20. package/es/utils/getResult.js +4 -2
  21. package/es/utils/parseHTML.js +14 -0
  22. package/es/utils/syncNode.js +109 -0
  23. package/es/utils/validateListener.js +14 -0
  24. package/lib/Component.cjs +729 -468
  25. package/lib/Emitter.cjs +182 -28
  26. package/lib/Model.cjs +237 -51
  27. package/lib/View.cjs +73 -31
  28. package/lib/core/Element.cjs +57 -0
  29. package/lib/core/EventsManager.cjs +43 -0
  30. package/lib/core/Interpolation.cjs +72 -0
  31. package/lib/core/InterpolationWrapper.cjs +16 -0
  32. package/lib/core/Partial.cjs +14 -0
  33. package/lib/core/PathManager.cjs +90 -0
  34. package/lib/core/SafeHTML.cjs +19 -0
  35. package/lib/index.cjs +13 -0
  36. package/lib/utils/deepFlat.cjs +4 -2
  37. package/lib/utils/findComment.cjs +44 -0
  38. package/lib/utils/getAttributesDiff.cjs +35 -0
  39. package/lib/utils/getAttributesHTML.cjs +27 -0
  40. package/lib/utils/getResult.cjs +4 -2
  41. package/lib/utils/parseHTML.cjs +16 -0
  42. package/lib/utils/syncNode.cjs +111 -0
  43. package/lib/utils/validateListener.cjs +16 -0
  44. package/package.json +11 -8
  45. package/src/Component.js +725 -466
  46. package/src/Emitter.js +182 -28
  47. package/src/Model.js +236 -51
  48. package/src/View.js +73 -31
  49. package/src/core/Element.js +55 -0
  50. package/src/core/EventsManager.js +41 -0
  51. package/src/core/Interpolation.js +70 -0
  52. package/src/core/InterpolationWrapper.js +14 -0
  53. package/src/core/Partial.js +12 -0
  54. package/src/core/PathManager.js +88 -0
  55. package/src/core/SafeHTML.js +17 -0
  56. package/src/index.js +4 -5
  57. package/src/utils/deepFlat.js +4 -2
  58. package/src/utils/findComment.js +40 -0
  59. package/src/utils/getAttributesDiff.js +31 -0
  60. package/src/utils/getAttributesHTML.js +23 -0
  61. package/src/utils/getResult.js +6 -2
  62. package/src/utils/parseHTML.js +12 -0
  63. package/src/utils/syncNode.js +107 -0
  64. package/src/utils/validateListener.js +12 -0
package/lib/Component.cjs CHANGED
@@ -1,26 +1,23 @@
1
1
  'use strict';
2
2
 
3
+ require('./Emitter.cjs');
4
+ var Model = require('./Model.cjs');
3
5
  var View = require('./View.cjs');
6
+ var core_SafeHTML = require('./core/SafeHTML.cjs');
7
+ var core_Partial = require('./core/Partial.cjs');
8
+ var core_InterpolationWrapper = require('./core/InterpolationWrapper.cjs');
9
+ var core_EventsManager = require('./core/EventsManager.cjs');
10
+ var core_PathManager = require('./core/PathManager.cjs');
11
+ var core_Element = require('./core/Element.cjs');
12
+ var core_Interpolation = require('./core/Interpolation.cjs');
13
+ var utils_validateListener = require('./utils/validateListener.cjs');
4
14
  var utils_getResult = require('./utils/getResult.cjs');
5
15
  var utils_deepFlat = require('./utils/deepFlat.cjs');
6
- require('./Emitter.cjs');
7
-
8
- /**
9
- * Wrapper class for HTML strings marked as safe.
10
- * @class SafeHTML
11
- * @param {string} value The HTML string to be marked as safe.
12
- * @property {string} value The HTML string.
13
- * @private
14
- */
15
- class SafeHTML {
16
- constructor(value) {
17
- this.value = value;
18
- }
19
-
20
- toString() {
21
- return this.value;
22
- }
23
- }
16
+ var utils_parseHTML = require('./utils/parseHTML.cjs');
17
+ var utils_findComment = require('./utils/findComment.cjs');
18
+ var utils_getAttributesHTML = require('./utils/getAttributesHTML.cjs');
19
+ require('./utils/getAttributesDiff.cjs');
20
+ require('./utils/syncNode.cjs');
24
21
 
25
22
  /**
26
23
  * Same as getResult, but pass context as argument to the expression.
@@ -32,10 +29,28 @@ class SafeHTML {
32
29
  */
33
30
  const getExpressionResult = (expression, context) => utils_getResult(expression, context, context);
34
31
 
32
+ /**
33
+ * Check if an element is a component root element.
34
+ * Component root elements have the data attribute ending with '-1'.
35
+ * @param {Element} el The element to check.
36
+ * @return {boolean} True if the element is a component root element.
37
+ * @private
38
+ */
39
+ const isComponent = (el) => el.hasAttribute(Component.ATTRIBUTE_ELEMENT) && el.getAttribute(Component.ATTRIBUTE_ELEMENT).endsWith('-1');
40
+
41
+ /**
42
+ * Check if an element has the Rasti data attribute.
43
+ * This includes both component root elements and regular tracked elements.
44
+ * @param {Element} el The element to check.
45
+ * @return {boolean} True if the element has the data attribute.
46
+ * @private
47
+ */
48
+ const isElement = (el) => el.hasAttribute(Component.ATTRIBUTE_ELEMENT);
49
+
35
50
  /**
36
51
  * Generate string with placeholders for interpolated expressions.
37
- * @param strings {array} Array of strings.
38
- * @param expressions {array} Array of expressions.
52
+ * @param {Array<string>} strings Array of strings.
53
+ * @param {Array<any>} expressions Array of expressions.
39
54
  * @return {string} String with placeholders.
40
55
  * @private
41
56
  */
@@ -45,7 +60,7 @@ const addPlaceholders = (strings, expressions) =>
45
60
  out.push(string);
46
61
  // Add expression placeholders.
47
62
  if (typeof expressions[i] !== 'undefined') {
48
- out.push(Component.PLACEHOLDER_EXPRESSION(i));
63
+ out.push(Component.PLACEHOLDER(i));
49
64
  }
50
65
  return out;
51
66
  }, []).join('');
@@ -53,12 +68,12 @@ const addPlaceholders = (strings, expressions) =>
53
68
  /**
54
69
  * Generate one dimensional array with strings and expressions.
55
70
  * @param main {string} The main template containing placeholders.
56
- * @param expressions {array} Array of expressions to replace placeholders.
71
+ * @param {Array<any>} expressions Array of expressions to replace placeholders.
57
72
  * @return {array} Array containing strings and expressions.
58
73
  * @private
59
74
  */
60
75
  const splitPlaceholders = (main, expressions) => {
61
- const PH = Component.PLACEHOLDER_EXPRESSION('(\\d+)');
76
+ const PH = Component.PLACEHOLDER('(\\d+)');
62
77
  const regExp = new RegExp(`${PH}`, 'g');
63
78
  const out = [];
64
79
  let lastIndex = 0;
@@ -77,47 +92,60 @@ const splitPlaceholders = (main, expressions) => {
77
92
 
78
93
  /**
79
94
  * Expand attributes.
80
- * @param attributes {array} Array of attributes as key, value pairs.
81
- * @param getExpressionResult {function} Function to render expressions.
95
+ * @param {Array<Array<any>>} attributes Array of attributes as key, value pairs.
96
+ * @param {Function} getExpressionResult Function to render expressions.
82
97
  * @return {object}
83
98
  * @property {object} all All attributes.
84
99
  * @property {object} events Event listeners.
85
100
  * @property {object} attributes Attributes.
86
101
  * @private
87
102
  */
88
- const expandAttributes = (attributes, getExpressionResult) => {
89
- const out = attributes.reduce((out, pair) => {
90
- const attribute = getExpressionResult(pair[0]);
91
- // Attribute without value.
92
- if (pair.length === 1) {
93
- if (typeof attribute === 'object') {
94
- // Expand objects as attributes.
95
- out.all = Object.assign(out.all, attribute);
96
- } else if (typeof attribute === 'string') {
97
- // Treat as boolean.
98
- out.all[attribute] = true;
99
- }
100
- } else {
101
- // Attribute with value.
102
- const value = getExpressionResult(pair[1]);
103
- out.all[attribute] = value;
103
+ const expandAttributes = (attributes, getExpressionResult) => attributes.reduce((out, pair) => {
104
+ const attribute = getExpressionResult(pair[0]);
105
+ // Attribute without value.
106
+ if (pair.length === 1) {
107
+ if (typeof attribute === 'object') {
108
+ // Expand objects as attributes.
109
+ out = Object.assign(out, attribute);
110
+ } else if (typeof attribute === 'string') {
111
+ // Treat as boolean.
112
+ out[attribute] = true;
104
113
  }
114
+ } else {
115
+ // Attribute with value.
116
+ const value = pair[2] ? getExpressionResult(pair[1]) : pair[1];
117
+ out[attribute] = value;
118
+ }
105
119
 
106
- return out;
107
- }, { all : {}, events : {}, attributes : {} });
120
+ return out;
121
+ }, {});
108
122
 
109
- Object.keys(out.all).forEach(key => {
123
+ /**
124
+ * Expand events.
125
+ * @param {object} attributes Attributes object.
126
+ * @param {EventsManager} eventsManager Events manager.
127
+ * @return {object} Attributes object.
128
+ * @private
129
+ */
130
+ const expandEvents = (attributes, eventsManager) => {
131
+ const out = {};
132
+ Object.keys(attributes).forEach(key => {
110
133
  // Check if key is an event listener.
111
134
  const match = key.match(/on(([A-Z]{1}[a-z]+)+)/);
135
+
112
136
  if (match && match[1]) {
113
- // Add event listener.
114
- out.events[match[1].toLowerCase()] = out.all[key];
137
+ const type = match[1].toLowerCase();
138
+ const listener = attributes[key];
139
+ if (listener) {
140
+ const index = eventsManager.addListener(listener, type);
141
+ // Add event listener index.
142
+ out[Component.ATTRIBUTE_EVENT(type)] = index;
143
+ }
115
144
  } else {
116
145
  // Add attribute.
117
- out.attributes[key] = out.all[key];
146
+ out[key] = attributes[key];
118
147
  }
119
148
  });
120
-
121
149
  return out;
122
150
  };
123
151
 
@@ -128,177 +156,351 @@ const expandAttributes = (attributes, getExpressionResult) => {
128
156
  * Returns the template with component tags replaced by expressions placeholders
129
157
  * modifies the expressions array adding the mount functions.
130
158
  * @param main {string} The main template.
159
+ * @param {Array<any>} expressions Array of expressions.
131
160
  * @return {string} The template with components tags replaced by expressions
132
161
  * placeholders.
133
162
  * @private
134
163
  */
135
164
  const expandComponents = (main, expressions) => {
136
- const PH = Component.PLACEHOLDER_EXPRESSION('(\\d+)');
165
+ const PH = Component.PLACEHOLDER('(\\d+)');
137
166
  // Match component tags.
138
167
  return main.replace(
139
168
  new RegExp(`<(${PH})([^>]*)>([\\s\\S]*?)</(${PH})>|<(${PH})([^>]*)/>`,'g'),
140
- function() {
141
- const { tag, attributes, inner, close, raw } = parseMatch(arguments, expressions);
169
+ (match, openTag, openIdx, nonVoidAttrs, inner, closeTag, closeIdx, selfClosingTag, selfClosingIdx, selfClosingAttrs) => {
170
+ let tag, close, attributesStr;
171
+
172
+ if (openTag) {
173
+ tag = typeof openIdx !== 'undefined' ? expressions[openIdx] : openTag;
174
+ close = typeof closeIdx !== 'undefined' ? expressions[closeIdx] : closeTag;
175
+ attributesStr = nonVoidAttrs;
176
+ } else {
177
+ tag = typeof selfClosingIdx !== 'undefined' ? expressions[selfClosingIdx] : selfClosingTag;
178
+ attributesStr = selfClosingAttrs;
179
+ }
142
180
  // No component found.
143
- if (!(tag.prototype instanceof Component)) return raw;
181
+ if (!(tag.prototype instanceof Component)) return match;
144
182
 
145
- let renderChildren;
183
+ let innerList;
146
184
  // Non void component.
147
185
  if (close) {
148
186
  // Close component tag must match open component tag.
149
- if (tag !== close) return raw;
187
+ if (tag !== close) return match;
188
+ // Process inner content same way as partial().
150
189
  // Recursively expand inner components.
151
- const list = splitPlaceholders(expandComponents(inner, expressions), expressions);
152
- // Create renderChildren function.
153
- renderChildren = function() {
154
- return utils_deepFlat(list.map(item => getExpressionResult(item, this)));
155
- };
190
+ const innerTemplate = expandComponents(inner, expressions);
191
+ // Parse partial elements to handle dynamic attributes and events.
192
+ const parsedInner = parsePartialElements(innerTemplate, expressions);
193
+ // Split into items.
194
+ innerList = splitPlaceholders(parsedInner, expressions);
156
195
  }
196
+ // Parse attributes.
197
+ const attributes = parseAttributes(attributesStr, expressions);
157
198
  // Create mount function.
158
199
  const mount = function() {
159
- const options = expandAttributes(attributes, value => getExpressionResult(value, this)).all;
160
- // Add renderChildren function to options.
161
- if (renderChildren) options.renderChildren = renderChildren.bind(this);
200
+ const options = expandAttributes(attributes, value => getExpressionResult(value, this));
201
+ // Add `renderChildren` function to options.
202
+ if (innerList) {
203
+ // Evaluate items in parent context and create Partial.
204
+ options.renderChildren = () => new core_Partial(innerList.map(item => getExpressionResult(item, this)));
205
+ }
162
206
  // Mount component.
163
207
  return tag.mount(options);
164
208
  };
165
209
  // Add mount function to expression.
166
210
  expressions.push(mount);
167
211
  // Replace whole string with expression placeholder.
168
- return Component.PLACEHOLDER_EXPRESSION(expressions.length - 1);
212
+ return Component.PLACEHOLDER(expressions.length - 1);
169
213
  }
170
214
  );
171
215
  };
172
216
 
173
217
  /**
174
- * Parse match data to get tag, attributes, inner html and close tag.
175
- * @param match {array}
176
- * @return {object}
177
- * @property {string} tag The tag.
178
- * @property {string} inner The inner html.
179
- * @property {string} close The closing tag.
180
- * @property {array} attributes Array of attributes as key, value pairs.
181
- * @property {string} raw The whole match.
218
+ * Replace elements in template.
219
+ * @param {string} template Template string.
220
+ * @param {Function} replacer Replacer function.
221
+ * @return {string} Template string with replaced elements.
182
222
  * @private
183
223
  */
184
- const parseMatch = (match, expressions) => {
185
- const PH = Component.PLACEHOLDER_EXPRESSION('(\\d+)');
224
+ const replaceElements = (template, replacer) => {
225
+ const PH = Component.PLACEHOLDER('(?:\\d+)');
226
+ return template.replace(
227
+ new RegExp(`<(${PH}|[a-z]+[1-6]?)(?:\\s*)((?:"[^"]*"|'[^']*'|[^>])*)(/?>)`, 'gi'),
228
+ replacer
229
+ );
230
+ };
186
231
 
187
- const [all, openTag, openIdx, nonVoidAttrs, inner, closeTag, closeIdx,
188
- selfClosingTag, selfClosingIdx, selfClosingAttrs] = match;
232
+ /**
233
+ * Parse all HTML elements in template and extract their attributes.
234
+ * @param {string} template Template string with placeholders.
235
+ * @param {Array} expressions Array of expressions.
236
+ * @param {Array} elements Array to store element references.
237
+ * @return {string} Template with parsed attributes.
238
+ * @throws {SyntaxError} If the template does not have a single root element or is a container component.
239
+ * @private
240
+ */
241
+ const parseElements = (template, expressions, elements) => {
242
+ const PH = Component.PLACEHOLDER('(?:\\d+)');
243
+ // Check if template is a container (single placeholder, no tag).
244
+ const containerMatch = template.match(new RegExp(`^\\s*${PH}\\s*$`));
245
+ if (containerMatch) return template;
246
+ // Validate that template has a root element.
247
+ const rootElementMatch = template.match(new RegExp(`^\\s*<([a-z]+[1-6]?|${PH})([^>]*)>([\\s\\S]*?)</(\\1|${PH})>\\s*$|^\\s*<([a-z]+[1-6]?|${PH})([^>]*)/>\\s*$`));
248
+ if (!rootElementMatch) throw new SyntaxError(`Template must have a single root element or be a container component: "${template.trim()}"`);
249
+
250
+ let elementUid = 0;
251
+ // Match all HTML elements including placeholders and self-closed elements.
252
+ return replaceElements(template, (match, tag, attributesStr, ending) => {
253
+ const isRoot = elementUid === 0;
254
+ const currentElementUid = ++elementUid;
255
+ // If there are no dynamic attributes, return original match.
256
+ if (!isRoot && !attributesStr.match(new RegExp(PH))) {
257
+ return match;
258
+ }
259
+ // Parse attributes.
260
+ const parsedAttributes = parseAttributes(attributesStr, expressions);
261
+ // Create element reference.
262
+ const generateElementUid = componentUid => `${componentUid}-${currentElementUid}`;
263
+ // Create function that returns attributes object.
264
+ const getAttributes = function() {
265
+ // Expand attributes and events.
266
+ const attributes = expandEvents(
267
+ expandAttributes(parsedAttributes, value => getExpressionResult(value, this)),
268
+ this.eventsManager
269
+ );
270
+ // Extend template attributes with `options.attributes`.
271
+ if (isRoot && this.attributes) {
272
+ Object.assign(attributes, utils_getResult(this.attributes, this));
273
+ }
274
+ // Add data attribute for element identification.
275
+ // First element gets the component uid, others get element uid.
276
+ attributes[Component.ATTRIBUTE_ELEMENT] = generateElementUid(this.uid);
277
+
278
+ return attributes;
279
+ };
280
+
281
+ const getSelector = function() {
282
+ return `[${Component.ATTRIBUTE_ELEMENT}="${generateElementUid(this.uid)}"]`;
283
+ };
284
+ // Add element reference to elements array.
285
+ elements.push({
286
+ getSelector,
287
+ getAttributes,
288
+ });
289
+ // Add new expression to expressions array.
290
+ expressions.push(function() {
291
+ const attributes = getAttributes.call(this);
292
+ return Component.markAsSafeHTML(utils_getAttributesHTML(attributes));
293
+ });
294
+ // Replace attributes with placeholder.
295
+ const placeholder = Component.PLACEHOLDER(expressions.length - 1);
296
+ // Preserve original tag ending (> or />)
297
+ return `<${tag} ${placeholder}${ending}`;
298
+ });
299
+ };
189
300
 
190
- const data = { raw : all, attributes : [] };
301
+ /**
302
+ * Parse elements in partial template.
303
+ * @param {string} template Template string with placeholders.
304
+ * @param {Array} expressions Array of expressions.
305
+ * @return {string} Template with parsed attributes.
306
+ * @private
307
+ */
308
+ const parsePartialElements = (template, expressions) => {
309
+ const PH = Component.PLACEHOLDER('(?:\\d+)');
310
+ // Match all HTML elements including placeholders and self-closed elements.
311
+ return replaceElements(template, (match, tag, attributesStr, ending) => {
312
+ // If there are no dynamic attributes, return original match.
313
+ if (!attributesStr.match(new RegExp(PH))) {
314
+ return match;
315
+ }
316
+ // Parse attributes.
317
+ const parsedAttributes = parseAttributes(attributesStr, expressions);
318
+ // Create function that returns attributes object.
319
+ const getAttributes = function() {
320
+ const attributes = expandEvents(
321
+ expandAttributes(parsedAttributes, value => getExpressionResult(value, this)),
322
+ this.eventsManager
323
+ );
324
+
325
+ return attributes;
326
+ };
327
+ // Add new expression to expressions array.
328
+ expressions.push(function() {
329
+ const attributes = getAttributes.call(this);
330
+ return Component.markAsSafeHTML(utils_getAttributesHTML(attributes));
331
+ });
332
+ // Replace attributes with placeholder.
333
+ const placeholder = Component.PLACEHOLDER(expressions.length - 1);
334
+ // Preserve original tag ending (> or />)
335
+ return `<${tag} ${placeholder}${ending}`;
336
+ });
337
+ };
191
338
 
192
- let attributesStr;
193
- if (openTag) {
194
- // Non void element.
195
- data.tag = typeof openIdx !== 'undefined' ? expressions[openIdx] : openTag;
196
- data.inner = inner;
197
- data.close = typeof closeIdx !== 'undefined' ? expressions[closeIdx] : closeTag;
198
- attributesStr = nonVoidAttrs;
199
- } else {
200
- // Self closing element.
201
- data.tag = typeof selfClosingIdx !== 'undefined' ? expressions[selfClosingIdx] : selfClosingTag;
202
- attributesStr = selfClosingAttrs;
203
- }
204
- // Parse attributes.
339
+ /**
340
+ * Parse all interpolations in template text content.
341
+ * @param {string} template Template string with placeholders.
342
+ * @param {Array} expressions Array of expressions.
343
+ * @param {Array} interpolations Array to store interpolation references.
344
+ * @return {string} Template with interpolation markers.
345
+ * @private
346
+ */
347
+ const parseInterpolations = (template, expressions, interpolations) => {
348
+ const PH = Component.PLACEHOLDER('(\\d+)');
349
+ let interpolationUid = 0;
350
+ // Match all expression placeholders.
351
+ return template.replace(
352
+ new RegExp(PH, 'g'),
353
+ function(match, expressionIndex, offset) {
354
+ // Check if this placeholder is inside an element tag (attribute).
355
+ // `offset` is the index of the match in the original string.
356
+ const beforeMatch = template.substring(0, offset);
357
+ const lastOpenTag = beforeMatch.lastIndexOf('<');
358
+ const lastCloseTag = beforeMatch.lastIndexOf('>');
359
+ // If we're inside an element tag, don't process as interpolation.
360
+ if (lastOpenTag > lastCloseTag) {
361
+ return match;
362
+ }
363
+
364
+ const currentInterpolationUid = ++interpolationUid;
365
+
366
+ function getStart() {
367
+ return Component.MARKER_START(`${this.uid}-${currentInterpolationUid}`);
368
+ }
369
+ function getEnd() {
370
+ return Component.MARKER_END(`${this.uid}-${currentInterpolationUid}`);
371
+ }
372
+ // Add interpolation reference to interpolations array.
373
+ interpolations.push({
374
+ getStart,
375
+ getEnd,
376
+ expression : expressions[expressionIndex]
377
+ });
378
+ // Add new expression to expressions array.
379
+ expressions.push(function() {
380
+ const result = getExpressionResult(expressions[expressionIndex], this);
381
+ const uid = `${this.uid}-${currentInterpolationUid}`;
382
+ return new core_InterpolationWrapper(uid, result);
383
+ });
384
+ // Replace with new placeholder.
385
+ return Component.PLACEHOLDER(expressions.length - 1);
386
+ }
387
+ );
388
+ };
389
+
390
+ /**
391
+ * Parse attributes string to extract dynamic attributes.
392
+ * @param {string} attributesStr Attributes string from HTML element.
393
+ * @param {Array} expressions Array of expressions.
394
+ * @return {Array} Array of attribute pairs [key, value] or [key, value, hasQuotes].
395
+ * @private
396
+ */
397
+ const parseAttributes = (attributesStr, expressions) => {
398
+ const PH = Component.PLACEHOLDER('(\\d+)');
399
+ const attributes = [];
400
+ // Parse attributes string with support for placeholders in both names and values.
205
401
  const regExp = new RegExp(`(${PH}|[\\w-]+)(?:=(["']?)(?:${PH}|((?:.?(?!["']?\\s+(?:\\S+)=|\\s*/?[>"']))+.))\\3)?`, 'g');
206
402
 
207
403
  let attributeMatch;
208
404
  while ((attributeMatch = regExp.exec(attributesStr)) !== null) {
209
- const [, attribute, attributeIdx,, valueIdx, value] = attributeMatch;
405
+ const [, attribute, attributeIdx, quotes, valueIdx, value] = attributeMatch;
210
406
 
211
- const attr = typeof attributeIdx !== 'undefined' ? expressions[attributeIdx] : attribute;
212
- const val = typeof valueIdx !== 'undefined' ? expressions[valueIdx] : value;
407
+ const attr = typeof attributeIdx !== 'undefined' ? expressions[parseInt(attributeIdx, 10)] : attribute;
408
+ const val = typeof valueIdx !== 'undefined' ? expressions[parseInt(valueIdx, 10)] : value;
213
409
 
214
410
  if (typeof val !== 'undefined') {
215
- data.attributes.push([attr, val]);
411
+ attributes.push([attr, val, !!quotes]);
216
412
  } else {
217
- data.attributes.push([attr]);
413
+ attributes.push([attr]);
218
414
  }
219
415
  }
220
416
 
221
- return data;
222
- };
223
-
224
- /*
225
- * HTML tags that are self closing.
226
- */
227
- const selfClosingTags = {
228
- area : true, base : true, br : true, col : true, embed : true, hr : true,
229
- img : true, input : true, link : true, meta : true, source : true, track : true, wbr : true
417
+ return attributes;
230
418
  };
231
419
 
232
420
  /*
233
421
  * These option keys will be extended on the component instance.
234
422
  */
235
- const componentOptions = ['key', 'state', 'onCreate', 'onChange', 'onRender'];
423
+ const componentOptions = ['key', 'state', 'onCreate', 'onChange', 'onHydrate', 'onRecycle', 'onUpdate'];
236
424
 
237
425
  /**
238
- * Components are a special kind of `View` that is designed to be easily composable,
239
- * making it simple to add child views and build complex user interfaces.
240
- * Unlike views, which are render-agnostic, components have a specific set of rendering
241
- * guidelines that allow for a more declarative development style.
242
- * 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.
243
- * @module
244
- * @extends Rasti.View
245
- * @param {object} options Object containing options. The following keys will be merged to `this`: model, state, key, onDestroy, onRender, onCreate, onChange.
246
- * @property {string} key A unique key to identify the component. Used to recycle child components.
247
- * @property {object} model A `Rasti.Model` or any emitter object containing data and business logic. The component will listen to `change` events and call `onChange` lifecycle method.
248
- * @property {object} state A `Rasti.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.
249
- * @see {@link #module_component_create Component.create}
250
- * @example
251
- * import { Component, Model } from 'rasti';
252
- * // Create Timer component.
253
- * const Timer = Component.create`
254
- * <div>
255
- * Seconds: <span>${({ model }) => model.seconds}</span>
256
- * </div>
257
- * `;
258
- * // Create model to store seconds.
259
- * const model = new Model({ seconds: 0 });
260
- * // Mount timer on body.
261
- * Timer.mount({ model }, document.body);
262
- * // Increment `model.seconds` every second.
263
- * setInterval(() => model.seconds++, 1000);
426
+ * @lends module:Component
264
427
  */
265
428
  class Component extends View {
266
429
  constructor(options = {}) {
267
430
  super(...arguments);
431
+ this.componentOptions = [];
268
432
  // Extend "this" with options.
269
433
  componentOptions.forEach(key => {
270
- if (key in options) this[key] = options[key];
434
+ if (key in options) {
435
+ this[key] = options[key];
436
+ this.componentOptions.push(key);
437
+ }
438
+ });
439
+ // Extract props from options that aren't component or view options.
440
+ const props = {};
441
+ Object.keys(options).forEach(key => {
442
+ if (!this.viewOptions.includes(key) && !this.componentOptions.includes(key)) {
443
+ props[key] = options[key];
444
+ }
271
445
  });
446
+ // Store props as Model for reactive updates.
447
+ this.props = new Model(props);
272
448
  // Store options by default.
273
449
  this.options = options;
274
450
  // Bind `partial` method to `this`.
275
451
  this.partial = this.partial.bind(this);
452
+ // Bind `onChange` method to `this`.
453
+ this.onChange = this.onChange.bind(this);
276
454
  // Call lifecycle method.
277
455
  this.onCreate.apply(this, arguments);
278
456
  }
279
457
 
280
458
  /**
281
- * Listen to `change` event on a model or emitter object and call `onChange` lifecycle method.
282
- * The listener will be removed when the component is destroyed.
283
- * By default the component will be subscribed to `this.model` and `this.state`.
284
- * @param {Rasti.Model} model A model or emitter object to listen to changes.
285
- * @return {Rasti.Component} The component instance.
459
+ * Get events object for automatic event delegation, based on data attributes.
460
+ * @return {object} The events object.
461
+ * @private
286
462
  */
287
- subscribe(model) {
288
- // Check if model has `on` method.
289
- if (!model.on) return;
290
- // Store bound onChange method.
291
- const onChange = this.onChange.bind(this);
292
- // Listen to model changes and store unbind function.
293
- const off = model.on('change', onChange);
294
- // Add unbind function to destroy queue.
295
- // So the component stops listening to model changes when destroyed.
296
- this.destroyQueue.push(
297
- // Rasti `on` method returns an unbind function.
298
- // But other libraries may return the object itself.
299
- typeof off === 'function' ? off : () => model.off('change', onChange)
300
- );
463
+ events() {
464
+ const events = {};
465
+ // Create events object.
466
+ this.eventsManager.types.forEach(type => {
467
+ const dataAttribute = Component.ATTRIBUTE_EVENT(type);
468
+ // Create a listener function that gets the listener index from the data attribute and calls the listener.
469
+ const listener = function(event, component, matched) {
470
+ // Get the listener index from the data attribute.
471
+ const index = matched.getAttribute(dataAttribute);
472
+ // Root element listener may not have a data attribute.
473
+ if (index) {
474
+ let currentListener = this.eventsManager.listeners[parseInt(index, 10)];
475
+ if (typeof currentListener === 'string') currentListener = this[currentListener];
476
+ utils_validateListener(currentListener);
477
+ // Call the listener.
478
+ currentListener.call(this, event, component, matched);
479
+ }
480
+ };
481
+ // Add an event listener to the events object for each event type, using the data attribute
482
+ // as both a CSS selector and to store the listener's index.
483
+ events[`${type} [${dataAttribute}]`] = listener;
484
+ // Add an event listener to the events object for each event type that matches the root element.
485
+ events[type] = listener;
486
+ });
301
487
 
488
+ return events;
489
+ }
490
+
491
+ /**
492
+ * Subscribes to a `change` event on a model or emitter object and invokes the `onChange` lifecycle method.
493
+ * The subscription is automatically cleaned up when the component is destroyed.
494
+ * By default, the component subscribes to changes on `this.model`, `this.state`, and `this.props`.
495
+ *
496
+ * @param {Object} model - The model or emitter object to listen to.
497
+ * @param {string} [type='change'] - The event type to listen for.
498
+ * @param {Function} [listener=this.onChange] - The callback to invoke when the event is emitted.
499
+ * @returns {Component} The current component instance for chaining.
500
+ */
501
+ subscribe(model, type = 'change', listener = this.onChange) {
502
+ // Check if model has `on` method.
503
+ if (model.on) this.listenTo(model, type, listener);
302
504
  return this;
303
505
  }
304
506
 
@@ -311,7 +513,7 @@ class Component extends View {
311
513
  * @private
312
514
  */
313
515
  isContainer() {
314
- return !!(!this.tag && this.template);
516
+ return this.template.elements.length === 0 && this.template.interpolations.length === 1;
315
517
  }
316
518
 
317
519
  /**
@@ -320,134 +522,107 @@ class Component extends View {
320
522
  * @private
321
523
  */
322
524
  ensureElement() {
525
+ // Store data event listeners.
526
+ this.eventsManager = new core_EventsManager();
527
+ // Store position tracking for recycling.
528
+ this.pathManager = new core_PathManager();
529
+ // Call template function.
530
+ this.template = utils_getResult(this.template, this);
323
531
  // If el is provided, delegate events.
324
532
  if (this.el) {
325
533
  // If "this.el" is a function, call it to get the element.
326
534
  this.el = utils_getResult(this.el, this);
327
- this.delegateEvents();
535
+ // Render the component as a string to generate children components.
536
+ this.toString();
537
+ // Hydrate the component.
538
+ this.hydrate(this.el.parentNode);
328
539
  }
329
540
  }
330
541
 
331
- /**
332
- * Locate the root element of the `Component` within a specified parent node.
333
- * This is achieved by searching for the element using the unique data attribute assigned to the `Component`.
334
- * @param {Node} parent - The parent node to search within.
335
- * @return {Node} The root element of the component, or `null` if not found.
336
- * @private
337
- */
338
- findElement(parent) {
339
- return (parent || document).querySelector(`[${Component.DATA_ATTRIBUTE_UID}="${this.uid}"]`);
340
- }
341
-
342
- /**
343
- * Retrieve the attributes to be applied to the element.
344
- * This includes attributes to be added, removed, and their HTML representation.
345
- * @return {object} An object containing the following properties:
346
- * @property {object} add - Attributes to be added to the element, with their values.
347
- * @property {object} remove - Attributes to be removed from the element.
348
- * @property {string} html - A string representation of the attributes for use in HTML.
349
- * @private
350
- */
351
- getAttributes() {
352
- const add = {};
353
- const remove = {};
354
- const html = [];
355
-
356
- const attributes = { [Component.DATA_ATTRIBUTE_UID] : this.uid };
357
-
358
- if (this.attributes) Object.assign(attributes, utils_getResult(this.attributes, this));
359
- // Store previous attributes.
360
- const previousAttributes = this.previousAttributes || {};
361
- this.previousAttributes = attributes;
362
-
363
- Object.keys(attributes).forEach(key => {
364
- let value = attributes[key];
365
- // Transform bool attribute values
366
- if (value === false) {
367
- remove[key] = true;
368
- } else if (value === true) {
369
- add[key] = '';
370
- html.push(key);
371
- } else {
372
- if (value === null || typeof value === 'undefined') value = '';
373
-
374
- add[key] = value;
375
- html.push(`${Component.sanitize(key)}="${Component.sanitize(value)}"`);
376
- }
377
- });
378
- // Remove attributes that were in previousAttributes but not in current attributes.
379
- Object.keys(previousAttributes).forEach(key => {
380
- if (!(key in attributes)) {
381
- remove[key] = true;
382
- }
383
- });
384
-
385
- return { add, remove, html : html.join(' ') };
386
- }
387
-
388
542
  /**
389
543
  * Used internally on the render process.
390
544
  * Attach the `Component` to the dom element providing `this.el`, delegate events,
391
- * subscribe to model changes and call `onRender` lifecycle method with `Component.RENDER_TYPE_HYDRATE` as argument.
545
+ * subscribe to model changes and call `onHydrate` lifecycle method.
392
546
  * @param parent {node} The parent node.
393
- * @return {Rasti.Component} The component instance.
547
+ * @return {Component} The component instance.
394
548
  * @private
395
549
  */
396
550
  hydrate(parent) {
397
- // Listen to model changes and call onChange.
398
- if (this.model) this.subscribe(this.model);
399
- // Listen to state changes and call onChange.
400
- if (this.state) this.subscribe(this.state);
551
+ ['model', 'state', 'props'].forEach(key => {
552
+ if (this[key]) this.subscribe(this[key]);
553
+ });
401
554
 
402
555
  if (this.isContainer()) {
556
+ // Get references for interpolation marker comments
557
+ this.template.interpolations[0].hydrate(parent);
558
+ // Call hydrate on children.
403
559
  this.children[0].hydrate(parent);
560
+ // Set the first element as the component's element.
404
561
  this.el = this.children[0].el;
405
562
  } else {
406
- this.el = this.findElement(parent);
563
+ // Search for every element in template using getSelector
564
+ this.template.elements.forEach((element, index) => {
565
+ if (index === 0) {
566
+ element.hydrate(parent);
567
+ if (this.el) element.ref = this.el;
568
+ else this.el = element.ref;
569
+ }
570
+ else {
571
+ element.hydrate(this.el);
572
+ }
573
+ });
574
+ // Delegate events.
407
575
  this.delegateEvents();
576
+ // Get references for interpolation marker comments
577
+ this.template.interpolations.forEach(interpolation => interpolation.hydrate(this.el));
408
578
  this.children.forEach(child => child.hydrate(this.el));
409
579
  }
410
- // Call `onRender` lifecycle method.
411
- this.onRender.call(this, Component.RENDER_TYPE_HYDRATE);
580
+ // Call `onHydrate` lifecycle method.
581
+ this.onHydrate.call(this);
412
582
  // Return `this` for chaining.
413
583
  return this;
414
584
  }
415
585
 
416
586
  /**
417
- * Used internally on the render process.
418
- * Reuse a `Component` that has `key` when its parent is rendered.
419
- * Call `onRender` lifecycle method with `Component.RENDER_TYPE_RECYCLE` as argument.
420
- * @param parent {node} The parent node.
421
- * @return {Rasti.Component} The component instance.
587
+ * Get a `comment` marker with same data attribute as this component.
588
+ * Used to replace the component when it is recycled.
589
+ * @return {string} The recycle placeholder.
422
590
  * @private
423
591
  */
424
- recycle(parent) {
425
- // If component is a container, call recycle on its child.
426
- if (this.isContainer()) {
427
- this.children[0].recycle(parent);
428
- } else {
429
- // Find placeholder element to be replaced. It has same data attribute as this component.
430
- const toBeReplaced = this.findElement(parent);
431
- // Replace it with this.el.
432
- toBeReplaced.replaceWith(this.el);
433
- }
434
- // Call `onRender` lifecycle method.
435
- this.onRender.call(this, Component.RENDER_TYPE_RECYCLE);
436
- // Return `this` for chaining.
437
- return this;
592
+ getRecycledMarker() {
593
+ return `<!--${Component.MARKER_RECYCLED(this.uid)}-->`;
438
594
  }
439
595
 
440
596
  /**
441
- * Destroy the `Component`.
442
- * Destroy children components if any, undelegate events, stop listening to events, call `onDestroy` lifecycle method.
443
- * @param {object} options Options object or any arguments passed to `destroy` method will be passed to `onDestroy` method.
444
- * @return {Rasti.View} Return `this` for chaining.
597
+ * Get the component nodes to be inserted into the DOM.
598
+ * Used internally during the render process, you usually don't need to call it if you use
599
+ * `mount()`.
600
+ * For components that render HTML elements you can safely rely on `this.el`.
601
+ * For container components that render another component you need the wrapper nodes to insert
602
+ * them into the DOM; use `getNodes()` for that.
603
+ * @return {Node[]} The component nodes.
445
604
  */
446
- destroy() {
447
- // Call super destroy method.
448
- super.destroy.apply(this, arguments);
449
- // Set destroyed flag to prevent a last render after destroyed.
450
- this.destroyed = true;
605
+ getNodes() {
606
+ return this.isContainer() ?
607
+ [this.template.interpolations[0].ref[0], ...this.children[0].getNodes(), this.template.interpolations[0].ref[1]] :
608
+ [this.el];
609
+ }
610
+
611
+ /**
612
+ * Used internally on the render process.
613
+ * Reuse a `Component` by replacing the placeholder comment with the real nodes.
614
+ * Call `onRecycle` lifecycle method.
615
+ * @param parent {node} The parent node.
616
+ * @return {Component} The component instance.
617
+ * @private
618
+ */
619
+ recycle(parent) {
620
+ // Locate the placeholder comment and replace it with the real nodes
621
+ const toBeReplaced = utils_findComment(parent, Component.MARKER_RECYCLED(this.uid), isComponent);
622
+ // Replace it with this.el.
623
+ toBeReplaced.replaceWith(...this.getNodes());
624
+ // Call `onRecycle` lifecycle method.
625
+ this.onRecycle.call(this);
451
626
  // Return `this` for chaining.
452
627
  return this;
453
628
  }
@@ -473,16 +648,22 @@ class Component extends View {
473
648
  }
474
649
 
475
650
  /**
476
- * Lifecycle method. Called after the component is rendered.
477
- * - When the component is rendered for the first time, this method is called with `Component.RENDER_TYPE_HYDRATE` as the argument.
478
- * - When the component is updated or re-rendered, this method is called with `Component.RENDER_TYPE_RENDER` as the argument.
479
- * - When the component is recycled (reused with the same key), this method is called with `Component.RENDER_TYPE_RECYCLE` as the argument.
480
- * @param {string} type - The render type. Possible values are: `Component.RENDER_TYPE_HYDRATE`, `Component.RENDER_TYPE_RENDER` and `Component.RENDER_TYPE_RECYCLE`.
651
+ * Lifecycle method. Called when the component is rendered for the first time and hydrated.
652
+ */
653
+ onHydrate() {}
654
+
655
+ /**
656
+ * Lifecycle method. Called when the component is recycled (reused with the same key) and added to the DOM again.
657
+ */
658
+ onRecycle() {}
659
+
660
+ /**
661
+ * Lifecycle method. Called when the component is updated or re-rendered.
481
662
  */
482
- onRender() {}
663
+ onUpdate() {}
483
664
 
484
665
  /**
485
- * Lifecycle method. Called when the view is destroyed.
666
+ * Lifecycle method. Called when the component is destroyed.
486
667
  * @param {object} options Options object or any arguments passed to `destroy` method.
487
668
  */
488
669
  onDestroy() {}
@@ -490,18 +671,18 @@ class Component extends View {
490
671
  /**
491
672
  * Tagged template helper method.
492
673
  * Used to create a partial template.
493
- * It will return a one-dimensional array with strings and expressions.
674
+ * It will return a Partial object that preserves structure for position-based recycling.
494
675
  * Components will be added as children by the parent component. Template strings literals
495
676
  * will be marked as safe HTML to be rendered.
496
677
  * This method is bound to the component instance by default.
497
678
  * @param {TemplateStringsArray} strings - Template strings.
498
679
  * @param {...any} expressions - Template expressions.
499
- * @return {Array} Array containing strings and expressions.
680
+ * @return {Partial} Partial object containing strings and expressions.
500
681
  * @example
501
682
  * import { Component } from 'rasti';
502
683
  * // Create a Title component.
503
684
  * const Title = Component.create`
504
- * <h1>${self => self.renderChildren()}</h1>
685
+ * <h1>${({ props }) => props.children}</h1>
505
686
  * `;
506
687
  * // Create Main component.
507
688
  * const Main = Component.create`
@@ -521,147 +702,191 @@ class Component extends View {
521
702
  * });
522
703
  */
523
704
  partial(strings, ...expressions) {
524
- return utils_deepFlat(
525
- splitPlaceholders(
526
- expandComponents(addPlaceholders(strings, expressions), expressions), expressions
527
- ).map(item => getExpressionResult(item, this))
528
- );
705
+ const items = splitPlaceholders(
706
+ parsePartialElements(
707
+ expandComponents(
708
+ addPlaceholders(strings, expressions),
709
+ expressions
710
+ ),
711
+ expressions
712
+ ),
713
+ expressions
714
+ ).map(item => getExpressionResult(item, this));
715
+
716
+ return new core_Partial(items);
529
717
  }
530
718
 
531
- getRecyclePlaceholder() {
532
- if (this.isContainer()) return this.children[0].getRecyclePlaceholder();
533
-
534
- const tag = utils_getResult(this.tag, this) || 'div';
535
- const attributes = `${Component.DATA_ATTRIBUTE_UID}="${this.uid}"`;
719
+ /**
720
+ * Render a template part.
721
+ * @param {any} part - The template part.
722
+ * @param {function} addChild - The addChild function.
723
+ * @return {string} The rendered template part.
724
+ * @private
725
+ */
726
+ renderTemplatePart(part, addChild) {
727
+ const result = getExpressionResult(part, this);
728
+
729
+ const parse = item => {
730
+ if (typeof item !== 'undefined' && item !== null && item !== false && item !== true) {
731
+ if (item instanceof core_SafeHTML) return item;
732
+ if (item instanceof Component) return addChild(item);
733
+
734
+ if (item instanceof core_Partial) {
735
+ this.pathManager.push();
736
+ const out = item.items.map(subItem => { this.pathManager.increment(); return parse(subItem); }).join('');
737
+ this.pathManager.pop();
738
+ return out;
739
+ }
740
+ // Handle arrays (user loops) - disable tracking.
741
+ if (Array.isArray(item)) {
742
+ this.pathManager.pause();
743
+ const out = utils_deepFlat(item).map(parse).join('');
744
+ this.pathManager.resume();
745
+ return out;
746
+ }
747
+ // InterpolationWrapper: add markers and process maintaining tracking.
748
+ if (item instanceof core_InterpolationWrapper) {
749
+ this.pathManager.increment();
750
+ const startMarker = `<!--${Component.MARKER_START(item.interpolationUid)}-->`;
751
+ const endMarker = `<!--${Component.MARKER_END(item.interpolationUid)}-->`;
752
+ return `${startMarker}${parse(item.result)}${endMarker}`;
753
+ }
754
+
755
+ return Component.sanitize(item);
756
+ }
757
+ // Return empty string if item is undefined, null, false, or true.
758
+ return '';
759
+ };
536
760
 
537
- return this.template || !selfClosingTags[tag] ?
538
- `<${tag} ${attributes}></${tag}>` :
539
- `<${tag} ${attributes} />`;
761
+ return `${parse(result)}`;
540
762
  }
541
763
 
542
- /*
543
- * Treat the whole view as a HTML string.
764
+ /**
765
+ * Render the component as a string.
766
+ * Used internally on the render process.
767
+ * Use it for server-side rendering or static site generation.
768
+ * @return {string} The rendered component.
544
769
  */
545
770
  toString() {
546
771
  // Normally there won't be any children, but if there are, destroy them.
547
772
  this.destroyChildren();
548
- // Container.
549
- if (this.isContainer()) return this.template.call(this, this.addChild.bind(this));
550
- // Get tag name.
551
- const tag = utils_getResult(this.tag, this) || 'div';
552
- // Get attributes.
553
- const attributes = this.getAttributes().html;
554
- // Replace expressions of inner template.
555
- const inner = this.template ? this.template.call(this, this.addChild.bind(this)) : '';
556
- // Generate outer template.
557
- return this.template || !selfClosingTags[tag] ?
558
- `<${tag} ${attributes}>${inner}</${tag}>` :
559
- `<${tag} ${attributes} />`;
773
+ // Normally there won't be any data event listeners, but if there are, clear them.
774
+ this.eventsManager.reset();
775
+ // Reset position tracking.
776
+ this.pathManager.reset();
777
+ // Bind addChild method.
778
+ const addChild = component => {
779
+ this.pathManager.track(component);
780
+ return this.addChild(component);
781
+ };
782
+ // Render the template parts.
783
+ return this.template.parts
784
+ .map(part => this.renderTemplatePart(part, addChild))
785
+ .join('');
560
786
  }
561
787
 
562
788
  /**
563
789
  * Render the `Component`.
564
- * - If `this.el` is not present, the `Component` will be rendered as a string inside a `DocumentFragment` and hydrated, making `this.el` available. The `onRender` lifecycle method will be called with `Component.RENDER_TYPE_HYDRATE` as an argument.
565
- * - 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 `onRender` lifecycle method will be called with `Component.RENDER_TYPE_RENDER` as an argument.
566
- * - When rendering child components, if the new children have the same key as the previous ones, they will be recycled. A recycled `Component` will call the `onRender` lifecycle method with `Component.RENDER_TYPE_RECYCLE` as an argument.
790
+ * - 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.
791
+ * - 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.
792
+ * - When rendering child components, recycling happens in two ways:
793
+ * - Components with a `key` are recycled if a previous child with the same key exists.
794
+ * - Unkeyed components are recycled if they have the same type and position in the template or partial.
795
+ * A recycled `Component` will call the `onRecycle` lifecycle method.
567
796
  * - If the active element is inside the component, it will retain focus after the render.
568
- * @return {Rasti.Component} The component instance.
797
+ * @return {Component} The component instance.
569
798
  */
570
799
  render() {
571
800
  // Prevent a last re render if view is already destroyed.
572
801
  if (this.destroyed) return this;
573
802
  // If `this.el` is not present, render the view as a string and hydrate it.
574
803
  if (!this.el) {
575
- const fragment = this.createElement('template');
576
- fragment.innerHTML = this;
577
- this.hydrate(fragment.content);
804
+ const fragment = utils_parseHTML(this);
805
+ this.hydrate(fragment);
578
806
  return this;
579
807
  }
580
- // Update attributes.
581
- if (!this.isContainer()) {
582
- const attributes = this.getAttributes();
583
- // Remove attributes.
584
- Object.keys(attributes.remove).forEach(key => {
585
- this.el.removeAttribute(key);
586
- });
587
- // Add attributes.
588
- Object.keys(attributes.add).forEach(key => {
589
- this.el.setAttribute(key, attributes.add[key]);
590
- });
591
- }
592
- // Check for `template` to see if view has innerHTML or a child component.
593
- if (this.template) {
594
- // Store active element.
595
- const activeElement = document.activeElement;
596
-
808
+ // Clear event listeners.
809
+ this.eventsManager.reset();
810
+ // Reset position tracking.
811
+ this.pathManager.reset();
812
+ // Store active element.
813
+ const activeElement = this.isContainer() ? null : document.activeElement;
814
+ // Update elements.
815
+ this.template.elements.forEach(element => element.update());
816
+ // Store previous children.
817
+ const previousChildren = this.children;
818
+ // Clear current children.
819
+ this.children = [];
820
+ // Update interpolations.
821
+ this.template.interpolations.forEach(interpolation => {
597
822
  const nextChildren = [];
598
823
  const recycledChildren = [];
599
824
 
600
- const previousChildren = this.children;
601
- this.children = [];
602
- // Replace expressions. Set html inside of `this.el`.
603
- const inner = this.template.call(this, component => {
825
+ this.pathManager.increment();
826
+
827
+ const addChild = component => {
604
828
  let out = component;
605
- // Check if child already exists.
606
- const found = component.key && previousChildren.find(
607
- previousChild => previousChild.key === component.key
608
- );
829
+ let found = null;
830
+ // Check if child already exists by key.
831
+ if (component.key) {
832
+ found = previousChildren.find(prev => prev.key === component.key);
833
+ } else {
834
+ // Find by position and type.
835
+ found = this.pathManager.findRecyclable(component.constructor);
836
+ }
609
837
 
610
838
  if (found) {
611
839
  // If child already exists, replace it html by its root element.
612
- out = found.getRecyclePlaceholder();
840
+ out = found.getRecycledMarker();
613
841
  // Add child to recycled children.
614
- recycledChildren.push(found);
615
- // Destroy new child component. Use recycled one instead.
616
- component.destroy();
842
+ recycledChildren.push([found, component]);
843
+ // Track the component.
844
+ if (!found.key) this.pathManager.track(found);
617
845
  } else {
618
- // Not found. Add new child component.
846
+ // Add new component.
619
847
  nextChildren.push(component);
848
+ // Track the component.
849
+ this.pathManager.track(component);
620
850
  }
621
- // Component html.
851
+ // Return the component or placeholder.
622
852
  return out;
623
- });
853
+ };
624
854
 
625
- if (this.isContainer()) {
626
- if (nextChildren[0]) {
627
- const fragment = this.createElement('template');
628
- fragment.innerHTML = inner;
629
- // Add new child to dom fragment and hydrate it.
630
- this.addChild(nextChildren[0]).hydrate(fragment.content);
631
- // Get next child element.
632
- const nextEl = fragment.content.children[0];
633
- // Replace `this.el` with nextEl.
634
- this.el.replaceWith(nextEl);
635
- // Set `this.el` to nextEl.
636
- this.el = nextEl;
637
- } else if (recycledChildren[0]) {
638
- this.addChild(recycledChildren[0]);
639
- } else {
640
- throw new Error('Container component must have a child component');
641
- }
642
- } else {
643
- this.el.innerHTML = inner;
644
- // Add new children. Hydrate them.
645
- nextChildren.forEach(nextChild => {
646
- this.addChild(nextChild).hydrate(this.el);
647
- });
648
- // Replace children root elements with recycled components.
649
- recycledChildren.forEach(recycledChild => {
650
- this.addChild(recycledChild).recycle(this.el);
651
- });
652
- }
653
- // Destroy unused children.
654
- previousChildren.forEach(previousChild => {
655
- const found = recycledChildren.indexOf(previousChild) > -1;
656
- if (!found) previousChild.destroy();
855
+ const fragment = utils_parseHTML(this.renderTemplatePart(interpolation.expression, addChild));
856
+ // Replace children root elements with recycled components.
857
+ recycledChildren.forEach(([recycled, discarded]) => {
858
+ this.addChild(recycled).recycle(fragment);
859
+ // Update props.
860
+ recycled.props.set(discarded.props.toJSON());
861
+ // Destroy discarded component.
862
+ discarded.destroy();
657
863
  });
658
- // Restore focus.
659
- if (this.el.contains(activeElement)) {
660
- activeElement.focus();
864
+ // Add new children. Hydrate them.
865
+ nextChildren.forEach(child => {
866
+ this.addChild(child).hydrate(fragment);
867
+ });
868
+
869
+ interpolation.update(fragment);
870
+ });
871
+ // Destroy unused children.
872
+ previousChildren.forEach(prev => {
873
+ if (this.children.indexOf(prev) < 0) prev.destroy();
874
+ });
875
+ // If container, set el to the child element.
876
+ if (this.isContainer()) {
877
+ this.el = this.children[0].el;
878
+ } else {
879
+ // If there are pending event types, delegate events again.
880
+ if (this.eventsManager.hasPendingTypes()) {
881
+ this.delegateEvents();
661
882
  }
662
883
  }
663
- // Call onRender lifecycle method.
664
- this.onRender.call(this, Component.RENDER_TYPE_RENDER);
884
+ // Restore focus.
885
+ if (activeElement && this.el.contains(activeElement)) {
886
+ activeElement.focus();
887
+ }
888
+ // Call onUpdate lifecycle method.
889
+ this.onUpdate.call(this);
665
890
  // Return this for chaining.
666
891
  return this;
667
892
  }
@@ -674,16 +899,16 @@ class Component extends View {
674
899
  * Be sure that the string is safe to be rendered, as it will be inserted into the DOM without any sanitization.
675
900
  * @static
676
901
  * @param {string} value
677
- * @return {Rasti.SafeHTML} A safe HTML object.
902
+ * @return {SafeHTML} A safe HTML object.
678
903
  */
679
904
  static markAsSafeHTML(value) {
680
- return new SafeHTML(value);
905
+ return new core_SafeHTML(value);
681
906
  }
682
907
 
683
908
  /**
684
909
  * Helper method used to extend a `Component`, creating a subclass.
685
910
  * @static
686
- * @param {object} object Object containing methods to be added to the new `Component` subclass. Also can be a function that receives the parent prototype and returns an object.
911
+ * @param {object|Function} object Object containing methods to be added to the new `Component` subclass. Also can be a function that receives the parent prototype and returns an object.
687
912
  */
688
913
  static extend(object) {
689
914
  const Current = this;
@@ -704,27 +929,28 @@ class Component extends View {
704
929
  * appends its element into the DOM (if `el` is provided).
705
930
  * And returns the view instance.
706
931
  * @static
707
- * @param {object} options The view options.
708
- * @param {node} el Dom element to append the view element.
709
- * @param {boolean} hydrate If true, the view will hydrate existing DOM.
710
- * @return {Rasti.Component}
932
+ * @param {object} [options] The view options.
933
+ * @param {node} [el] Dom element to append the view element.
934
+ * @param {boolean} [hydrate] If true, the view will hydrate existing DOM.
935
+ * @return {Component} The component instance.
711
936
  */
712
937
  static mount(options, el, hydrate) {
713
- // Instantiate view.
714
- const view = new this(options);
938
+ // Instantiate component.
939
+ const component = new this(options);
715
940
  // If `el` is passed, mount component.
716
941
  if (el) {
717
942
  if (hydrate) {
943
+ // Generate subcomponents.
944
+ component.toString();
718
945
  // Hydrate existing DOM.
719
- view.toString();
720
- view.hydrate(el);
946
+ component.hydrate(el);
721
947
  } else {
722
948
  // Append element to the DOM.
723
- el.appendChild(view.render().el);
949
+ el.append(...component.render().getNodes());
724
950
  }
725
951
  }
726
- // Return view instance.
727
- return view;
952
+ // Return component instance.
953
+ return component;
728
954
  }
729
955
 
730
956
  /**
@@ -737,16 +963,45 @@ class Component extends View {
737
963
  * - Template interpolations that are functions will be evaluated during the render process, receiving the view instance as an argument and being bound to it. If the function returns `null`, `undefined`, `false`, or an empty string, the interpolation won't render any content.
738
964
  * ```javascript
739
965
  * const Button = Component.create`
740
- * <button class="${({ options }) => options.className}">
741
- * ${({ options }) => options.renderChildren()}
966
+ * <button class="${({ props }) => props.className}">
967
+ * ${({ props }) => props.children}
968
+ * </button>
969
+ * `;
970
+ * ```
971
+ * - Attach DOM event handlers per element using camel-cased attributes.
972
+ * Event handlers are automatically bound to the component instance (`this`).
973
+ * Internally, Rasti uses event delegation to the component's root element for performance.
974
+ *
975
+ * **Attribute Quoting:**
976
+ * - **Quoted attributes** (`onClick="${handler}"`) evaluate the expression first, useful for dynamic values
977
+ * - **Unquoted attributes** (`onClick=${handler}`) pass the function reference directly
978
+ *
979
+ * **Listener Signature:** `(event, component, matched)`
980
+ * - `event`: The native DOM event object
981
+ * - `component`: The component instance (same as `this`)
982
+ * - `matched`: The element that matched the event (useful for delegation)
983
+ *
984
+ * ```javascript
985
+ * const Button = Component.create`
986
+ * <button
987
+ * onClick=${function(event, component, matched) {
988
+ * // this === component
989
+ * console.log('Button clicked:', matched);
990
+ * }}
991
+ * onMouseOver="${({ model }) => () => model.isHovered = true}"
992
+ * onMouseOut="${({ model }) => () => model.isHovered = false}"
993
+ * >
994
+ * Click me
742
995
  * </button>
743
996
  * `;
744
997
  * ```
745
- * - Event handlers should be passed, at the root element as camelized attributes, in the format `onEventName=${{'selector' : listener }}`. They will be transformed to an event object and delegated to the root element. See {@link #module_view__delegateevents View.delegateEvents}.
998
+ *
999
+ * If you need custom delegation (e.g., `{'click .selector': 'handler'}`),
1000
+ * you may override the `events` property as described in {@link #module_view__delegateevents View.delegateEvents}.
746
1001
  * - Boolean attributes should be passed in the format `attribute="${() => true}"`. `false` attributes won't be rendered. `true` attributes will be rendered without a value.
747
1002
  * ```javascript
748
1003
  * const Input = Component.create`
749
- * <input type="text" disabled=${({ options }) => options.disabled} />
1004
+ * <input type="text" disabled=${({ props }) => props.disabled} />
750
1005
  * `;
751
1006
  * ```
752
1007
  * - If the interpolated function returns a component instance, it will be added as a child component.
@@ -755,21 +1010,21 @@ class Component extends View {
755
1010
  * // Create a button component.
756
1011
  * const Button = Component.create`
757
1012
  * <button class="button">
758
- * ${({ options }) => options.renderChildren()}
1013
+ * ${({ props }) => props.children}
759
1014
  * </button>
760
1015
  * `;
761
1016
  * // Create a navigation component. Add buttons as children. Iterate over items.
762
1017
  * const Navigation = Component.create`
763
1018
  * <nav>
764
- * ${({ options }) => options.items.map(
765
- * item => Button.mount({ renderChildren: () => item.label })
1019
+ * ${({ props }) => props.items.map(
1020
+ * item => Button.mount({ children : item.label })
766
1021
  * )}
767
1022
  * </nav>
768
1023
  * `;
769
1024
  * // Create a header component. Add navigation as a child.
770
1025
  * const Header = Component.create`
771
1026
  * <header>
772
- * ${({ options }) => Navigation.mount({ items : options.items})}
1027
+ * ${({ props }) => Navigation.mount({ items : props.items})}
773
1028
  * </header>
774
1029
  * `;
775
1030
  * ```
@@ -778,13 +1033,13 @@ class Component extends View {
778
1033
  * // Create a button component.
779
1034
  * const Button = Component.create`
780
1035
  * <button class="button">
781
- * ${({ options }) => options.renderChildren()}
1036
+ * ${({ props }) => props.children}
782
1037
  * </button>
783
1038
  * `;
784
1039
  * // Create a navigation component. Add buttons as children. Iterate over items.
785
1040
  * const Navigation = Component.create`
786
1041
  * <nav>
787
- * ${({ options, partial }) => options.items.map(
1042
+ * ${({ props, partial }) => props.items.map(
788
1043
  * item => partial`<${Button}>${item.label}</${Button}>`
789
1044
  * )}
790
1045
  * </nav>
@@ -792,7 +1047,7 @@ class Component extends View {
792
1047
  * // Create a header component. Add navigation as a child.
793
1048
  * const Header = Component.create`
794
1049
  * <header>
795
- * <${Navigation} items="${({ options }) => options.items}" />
1050
+ * <${Navigation} items="${({ props }) => props.items}" />
796
1051
  * </header>
797
1052
  * `;
798
1053
  * ```
@@ -800,8 +1055,8 @@ class Component extends View {
800
1055
  * ```javascript
801
1056
  * // Create a button component.
802
1057
  * const Button = Component.create`
803
- * <button class="${({ options }) => options.className}">
804
- * ${self => self.renderChildren()}
1058
+ * <button class="${({ props }) => props.className}">
1059
+ * ${({ props }) => props.children}
805
1060
  * </button>
806
1061
  * `;
807
1062
  * // Create a container that renders a Button component.
@@ -810,104 +1065,110 @@ class Component extends View {
810
1065
  * `;
811
1066
  * // Create a container that renders a Button component, using a function.
812
1067
  * const ButtonCancel = Component.create(() => Button.mount({
813
- * className: 'cancel',
814
- * renderChildren: () => 'Cancel'
1068
+ * className : 'cancel',
1069
+ * children : 'Cancel'
815
1070
  * }));
816
1071
  * ```
817
1072
  * @static
818
- * @param {string|function} strings - HTML template for the component or a function that mounts a sub component.
1073
+ * @param {string|Function} strings - HTML template for the component or a function that mounts a sub component.
819
1074
  * @param {...*} expressions - The expressions to be interpolated within the template.
820
- * @return {Rasti.Component} The newly created component class.
1075
+ * @return {Component} The newly created component class.
821
1076
  */
822
1077
  static create(strings, ...expressions) {
823
- const PH = Component.PLACEHOLDER_EXPRESSION('(\\d+)');
824
1078
  // Containers can be created using create as a functions instead of a tagged template.
825
1079
  if (typeof strings === 'function') {
826
1080
  expressions = [strings];
827
1081
  strings = ['', ''];
828
1082
  }
829
-
830
- let tag, attributes, events, template;
831
- // Create output string for main template. Add placeholders for new lines.
832
- const main = expandComponents(addPlaceholders(strings, expressions), expressions);
833
-
834
- let match = main.match(
835
- new RegExp(`^\\s*<([a-z]+[1-6]?|${PH})([^>]*)>([\\s\\S]*?)</(\\1|${PH})>\\s*$|^\\s*<([a-z]+[1-6]?|${PH})([^>]*)/>\\s*$`)
1083
+ // Create elements, interpolations and parts arrays.
1084
+ const elements = [], interpolations = [];
1085
+ const parts = splitPlaceholders(
1086
+ parseInterpolations(
1087
+ parseElements(
1088
+ expandComponents(
1089
+ addPlaceholders(
1090
+ strings,
1091
+ expressions
1092
+ ).trim(),
1093
+ expressions
1094
+ ),
1095
+ expressions,
1096
+ elements
1097
+ ),
1098
+ expressions,
1099
+ interpolations
1100
+ ),
1101
+ expressions
836
1102
  );
837
-
838
- if (match) {
839
- // It's a component with tag.
840
- const { tag : tagExpression, attributes : attributesAndEvents, inner, close } = parseMatch(match, expressions);
841
- // Get tag, attributes.
842
- tag = function() {
843
- return Component.sanitize(getExpressionResult(tagExpression, this));
844
- };
845
- // Get attributes.
846
- attributes = function() {
847
- return expandAttributes(attributesAndEvents, value => getExpressionResult(value, this)).attributes;
848
- };
849
- // Get events.
850
- events = function() {
851
- const onlyEvents = expandAttributes(attributesAndEvents, value => getExpressionResult(value, this)).events;
852
-
853
- return Object.keys(onlyEvents).reduce((out, key) => {
854
- const typeListeners = getExpressionResult(onlyEvents[key], this);
855
-
856
- Object.keys(typeListeners).forEach(selector => {
857
- out[`${key}${selector === '&' ? '' : ` ${selector}`}`] = typeListeners[selector];
858
- });
859
-
860
- return out;
861
- }, {});
862
- };
863
- // If there is a closing tag, get template.
864
- if (close) {
865
- const list = inner ? splitPlaceholders(inner, expressions) : [];
866
- template = function(addChild) {
867
- return utils_deepFlat(list.map(item => getExpressionResult(item, this))).map(item => {
868
- if (typeof item !== 'undefined' && item !== null && item !== false && item !== true) {
869
- if (item instanceof SafeHTML) return item;
870
- if (item instanceof Component) return addChild(item);
871
- return Component.sanitize(item);
872
- }
873
- return '';
874
- }).join('');
875
- };
876
- }
877
- } else {
878
- // It's a container.
879
- match = main.match(new RegExp(`^\\s*${PH}\\s*$`));
880
-
881
- if (match) {
882
- // If there is only one expression and no tag, is a container.
883
- template = function(addChild) {
884
- // Replace expressions.
885
- return addChild(getExpressionResult(expressions[match[1]], this)).toString();
1103
+ // Create subclass for this component.
1104
+ return this.extend({
1105
+ template() {
1106
+ return {
1107
+ elements : elements.map(element => new core_Element({
1108
+ getSelector : element.getSelector.bind(this),
1109
+ getAttributes : element.getAttributes.bind(this)
1110
+ })),
1111
+ interpolations : interpolations.map(interpolation => new core_Interpolation({
1112
+ getStart : interpolation.getStart.bind(this),
1113
+ getEnd : interpolation.getEnd.bind(this),
1114
+ expression : interpolation.expression,
1115
+ isComponent,
1116
+ isElement
1117
+ })),
1118
+ parts,
886
1119
  };
887
- } else {
888
- throw new SyntaxError('Invalid component');
889
1120
  }
890
- }
891
-
892
- const Current = this;
893
- // Create subclass for this component.
894
- return Current.extend({
895
- // Set root element tag.
896
- tag,
897
- // Set attributes.
898
- attributes,
899
- // Set events.
900
- events,
901
- // Set template.
902
- template
903
1121
  });
904
1122
  }
905
1123
  }
906
1124
 
907
- Component.PLACEHOLDER_EXPRESSION = (idx) => `__RASTI_{${idx}}__`;
908
- Component.DATA_ATTRIBUTE_UID = 'data-rasti-uid';
909
- Component.RENDER_TYPE_HYDRATE = 'hydrate';
910
- Component.RENDER_TYPE_RECYCLE = 'recycle';
911
- Component.RENDER_TYPE_RENDER = 'render';
1125
+ /*
1126
+ * Attributes used to identify elements and events.
1127
+ */
1128
+ Component.ATTRIBUTE_ELEMENT = 'data-rasti-el';
1129
+ Component.ATTRIBUTE_EVENT = (type) => `data-rasti-on-${type}`;
1130
+
1131
+ /*
1132
+ * Placeholders used to temporarily replace expressions in the template.
1133
+ */
1134
+ Component.PLACEHOLDER = (idx) => `__RASTI-${idx}__`;
1135
+
1136
+ /*
1137
+ * Markers used to identify interpolation and recycled components.
1138
+ */
1139
+ Component.MARKER_RECYCLED = (uid) => `rasti-recycled-${uid}`;
1140
+ Component.MARKER_START = (uid) => `rasti-start-${uid}`;
1141
+ Component.MARKER_END = (uid) => `rasti-end-${uid}`;
1142
+
1143
+ /**
1144
+ * Components are a special kind of `View` that is designed to be easily composable,
1145
+ * making it simple to add child views and build complex user interfaces.
1146
+ * Unlike views, which are render-agnostic, components have a specific set of rendering
1147
+ * guidelines that allow for a more declarative development style.
1148
+ * 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.
1149
+ * @module
1150
+ * @extends View
1151
+ * @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`.
1152
+ * @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.
1153
+ * @property {Rasti.Model} [model] A `Rasti.Model` or any emitter object containing data and business logic. The component will listen to `change` events and call `onChange` lifecycle method.
1154
+ * @property {Rasti.Model} [state] A `Rasti.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.
1155
+ * @property {Rasti.Model} [props] Automatically created from any options not merged to the component instance. Contains props passed from parent component as a `Rasti.Model`. The component will listen to `change` events on props and call `onChange` lifecycle method. When a component with a `key` is recycled during parent re-render, new props are automatically updated and any changes trigger a re-render.
1156
+ * @see {@link #module_component_create Component.create}
1157
+ * @example
1158
+ * import { Component, Model } from 'rasti';
1159
+ * // Create Timer component.
1160
+ * const Timer = Component.create`
1161
+ * <div>
1162
+ * Seconds: <span>${({ model }) => model.seconds}</span>
1163
+ * </div>
1164
+ * `;
1165
+ * // Create model to store seconds.
1166
+ * const model = new Model({ seconds: 0 });
1167
+ * // Mount timer on body.
1168
+ * Timer.mount({ model }, document.body);
1169
+ * // Increment `model.seconds` every second.
1170
+ * setInterval(() => model.seconds++, 1000);
1171
+ */
1172
+ var Component$1 = Component.create`<div></div>`;
912
1173
 
913
- module.exports = Component;
1174
+ module.exports = Component$1;