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