@tylix/compiler 0.5.2 → 0.7.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 (61) hide show
  1. package/LICENSE +21 -0
  2. package/package.json +30 -2
  3. package/src/ast/nodes.js +219 -16
  4. package/src/ast/substituteCapabilityRefs.js +185 -61
  5. package/src/codegen/emitStatementLines.js +98 -54
  6. package/src/codegen/generateExpression.js +339 -36
  7. package/src/codegen/generateMethod.js +5 -3
  8. package/src/codegen/generatePage.js +74 -44
  9. package/src/codegen/generateStatement.js +169 -20
  10. package/src/codegen/generateTemplate.js +183 -101
  11. package/src/codegen/generateTemplateExpression.js +102 -59
  12. package/src/codegen/jsGlobals.js +211 -0
  13. package/src/compileComponent.js +39 -8
  14. package/src/imports/extractImports.js +112 -26
  15. package/src/imports/resolveImports.js +186 -0
  16. package/src/index.js +3 -2
  17. package/src/lexer/Lexer.js +430 -235
  18. package/src/lexer/tokenTypes.js +32 -7
  19. package/src/parser/Parser.js +2176 -325
  20. package/src/parser/languageOptions.js +16 -0
  21. package/src/parser/parseExpressionString.js +23 -7
  22. package/src/parser/parsePageFile.js +139 -58
  23. package/src/parser/parseTemplate.js +350 -62
  24. package/src/renderPageDocument.js +338 -56
  25. package/src/runtime/capability.js +39 -17
  26. package/src/runtime/loadingIndicator.js +91 -29
  27. package/src/runtime/reactive.js +362 -64
  28. package/src/runtime/useApi.js +74 -13
  29. package/src/runtime/useChannel.js +27 -6
  30. package/src/typecheck/buildVirtualTs.js +23 -12
  31. package/src/typecheck/tylix-globals.d.ts +23 -4
  32. package/src/typecheck/typedTemplateExpr.js +195 -53
  33. package/src/typecheckPage.js +28 -4
  34. package/src/codegen/generateExpression.array.test.js +0 -13
  35. package/src/codegen/generateExpression.callexpr.test.js +0 -19
  36. package/src/codegen/generateExpression.test.js +0 -59
  37. package/src/codegen/generateMethod.asyncawait.test.js +0 -37
  38. package/src/codegen/generateMethod.ifstatement.test.js +0 -20
  39. package/src/codegen/generateMethod.test.js +0 -81
  40. package/src/codegen/generatePage.onmount.test.js +0 -46
  41. package/src/codegen/generatePage.test.js +0 -138
  42. package/src/codegen/generateStatement.test.js +0 -31
  43. package/src/codegen/generateTemplate.ifeach.test.js +0 -138
  44. package/src/codegen/generateTemplate.test.js +0 -149
  45. package/src/codegen/generateTemplateExpression.test.js +0 -34
  46. package/src/compileComponent.test.js +0 -121
  47. package/src/imports/resolvePackageComponents.js +0 -41
  48. package/src/lexer/Lexer.test.js +0 -151
  49. package/src/parser/Parser.array.test.js +0 -37
  50. package/src/parser/Parser.asyncawait.test.js +0 -33
  51. package/src/parser/Parser.ifstatement.test.js +0 -20
  52. package/src/parser/Parser.onmount.test.js +0 -18
  53. package/src/parser/Parser.test.js +0 -315
  54. package/src/parser/parseComponent.test.js +0 -53
  55. package/src/parser/parsePageFile.test.js +0 -101
  56. package/src/parser/parseTemplate.ifeach.test.js +0 -33
  57. package/src/parser/parseTemplate.pre.test.js +0 -39
  58. package/src/parser/parseTemplate.test.js +0 -112
  59. package/src/renderPageDocument.test.js +0 -125
  60. package/src/runtime/reactive.test.js +0 -106
  61. package/test/dashboard-syntax.test.js +0 -116
@@ -5,13 +5,44 @@ import {
5
5
  InterpolationNode,
6
6
  IfNode,
7
7
  EachNode,
8
+ TemplateLiteralExpr,
8
9
  } from '../ast/nodes.js'
9
10
  import { parseExpressionString } from './parseExpressionString.js'
10
11
 
11
- const TAG_NAME_RE = /^[a-zA-Z][a-zA-Z0-9-]*/
12
- const ATTR_NAME_RE = /^[a-zA-Z][a-zA-Z0-9-]*/
13
- const INTERP_ATTR_RE = /^\{\{\s*([\s\S]*?)\s*\}\}$/
14
- const EACH_HEADER_RE = /^([A-Za-z_$][A-Za-z0-9_$]*)\s+in\s+([\s\S]+)$/
12
+ // Sticky regexes: matched at TemplateParser.pos via matchAt().
13
+ const TAG_NAME_RE = /[a-zA-Z][a-zA-Z0-9-]*/y
14
+ const ATTR_NAME_RE = /[a-zA-Z_:][a-zA-Z0-9_:.-]*/y
15
+
16
+ // Elements that never have children or a closing tag, so
17
+ // `<br>`, `<img src="x">` and `<input>` work without a trailing "/".
18
+ const VOID_ELEMENTS = new Set([
19
+ 'area',
20
+ 'base',
21
+ 'br',
22
+ 'col',
23
+ 'embed',
24
+ 'hr',
25
+ 'img',
26
+ 'input',
27
+ 'link',
28
+ 'meta',
29
+ 'param',
30
+ 'source',
31
+ 'track',
32
+ 'wbr',
33
+ ])
34
+
35
+ // HTML whitespace only -- NOT \s, which also matches U+00A0 and would
36
+ // swallow a literal non-breaking space.
37
+ const WS_ONLY_RE = /^[ \t\r\n\f]*$/
38
+ const WS_RUN_RE = /[ \t\r\n\f]+/g
39
+
40
+ // {{#each item in items}} {{#each item of items}}
41
+ // {{#each item, i in items}} {{#each [k, v] in Object.entries(o)}}
42
+ // {{#each { id, name } in rows}}
43
+ // group 1: item (name or destructuring pattern), 2: index name, 3: iterable
44
+ const EACH_HEADER_RE =
45
+ /^(\[[^\]]*\]|\{[^}]*\}|[A-Za-z_$][A-Za-z0-9_$]*)(?:\s*,\s*([A-Za-z_$][A-Za-z0-9_$]*))?\s+(?:in|of)\s+([\s\S]+)$/
15
46
 
16
47
  const NAMED_ENTITIES = {
17
48
  amp: '&',
@@ -20,6 +51,9 @@ const NAMED_ENTITIES = {
20
51
  quot: '"',
21
52
  apos: "'",
22
53
  nbsp: '\u00A0',
54
+ ensp: '\u2002',
55
+ emsp: '\u2003',
56
+ thinsp: '\u2009',
23
57
  larr: '\u2190',
24
58
  rarr: '\u2192',
25
59
  uarr: '\u2191',
@@ -27,6 +61,26 @@ const NAMED_ENTITIES = {
27
61
  mdash: '\u2014',
28
62
  ndash: '\u2013',
29
63
  hellip: '\u2026',
64
+ bull: '\u2022',
65
+ middot: '\u00B7',
66
+ times: '\u00D7',
67
+ divide: '\u00F7',
68
+ plusmn: '\u00B1',
69
+ deg: '\u00B0',
70
+ laquo: '\u00AB',
71
+ raquo: '\u00BB',
72
+ lsquo: '\u2018',
73
+ rsquo: '\u2019',
74
+ ldquo: '\u201C',
75
+ rdquo: '\u201D',
76
+ euro: '\u20AC',
77
+ pound: '\u00A3',
78
+ yen: '\u00A5',
79
+ cent: '\u00A2',
80
+ sect: '\u00A7',
81
+ para: '\u00B6',
82
+ hearts: '\u2665',
83
+ check: '\u2713',
30
84
  copy: '\u00A9',
31
85
  reg: '\u00AE',
32
86
  trade: '\u2122',
@@ -54,8 +108,43 @@ function decodeHtmlEntities(text) {
54
108
  })
55
109
  }
56
110
 
57
- export function parseTemplate(source) {
58
- const parser = new TemplateParser(source)
111
+ // Finds the "}}" that closes a {{ ... }} whose content starts at
112
+ // `from` in `source`. Skips nested braces and string/template
113
+ // literals, so {{ fn({a:{b:1}}) }} and {{ "}}" }} work, where a plain
114
+ // indexOf('}}') would cut the expression short. A free function so
115
+ // attribute values can be scanned the same way as template text.
116
+ function findInterpEnd(source, from) {
117
+ let depth = 0
118
+ let quote = null
119
+ for (let i = from; i < source.length; i++) {
120
+ const c = source[i]
121
+ if (quote) {
122
+ if (c === '\\') i++
123
+ else if (c === quote) quote = null
124
+ continue
125
+ }
126
+ if (c === '"' || c === "'" || c === '`') {
127
+ quote = c
128
+ continue
129
+ }
130
+ if (c === '{') depth++
131
+ else if (c === '}') {
132
+ if (depth === 0 && source[i + 1] === '}') return i
133
+ if (depth > 0) depth--
134
+ }
135
+ }
136
+ return -1
137
+ }
138
+
139
+ // `options` are the project's language options (see
140
+ // parser/languageOptions.js), e.g. { not: 'loose' }. They are passed
141
+ // to every expression parsed out of the template, so `{{ not a has b }}`
142
+ // follows the same `not` mode as script code.
143
+ //
144
+ // HTML comments (<!-- ... -->) are allowed anywhere a node is allowed
145
+ // and produce no output.
146
+ export function parseTemplate(source, options = {}) {
147
+ const parser = new TemplateParser(source, options)
59
148
  const nodes = parser.parseNodes(null)
60
149
  if (parser.pos < parser.source.length) {
61
150
  throw new Error(
@@ -66,15 +155,15 @@ export function parseTemplate(source) {
66
155
  }
67
156
 
68
157
  class TemplateParser {
69
- constructor(source) {
158
+ constructor(source, options = {}) {
159
+ this.options = options
70
160
  this.source = source
71
161
  this.pos = 0
162
+ // Set by parseNodes: which marker it stopped at (the stopMarker,
163
+ // one of alsoStopAt, or null for a closing tag).
164
+ this.stopHit = null
72
165
  // Precomputed once so lineAt() is a binary search instead of
73
- // rescanning from the start on every node -- parsing jumps around
74
- // via indexOf() in several places (interpolations, {{#if}}/
75
- // {{#each}} headers), so a running line counter threaded
76
- // incrementally (the way Lexer does it) would miss newlines that
77
- // fall inside a skipped range.
166
+ // rescanning from the start on every node.
78
167
  this.lineStarts = [0]
79
168
  for (let i = 0; i < source.length; i++) {
80
169
  if (source[i] === '\n') this.lineStarts.push(i + 1)
@@ -85,9 +174,28 @@ class TemplateParser {
85
174
  return this.source.slice(this.pos)
86
175
  }
87
176
 
88
- // 1-based line number containing `pos`. Binary search over
89
- // lineStarts -- called once per node, so this stays cheap even on
90
- // large templates.
177
+ // True when the source at the current position starts with `str`.
178
+ // Same as remaining().startsWith(str) without copying the rest of
179
+ // the template on every check.
180
+ at(str) {
181
+ return this.source.startsWith(str, this.pos)
182
+ }
183
+
184
+ matchAt(re) {
185
+ re.lastIndex = this.pos
186
+ return re.exec(this.source)
187
+ }
188
+
189
+ // A "<" starts markup only before a letter, "/" or "!--". Anything
190
+ // else ("a < b", "<3") is literal text.
191
+ isTagStart() {
192
+ if (this.source[this.pos] !== '<') return false
193
+ const next = this.source[this.pos + 1]
194
+ if (next === undefined) return false
195
+ return /[a-zA-Z/]/.test(next) || this.at('<!--')
196
+ }
197
+
198
+ // 1-based line number containing `pos`.
91
199
  lineAt(pos) {
92
200
  let lo = 0
93
201
  let hi = this.lineStarts.length - 1
@@ -99,48 +207,87 @@ class TemplateParser {
99
207
  return lo + 1
100
208
  }
101
209
 
210
+ findInterpEnd(from) {
211
+ return findInterpEnd(this.source, from)
212
+ }
213
+
214
+ // <!-- ... --> is skipped entirely: nothing inside it is parsed,
215
+ // so {{ }} and tags inside a comment are inert.
216
+ skipComment() {
217
+ const line = this.lineAt(this.pos)
218
+ const end = this.source.indexOf('-->', this.pos + 4)
219
+ if (end === -1) {
220
+ throw new Error(
221
+ `Unterminated HTML comment starting at line ${line}: missing '-->'`,
222
+ )
223
+ }
224
+ this.pos = end + 3
225
+ }
226
+
102
227
  // Parses sibling nodes. `stopTag` (an HTML tag name) or `stopMarker`
103
228
  // (a literal like "{{/if}}") tell this call when to return; nested
104
229
  // control blocks / elements consume their own closing marker before
105
230
  // returning, so recursion handles arbitrary nesting automatically.
106
- parseNodes(stopTag, stopMarker = null) {
231
+ // `alsoStopAt` lists marker PREFIXES (like "{{#else") that end this
232
+ // call WITHOUT being consumed, so the caller can parse them itself.
233
+ // After returning, this.stopHit says which one ended the call.
234
+ parseNodes(stopTag, stopMarker = null, alsoStopAt = []) {
107
235
  const nodes = []
108
236
  while (this.pos < this.source.length) {
109
- if (stopMarker && this.remaining().startsWith(stopMarker)) {
237
+ if (stopMarker && this.at(stopMarker)) {
110
238
  this.pos += stopMarker.length
239
+ this.stopHit = stopMarker
111
240
  return nodes
112
241
  }
113
242
 
114
- if (this.remaining().startsWith('</')) {
243
+ const also = alsoStopAt.find((m) => this.at(m))
244
+ if (also) {
245
+ this.stopHit = also
246
+ return nodes
247
+ }
248
+
249
+ if (this.at('<!--')) {
250
+ this.skipComment()
251
+ continue
252
+ }
253
+
254
+ if (this.at('</')) {
255
+ this.stopHit = null
115
256
  if (stopTag === null) return nodes
116
257
  this.consumeClosingTag(stopTag)
117
258
  return nodes
118
259
  }
119
260
 
120
- if (this.remaining().startsWith('{{#if')) {
261
+ if (this.at('{{#if')) {
121
262
  nodes.push(this.parseIfBlock())
122
263
  continue
123
264
  }
124
265
 
125
- if (this.remaining().startsWith('{{#each')) {
266
+ if (this.at('{{#each')) {
126
267
  nodes.push(this.parseEachBlock())
127
268
  continue
128
269
  }
129
270
 
130
- if (this.remaining().startsWith('{{')) {
271
+ if (this.at('{{')) {
131
272
  nodes.push(this.parseInterpolation())
132
273
  continue
133
274
  }
134
275
 
135
- if (this.source[this.pos] === '<') {
276
+ if (this.isTagStart()) {
136
277
  nodes.push(this.parseElement())
137
278
  continue
138
279
  }
139
280
 
140
281
  const text = this.parseText()
141
- const collapsed = decodeHtmlEntities(text.replace(/\s+/g, ' '))
142
- if (collapsed.trim().length > 0) {
143
- nodes.push(TextNode(collapsed))
282
+ if (WS_ONLY_RE.test(text)) {
283
+ // JSX rule: whitespace-only runs containing a newline are
284
+ // formatting and get dropped; a run on a single line sits
285
+ // BETWEEN inline content (`{{ first }} {{ last }}`,
286
+ // `<b>a</b> <i>b</i>`) and collapses to one real space.
287
+ if (!text.includes('\n')) nodes.push(TextNode(' '))
288
+ } else {
289
+ // Collapse first, decode after, so `&nbsp;` survives.
290
+ nodes.push(TextNode(decodeHtmlEntities(text.replace(WS_RUN_RE, ' '))))
144
291
  }
145
292
  }
146
293
 
@@ -152,15 +299,20 @@ class TemplateParser {
152
299
  if (stopTag !== null) {
153
300
  throw new Error(`Unclosed tag <${stopTag}>: reached end of template`)
154
301
  }
302
+ this.stopHit = null
155
303
  return nodes
156
304
  }
157
305
 
306
+ // Always consumes at least one character: when parseNodes lands
307
+ // here the position is not at "{{" or real markup, so a "<" at the
308
+ // very start is a literal "<" (as in "a < b").
158
309
  parseText() {
159
310
  const start = this.pos
311
+ this.pos++
160
312
  while (
161
313
  this.pos < this.source.length &&
162
- this.source[this.pos] !== '<' &&
163
- !this.remaining().startsWith('{{')
314
+ !this.isTagStart() &&
315
+ !this.at('{{')
164
316
  ) {
165
317
  this.pos++
166
318
  }
@@ -170,13 +322,21 @@ class TemplateParser {
170
322
  parseInterpolation() {
171
323
  const line = this.lineAt(this.pos)
172
324
  const start = this.pos + 2
173
- const end = this.source.indexOf('}}', start)
325
+ const end = this.findInterpEnd(start)
174
326
  if (end === -1) {
175
327
  throw new Error("Unterminated interpolation: missing '}}'")
176
328
  }
177
329
  const exprSource = this.source.slice(start, end).trim()
330
+ if (exprSource.startsWith('#') || exprSource.startsWith('/')) {
331
+ throw new Error(
332
+ `Unexpected block tag "{{${exprSource}}}" at line ${line}: it has no matching opening or closing tag (check {{#if}} / {{#each}} / {{#else}} / {{/if}} / {{/each}})`,
333
+ )
334
+ }
178
335
  this.pos = end + 2
179
- return { ...InterpolationNode(parseExpressionString(exprSource)), line }
336
+ return {
337
+ ...InterpolationNode(parseExpressionString(exprSource, this.options)),
338
+ line,
339
+ }
180
340
  }
181
341
 
182
342
  parseIfBlock() {
@@ -184,16 +344,51 @@ class TemplateParser {
184
344
  this.pos += 2 // "{{"
185
345
  this.pos += 3 // "#if"
186
346
  this.skipWhitespace()
187
- const end = this.source.indexOf('}}', this.pos)
347
+ const end = this.findInterpEnd(this.pos)
188
348
  if (end === -1) {
189
349
  throw new Error("Unterminated {{#if}} header: missing '}}'")
190
350
  }
191
351
  const conditionSource = this.source.slice(this.pos, end).trim()
192
352
  this.pos = end + 2
353
+ return this.parseIfRest(conditionSource, line)
354
+ }
355
+
356
+ // Parses the body of an {{#if}} (header already consumed), plus an
357
+ // optional {{#else}} or {{#else if cond}} chain. An else-if is a
358
+ // nested IfNode in elseChildren that shares the single {{/if}}.
359
+ parseIfRest(conditionSource, line) {
360
+ const children = this.parseNodes(null, '{{/if}}', ['{{#else'])
361
+
362
+ let elseChildren = null
363
+ if (this.stopHit === '{{#else') {
364
+ this.pos += '{{#else'.length
365
+ this.skipWhitespace()
366
+ const elseLine = this.lineAt(this.pos)
367
+ const end = this.findInterpEnd(this.pos)
368
+ if (end === -1) {
369
+ throw new Error("Unterminated {{#else}} header: missing '}}'")
370
+ }
371
+ const header = this.source.slice(this.pos, end).trim()
372
+ this.pos = end + 2
373
+
374
+ const elseIf = /^if\b\s*([\s\S]+)$/.exec(header)
375
+ if (header === '') {
376
+ elseChildren = this.parseNodes(null, '{{/if}}')
377
+ } else if (elseIf) {
378
+ elseChildren = [this.parseIfRest(elseIf[1].trim(), elseLine)]
379
+ } else {
380
+ throw new Error(
381
+ `Invalid {{#else}} header "${header}" at line ${elseLine}: expected {{#else}} or {{#else if condition}}`,
382
+ )
383
+ }
384
+ }
193
385
 
194
- const children = this.parseNodes(null, '{{/if}}')
195
386
  return {
196
- ...IfNode(parseExpressionString(conditionSource), children),
387
+ ...IfNode(
388
+ parseExpressionString(conditionSource, this.options),
389
+ children,
390
+ elseChildren,
391
+ ),
197
392
  line,
198
393
  }
199
394
  }
@@ -203,7 +398,7 @@ class TemplateParser {
203
398
  this.pos += 2 // "{{"
204
399
  this.pos += 5 // "#each"
205
400
  this.skipWhitespace()
206
- const end = this.source.indexOf('}}', this.pos)
401
+ const end = this.findInterpEnd(this.pos)
207
402
  if (end === -1) {
208
403
  throw new Error("Unterminated {{#each}} header: missing '}}'")
209
404
  }
@@ -213,15 +408,41 @@ class TemplateParser {
213
408
  const match = EACH_HEADER_RE.exec(header)
214
409
  if (!match) {
215
410
  throw new Error(
216
- `Invalid {{#each}} header "${header}": expected "item in items"`,
411
+ `Invalid {{#each}} header "${header}": expected "item in items", "item, index in items" or "[a, b] in pairs"`,
217
412
  )
218
413
  }
219
414
  const itemName = match[1]
220
- const iterableSource = match[2].trim()
415
+ const indexName = match[2] ?? null
416
+ const iterableSource = match[3].trim()
417
+
418
+ const children = this.parseNodes(null, '{{/each}}', ['{{#else'])
419
+
420
+ let elseChildren = null
421
+ if (this.stopHit === '{{#else') {
422
+ this.pos += '{{#else'.length
423
+ this.skipWhitespace()
424
+ const elseEnd = this.findInterpEnd(this.pos)
425
+ if (elseEnd === -1) {
426
+ throw new Error("Unterminated {{#else}} header: missing '}}'")
427
+ }
428
+ const elseHeader = this.source.slice(this.pos, elseEnd).trim()
429
+ if (elseHeader !== '') {
430
+ throw new Error(
431
+ `{{#else}} inside {{#each}} takes no condition (got "${elseHeader}")`,
432
+ )
433
+ }
434
+ this.pos = elseEnd + 2
435
+ elseChildren = this.parseNodes(null, '{{/each}}')
436
+ }
221
437
 
222
- const children = this.parseNodes(null, '{{/each}}')
223
438
  return {
224
- ...EachNode(itemName, parseExpressionString(iterableSource), children),
439
+ ...EachNode(
440
+ itemName,
441
+ parseExpressionString(iterableSource, this.options),
442
+ children,
443
+ indexName,
444
+ elseChildren,
445
+ ),
225
446
  line,
226
447
  }
227
448
  }
@@ -233,7 +454,7 @@ class TemplateParser {
233
454
  const attributes = this.parseAttributes()
234
455
 
235
456
  this.skipWhitespace()
236
- if (this.remaining().startsWith('/>')) {
457
+ if (this.at('/>')) {
237
458
  this.pos += 2
238
459
  return { ...ElementNode(tag, attributes, []), line }
239
460
  }
@@ -243,6 +464,11 @@ class TemplateParser {
243
464
  }
244
465
  this.pos++
245
466
 
467
+ // <br>, <img ...>, <input ...>: no children, no closing tag.
468
+ if (VOID_ELEMENTS.has(tag)) {
469
+ return { ...ElementNode(tag, attributes, []), line }
470
+ }
471
+
246
472
  // <pre> is a raw-text element, same idea as <script>/<style> in
247
473
  // real HTML: its content is captured verbatim -- no whitespace
248
474
  // collapsing, and critically no {{ }} interpolation/control-flow
@@ -283,7 +509,7 @@ class TemplateParser {
283
509
  }
284
510
 
285
511
  readTagName() {
286
- const match = TAG_NAME_RE.exec(this.remaining())
512
+ const match = this.matchAt(TAG_NAME_RE)
287
513
  if (!match) {
288
514
  throw new Error(`Expected a tag name at position ${this.pos}`)
289
515
  }
@@ -297,7 +523,7 @@ class TemplateParser {
297
523
  while (
298
524
  this.pos < this.source.length &&
299
525
  this.source[this.pos] !== '>' &&
300
- !this.remaining().startsWith('/>')
526
+ !this.at('/>')
301
527
  ) {
302
528
  attributes.push(this.parseAttribute())
303
529
  this.skipWhitespace()
@@ -307,7 +533,7 @@ class TemplateParser {
307
533
 
308
534
  parseAttribute() {
309
535
  const line = this.lineAt(this.pos)
310
- const nameMatch = ATTR_NAME_RE.exec(this.remaining())
536
+ const nameMatch = this.matchAt(ATTR_NAME_RE)
311
537
  if (!nameMatch) {
312
538
  throw new Error(`Expected an attribute name at position ${this.pos}`)
313
539
  }
@@ -316,10 +542,7 @@ class TemplateParser {
316
542
  this.skipWhitespace()
317
543
 
318
544
  // No '=' following the name means a bare boolean attribute
319
- // (e.g. <input disabled>, <div data-tylix-slot>) rather than a
320
- // parse error -- matches real HTML's own boolean-attribute
321
- // convention, so devs coming from plain HTML don't hit a
322
- // surprising "Expected '=' after attribute name" wall.
545
+ // (e.g. <input disabled>, <div data-tylix-slot>).
323
546
  if (this.source[this.pos] !== '=') {
324
547
  return { ...AttributeNode(name, true, false), line }
325
548
  }
@@ -328,28 +551,93 @@ class TemplateParser {
328
551
  this.skipWhitespace()
329
552
 
330
553
  const quote = this.source[this.pos]
331
- if (quote !== '"' && quote !== "'") {
332
- throw new Error(`Expected a quoted value for attribute '${name}'`)
333
- }
334
- this.pos++
335
- const valueStart = this.pos
336
- while (this.pos < this.source.length && this.source[this.pos] !== quote) {
554
+ let rawValue
555
+
556
+ if (quote === '"' || quote === "'") {
557
+ this.pos++
558
+ const valueStart = this.pos
559
+ while (this.pos < this.source.length && this.source[this.pos] !== quote) {
560
+ this.pos++
561
+ }
562
+ if (this.pos >= this.source.length) {
563
+ throw new Error(`Unterminated attribute value for '${name}'`)
564
+ }
565
+ rawValue = this.source.slice(valueStart, this.pos)
337
566
  this.pos++
567
+ } else {
568
+ // Unquoted value (<input type=text>): runs to whitespace or
569
+ // '>'. A {{ ... }} inside it is scanned as a unit, so
570
+ // `value={{ a + b }}` keeps its spaces.
571
+ const valueStart = this.pos
572
+ while (
573
+ this.pos < this.source.length &&
574
+ !/[\s>]/.test(this.source[this.pos])
575
+ ) {
576
+ if (this.at('{{')) {
577
+ const end = this.findInterpEnd(this.pos + 2)
578
+ if (end === -1) {
579
+ throw new Error(
580
+ `Unterminated '{{' in attribute '${name}' at line ${line}`,
581
+ )
582
+ }
583
+ this.pos = end + 2
584
+ } else {
585
+ this.pos++
586
+ }
587
+ }
588
+ rawValue = this.source.slice(valueStart, this.pos)
589
+ if (rawValue === '') {
590
+ throw new Error(`Expected a value for attribute '${name}'`)
591
+ }
338
592
  }
339
- if (this.pos >= this.source.length) {
340
- throw new Error(`Unterminated attribute value for '${name}'`)
593
+
594
+ return { ...this.buildAttribute(name, rawValue, line), line }
595
+ }
596
+
597
+ // Splits an attribute value into literal text and {{ }} parts.
598
+ // "plain" -> static string
599
+ // "{{ expr }}" -> the expression itself (type kept:
600
+ // numbers stay numbers, etc.)
601
+ // "btn {{ a }} x-{{ b }}" -> a template literal
602
+ // Literal text has HTML entities decoded (title="a &amp; b").
603
+ buildAttribute(name, rawValue, line) {
604
+ if (!rawValue.includes('{{')) {
605
+ return AttributeNode(name, decodeHtmlEntities(rawValue), false)
341
606
  }
342
- const rawValue = this.source.slice(valueStart, this.pos)
343
- this.pos++
344
607
 
345
- const interpMatch = INTERP_ATTR_RE.exec(rawValue)
346
- if (interpMatch) {
347
- return {
348
- ...AttributeNode(name, parseExpressionString(interpMatch[1]), true),
349
- line,
608
+ const parts = []
609
+ let text = ''
610
+ let i = 0
611
+ while (i < rawValue.length) {
612
+ if (rawValue.startsWith('{{', i)) {
613
+ const end = findInterpEnd(rawValue, i + 2)
614
+ if (end === -1) {
615
+ throw new Error(
616
+ `Unterminated '{{' in attribute '${name}' at line ${line}`,
617
+ )
618
+ }
619
+ if (text) {
620
+ parts.push({ type: 'text', value: decodeHtmlEntities(text) })
621
+ text = ''
622
+ }
623
+ parts.push({
624
+ type: 'expr',
625
+ expression: parseExpressionString(
626
+ rawValue.slice(i + 2, end).trim(),
627
+ this.options,
628
+ ),
629
+ })
630
+ i = end + 2
631
+ } else {
632
+ text += rawValue[i++]
350
633
  }
351
634
  }
352
- return { ...AttributeNode(name, rawValue, false), line }
635
+ if (text) parts.push({ type: 'text', value: decodeHtmlEntities(text) })
636
+
637
+ if (parts.length === 1 && parts[0].type === 'expr') {
638
+ return AttributeNode(name, parts[0].expression, true)
639
+ }
640
+ return AttributeNode(name, TemplateLiteralExpr(parts), true)
353
641
  }
354
642
 
355
643
  skipWhitespace() {
@@ -357,4 +645,4 @@ class TemplateParser {
357
645
  this.pos++
358
646
  }
359
647
  }
360
- }
648
+ }