@tylix/compiler 1.1.0 → 1.3.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.
- package/README.md +62 -0
- package/package.json +1 -1
- package/src/ast/nodes.js +13 -1
- package/src/codegen/generateExpression.js +13 -4
- package/src/codegen/generateTemplate.js +333 -12
- package/src/compileComponent.js +4 -2
- package/src/diagnostics/diagnose.js +360 -0
- package/src/index.js +2 -1
- package/src/lexer/Lexer.js +13 -0
- package/src/parser/Parser.js +33 -0
- package/src/parser/parseComponentFile.js +21 -5
- package/src/parser/parseExpressionString.js +4 -0
- package/src/parser/parsePageFile.js +6 -0
- package/src/parser/parseTemplate.js +205 -30
- package/src/renderPageDocument.js +26 -5
- package/src/runtime/capability.js +7 -0
- package/src/runtime/devtoolsHook.js +389 -0
- package/src/typecheck/buildVirtualTs.js +18 -3
- package/src/typecheck/typecheckVirtualFile.js +24 -0
- package/src/typecheck/typedTemplateExpr.js +18 -1
- package/src/typecheckPage.js +6 -4
package/README.md
CHANGED
|
@@ -26,6 +26,68 @@ from "tylix-icons"`) by reading a `tylix-components.json` manifest
|
|
|
26
26
|
- `compileComponent` and `renderPageDocument` as the main entry points
|
|
27
27
|
tying parsing → typecheck → codegen together
|
|
28
28
|
|
|
29
|
+
- **Diagnostics** — `diagnoseTyx(source, { typecheck, language })` returns
|
|
30
|
+
every problem with its line and column in the file, plus an outline of
|
|
31
|
+
the file's props, state, computed values and actions (used by
|
|
32
|
+
`tylix check`, the dev error page and the language server)
|
|
33
|
+
|
|
34
|
+
## Template syntax
|
|
35
|
+
|
|
36
|
+
```html
|
|
37
|
+
<p>{{ user.name }}</p> <!-- text -->
|
|
38
|
+
<a href="{{ `/posts/${post.id}` }}">…</a> <!-- attributes -->
|
|
39
|
+
<button onclick="{{ save() }}">Save</button> <!-- events -->
|
|
40
|
+
|
|
41
|
+
{{#if loading}}…{{#else if error}}…{{#else}}…{{/if}}
|
|
42
|
+
{{#each item, i in items}}…{{#else}}empty{{/each}}
|
|
43
|
+
|
|
44
|
+
<!-- two-way binding -->
|
|
45
|
+
<input bind:value="{{ query }}" /> <!-- also type=number (stores numbers), textarea, select, select multiple -->
|
|
46
|
+
<input type="checkbox" bind:checked="{{ agree }}" />
|
|
47
|
+
<input type="radio" value="s" bind:group="{{ size }}" />
|
|
48
|
+
<input type="checkbox" value="a" bind:group="{{ tags }}" /> <!-- array of checked values -->
|
|
49
|
+
|
|
50
|
+
<!-- classes and styles -->
|
|
51
|
+
<li class="item" class:active="{{ id is selected }}" class:done /> <!-- class:done = class:done="{{ done }}" -->
|
|
52
|
+
<div style:color="{{ color }}" style:--gap="{{ gap }}" style:fontSize="{{ size }}"></div>
|
|
53
|
+
|
|
54
|
+
<!-- event modifiers -->
|
|
55
|
+
<form onsubmit.prevent="{{ save() }}">
|
|
56
|
+
<a onclick.prevent.stop="{{ open() }}">
|
|
57
|
+
<input onkeydown.enter="{{ add() }}" onkeydown.esc="{{ cancel() }}" />
|
|
58
|
+
<textarea onkeydown.ctrl.enter="{{ send() }}"></textarea>
|
|
59
|
+
<!-- prevent stop self once capture passive · ctrl shift alt meta ·
|
|
60
|
+
enter esc space tab up down left right delete backspace -->
|
|
61
|
+
|
|
62
|
+
<!-- promises -->
|
|
63
|
+
{{#await loadPosts()}}
|
|
64
|
+
<p>Loading…</p>
|
|
65
|
+
{{#then posts}}
|
|
66
|
+
{{#each p in posts}}<h2>{{ p.title }}</h2>{{/each}}
|
|
67
|
+
{{#catch error}}
|
|
68
|
+
<p>{{ error.message }}</p>
|
|
69
|
+
{{/await}}
|
|
70
|
+
{{#await stats then s}}{{ s.total }}{{/await}} <!-- no pending branch -->
|
|
71
|
+
|
|
72
|
+
<!-- trusted HTML (scripts in it never run) -->
|
|
73
|
+
<article>{{@html post.bodyHtml}}</article>
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Components take children. Inside the component, `<slot />` renders
|
|
77
|
+
them, `<slot name="x">` renders the children marked `slot="x"`, and
|
|
78
|
+
content inside `<slot>` is the fallback:
|
|
79
|
+
|
|
80
|
+
```html
|
|
81
|
+
<!-- Card.tyx -->
|
|
82
|
+
<article><h2>{{ title }}</h2><slot>No content</slot><footer><slot name="footer" /></footer></article>
|
|
83
|
+
|
|
84
|
+
<!-- a page -->
|
|
85
|
+
<Card title="Hello">
|
|
86
|
+
<p>Body, with the page's own state: {{ count }}</p>
|
|
87
|
+
<button slot="footer" onclick="{{ count = count + 1 }}">+1</button>
|
|
88
|
+
</Card>
|
|
89
|
+
```
|
|
90
|
+
|
|
29
91
|
## Usage
|
|
30
92
|
|
|
31
93
|
Used internally by `@tylix/core` (dev server) and `@tylix/cli`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tylix/compiler",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.0",
|
|
4
4
|
"description": "Compiler for Tylix .tyx pages and components: parses, type-checks and compiles them to server-rendered HTML and client JavaScript.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Mbiyrukzz",
|
package/src/ast/nodes.js
CHANGED
|
@@ -435,4 +435,16 @@ export function TypeDeclaration(kind, name, source) {
|
|
|
435
435
|
// members: [{ name, init: expression | null }]
|
|
436
436
|
export function EnumDeclaration(name, members) {
|
|
437
437
|
return { type: 'EnumDeclaration', name, members }
|
|
438
|
-
}
|
|
438
|
+
}
|
|
439
|
+
// {{#await promise}}pending{{#then value}}…{{#catch error}}…{{/await}}
|
|
440
|
+
// and the short form {{#await promise then value}}…{{/await}}.
|
|
441
|
+
// pending/thenChildren/catchChildren are null when the block has no
|
|
442
|
+
// such branch; thenName/catchName are null when nothing is bound.
|
|
443
|
+
export function AwaitNode(promise, pending, thenName, thenChildren, catchName, catchChildren) {
|
|
444
|
+
return { type: 'Await', promise, pending, thenName, thenChildren, catchName, catchChildren }
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
// {{@html expr}}: trusted HTML inserted as markup.
|
|
448
|
+
export function RawHtmlNode(expression) {
|
|
449
|
+
return { type: 'RawHtml', expression }
|
|
450
|
+
}
|
|
@@ -226,6 +226,15 @@ export function generateClass(node, typed = false) {
|
|
|
226
226
|
* `(await f()).x` and `ok && (count = count + 1)` are only valid JS
|
|
227
227
|
* with the parens, and the extra pair is harmless at statement level.
|
|
228
228
|
*/
|
|
229
|
+
// An arrow / function expression used as an operand keeps its own
|
|
230
|
+
// parentheses: `a ?? (v => v)` must not come out as `a ?? (v) => v`,
|
|
231
|
+
// which is a syntax error.
|
|
232
|
+
const FUNCTION_NODES = new Set(['ArrowFunctionExpression', 'FunctionExpression'])
|
|
233
|
+
function operand(node, typed) {
|
|
234
|
+
const src = generateExpression(node, typed)
|
|
235
|
+
return FUNCTION_NODES.has(node?.type) ? `(${src})` : src
|
|
236
|
+
}
|
|
237
|
+
|
|
229
238
|
export function generateExpression(node, typed = false) {
|
|
230
239
|
switch (node.type) {
|
|
231
240
|
case 'Literal':
|
|
@@ -243,7 +252,7 @@ export function generateExpression(node, typed = false) {
|
|
|
243
252
|
return `${memberObjectSource(node.object, typed)}${node.optional ? '?.' : '.'}${node.property}`
|
|
244
253
|
|
|
245
254
|
case 'NullishCoalescingExpression':
|
|
246
|
-
return `(${
|
|
255
|
+
return `(${operand(node.left, typed)} ?? ${operand(node.right, typed)})`
|
|
247
256
|
|
|
248
257
|
case 'NewExpression': {
|
|
249
258
|
const args = node.args.map((a) => generateExpression(a, typed)).join(', ')
|
|
@@ -252,10 +261,10 @@ export function generateExpression(node, typed = false) {
|
|
|
252
261
|
}
|
|
253
262
|
|
|
254
263
|
case 'BinaryExpression':
|
|
255
|
-
return `(${
|
|
264
|
+
return `(${operand(node.left, typed)} ${node.operator} ${operand(node.right, typed)})`
|
|
256
265
|
|
|
257
266
|
case 'UnaryExpression':
|
|
258
|
-
return `(${unaryPrefix(node.operator)}${
|
|
267
|
+
return `(${unaryPrefix(node.operator)}${operand(node.argument, typed)})`
|
|
259
268
|
|
|
260
269
|
case 'UpdateExpression': {
|
|
261
270
|
const arg = generateExpression(node.argument, typed)
|
|
@@ -263,7 +272,7 @@ export function generateExpression(node, typed = false) {
|
|
|
263
272
|
}
|
|
264
273
|
|
|
265
274
|
case 'TernaryExpression':
|
|
266
|
-
return `(${
|
|
275
|
+
return `(${operand(node.condition, typed)} ? ${generateExpression(node.consequent, typed)} : ${generateExpression(node.alternate, typed)})`
|
|
267
276
|
|
|
268
277
|
// `(a, b, c)` -- the comma operator.
|
|
269
278
|
case 'SequenceExpression':
|
|
@@ -7,6 +7,53 @@ import { paramNames } from './jsGlobals.js'
|
|
|
7
7
|
// so onClick works too). Capitalized component tags handle their own
|
|
8
8
|
// onXxx callback props separately in compileElement.
|
|
9
9
|
const EVENT_ATTR_PREFIX = /^on[a-z]+$/i
|
|
10
|
+
// onclick.prevent.stop, onkeydown.enter, onsubmit.prevent ...
|
|
11
|
+
const EVENT_WITH_MODIFIERS = /^on([a-z]+)((?:\.[a-z0-9]+)*)$/i
|
|
12
|
+
|
|
13
|
+
const KEY_MODIFIERS = {
|
|
14
|
+
enter: ['Enter'],
|
|
15
|
+
esc: ['Escape'],
|
|
16
|
+
escape: ['Escape'],
|
|
17
|
+
space: [' ', 'Spacebar'],
|
|
18
|
+
tab: ['Tab'],
|
|
19
|
+
up: ['ArrowUp'],
|
|
20
|
+
down: ['ArrowDown'],
|
|
21
|
+
left: ['ArrowLeft'],
|
|
22
|
+
right: ['ArrowRight'],
|
|
23
|
+
delete: ['Delete', 'Backspace'],
|
|
24
|
+
backspace: ['Backspace'],
|
|
25
|
+
}
|
|
26
|
+
const SYSTEM_MODIFIERS = { ctrl: 'ctrlKey', shift: 'shiftKey', alt: 'altKey', meta: 'metaKey' }
|
|
27
|
+
const OPTION_MODIFIERS = { once: 'once: true', capture: 'capture: true', passive: 'passive: true' }
|
|
28
|
+
|
|
29
|
+
// Turns modifiers into guard statements run before the handler, and
|
|
30
|
+
// addEventListener options.
|
|
31
|
+
function eventModifiers(modifiers, attr) {
|
|
32
|
+
const checks = []
|
|
33
|
+
const actions = []
|
|
34
|
+
const options = []
|
|
35
|
+
const keys = []
|
|
36
|
+
for (const m of modifiers) {
|
|
37
|
+
const lower = m.toLowerCase()
|
|
38
|
+
if (lower === 'prevent') actions.push('$event.preventDefault();')
|
|
39
|
+
else if (lower === 'stop') actions.push('$event.stopPropagation();')
|
|
40
|
+
else if (lower === 'self') checks.push('$event.target !== $event.currentTarget')
|
|
41
|
+
else if (OPTION_MODIFIERS[lower]) options.push(OPTION_MODIFIERS[lower])
|
|
42
|
+
else if (SYSTEM_MODIFIERS[lower]) checks.push(`!$event.${SYSTEM_MODIFIERS[lower]}`)
|
|
43
|
+
else if (KEY_MODIFIERS[lower]) keys.push(...KEY_MODIFIERS[lower])
|
|
44
|
+
else {
|
|
45
|
+
throw new Error(
|
|
46
|
+
`Unknown event modifier ".${m}" on ${attr.name} (line ${attr.line}). Use prevent, stop, self, once, capture, passive, ctrl, shift, alt, meta, or a key: ${Object.keys(KEY_MODIFIERS).join(', ')}`,
|
|
47
|
+
)
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
if (keys.length) checks.unshift(`!${JSON.stringify(keys)}.includes($event.key)`)
|
|
51
|
+
if (options.includes('passive: true') && actions.includes('$event.preventDefault();')) {
|
|
52
|
+
throw new Error(`${attr.name}: .passive and .prevent cannot be combined (line ${attr.line})`)
|
|
53
|
+
}
|
|
54
|
+
const guards = (checks.length ? `if (${checks.join(' || ')}) return; ` : '') + actions.join(' ') + (actions.length ? ' ' : '')
|
|
55
|
+
return { guards, options }
|
|
56
|
+
}
|
|
10
57
|
const COMPONENT_TAG_PATTERN = /^[A-Z]/
|
|
11
58
|
|
|
12
59
|
// A handler whose expression is one of these node types is a function
|
|
@@ -78,7 +125,7 @@ function compileNode(node, lines, scope, inSvg = false) {
|
|
|
78
125
|
const expr = generateTemplateExpression(node.expression, scope)
|
|
79
126
|
lines.push(`const ${varName} = document.createTextNode("");`)
|
|
80
127
|
lines.push(
|
|
81
|
-
`effect(() => { const
|
|
128
|
+
`effect(() => { const __v = ${guard(expr, '""', '{{ }} interpolation', node.line)}; ${varName}.nodeValue = __v == null ? "" : __v; });`,
|
|
82
129
|
)
|
|
83
130
|
return varName
|
|
84
131
|
}
|
|
@@ -95,6 +142,25 @@ function compileNode(node, lines, scope, inSvg = false) {
|
|
|
95
142
|
return compileElement(node, lines, scope, inSvg)
|
|
96
143
|
}
|
|
97
144
|
|
|
145
|
+
if (node.type === 'Await') {
|
|
146
|
+
return compileAwait(node, lines, scope, inSvg)
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
if (node.type === 'RawHtml') {
|
|
150
|
+
const startVar = nextVar('htmlStart')
|
|
151
|
+
const endVar = nextVar('htmlEnd')
|
|
152
|
+
const containerVar = nextVar('htmlContainer')
|
|
153
|
+
const expr = guard(generateTemplateExpression(node.expression, scope), '""', '{{@html}}', node.line)
|
|
154
|
+
emitRangeOpen(lines, startVar, endVar, containerVar, 'html')
|
|
155
|
+
// <template> parses the markup without running any <script> in it.
|
|
156
|
+
lines.push(` const __v = ${expr};`)
|
|
157
|
+
lines.push(` const __t = document.createElement("template");`)
|
|
158
|
+
lines.push(` __t.innerHTML = __v == null ? "" : String(__v);`)
|
|
159
|
+
lines.push(` __frag.appendChild(__t.content);`)
|
|
160
|
+
emitRangeClose(lines, endVar)
|
|
161
|
+
return containerVar
|
|
162
|
+
}
|
|
163
|
+
|
|
98
164
|
throw new Error(`generateTemplate: unknown node type "${node.type}"`)
|
|
99
165
|
}
|
|
100
166
|
|
|
@@ -112,7 +178,7 @@ function compileChildrenIntoFragment(children, scope, fragVar, inSvg = false) {
|
|
|
112
178
|
}
|
|
113
179
|
|
|
114
180
|
function emitBranch(lines, children, scope, inSvg, indent) {
|
|
115
|
-
compileChildrenIntoFragment(children, scope, '
|
|
181
|
+
compileChildrenIntoFragment(children, scope, '__frag', inSvg).forEach((l) =>
|
|
116
182
|
lines.push(`${indent}${l}`),
|
|
117
183
|
)
|
|
118
184
|
}
|
|
@@ -133,12 +199,12 @@ function emitRangeOpen(lines, startVar, endVar, containerVar, label) {
|
|
|
133
199
|
lines.push(
|
|
134
200
|
` while (${startVar}.nextSibling && ${startVar}.nextSibling !== ${endVar}) ${startVar}.nextSibling.remove();`,
|
|
135
201
|
)
|
|
136
|
-
lines.push(` const
|
|
202
|
+
lines.push(` const __frag = document.createDocumentFragment();`)
|
|
137
203
|
}
|
|
138
204
|
|
|
139
205
|
function emitRangeClose(lines, endVar) {
|
|
140
206
|
lines.push(
|
|
141
|
-
` if (${endVar}.parentNode) { ${endVar}.parentNode.insertBefore(
|
|
207
|
+
` if (${endVar}.parentNode) { ${endVar}.parentNode.insertBefore(__frag, ${endVar}); }`,
|
|
142
208
|
)
|
|
143
209
|
lines.push(`});`)
|
|
144
210
|
}
|
|
@@ -190,6 +256,61 @@ function compileIf(node, lines, scope, inSvg = false) {
|
|
|
190
256
|
return containerVar
|
|
191
257
|
}
|
|
192
258
|
|
|
259
|
+
// {{#await}}: one effect follows the promise expression and records
|
|
260
|
+
// where it is (pending / then / catch) in a plain holder, then bumps a
|
|
261
|
+
// reactive counter. The block's range effect reads that counter and
|
|
262
|
+
// renders the matching branch, so everything it creates (nested blocks,
|
|
263
|
+
// interpolations) has a normal owner and is disposed on the next run --
|
|
264
|
+
// nothing is rendered from inside the promise callback itself. A
|
|
265
|
+
// promise that settles after a newer one replaced it is ignored.
|
|
266
|
+
function compileAwait(node, lines, scope, inSvg = false) {
|
|
267
|
+
const holder = nextVar('awaitState')
|
|
268
|
+
const signal = nextVar('awaitSignal')
|
|
269
|
+
const startVar = nextVar('awaitStart')
|
|
270
|
+
const endVar = nextVar('awaitEnd')
|
|
271
|
+
const containerVar = nextVar('awaitContainer')
|
|
272
|
+
const expr = guard(generateTemplateExpression(node.promise, scope), 'undefined', '{{#await}} promise', node.line)
|
|
273
|
+
const hasCatch = node.catchChildren !== null
|
|
274
|
+
const where = JSON.stringify(`Tylix: {{#await}} at line ${node.line} rejected:`)
|
|
275
|
+
|
|
276
|
+
lines.push(`const ${holder} = { phase: "pending", value: undefined, token: 0 };`)
|
|
277
|
+
lines.push(`const ${signal} = reactive({ n: 0 });`)
|
|
278
|
+
lines.push(`effect(() => {`)
|
|
279
|
+
lines.push(` const __p = ${expr};`)
|
|
280
|
+
lines.push(` const __token = ++${holder}.token;`)
|
|
281
|
+
lines.push(` if (__p != null && typeof __p.then === "function") {`)
|
|
282
|
+
lines.push(` ${holder}.phase = "pending"; ${holder}.value = undefined;`)
|
|
283
|
+
lines.push(` Promise.resolve(__p).then(`)
|
|
284
|
+
lines.push(` (__v) => { if (${holder}.token !== __token) return; ${holder}.phase = "then"; ${holder}.value = __v; untracked(() => { ${signal}.n++; }); },`)
|
|
285
|
+
lines.push(` (e) => { if (${holder}.token !== __token) return; ${hasCatch ? '' : `console.error(${where}, e); `}${holder}.phase = "catch"; ${holder}.value = e; untracked(() => { ${signal}.n++; }); },`)
|
|
286
|
+
lines.push(` );`)
|
|
287
|
+
lines.push(` } else {`)
|
|
288
|
+
lines.push(` ${holder}.phase = "then"; ${holder}.value = __p;`)
|
|
289
|
+
lines.push(` }`)
|
|
290
|
+
lines.push(` untracked(() => { ${signal}.n++; });`)
|
|
291
|
+
lines.push(`});`)
|
|
292
|
+
|
|
293
|
+
emitRangeOpen(lines, startVar, endVar, containerVar, 'await')
|
|
294
|
+
lines.push(` ${signal}.n;`)
|
|
295
|
+
lines.push(` if (${holder}.phase === "pending") {`)
|
|
296
|
+
if (node.pending) emitBranch(lines, node.pending, scope, inSvg, ' ')
|
|
297
|
+
lines.push(` } else if (${holder}.phase === "then") {`)
|
|
298
|
+
if (node.thenChildren) {
|
|
299
|
+
if (node.thenName) lines.push(` const ${node.thenName} = ${holder}.value;`)
|
|
300
|
+
const inner = new Set([...scope, ...(node.thenName ? paramNames([node.thenName]) : [])])
|
|
301
|
+
emitBranch(lines, node.thenChildren, inner, inSvg, ' ')
|
|
302
|
+
}
|
|
303
|
+
lines.push(` } else {`)
|
|
304
|
+
if (node.catchChildren) {
|
|
305
|
+
if (node.catchName) lines.push(` const ${node.catchName} = ${holder}.value;`)
|
|
306
|
+
const inner = new Set([...scope, ...(node.catchName ? paramNames([node.catchName]) : [])])
|
|
307
|
+
emitBranch(lines, node.catchChildren, inner, inSvg, ' ')
|
|
308
|
+
}
|
|
309
|
+
lines.push(` }`)
|
|
310
|
+
emitRangeClose(lines, endVar)
|
|
311
|
+
return containerVar
|
|
312
|
+
}
|
|
313
|
+
|
|
193
314
|
// {{#each item in items}}, {{#each item, i in items}},
|
|
194
315
|
// {{#each [k, v] in Object.entries(o)}}, {{#each { id } in rows}}.
|
|
195
316
|
// `{{#else}}` renders when the list is empty. A null/undefined list
|
|
@@ -237,6 +358,13 @@ function compileElement(node, lines, scope, inSvg = false) {
|
|
|
237
358
|
const varName = nextVar('component')
|
|
238
359
|
const tagLiteral = JSON.stringify(node.tag)
|
|
239
360
|
|
|
361
|
+
for (const attr of node.attributes) {
|
|
362
|
+
if (/^(bind|class|style):/.test(attr.name) || /^on[A-Za-z]+\./.test(attr.name)) {
|
|
363
|
+
throw new Error(
|
|
364
|
+
`<${node.tag}> ${attr.name}: bind:, class:, style: and event modifiers only work on HTML elements, not components (line ${attr.line})`,
|
|
365
|
+
)
|
|
366
|
+
}
|
|
367
|
+
}
|
|
240
368
|
const propEntries = node.attributes.map((attr) => {
|
|
241
369
|
const key = JSON.stringify(attr.name)
|
|
242
370
|
if (!attr.dynamic) return `${key}: ${JSON.stringify(attr.value)}`
|
|
@@ -256,6 +384,11 @@ function compileElement(node, lines, scope, inSvg = false) {
|
|
|
256
384
|
// of being a snapshot taken at mount().
|
|
257
385
|
return `get ${key}() { return ${guard(expr, 'undefined', `<${node.tag}> prop "${attr.name}"`, attr.line)}; }`
|
|
258
386
|
})
|
|
387
|
+
// Children become render functions the component calls from its
|
|
388
|
+
// <slot> elements. They are compiled HERE, in the parent's scope,
|
|
389
|
+
// so they see the parent's state and any {{#each}} variables.
|
|
390
|
+
const slotFns = compileSlotFunctions(node, scope, inSvg)
|
|
391
|
+
if (slotFns) propEntries.push(`"__slots": ${slotFns}`)
|
|
259
392
|
const propsExpr = `{ ${propEntries.join(', ')} }`
|
|
260
393
|
|
|
261
394
|
lines.push(`let ${varName};`)
|
|
@@ -282,6 +415,10 @@ function compileElement(node, lines, scope, inSvg = false) {
|
|
|
282
415
|
const nsForThisNode = inSvg || isSvgRoot
|
|
283
416
|
const childInSvg = isSvgRoot ? true : inSvg
|
|
284
417
|
|
|
418
|
+
if (node.tag === 'slot' && !inSvg) {
|
|
419
|
+
return compileSlot(node, lines, scope)
|
|
420
|
+
}
|
|
421
|
+
|
|
285
422
|
const varName = nextVar('el')
|
|
286
423
|
if (nsForThisNode) {
|
|
287
424
|
lines.push(
|
|
@@ -293,15 +430,28 @@ function compileElement(node, lines, scope, inSvg = false) {
|
|
|
293
430
|
)
|
|
294
431
|
}
|
|
295
432
|
|
|
433
|
+
const directives = { classes: [], styles: [], binds: [] }
|
|
434
|
+
let classAttr = null
|
|
435
|
+
let styleAttr = null
|
|
296
436
|
for (const attr of node.attributes) {
|
|
297
|
-
|
|
437
|
+
if (attr.name.startsWith('class:')) directives.classes.push(attr)
|
|
438
|
+
else if (attr.name.startsWith('style:')) directives.styles.push(attr)
|
|
439
|
+
else if (attr.name.startsWith('bind:')) directives.binds.push(attr)
|
|
440
|
+
else if (attr.name === 'class' && attr.dynamic) classAttr = attr
|
|
441
|
+
else if (attr.name === 'style' && attr.dynamic) styleAttr = attr
|
|
442
|
+
else compileAttribute(varName, node.tag, attr, lines, scope)
|
|
298
443
|
}
|
|
444
|
+
compileClassAndStyle(varName, classAttr, styleAttr, directives, lines, scope)
|
|
299
445
|
|
|
300
446
|
for (const child of node.children) {
|
|
301
447
|
const childVar = compileNode(child, lines, scope, childInSvg)
|
|
302
448
|
lines.push(`${varName}.appendChild(${childVar});`)
|
|
303
449
|
}
|
|
304
450
|
|
|
451
|
+
// After the children, so a <select>'s options exist before its value
|
|
452
|
+
// is set.
|
|
453
|
+
for (const attr of directives.binds) compileBind(varName, node, attr, lines, scope)
|
|
454
|
+
|
|
305
455
|
return varName
|
|
306
456
|
}
|
|
307
457
|
|
|
@@ -329,8 +479,11 @@ const BOOLEAN_ATTRS = new Set([
|
|
|
329
479
|
])
|
|
330
480
|
|
|
331
481
|
function compileAttribute(elVar, tag, attr, lines, scope) {
|
|
332
|
-
|
|
333
|
-
|
|
482
|
+
const eventMatch = EVENT_WITH_MODIFIERS.exec(attr.name)
|
|
483
|
+
if (eventMatch && (eventMatch[2] || EVENT_ATTR_PREFIX.test(attr.name))) {
|
|
484
|
+
const eventName = eventMatch[1].toLowerCase()
|
|
485
|
+
const modifiers = eventMatch[2] ? eventMatch[2].slice(1).split('.') : []
|
|
486
|
+
const { guards, options } = eventModifiers(modifiers, attr)
|
|
334
487
|
if (!attr.dynamic) {
|
|
335
488
|
throw new Error(
|
|
336
489
|
`Event attribute "${attr.name}" must use {{ }} binding, got a static string.`,
|
|
@@ -343,10 +496,11 @@ function compileAttribute(elVar, tag, attr, lines, scope) {
|
|
|
343
496
|
const scopeWithEvent = new Set([...scope, '$event', 'event'])
|
|
344
497
|
const expr = generateTemplateExpression(attr.value, scopeWithEvent)
|
|
345
498
|
|
|
499
|
+
const opts = options.length ? `, { ${options.join(', ')} }` : ''
|
|
346
500
|
if (FUNCTION_VALUED.has(attr.value.type)) {
|
|
347
501
|
// Function value: call it with the event.
|
|
348
502
|
lines.push(
|
|
349
|
-
`${elVar}.addEventListener(${JSON.stringify(eventName)}, ($event) => { const event = $event; ${expr}($event); });`,
|
|
503
|
+
`${elVar}.addEventListener(${JSON.stringify(eventName)}, ($event) => { const event = $event; ${guards}${expr}($event); }${opts});`,
|
|
350
504
|
)
|
|
351
505
|
return
|
|
352
506
|
}
|
|
@@ -355,7 +509,7 @@ function compileAttribute(elVar, tag, attr, lines, scope) {
|
|
|
355
509
|
// `await` become async arrows.
|
|
356
510
|
const asyncPrefix = /\bawait\b/.test(expr) ? 'async ' : ''
|
|
357
511
|
lines.push(
|
|
358
|
-
`${elVar}.addEventListener(${JSON.stringify(eventName)}, ${asyncPrefix}($event) => { const event = $event; ${expr}; });`,
|
|
512
|
+
`${elVar}.addEventListener(${JSON.stringify(eventName)}, ${asyncPrefix}($event) => { const event = $event; ${guards}${expr}; }${opts});`,
|
|
359
513
|
)
|
|
360
514
|
return
|
|
361
515
|
}
|
|
@@ -374,7 +528,7 @@ function compileAttribute(elVar, tag, attr, lines, scope) {
|
|
|
374
528
|
// `value` shows null/undefined as empty, `checked` is coerced.
|
|
375
529
|
if (attr.name === 'value') {
|
|
376
530
|
lines.push(
|
|
377
|
-
`effect(() => { const
|
|
531
|
+
`effect(() => { const __v = ${expr}; ${elVar}.value = __v == null ? "" : __v; });`,
|
|
378
532
|
)
|
|
379
533
|
} else {
|
|
380
534
|
lines.push(`effect(() => { ${elVar}.${attr.name} = !!(${expr}); });`)
|
|
@@ -390,7 +544,7 @@ function compileAttribute(elVar, tag, attr, lines, scope) {
|
|
|
390
544
|
// string "undefined". false/0/"" are real values and are kept
|
|
391
545
|
// (aria-expanded="false" must stay).
|
|
392
546
|
lines.push(
|
|
393
|
-
`effect(() => { const
|
|
547
|
+
`effect(() => { const __v = ${expr}; if (__v == null) { ${elVar}.removeAttribute(${nameLit}); } else { ${elVar}.setAttribute(${nameLit}, __v); } });`,
|
|
394
548
|
)
|
|
395
549
|
}
|
|
396
550
|
return
|
|
@@ -399,4 +553,171 @@ function compileAttribute(elVar, tag, attr, lines, scope) {
|
|
|
399
553
|
lines.push(
|
|
400
554
|
`${elVar}.setAttribute(${JSON.stringify(attr.name)}, ${JSON.stringify(attr.value)});`,
|
|
401
555
|
)
|
|
402
|
-
}
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
// <Card>children</Card>: children grouped by their slot="" attribute
|
|
559
|
+
// (default slot otherwise), each compiled into
|
|
560
|
+
// (document) => DocumentFragment, in the parent's scope.
|
|
561
|
+
function compileSlotFunctions(node, scope, inSvg) {
|
|
562
|
+
const groups = new Map()
|
|
563
|
+
for (const child of node.children) {
|
|
564
|
+
let name = 'default'
|
|
565
|
+
let target = child
|
|
566
|
+
if (child.type === 'Element') {
|
|
567
|
+
const slotAttr = child.attributes.find((a) => a.name === 'slot')
|
|
568
|
+
if (slotAttr) {
|
|
569
|
+
if (slotAttr.dynamic) {
|
|
570
|
+
throw new Error(`slot="" must be a fixed name, not {{ }} (line ${slotAttr.line})`)
|
|
571
|
+
}
|
|
572
|
+
name = String(slotAttr.value)
|
|
573
|
+
target = { ...child, attributes: child.attributes.filter((a) => a !== slotAttr) }
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
if (!groups.has(name)) groups.set(name, [])
|
|
577
|
+
groups.get(name).push(target)
|
|
578
|
+
}
|
|
579
|
+
if (groups.size === 0) return null
|
|
580
|
+
const entries = [...groups].map(([name, children]) => {
|
|
581
|
+
const body = compileChildrenIntoFragment(children, scope, '__frag', inSvg)
|
|
582
|
+
return `${JSON.stringify(name)}: (document) => { const __frag = document.createDocumentFragment(); ${body.join(' ')} return __frag; }`
|
|
583
|
+
})
|
|
584
|
+
return `{ ${entries.join(', ')} }`
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
// <slot /> or <slot name="footer">fallback</slot> inside a component:
|
|
588
|
+
// what the parent passed for that slot, else the fallback children.
|
|
589
|
+
function compileSlot(node, lines, scope) {
|
|
590
|
+
const nameAttr = node.attributes.find((a) => a.name === 'name')
|
|
591
|
+
if (nameAttr && nameAttr.dynamic) {
|
|
592
|
+
throw new Error(`<slot name=""> must be a fixed name, not {{ }} (line ${nameAttr.line})`)
|
|
593
|
+
}
|
|
594
|
+
const name = JSON.stringify(nameAttr ? String(nameAttr.value) : 'default')
|
|
595
|
+
const varName = nextVar('slot')
|
|
596
|
+
const fallback = compileChildrenIntoFragment(node.children, scope, '__frag', false)
|
|
597
|
+
lines.push(
|
|
598
|
+
`const ${varName} = (() => { const __slots = instance.__props && instance.__props.__slots; if (__slots && typeof __slots[${name}] === "function") return __slots[${name}](document); const __frag = document.createDocumentFragment(); ${fallback.join(' ')} return __frag; })();`,
|
|
599
|
+
)
|
|
600
|
+
return varName
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
// class:name="{{ cond }}", style:prop="{{ value }}", plus a dynamic
|
|
604
|
+
// class="" / style="". When both kinds are present they share ONE
|
|
605
|
+
// effect: rewriting the class attribute would otherwise drop classes
|
|
606
|
+
// a class: directive had added.
|
|
607
|
+
function compileClassAndStyle(elVar, classAttr, styleAttr, directives, lines, scope) {
|
|
608
|
+
const valueOf = (attr, what) => {
|
|
609
|
+
// class:active with no value is short for class:active="{{ active }}"
|
|
610
|
+
if (!attr.dynamic) {
|
|
611
|
+
const short = attr.name.split(':')[1]
|
|
612
|
+
if (attr.value !== true || !/^[A-Za-z_$][\w$]*$/.test(short)) {
|
|
613
|
+
throw new Error(`${attr.name} needs a {{ }} value (line ${attr.line})`)
|
|
614
|
+
}
|
|
615
|
+
return generateTemplateExpression({ type: 'Identifier', name: short }, scope)
|
|
616
|
+
}
|
|
617
|
+
return generateTemplateExpression(attr.value, scope)
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
const classToggles = directives.classes.map((attr) => {
|
|
621
|
+
const name = attr.name.slice('class:'.length)
|
|
622
|
+
if (!name) throw new Error(`class: needs a class name, like class:active (line ${attr.line})`)
|
|
623
|
+
const cond = guard(valueOf(attr), 'false', `attribute "${attr.name}"`, attr.line)
|
|
624
|
+
return `${elVar}.classList.toggle(${JSON.stringify(name)}, !!(${cond}));`
|
|
625
|
+
})
|
|
626
|
+
const styleSets = directives.styles.map((attr) => {
|
|
627
|
+
let prop = attr.name.slice('style:'.length)
|
|
628
|
+
if (!prop) throw new Error(`style: needs a property, like style:color (line ${attr.line})`)
|
|
629
|
+
if (!prop.startsWith('--')) prop = prop.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)
|
|
630
|
+
const value = guard(valueOf(attr), 'undefined', `attribute "${attr.name}"`, attr.line)
|
|
631
|
+
return `{ const __v = ${value}; if (__v == null || __v === false) { ${elVar}.style.removeProperty(${JSON.stringify(prop)}); } else { ${elVar}.style.setProperty(${JSON.stringify(prop)}, String(__v)); } }`
|
|
632
|
+
})
|
|
633
|
+
|
|
634
|
+
const setAttr = (attr) => {
|
|
635
|
+
const v = guard(generateTemplateExpression(attr.value, scope), 'undefined', `attribute "${attr.name}"`, attr.line)
|
|
636
|
+
return `{ const __v = ${v}; if (__v == null) { ${elVar}.removeAttribute(${JSON.stringify(attr.name)}); } else { ${elVar}.setAttribute(${JSON.stringify(attr.name)}, __v); } }`
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
if (classAttr) lines.push(`effect(() => { ${setAttr(classAttr)} ${classToggles.join(' ')} });`)
|
|
640
|
+
else for (const t of classToggles) lines.push(`effect(() => { ${t} });`)
|
|
641
|
+
if (styleAttr) lines.push(`effect(() => { ${setAttr(styleAttr)} ${styleSets.join(' ')} });`)
|
|
642
|
+
else for (const t of styleSets) lines.push(`effect(() => { ${t} });`)
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
const BINDABLE = {
|
|
646
|
+
value: new Set(['input', 'textarea', 'select']),
|
|
647
|
+
checked: new Set(['input']),
|
|
648
|
+
group: new Set(['input']),
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
// bind:value / bind:checked / bind:group: the element shows the value,
|
|
652
|
+
// and user input writes it back.
|
|
653
|
+
function compileBind(elVar, node, attr, lines, scope) {
|
|
654
|
+
const prop = attr.name.slice('bind:'.length)
|
|
655
|
+
const where = `${attr.name} on <${node.tag}> (line ${attr.line})`
|
|
656
|
+
if (!BINDABLE[prop]) {
|
|
657
|
+
throw new Error(`Unsupported ${where}: use bind:value, bind:checked or bind:group`)
|
|
658
|
+
}
|
|
659
|
+
if (!BINDABLE[prop].has(node.tag)) {
|
|
660
|
+
throw new Error(`${where}: ${prop} can only be bound on ${[...BINDABLE[prop]].map((t) => `<${t}>`).join(', ')}`)
|
|
661
|
+
}
|
|
662
|
+
if (!attr.dynamic) throw new Error(`${where} needs a {{ }} value, like bind:value="{{ query }}"`)
|
|
663
|
+
const target = attr.value
|
|
664
|
+
const assignable =
|
|
665
|
+
(target.type === 'Identifier' && !scope.has(target.name)) ||
|
|
666
|
+
(target.type === 'MemberExpression' && !hasOptionalLink(target))
|
|
667
|
+
if (!assignable) {
|
|
668
|
+
throw new Error(`${where} must name a state field or a property (like {{ query }} or {{ item.done }}), not a computed value, loop variable or call`)
|
|
669
|
+
}
|
|
670
|
+
const lhs = generateTemplateExpression(target, scope)
|
|
671
|
+
const read = guard(lhs, 'undefined', `attribute "${attr.name}"`, attr.line)
|
|
672
|
+
const staticAttr = (name) => {
|
|
673
|
+
const a = node.attributes.find((x) => x.name === name && !x.dynamic)
|
|
674
|
+
return a ? String(a.value).toLowerCase() : null
|
|
675
|
+
}
|
|
676
|
+
const type = staticAttr('type')
|
|
677
|
+
const multiple = node.attributes.some((a) => a.name === 'multiple')
|
|
678
|
+
|
|
679
|
+
if (prop === 'checked') {
|
|
680
|
+
lines.push(`effect(() => { ${elVar}.checked = !!(${read}); });`)
|
|
681
|
+
lines.push(`${elVar}.addEventListener("change", () => { ${lhs} = ${elVar}.checked; });`)
|
|
682
|
+
return
|
|
683
|
+
}
|
|
684
|
+
if (prop === 'group') {
|
|
685
|
+
if (type !== 'radio' && type !== 'checkbox') throw new Error(`${where}: bind:group needs type="radio" or type="checkbox"`)
|
|
686
|
+
if (type === 'radio') {
|
|
687
|
+
lines.push(`effect(() => { ${elVar}.checked = ${read} === ${elVar}.value; });`)
|
|
688
|
+
lines.push(`${elVar}.addEventListener("change", () => { if (${elVar}.checked) ${lhs} = ${elVar}.value; });`)
|
|
689
|
+
} else {
|
|
690
|
+
// checkbox group: the bound value is an array of checked values
|
|
691
|
+
lines.push(`effect(() => { const __v = ${read}; ${elVar}.checked = Array.isArray(__v) && __v.includes(${elVar}.value); });`)
|
|
692
|
+
lines.push(`${elVar}.addEventListener("change", () => { const __cur = Array.isArray(${lhs}) ? ${lhs}.filter((x) => x !== ${elVar}.value) : []; ${lhs} = ${elVar}.checked ? [...__cur, ${elVar}.value] : __cur; });`)
|
|
693
|
+
}
|
|
694
|
+
return
|
|
695
|
+
}
|
|
696
|
+
// value
|
|
697
|
+
if (node.tag === 'select' && multiple) {
|
|
698
|
+
lines.push(`effect(() => { const __v = ${read}; const __list = Array.isArray(__v) ? __v.map(String) : []; for (const o of ${elVar}.options) o.selected = __list.includes(o.value); });`)
|
|
699
|
+
lines.push(`${elVar}.addEventListener("change", () => { ${lhs} = Array.from(${elVar}.selectedOptions, (o) => o.value); });`)
|
|
700
|
+
return
|
|
701
|
+
}
|
|
702
|
+
if (type === 'checkbox' || type === 'radio') {
|
|
703
|
+
throw new Error(`${where}: use bind:checked for a checkbox, or bind:group for radios`)
|
|
704
|
+
}
|
|
705
|
+
const numeric = type === 'number' || type === 'range'
|
|
706
|
+
const event = node.tag === 'select' ? 'change' : 'input'
|
|
707
|
+
const fromInput = numeric ? `(${elVar}.value === "" ? null : Number(${elVar}.value))` : `${elVar}.value`
|
|
708
|
+
// Only write when the field shows something else, so typing is never
|
|
709
|
+
// interrupted (for numbers, "1." and "1.0" already mean 1).
|
|
710
|
+
const same = numeric
|
|
711
|
+
? `(${elVar}.value === "" ? __v == null : Number(${elVar}.value) === __v)`
|
|
712
|
+
: `(${elVar}.value === __s)`
|
|
713
|
+
lines.push(`effect(() => { const __v = ${read}; const __s = __v == null ? "" : String(__v); if (!${same}) ${elVar}.value = __s; });`)
|
|
714
|
+
lines.push(`${elVar}.addEventListener(${JSON.stringify(event)}, () => { ${lhs} = ${fromInput}; });`)
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
// a?.b.c is not assignable either.
|
|
718
|
+
function hasOptionalLink(node) {
|
|
719
|
+
for (let n = node; n && n.type === 'MemberExpression'; n = n.object) {
|
|
720
|
+
if (n.optional) return true
|
|
721
|
+
}
|
|
722
|
+
return false
|
|
723
|
+
}
|
package/src/compileComponent.js
CHANGED
|
@@ -9,7 +9,7 @@ import {
|
|
|
9
9
|
generateStatement,
|
|
10
10
|
declaredNames,
|
|
11
11
|
} from './codegen/generateStatement.js'
|
|
12
|
-
import { reactive, effect } from './runtime/reactive.js'
|
|
12
|
+
import { reactive, effect, untracked } from './runtime/reactive.js'
|
|
13
13
|
import { useApi } from './runtime/useApi.js'
|
|
14
14
|
|
|
15
15
|
/**
|
|
@@ -76,9 +76,11 @@ export function compileComponent(
|
|
|
76
76
|
'effect',
|
|
77
77
|
'instance',
|
|
78
78
|
'components',
|
|
79
|
+
'reactive',
|
|
80
|
+
'untracked',
|
|
79
81
|
`${code}\nreturn ${rootVar};`,
|
|
80
82
|
)
|
|
81
|
-
const node = renderFn(document, effect, instance, components)
|
|
83
|
+
const node = renderFn(document, effect, instance, components, reactive, untracked)
|
|
82
84
|
return { node, instance }
|
|
83
85
|
},
|
|
84
86
|
}
|