@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
@@ -1,12 +1,18 @@
1
- import { generateExpression } from './generateExpression.js'
1
+ import {
2
+ generateExpression,
3
+ generateParams,
4
+ generateClass,
5
+ functionSignature,
6
+ } from './generateExpression.js'
2
7
 
3
8
  /**
4
9
  * Compiles a single statement AST node into a JS source line.
5
10
  *
6
11
  * `typed` is threaded through to generateExpression so a block-bodied
7
12
  * arrow compiled for the virtual .ts file keeps its `: any` param
8
- * annotations on nested arrows. It defaults to false, so every
9
- * existing caller (generateMethod, generateCapability) is unchanged.
13
+ * annotations on nested arrows, and so local declarations keep their
14
+ * `: Type`. It defaults to false, so every existing caller
15
+ * (generateMethod, generateCapability) is unchanged.
10
16
  */
11
17
  export function generateStatement(node, typed = false) {
12
18
  const expr = (n) => generateExpression(n, typed)
@@ -14,6 +20,25 @@ export function generateStatement(node, typed = false) {
14
20
  list.map((s) => ` ${generateStatement(s, typed)}`).join('\n')
15
21
 
16
22
  switch (node.type) {
23
+ case 'EmptyStatement':
24
+ return ';'
25
+
26
+ case 'DebuggerStatement':
27
+ return 'debugger;'
28
+
29
+ // `type X = ...` / `interface X {...}` exist only for the checker.
30
+ case 'TypeDeclaration':
31
+ return typed ? node.source : ''
32
+
33
+ case 'EnumDeclaration':
34
+ return generateEnum(node, typed)
35
+
36
+ case 'BlockStatement':
37
+ return `{\n${stmts(node.body)}\n }`
38
+
39
+ case 'LabeledStatement':
40
+ return `${node.label}: ${generateStatement(node.body, typed)}`
41
+
17
42
  case 'ReturnStatement':
18
43
  return node.argument ? `return ${expr(node.argument)};` : 'return;'
19
44
 
@@ -24,7 +49,18 @@ export function generateStatement(node, typed = false) {
24
49
  return `${expr(node.expression)};`
25
50
 
26
51
  case 'VariableDeclaration':
27
- return `${node.kind} ${generateDeclarationTarget(node.name, typed)} = ${expr(node.init)};`
52
+ return `${declarationSource(node, typed)};`
53
+
54
+ case 'ClassDeclaration':
55
+ return generateClass(node, typed)
56
+
57
+ case 'FunctionDeclaration': {
58
+ const { generics, ret } = functionSignature(node, typed)
59
+ const head = `${node.isAsync ? 'async ' : ''}function${node.isGenerator ? '*' : ''} ${node.name}${generics}(${generateParams(node.params, typed)})${ret}`
60
+ // Overload signature: checker-only.
61
+ if (node.body == null) return typed ? `${head};` : ''
62
+ return `${head} {\n${stmts(node.body)}\n }`
63
+ }
28
64
 
29
65
  case 'IfStatement': {
30
66
  let out = `if (${expr(node.condition)}) {\n${stmts(node.consequent)}\n }`
@@ -37,6 +73,9 @@ export function generateStatement(node, typed = false) {
37
73
  case 'WhileStatement':
38
74
  return `while (${expr(node.condition)}) {\n${stmts(node.body)}\n }`
39
75
 
76
+ case 'DoWhileStatement':
77
+ return `do {\n${stmts(node.body)}\n } while (${expr(node.condition)});`
78
+
40
79
  // Each clause body is wrapped in its own braces so `const`/`let`
41
80
  // declared in one case can't collide with another, and a `break`
42
81
  // is appended so there is never accidental fallthrough. (A
@@ -54,7 +93,13 @@ export function generateStatement(node, typed = false) {
54
93
  }
55
94
 
56
95
  case 'ForInStatement':
57
- return `for (const ${node.varName} of ${expr(node.iterable)}) {\n${stmts(node.body)}\n }`
96
+ return `for ${node.isAwait ? 'await ' : ''}(${node.declKind ?? 'const'} ${generateDeclarationTarget(node.varName, typed)} of ${expr(node.iterable)}) {\n${stmts(node.body)}\n }`
97
+
98
+ case 'ForKeysStatement':
99
+ return `for (${node.declKind ?? 'const'} ${generateDeclarationTarget(node.varName, typed)} in ${expr(node.object)}) {\n${stmts(node.body)}\n }`
100
+
101
+ case 'ForStatement':
102
+ return `for (${forHeaderSource(node, typed)}) {\n${stmts(node.body)}\n }`
58
103
 
59
104
  case 'ForRangeStatement':
60
105
  return `for (let ${node.varName} = ${expr(node.start)}; ${node.varName} < ${expr(node.end)}; ${node.varName}++) {\n${stmts(node.body)}\n }`
@@ -63,19 +108,35 @@ export function generateStatement(node, typed = false) {
63
108
  return `for (let __i = 0; __i < ${expr(node.count)}; __i++) {\n${stmts(node.body)}\n }`
64
109
 
65
110
  case 'BreakStatement':
66
- return 'break;'
111
+ return node.label ? `break ${node.label};` : 'break;'
67
112
 
68
113
  case 'ContinueStatement':
69
- return 'continue;'
114
+ return node.label ? `continue ${node.label};` : 'continue;'
70
115
 
71
116
  case 'TryStatement': {
72
117
  let out = `try {\n${stmts(node.tryBlock)}\n }`
73
118
 
74
119
  if (node.catchBlock) {
75
- const catchHeader = node.catchParam
76
- ? `catch (${node.catchParam})`
77
- : 'catch'
78
- out += ` ${catchHeader} {\n${stmts(node.catchBlock)}\n }`
120
+ let header = 'catch'
121
+ let prelude = ''
122
+ if (node.catchParam != null) {
123
+ if (typeof node.catchParam === 'string') {
124
+ // Typed: JS gives the catch variable `any` semantics, so
125
+ // the virtual file does too (TypeScript's default would
126
+ // be `unknown` under strict).
127
+ header = typed
128
+ ? `catch (${node.catchParam}: ${node.catchType ?? 'any'})`
129
+ : `catch (${node.catchParam})`
130
+ } else if (typed) {
131
+ // TypeScript forbids a destructuring pattern directly in
132
+ // a catch clause with a type, so bind it on the next line.
133
+ header = 'catch (__caught: any)'
134
+ prelude = ` const ${generateDeclarationTarget(node.catchParam, true)} = __caught;\n`
135
+ } else {
136
+ header = `catch (${generateDeclarationTarget(node.catchParam)})`
137
+ }
138
+ }
139
+ out += ` ${header} {\n${prelude}${stmts(node.catchBlock)}\n }`
79
140
  }
80
141
 
81
142
  if (node.finallyBlock) {
@@ -90,15 +151,103 @@ export function generateStatement(node, typed = false) {
90
151
  }
91
152
  }
92
153
 
93
- // Renders a VariableDeclaration's binding target -- a plain identifier
94
- // (the base case), or -- for destructuring -- a nested ObjectPattern/
95
- // ArrayPattern, each with optional per-field renames, defaults, and a
96
- // rest element, recursing through `binding` so patterns can nest
97
- // arbitrarily deep (e.g. `const { data: { id, name } } = result`)
98
- // instead of only supporting one flat level. Matches real JS
99
- // destructuring syntax so the generated line is exactly what a
100
- // hand-written `const { a } = x` would look like.
101
- function generateDeclarationTarget(target, typed = false) {
154
+ // Real JS: a plain object with TypeScript-style reverse mapping for
155
+ // numeric members. Typed: a real TS `enum`.
156
+ // enum Color { Red, Green = 5, Blue } -> Red 0, Green 5, Blue 6
157
+ function generateEnum(node, typed) {
158
+ if (typed) {
159
+ const members = node.members.map((m) => {
160
+ const key = /^[A-Za-z_$][\w$]*$/.test(m.name) ? m.name : JSON.stringify(m.name)
161
+ return m.init ? `${key} = ${generateExpression(m.init, true)}` : key
162
+ })
163
+ return `enum ${node.name} { ${members.join(', ')} }`
164
+ }
165
+ const body = node.members
166
+ .map((m) => {
167
+ const k = JSON.stringify(m.name)
168
+ if (m.init && m.init.type === 'Literal' && typeof m.init.value === 'string') {
169
+ return `__e[${k}] = ${JSON.stringify(m.init.value)};`
170
+ }
171
+ const set = m.init ? `__n = ${generateExpression(m.init)}; ` : ''
172
+ return `${set}__e[__e[${k}] = __n] = ${k}; __n++;`
173
+ })
174
+ .join(' ')
175
+ return `const ${node.name} = (() => { const __e = {}; let __n = 0; ${body} return __e; })();`
176
+ }
177
+
178
+ // Names a statement declares at its own scope (functions, classes,
179
+ // enums, const/let including destructured ones). Used to expose
180
+ // module-level helpers to templates.
181
+ export function declaredNames(stmt) {
182
+ if (
183
+ stmt.type === 'FunctionDeclaration' ||
184
+ stmt.type === 'ClassDeclaration' ||
185
+ stmt.type === 'EnumDeclaration'
186
+ ) {
187
+ return stmt.name ? [stmt.name] : []
188
+ }
189
+ if (stmt.type === 'VariableDeclaration') {
190
+ return [stmt.name, ...(stmt.more ?? []).map((m) => m.name)].flatMap(patternNames)
191
+ }
192
+ return []
193
+ }
194
+
195
+ function patternNames(t) {
196
+ if (typeof t === 'string') return [t]
197
+ if (t.type === 'ObjectPattern') {
198
+ return [
199
+ ...t.properties.flatMap((p) => patternNames(p.binding)),
200
+ ...(t.rest ? [t.rest] : []),
201
+ ]
202
+ }
203
+ return [
204
+ ...t.elements.flatMap((el) => (el === null ? [] : patternNames(el.binding))),
205
+ ...(t.rest ? [t.rest] : []),
206
+ ]
207
+ }
208
+
209
+ // `const a: A = 1, { b } = x` -- the declaration WITHOUT a trailing
210
+ // semicolon (used by statements and by C-style for headers). A null
211
+ // init (`let x`) emits just the target. Type annotations are emitted
212
+ // only in typed mode (the virtual .ts); real JS output omits them.
213
+ export function declarationSource(node, typed = false) {
214
+ const one = (name, init, type) => {
215
+ const target = generateDeclarationTarget(name, typed)
216
+ const annotation = typed && type ? `: ${type}` : ''
217
+ return init == null
218
+ ? `${target}${annotation}`
219
+ : `${target}${annotation} = ${generateExpression(init, typed)}`
220
+ }
221
+ const parts = [
222
+ one(node.name, node.init, node.typeAnnotation),
223
+ ...(node.more ?? []).map((m) => one(m.name, m.init, m.typeAnnotation)),
224
+ ]
225
+ return `${node.kind} ${parts.join(', ')}`
226
+ }
227
+
228
+ // The three parts of a C-style `for (init; test; update)` header.
229
+ export function forHeaderSource(node, typed = false) {
230
+ const init = !node.init
231
+ ? ''
232
+ : node.init.type === 'VariableDeclaration'
233
+ ? declarationSource(node.init, typed)
234
+ : node.init.expressions.map((e) => generateExpression(e, typed)).join(', ')
235
+ const test = node.test ? generateExpression(node.test, typed) : ''
236
+ const update = (node.update ?? [])
237
+ .map((e) => generateExpression(e, typed))
238
+ .join(', ')
239
+ return `${init}; ${test}; ${update}`
240
+ }
241
+
242
+ // Renders a binding target -- a plain identifier (the base case), or
243
+ // -- for destructuring -- a nested ObjectPattern/ArrayPattern, each
244
+ // with optional per-field renames, defaults, and a rest element,
245
+ // recursing through `binding` so patterns can nest arbitrarily deep
246
+ // (e.g. `const { data: { id, name } } = result`) instead of only
247
+ // supporting one flat level. Matches real JS destructuring syntax so
248
+ // the generated line is exactly what a hand-written `const { a } = x`
249
+ // would look like.
250
+ export function generateDeclarationTarget(target, typed = false) {
102
251
  if (typeof target === 'string') {
103
252
  return target
104
253
  }
@@ -1,8 +1,25 @@
1
1
  import { generateTemplateExpression } from './generateTemplateExpression.js'
2
-
3
- const EVENT_ATTR_PREFIX = /^on(click|input|change|submit)$/i
2
+ import { paramNames } from './jsGlobals.js'
3
+
4
+ // Any attribute named on<event> on a plain HTML element is an event
5
+ // listener: onclick, onkeydown, onblur, onmouseenter, ondblclick,
6
+ // onscroll, onsubmit, oninput, oncontextmenu, ... (case-insensitive,
7
+ // so onClick works too). Capitalized component tags handle their own
8
+ // onXxx callback props separately in compileElement.
9
+ const EVENT_ATTR_PREFIX = /^on[a-z]+$/i
4
10
  const COMPONENT_TAG_PATTERN = /^[A-Z]/
5
11
 
12
+ // A handler whose expression is one of these node types is a function
13
+ // VALUE that gets called with the event: onclick="{{ save }}",
14
+ // "{{ Auth.logout }}", "{{ e => doIt(e.target.value) }}". Anything
15
+ // else is a STATEMENT run when the event fires: "{{ count++ }}",
16
+ // "{{ save(item) }}", "{{ ok and save() }}", "{{ open ? close() : open() }}".
17
+ const FUNCTION_VALUED = new Set([
18
+ 'Identifier',
19
+ 'MemberExpression',
20
+ 'ArrowFunctionExpression',
21
+ ])
22
+
6
23
  const SVG_NS = 'http://www.w3.org/2000/svg'
7
24
 
8
25
  let nodeCounter = 0
@@ -10,6 +27,18 @@ function nextVar(prefix) {
10
27
  return `${prefix}${nodeCounter++}`
11
28
  }
12
29
 
30
+ // Wraps a render-time expression so a throw (for example
31
+ // `post.createdAt.toLocaleDateString()` while `post` is still null)
32
+ // is logged with its template line and replaced by `fallback`, instead
33
+ // of aborting the whole mount. Reads made before the throw are still
34
+ // tracked, so the effect re-runs once the data arrives. Not used for
35
+ // event handlers, which already report errors through the browser.
36
+ function guard(exprSrc, fallback, what, line) {
37
+ const where = line ? ` at line ${line}` : ''
38
+ const label = JSON.stringify(`Tylix: error in ${what}${where}:`)
39
+ return `(() => { try { return ${exprSrc}; } catch (e) { console.error(${label}, e); return ${fallback}; } })()`
40
+ }
41
+
13
42
  /**
14
43
  * Compiles a template AST into the BODY of a render(instance,
15
44
  * document, components) function as a JS source string. No virtual
@@ -48,7 +77,9 @@ function compileNode(node, lines, scope, inSvg = false) {
48
77
  const varName = nextVar('text')
49
78
  const expr = generateTemplateExpression(node.expression, scope)
50
79
  lines.push(`const ${varName} = document.createTextNode("");`)
51
- lines.push(`effect(() => { ${varName}.nodeValue = ${expr}; });`)
80
+ lines.push(
81
+ `effect(() => { const v = ${guard(expr, '""', '{{ }} interpolation', node.line)}; ${varName}.nodeValue = v == null ? "" : v; });`,
82
+ )
52
83
  return varName
53
84
  }
54
85
 
@@ -66,10 +97,11 @@ function compileNode(node, lines, scope, inSvg = false) {
66
97
 
67
98
  throw new Error(`generateTemplate: unknown node type "${node.type}"`)
68
99
  }
100
+
69
101
  // Renders node.children into a local fragment and returns the lines
70
- // needed to build it plus the fragment's own variable name, without
71
- // touching the caller's `lines` array directly (used inside effect
72
- // callbacks below, which need their own nested block of statements).
102
+ // needed to build it, without touching the caller's `lines` array
103
+ // directly (used inside effect callbacks below, which need their own
104
+ // nested block of statements).
73
105
  function compileChildrenIntoFragment(children, scope, fragVar, inSvg = false) {
74
106
  const childLines = []
75
107
  const childVars = children.map((child) =>
@@ -79,83 +111,123 @@ function compileChildrenIntoFragment(children, scope, fragVar, inSvg = false) {
79
111
  return childLines
80
112
  }
81
113
 
82
- // Conditional rendering with no VDOM: an anchor comment node marks
83
- // the block's position; on first run (before the anchor is even
84
- // attached to the real DOM by the caller) content builds into the
85
- // same fragment that holds the anchor. On every later run (state
86
- // changed), previous nodes are removed and new ones inserted right
87
- // after the anchor in the live DOM.
88
- function compileIf(node, lines, scope, inSvg = false) {
89
- const anchorVar = nextVar('ifAnchor')
90
- const containerVar = nextVar('ifContainer')
91
- const nodesVar = nextVar('ifNodes')
92
- const initialVar = nextVar('ifInitial')
93
- const condExpr = generateTemplateExpression(node.condition, scope)
114
+ function emitBranch(lines, children, scope, inSvg, indent) {
115
+ compileChildrenIntoFragment(children, scope, 'frag', inSvg).forEach((l) =>
116
+ lines.push(`${indent}${l}`),
117
+ )
118
+ }
94
119
 
95
- lines.push(`const ${anchorVar} = document.createComment("if");`)
120
+ // Every {{#if}} / {{#each}} block owns the DOM range BETWEEN two
121
+ // comment markers (start, end). On every run the whole range is
122
+ // cleared and the new content is inserted before the end marker.
123
+ // Because nested blocks live inside the parent's range, a parent
124
+ // re-run also removes whatever its children inserted later -- the old
125
+ // "remember the nodes from the first run" approach leaked those.
126
+ function emitRangeOpen(lines, startVar, endVar, containerVar, label) {
127
+ lines.push(`const ${startVar} = document.createComment(${JSON.stringify(label)});`)
128
+ lines.push(`const ${endVar} = document.createComment(${JSON.stringify('/' + label)});`)
96
129
  lines.push(`const ${containerVar} = document.createDocumentFragment();`)
97
- lines.push(`${containerVar}.appendChild(${anchorVar});`)
98
- lines.push(`let ${nodesVar} = [];`)
99
- lines.push(`let ${initialVar} = true;`)
130
+ lines.push(`${containerVar}.appendChild(${startVar});`)
131
+ lines.push(`${containerVar}.appendChild(${endVar});`)
100
132
  lines.push(`effect(() => {`)
101
- lines.push(` for (const n of ${nodesVar}) n.remove();`)
102
- lines.push(` ${nodesVar} = [];`)
103
- lines.push(` if (${condExpr}) {`)
104
- lines.push(` const frag = document.createDocumentFragment();`)
105
- const childLines = compileChildrenIntoFragment(
106
- node.children,
107
- scope,
108
- 'frag',
109
- inSvg,
133
+ lines.push(
134
+ ` while (${startVar}.nextSibling && ${startVar}.nextSibling !== ${endVar}) ${startVar}.nextSibling.remove();`,
110
135
  )
111
- childLines.forEach((l) => lines.push(` ${l}`))
112
- lines.push(` ${nodesVar} = Array.from(frag.childNodes);`)
113
- lines.push(` if (${initialVar}) { ${containerVar}.appendChild(frag); }`)
136
+ lines.push(` const frag = document.createDocumentFragment();`)
137
+ }
138
+
139
+ function emitRangeClose(lines, endVar) {
114
140
  lines.push(
115
- ` else { ${anchorVar}.parentNode.insertBefore(frag, ${anchorVar}.nextSibling); }`,
141
+ ` if (${endVar}.parentNode) { ${endVar}.parentNode.insertBefore(frag, ${endVar}); }`,
116
142
  )
117
- lines.push(` }`)
118
- lines.push(` ${initialVar} = false;`)
119
143
  lines.push(`});`)
144
+ }
145
+
146
+ // Conditional rendering with no VDOM. `{{#else}}` / `{{#else if}}`
147
+ // branches render into the same slot when the condition is false.
148
+ function compileIf(node, lines, scope, inSvg = false) {
149
+ const startVar = nextVar('ifStart')
150
+ const endVar = nextVar('ifEnd')
151
+ const containerVar = nextVar('ifContainer')
152
+
153
+ // `{{#else if}}` chains (and an {{#else}} holding nothing but one
154
+ // {{#if}}, which means the same thing) are flattened into a single
155
+ // if / else if / else so the whole chain is ONE effect.
156
+ const branches = []
157
+ let current = node
158
+ let finalElse = null
159
+ while (true) {
160
+ branches.push({
161
+ cond: guard(
162
+ generateTemplateExpression(current.condition, scope),
163
+ 'false',
164
+ '{{#if}} condition',
165
+ current.line,
166
+ ),
167
+ children: current.children,
168
+ })
169
+ const rest = current.elseChildren
170
+ if (rest && rest.length === 1 && rest[0].type === 'If') {
171
+ current = rest[0]
172
+ continue
173
+ }
174
+ finalElse = rest
175
+ break
176
+ }
177
+
178
+ emitRangeOpen(lines, startVar, endVar, containerVar, 'if')
179
+ branches.forEach((b, i) => {
180
+ lines.push(i === 0 ? ` if (${b.cond}) {` : ` } else if (${b.cond}) {`)
181
+ emitBranch(lines, b.children, scope, inSvg, ' ')
182
+ })
183
+ if (finalElse) {
184
+ lines.push(` } else {`)
185
+ emitBranch(lines, finalElse, scope, inSvg, ' ')
186
+ }
187
+ lines.push(` }`)
188
+ emitRangeClose(lines, endVar)
120
189
 
121
190
  return containerVar
122
191
  }
123
192
 
193
+ // {{#each item in items}}, {{#each item, i in items}},
194
+ // {{#each [k, v] in Object.entries(o)}}, {{#each { id } in rows}}.
195
+ // `{{#else}}` renders when the list is empty. A null/undefined list
196
+ // (or one whose expression throws) renders as empty.
124
197
  function compileEach(node, lines, scope, inSvg = false) {
125
- const anchorVar = nextVar('eachAnchor')
198
+ const startVar = nextVar('eachStart')
199
+ const endVar = nextVar('eachEnd')
126
200
  const containerVar = nextVar('eachContainer')
127
- const nodesVar = nextVar('eachNodes')
128
- const initialVar = nextVar('eachInitial')
201
+ const listVar = nextVar('eachList')
202
+ const indexVar = nextVar('eachIndex')
129
203
  const iterableExpr = generateTemplateExpression(node.iterable, scope)
130
- const innerScope = new Set([...scope, node.itemName])
204
+ const innerScope = new Set([
205
+ ...scope,
206
+ ...paramNames([node.itemName]),
207
+ ...(node.indexName ? [node.indexName] : []),
208
+ ])
131
209
 
132
- lines.push(`const ${anchorVar} = document.createComment("each");`)
133
- lines.push(`const ${containerVar} = document.createDocumentFragment();`)
134
- lines.push(`${containerVar}.appendChild(${anchorVar});`)
135
- lines.push(`let ${nodesVar} = [];`)
136
- lines.push(`let ${initialVar} = true;`)
137
- lines.push(`effect(() => {`)
138
- lines.push(` for (const n of ${nodesVar}) n.remove();`)
139
- lines.push(` const frag = document.createDocumentFragment();`)
140
- lines.push(` for (const ${node.itemName} of ${iterableExpr}) {`)
141
- const childLines = compileChildrenIntoFragment(
142
- node.children,
143
- innerScope,
144
- 'frag',
145
- inSvg,
146
- )
147
- childLines.forEach((l) => lines.push(` ${l}`))
148
- lines.push(` }`)
149
- lines.push(` ${nodesVar} = Array.from(frag.childNodes);`)
150
- lines.push(` if (${initialVar}) { ${containerVar}.appendChild(frag); }`)
210
+ emitRangeOpen(lines, startVar, endVar, containerVar, 'each')
151
211
  lines.push(
152
- ` else { ${anchorVar}.parentNode.insertBefore(frag, ${anchorVar}.nextSibling); }`,
212
+ ` const ${listVar} = Array.from(${guard(iterableExpr, '[]', '{{#each}} list', node.line)} ?? []);`,
153
213
  )
154
- lines.push(` ${initialVar} = false;`)
155
- lines.push(`});`)
214
+ if (node.indexName) lines.push(` let ${indexVar} = 0;`)
215
+ lines.push(` for (const ${node.itemName} of ${listVar}) {`)
216
+ if (node.indexName) {
217
+ lines.push(` const ${node.indexName} = ${indexVar}++;`)
218
+ }
219
+ emitBranch(lines, node.children, innerScope, inSvg, ' ')
220
+ lines.push(` }`)
221
+ if (node.elseChildren) {
222
+ lines.push(` if (${listVar}.length === 0) {`)
223
+ emitBranch(lines, node.elseChildren, scope, inSvg, ' ')
224
+ lines.push(` }`)
225
+ }
226
+ emitRangeClose(lines, endVar)
156
227
 
157
228
  return containerVar
158
229
  }
230
+
159
231
  function isComponentTag(tag) {
160
232
  return COMPONENT_TAG_PATTERN.test(tag)
161
233
  }
@@ -166,22 +238,23 @@ function compileElement(node, lines, scope, inSvg = false) {
166
238
  const tagLiteral = JSON.stringify(node.tag)
167
239
 
168
240
  const propEntries = node.attributes.map((attr) => {
169
- let expr
170
- if (attr.dynamic) {
171
- expr = generateTemplateExpression(attr.value, scope)
172
- // Callback props (onXxx="{{ methodName }}") pass a bare
173
- // instance-method reference. `generateTemplateExpression`
174
- // turns `methodName` into `instance.methodName`, but handing
175
- // that off as a plain value loses its `this` binding the
176
- // moment the child calls it. Bind it here, while we still
177
- // have `instance` in scope.
178
- if (/^on[A-Z]/.test(attr.name) && attr.value.type === 'Identifier') {
179
- expr = `(${expr}).bind(instance)`
180
- }
181
- } else {
182
- expr = JSON.stringify(attr.value)
241
+ const key = JSON.stringify(attr.name)
242
+ if (!attr.dynamic) return `${key}: ${JSON.stringify(attr.value)}`
243
+
244
+ let expr = generateTemplateExpression(attr.value, scope)
245
+
246
+ // Callback props (onXxx="{{ methodName }}") are plain values. A bare
247
+ // instance-method reference loses its `this` the moment the child
248
+ // calls it, so bind it here while `instance` is still in scope.
249
+ if (/^on[A-Z]/.test(attr.name)) {
250
+ if (attr.value.type === 'Identifier') expr = `(${expr}).bind(instance)`
251
+ return `${key}: ${expr}`
183
252
  }
184
- return `${JSON.stringify(attr.name)}: ${expr}`
253
+
254
+ // Everything else is a lazy getter: the child reads it inside its
255
+ // own effects, so `<Child value="{{ count }}">` stays live instead
256
+ // of being a snapshot taken at mount().
257
+ return `get ${key}() { return ${guard(expr, 'undefined', `<${node.tag}> prop "${attr.name}"`, attr.line)}; }`
185
258
  })
186
259
  const propsExpr = `{ ${propEntries.join(', ')} }`
187
260
 
@@ -204,8 +277,7 @@ function compileElement(node, lines, scope, inSvg = false) {
204
277
  // Once we're inside an <svg>, every descendant (path, circle, g,
205
278
  // etc.) needs the SVG namespace too -- createElement() without a
206
279
  // namespace produces a non-rendering element that still LOOKS
207
- // correct in the DOM inspector (right tag name, right attributes),
208
- // which is exactly what made this bug so hard to spot.
280
+ // correct in the DOM inspector.
209
281
  const isSvgRoot = node.tag === 'svg'
210
282
  const nsForThisNode = inSvg || isSvgRoot
211
283
  const childInSvg = isSvgRoot ? true : inSvg
@@ -232,6 +304,7 @@ function compileElement(node, lines, scope, inSvg = false) {
232
304
 
233
305
  return varName
234
306
  }
307
+
235
308
  // Attributes that reflect live user-editable DOM state -- setting
236
309
  // them via setAttribute() only seeds the *initial* value; once the
237
310
  // user interacts with the control, the live property diverges from
@@ -241,10 +314,8 @@ const LIVE_PROPERTY_ATTRS = new Set(['value', 'checked'])
241
314
  const LIVE_PROPERTY_TAGS = new Set(['input', 'textarea', 'select'])
242
315
 
243
316
  // Attributes where HTML only cares whether they're *present*, not
244
- // their string value -- setAttribute(name, "false") is still
245
- // truthy to the browser, same as "true" or "". These need
246
- // add/removeAttribute based on the JS value's truthiness, not a
247
- // literal setAttribute call with the stringified value.
317
+ // their string value. These need add/removeAttribute based on the JS
318
+ // value's truthiness, not a literal setAttribute call.
248
319
  const BOOLEAN_ATTRS = new Set([
249
320
  'disabled',
250
321
  'checked',
@@ -270,45 +341,56 @@ function compileAttribute(elVar, tag, attr, lines, scope) {
270
341
  // bare "event" -- both are treated as the same local so neither
271
342
  // gets mistakenly prefixed with "instance.".
272
343
  const scopeWithEvent = new Set([...scope, '$event', 'event'])
344
+ const expr = generateTemplateExpression(attr.value, scopeWithEvent)
273
345
 
274
- if (
275
- attr.value.type === 'CallExpression' ||
276
- attr.value.type === 'AssignmentExpression'
277
- ) {
278
- const expr = generateTemplateExpression(attr.value, scopeWithEvent)
346
+ if (FUNCTION_VALUED.has(attr.value.type)) {
347
+ // Function value: call it with the event.
279
348
  lines.push(
280
- `${elVar}.addEventListener(${JSON.stringify(eventName)}, ($event) => { const event = $event; ${expr}; });`,
349
+ `${elVar}.addEventListener(${JSON.stringify(eventName)}, ($event) => { const event = $event; ${expr}($event); });`,
281
350
  )
282
351
  return
283
352
  }
284
353
 
285
- const expr = generateTemplateExpression(attr.value, scopeWithEvent)
354
+ // Statement: run it when the event fires. Handlers that contain
355
+ // `await` become async arrows.
356
+ const asyncPrefix = /\bawait\b/.test(expr) ? 'async ' : ''
286
357
  lines.push(
287
- `${elVar}.addEventListener(${JSON.stringify(eventName)}, ($event) => { const event = $event; ${expr}($event); });`,
358
+ `${elVar}.addEventListener(${JSON.stringify(eventName)}, ${asyncPrefix}($event) => { const event = $event; ${expr}; });`,
288
359
  )
289
360
  return
290
361
  }
291
362
 
292
363
  if (attr.dynamic) {
293
- const expr = generateTemplateExpression(attr.value, scope)
364
+ const raw = generateTemplateExpression(attr.value, scope)
365
+ const expr = guard(raw, 'undefined', `attribute "${attr.name}"`, attr.line)
366
+ const nameLit = JSON.stringify(attr.name)
294
367
  const useProperty =
295
368
  LIVE_PROPERTY_ATTRS.has(attr.name) && LIVE_PROPERTY_TAGS.has(tag)
296
369
  const useBoolean = BOOLEAN_ATTRS.has(attr.name) && !useProperty
370
+
297
371
  if (useProperty) {
298
372
  // Set the live DOM property, not the attribute, so re-renders
299
- // after the user has typed (e.g. clearing the form on submit)
300
- // actually update what's on screen.
301
- lines.push(`effect(() => { ${elVar}.${attr.name} = ${expr}; });`)
373
+ // after the user has typed actually update what's on screen.
374
+ // `value` shows null/undefined as empty, `checked` is coerced.
375
+ if (attr.name === 'value') {
376
+ lines.push(
377
+ `effect(() => { const v = ${expr}; ${elVar}.value = v == null ? "" : v; });`,
378
+ )
379
+ } else {
380
+ lines.push(`effect(() => { ${elVar}.${attr.name} = !!(${expr}); });`)
381
+ }
302
382
  } else if (useBoolean) {
303
383
  // Boolean attribute: presence, not string value, is what
304
- // matters to the browser. Add it (empty string) when truthy,
305
- // remove it entirely when falsy.
384
+ // matters to the browser.
306
385
  lines.push(
307
- `effect(() => { if (${expr}) { ${elVar}.setAttribute(${JSON.stringify(attr.name)}, ""); } else { ${elVar}.removeAttribute(${JSON.stringify(attr.name)}); } });`,
386
+ `effect(() => { if (${expr}) { ${elVar}.setAttribute(${nameLit}, ""); } else { ${elVar}.removeAttribute(${nameLit}); } });`,
308
387
  )
309
388
  } else {
389
+ // null/undefined remove the attribute instead of writing the
390
+ // string "undefined". false/0/"" are real values and are kept
391
+ // (aria-expanded="false" must stay).
310
392
  lines.push(
311
- `effect(() => { ${elVar}.setAttribute(${JSON.stringify(attr.name)}, ${expr}); });`,
393
+ `effect(() => { const v = ${expr}; if (v == null) { ${elVar}.removeAttribute(${nameLit}); } else { ${elVar}.setAttribute(${nameLit}, v); } });`,
312
394
  )
313
395
  }
314
396
  return
@@ -317,4 +399,4 @@ function compileAttribute(elVar, tag, attr, lines, scope) {
317
399
  lines.push(
318
400
  `${elVar}.setAttribute(${JSON.stringify(attr.name)}, ${JSON.stringify(attr.value)});`,
319
401
  )
320
- }
402
+ }