@tylix/compiler 0.1.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 (49) hide show
  1. package/package.json +12 -0
  2. package/src/ast/nodes.js +143 -0
  3. package/src/codegen/generateExpression.array.test.js +13 -0
  4. package/src/codegen/generateExpression.callexpr.test.js +19 -0
  5. package/src/codegen/generateExpression.js +92 -0
  6. package/src/codegen/generateExpression.test.js +59 -0
  7. package/src/codegen/generateMethod.asyncawait.test.js +37 -0
  8. package/src/codegen/generateMethod.ifstatement.test.js +20 -0
  9. package/src/codegen/generateMethod.js +13 -0
  10. package/src/codegen/generateMethod.test.js +79 -0
  11. package/src/codegen/generatePage.js +79 -0
  12. package/src/codegen/generatePage.onmount.test.js +33 -0
  13. package/src/codegen/generatePage.test.js +138 -0
  14. package/src/codegen/generateStatement.js +64 -0
  15. package/src/codegen/generateStatement.test.js +31 -0
  16. package/src/codegen/generateTemplate.ifeach.test.js +138 -0
  17. package/src/codegen/generateTemplate.js +264 -0
  18. package/src/codegen/generateTemplate.test.js +149 -0
  19. package/src/codegen/generateTemplateExpression.js +55 -0
  20. package/src/codegen/generateTemplateExpression.test.js +34 -0
  21. package/src/compileComponent.js +54 -0
  22. package/src/compileComponent.test.js +121 -0
  23. package/src/index.js +15 -0
  24. package/src/lexer/Lexer.js +336 -0
  25. package/src/lexer/Lexer.test.js +151 -0
  26. package/src/lexer/tokenTypes.js +114 -0
  27. package/src/parser/Parser.array.test.js +37 -0
  28. package/src/parser/Parser.asyncawait.test.js +33 -0
  29. package/src/parser/Parser.ifstatement.test.js +20 -0
  30. package/src/parser/Parser.js +677 -0
  31. package/src/parser/Parser.onmount.test.js +18 -0
  32. package/src/parser/Parser.test.js +227 -0
  33. package/src/parser/parseComponent.js +29 -0
  34. package/src/parser/parseComponent.test.js +53 -0
  35. package/src/parser/parseComponentFile.js +55 -0
  36. package/src/parser/parseExpressionString.js +13 -0
  37. package/src/parser/parsePageFile.js +94 -0
  38. package/src/parser/parsePageFile.test.js +101 -0
  39. package/src/parser/parseTemplate.ifeach.test.js +33 -0
  40. package/src/parser/parseTemplate.js +319 -0
  41. package/src/parser/parseTemplate.pre.test.js +39 -0
  42. package/src/parser/parseTemplate.test.js +96 -0
  43. package/src/renderPageDocument.js +250 -0
  44. package/src/renderPageDocument.test.js +125 -0
  45. package/src/runtime/loadingIndicator.js +35 -0
  46. package/src/runtime/reactive.js +59 -0
  47. package/src/runtime/reactive.test.js +106 -0
  48. package/src/runtime/useApi.js +45 -0
  49. package/src/runtime/useChannel.js +38 -0
@@ -0,0 +1,138 @@
1
+ import { test } from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import { generatePage } from './generatePage.js'
4
+ import { reactive, effect } from '../runtime/reactive.js'
5
+ import { Parser } from '../parser/Parser.js'
6
+ import { Lexer } from '../lexer/Lexer.js'
7
+
8
+ function compileAndLoad(source, className = 'Page') {
9
+ const tokens = new Lexer(source).tokenize()
10
+ const page = new Parser(tokens).parse()
11
+ const classSource = generatePage(page, className)
12
+ // reactive must be in scope for the generated class body to run
13
+ return new Function('reactive', `return ${classSource}`)(reactive)
14
+ }
15
+
16
+ test('generates working state initializers for array, object, and null values, not just numbers/strings', () => {
17
+ const source = `
18
+ state
19
+ items: []
20
+ config: { enabled: true }
21
+ selectedId: null
22
+ `
23
+ const Page = compileAndLoad(source, 'TestPage')
24
+ const instance = new Page()
25
+
26
+ assert.deepEqual(instance.items, [])
27
+ assert.deepEqual(instance.config, { enabled: true })
28
+ assert.equal(instance.selectedId, null)
29
+ })
30
+
31
+ test('generates a class with reactive state accessible via this.<name>', () => {
32
+ const Page = compileAndLoad(`state { count: 0 }`)
33
+ const instance = new Page()
34
+ assert.equal(instance.count, 0)
35
+ instance.count = 5
36
+ assert.equal(instance.count, 5)
37
+ })
38
+
39
+ test('state writes trigger reactive effects (proves no manual re-render wiring needed)', () => {
40
+ const Page = compileAndLoad(`state { count: 0 }`)
41
+ const instance = new Page()
42
+ let seen = null
43
+
44
+ effect(() => {
45
+ seen = instance.count
46
+ })
47
+
48
+ assert.equal(seen, 0)
49
+ instance.count = 42
50
+ assert.equal(seen, 42)
51
+ })
52
+
53
+ test('generates working action methods that mutate state', () => {
54
+ const source = `
55
+ state { count: 0 }
56
+ action {
57
+ increment() {
58
+ this.count = this.count + 1;
59
+ }
60
+ }`
61
+ const Page = compileAndLoad(source)
62
+ const instance = new Page()
63
+
64
+ instance.increment()
65
+ assert.equal(instance.count, 1)
66
+ instance.increment()
67
+ assert.equal(instance.count, 2)
68
+ })
69
+
70
+ test('generates working computed getters derived from state', () => {
71
+ const source = `
72
+ state { count: 3 }
73
+ computed {
74
+ doubled() {
75
+ return this.count * 2;
76
+ }
77
+ }`
78
+ const Page = compileAndLoad(source)
79
+ const instance = new Page()
80
+
81
+ assert.equal(instance.doubled, 6)
82
+ instance.count = 10
83
+ assert.equal(instance.doubled, 20)
84
+ })
85
+
86
+ test('computed getters are reactive when read inside an effect', () => {
87
+ const source = `
88
+ state { count: 3 }
89
+ computed {
90
+ doubled() {
91
+ return this.count * 2;
92
+ }
93
+ }`
94
+ const Page = compileAndLoad(source)
95
+ const instance = new Page()
96
+ let seenDoubled = null
97
+
98
+ effect(() => {
99
+ seenDoubled = instance.doubled
100
+ })
101
+
102
+ assert.equal(seenDoubled, 6)
103
+ instance.count = 5
104
+ assert.equal(seenDoubled, 10)
105
+ })
106
+
107
+ test('generates a full realistic counter page end to end', () => {
108
+ const source = `
109
+ state { count: 0 }
110
+ computed {
111
+ doubled() {
112
+ return this.count * 2;
113
+ }
114
+ }
115
+ action {
116
+ increment() {
117
+ this.count = this.count + 1;
118
+ }
119
+ reset() {
120
+ this.count = 0;
121
+ }
122
+ }`
123
+ const Page = compileAndLoad(source, 'Counter')
124
+ const instance = new Page()
125
+
126
+ assert.equal(instance.count, 0)
127
+ assert.equal(instance.doubled, 0)
128
+
129
+ instance.increment()
130
+ instance.increment()
131
+ instance.increment()
132
+
133
+ assert.equal(instance.count, 3)
134
+ assert.equal(instance.doubled, 6)
135
+
136
+ instance.reset()
137
+ assert.equal(instance.count, 0)
138
+ })
@@ -0,0 +1,64 @@
1
+ import { generateExpression } from './generateExpression.js'
2
+
3
+ /**
4
+ * Compiles a single statement AST node into a JS source line.
5
+ */
6
+ export function generateStatement(node) {
7
+ switch (node.type) {
8
+ case 'ReturnStatement':
9
+ return node.argument
10
+ ? `return ${generateExpression(node.argument)};`
11
+ : 'return;'
12
+
13
+ case 'ExpressionStatement':
14
+ return `${generateExpression(node.expression)};`
15
+
16
+ case 'VariableDeclaration':
17
+ return `${node.kind} ${node.name} = ${generateExpression(node.init)};`
18
+
19
+ case 'IfStatement': {
20
+ const cond = generateExpression(node.condition)
21
+ const body = node.consequent
22
+ .map((s) => ` ${generateStatement(s)}`)
23
+ .join('\n')
24
+ let out = `if (${cond}) {\n${body}\n }`
25
+ if (node.alternate) {
26
+ const elseBody = node.alternate
27
+ .map((s) => ` ${generateStatement(s)}`)
28
+ .join('\n')
29
+ out += ` else {\n${elseBody}\n }`
30
+ }
31
+ return out
32
+ }
33
+
34
+ case 'ForInStatement': {
35
+ const body = node.body
36
+ .map((s) => ` ${generateStatement(s)}`)
37
+ .join('\n')
38
+ return `for (const ${node.varName} of ${generateExpression(node.iterable)}) {\n${body}\n }`
39
+ }
40
+
41
+ case 'ForRangeStatement': {
42
+ const body = node.body
43
+ .map((s) => ` ${generateStatement(s)}`)
44
+ .join('\n')
45
+ return `for (let ${node.varName} = ${generateExpression(node.start)}; ${node.varName} < ${generateExpression(node.end)}; ${node.varName}++) {\n${body}\n }`
46
+ }
47
+
48
+ case 'RepeatStatement': {
49
+ const body = node.body
50
+ .map((s) => ` ${generateStatement(s)}`)
51
+ .join('\n')
52
+ return `for (let __i = 0; __i < ${generateExpression(node.count)}; __i++) {\n${body}\n }`
53
+ }
54
+
55
+ case 'BreakStatement':
56
+ return 'break;'
57
+
58
+ case 'ContinueStatement':
59
+ return 'continue;'
60
+
61
+ default:
62
+ throw new Error(`generateStatement: unknown node type "${node.type}"`)
63
+ }
64
+ }
@@ -0,0 +1,31 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { generateStatement } from "./generateStatement.js";
4
+ import {
5
+ ReturnStatement,
6
+ ExpressionStatement,
7
+ AssignmentExpr,
8
+ BinaryExpr,
9
+ MemberExpr,
10
+ Identifier,
11
+ Literal,
12
+ } from "../ast/nodes.js";
13
+
14
+ test("generates a return statement", () => {
15
+ const node = ReturnStatement(BinaryExpr("*", MemberExpr(Identifier("this"), "count"), Literal(2)));
16
+ assert.equal(generateStatement(node), "return (this.count * 2);");
17
+ });
18
+
19
+ test("generates an expression statement wrapping an assignment", () => {
20
+ const node = ExpressionStatement(
21
+ AssignmentExpr(
22
+ MemberExpr(Identifier("this"), "count"),
23
+ BinaryExpr("+", MemberExpr(Identifier("this"), "count"), Literal(1))
24
+ )
25
+ );
26
+ assert.equal(generateStatement(node), "this.count = (this.count + 1);");
27
+ });
28
+
29
+ test("throws on an unknown statement type", () => {
30
+ assert.throws(() => generateStatement({ type: "Bogus" }), /unknown node type "Bogus"/);
31
+ });
@@ -0,0 +1,138 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { JSDOM } from "jsdom";
4
+ import { generateTemplate } from "./generateTemplate.js";
5
+ import { parseTemplate } from "../parser/parseTemplate.js";
6
+ import { reactive, effect } from "../runtime/reactive.js";
7
+
8
+ function renderToDom(templateSource, instance) {
9
+ const nodes = parseTemplate(templateSource);
10
+ const { code, rootVar } = generateTemplate(nodes);
11
+ const dom = new JSDOM();
12
+ const { document } = dom.window;
13
+ const fn = new Function("document", "effect", "instance", "components", `${code}\nreturn ${rootVar};`);
14
+ const rootNode = fn(document, effect, instance, {});
15
+ return { rootNode, document };
16
+ }
17
+
18
+ test("renders the if branch when condition is true, hides it when false", () => {
19
+ const instance = reactive({ visible: true });
20
+ const { rootNode } = renderToDom(`<div>{{#if visible}}<p>Shown</p>{{/if}}</div>`, instance);
21
+
22
+ assert.equal(rootNode.querySelector("p")?.textContent, "Shown");
23
+ instance.visible = false;
24
+ assert.equal(rootNode.querySelector("p"), null);
25
+ instance.visible = true;
26
+ assert.equal(rootNode.querySelector("p")?.textContent, "Shown");
27
+ });
28
+
29
+ test("renders a list with {{#each}}, using the loop variable bare (not instance.<var>)", () => {
30
+ const instance = reactive({ posts: [{ title: "First" }, { title: "Second" }] });
31
+ const { rootNode } = renderToDom(
32
+ `<ul>{{#each post in posts}}<li>{{ post.title }}</li>{{/each}}</ul>`,
33
+ instance
34
+ );
35
+
36
+ const items = rootNode.querySelectorAll("li");
37
+ assert.equal(items.length, 2);
38
+ assert.equal(items[0].textContent, "First");
39
+ assert.equal(items[1].textContent, "Second");
40
+ });
41
+
42
+ test("each list rebuilds correctly when the underlying array changes", () => {
43
+ const instance = reactive({ posts: [{ title: "A" }] });
44
+ const { rootNode } = renderToDom(
45
+ `<ul>{{#each post in posts}}<li>{{ post.title }}</li>{{/each}}</ul>`,
46
+ instance
47
+ );
48
+
49
+ assert.equal(rootNode.querySelectorAll("li").length, 1);
50
+ instance.posts = [{ title: "X" }, { title: "Y" }, { title: "Z" }];
51
+ const items = rootNode.querySelectorAll("li");
52
+ assert.equal(items.length, 3);
53
+ assert.equal(items[1].textContent, "Y");
54
+ });
55
+
56
+ test("nested if inside each correctly filters items reactively", () => {
57
+ const instance = reactive({
58
+ posts: [
59
+ { title: "Visible", published: true },
60
+ { title: "Hidden", published: false },
61
+ ],
62
+ });
63
+ const { rootNode } = renderToDom(
64
+ `<ul>{{#each post in posts}}{{#if post.published}}<li>{{ post.title }}</li>{{/if}}{{/each}}</ul>`,
65
+ instance
66
+ );
67
+
68
+ const items = rootNode.querySelectorAll("li");
69
+ assert.equal(items.length, 1);
70
+ assert.equal(items[0].textContent, "Visible");
71
+ });
72
+
73
+ test("event binding with a CallExpression passes explicit arguments, not the DOM event", () => {
74
+ const instance = reactive({
75
+ posts: [{ id: 1, title: "A" }, { id: 2, title: "B" }],
76
+ });
77
+ const removed = [];
78
+ instance.remove = function (id) {
79
+ removed.push(id);
80
+ this.posts = this.posts.filter((p) => p.id !== id);
81
+ };
82
+
83
+ const { rootNode, document } = renderToDom(
84
+ `<ul>{{#each post in posts}}<li>{{ post.title }}<button onclick="{{ remove(post.id) }}">x</button></li>{{/each}}</ul>`,
85
+ instance
86
+ );
87
+
88
+ const firstButton = rootNode.querySelectorAll("button")[0];
89
+ firstButton.dispatchEvent(new document.defaultView.Event("click"));
90
+
91
+ assert.deepEqual(removed, [1]);
92
+ assert.equal(rootNode.querySelectorAll("li").length, 1);
93
+ assert.equal(rootNode.querySelector("li").textContent.includes("B"), true);
94
+ });
95
+
96
+ test("event is available as a bare scoped identifier for oninput handlers with arguments", () => {
97
+ const instance = reactive({ name: "" });
98
+ instance.setField = function (field, value) {
99
+ this[field] = value;
100
+ };
101
+
102
+ const nodes = parseTemplate(`<input oninput="{{ setField('name', event.target.value) }}" />`);
103
+ const { code, rootVar } = generateTemplate(nodes);
104
+
105
+ const dom = new JSDOM();
106
+ const { document } = dom.window;
107
+ const fn = new Function("document", "effect", "instance", "components", `${code}\nreturn ${rootVar};`);
108
+ const inputEl = fn(document, effect, instance, {});
109
+
110
+ document.body.appendChild(inputEl);
111
+ inputEl.value = "Ada";
112
+ inputEl.dispatchEvent(new document.defaultView.Event("input"));
113
+
114
+ assert.equal(instance.name, "Ada");
115
+ });
116
+
117
+ test("event can be passed as an explicit argument and calls preventDefault on the real DOM event", () => {
118
+ let prevented = false;
119
+ const instance = reactive({});
120
+ instance.create = function (event) {
121
+ event.preventDefault();
122
+ prevented = true;
123
+ };
124
+
125
+ const nodes = parseTemplate(`<form onsubmit="{{ create(event) }}"></form>`);
126
+ const { code, rootVar } = generateTemplate(nodes);
127
+
128
+ const dom = new JSDOM();
129
+ const { document } = dom.window;
130
+ const fn = new Function("document", "effect", "instance", "components", `${code}
131
+ return ${rootVar};`);
132
+ const formEl = fn(document, effect, instance, {});
133
+
134
+ document.body.appendChild(formEl);
135
+ formEl.dispatchEvent(new document.defaultView.Event("submit", { cancelable: true }));
136
+
137
+ assert.equal(prevented, true);
138
+ });
@@ -0,0 +1,264 @@
1
+ import { generateTemplateExpression } from './generateTemplateExpression.js'
2
+
3
+ const EVENT_ATTR_PREFIX = /^on(click|input|change|submit)$/i
4
+ const COMPONENT_TAG_PATTERN = /^[A-Z]/
5
+
6
+ let nodeCounter = 0
7
+ function nextVar(prefix) {
8
+ return `${prefix}${nodeCounter++}`
9
+ }
10
+
11
+ /**
12
+ * Compiles a template AST into the BODY of a render(instance,
13
+ * document, components) function as a JS source string. No virtual
14
+ * DOM: state changes update exactly the text/attribute/if-branch/
15
+ * each-list that depends on them. `scope` tracks local names (each
16
+ * loop variables) so they're referenced bare instead of prefixed with
17
+ * "instance.".
18
+ */
19
+ export function generateTemplate(nodes) {
20
+ nodeCounter = 0
21
+ const lines = []
22
+ const rootVars = nodes.map((node) => compileNode(node, lines, new Set()))
23
+
24
+ if (rootVars.length === 1) {
25
+ return { code: lines.join('\n'), rootVar: rootVars[0] }
26
+ }
27
+
28
+ const fragmentVar = nextVar('fragment')
29
+ lines.push(`const ${fragmentVar} = document.createDocumentFragment();`)
30
+ rootVars.forEach((v) => lines.push(`${fragmentVar}.appendChild(${v});`))
31
+ return { code: lines.join('\n'), rootVar: fragmentVar }
32
+ }
33
+
34
+ function compileNode(node, lines, scope) {
35
+ if (node.type === 'Text') {
36
+ const varName = nextVar('text')
37
+ lines.push(
38
+ `const ${varName} = document.createTextNode(${JSON.stringify(node.value)});`,
39
+ )
40
+ return varName
41
+ }
42
+
43
+ if (node.type === 'Interpolation') {
44
+ const varName = nextVar('text')
45
+ const expr = generateTemplateExpression(node.expression, scope)
46
+ lines.push(`const ${varName} = document.createTextNode("");`)
47
+ lines.push(`effect(() => { ${varName}.nodeValue = ${expr}; });`)
48
+ return varName
49
+ }
50
+
51
+ if (node.type === 'If') {
52
+ return compileIf(node, lines, scope)
53
+ }
54
+
55
+ if (node.type === 'Each') {
56
+ return compileEach(node, lines, scope)
57
+ }
58
+
59
+ if (node.type === 'Element') {
60
+ return compileElement(node, lines, scope)
61
+ }
62
+
63
+ throw new Error(`generateTemplate: unknown node type "${node.type}"`)
64
+ }
65
+
66
+ // Renders node.children into a local fragment and returns the lines
67
+ // needed to build it plus the fragment's own variable name, without
68
+ // touching the caller's `lines` array directly (used inside effect
69
+ // callbacks below, which need their own nested block of statements).
70
+ function compileChildrenIntoFragment(children, scope, fragVar) {
71
+ const childLines = []
72
+ const childVars = children.map((child) =>
73
+ compileNode(child, childLines, scope),
74
+ )
75
+ childLines.push(...childVars.map((v) => `${fragVar}.appendChild(${v});`))
76
+ return childLines
77
+ }
78
+
79
+ // Conditional rendering with no VDOM: an anchor comment node marks
80
+ // the block's position; on first run (before the anchor is even
81
+ // attached to the real DOM by the caller) content builds into the
82
+ // same fragment that holds the anchor. On every later run (state
83
+ // changed), previous nodes are removed and new ones inserted right
84
+ // after the anchor in the live DOM.
85
+ function compileIf(node, lines, scope) {
86
+ const anchorVar = nextVar('ifAnchor')
87
+ const containerVar = nextVar('ifContainer')
88
+ const nodesVar = nextVar('ifNodes')
89
+ const initialVar = nextVar('ifInitial')
90
+ const condExpr = generateTemplateExpression(node.condition, scope)
91
+
92
+ lines.push(`const ${anchorVar} = document.createComment("if");`)
93
+ lines.push(`const ${containerVar} = document.createDocumentFragment();`)
94
+ lines.push(`${containerVar}.appendChild(${anchorVar});`)
95
+ lines.push(`let ${nodesVar} = [];`)
96
+ lines.push(`let ${initialVar} = true;`)
97
+ lines.push(`effect(() => {`)
98
+ lines.push(` for (const n of ${nodesVar}) n.remove();`)
99
+ lines.push(` ${nodesVar} = [];`)
100
+ lines.push(` if (${condExpr}) {`)
101
+ lines.push(` const frag = document.createDocumentFragment();`)
102
+ const childLines = compileChildrenIntoFragment(node.children, scope, 'frag')
103
+ childLines.forEach((l) => lines.push(` ${l}`))
104
+ lines.push(` ${nodesVar} = Array.from(frag.childNodes);`)
105
+ lines.push(` if (${initialVar}) { ${containerVar}.appendChild(frag); }`)
106
+ lines.push(
107
+ ` else { ${anchorVar}.parentNode.insertBefore(frag, ${anchorVar}.nextSibling); }`,
108
+ )
109
+ lines.push(` }`)
110
+ lines.push(` ${initialVar} = false;`)
111
+ lines.push(`});`)
112
+
113
+ return containerVar
114
+ }
115
+
116
+ // List rendering, same anchor/rebuild strategy as compileIf, but
117
+ // iterating a reactive array each time the effect runs. Not keyed
118
+ // diffing -- every dependency change rebuilds the whole list, which
119
+ // is the deliberate simplification for v1.
120
+ function compileEach(node, lines, scope) {
121
+ const anchorVar = nextVar('eachAnchor')
122
+ const containerVar = nextVar('eachContainer')
123
+ const nodesVar = nextVar('eachNodes')
124
+ const initialVar = nextVar('eachInitial')
125
+ const iterableExpr = generateTemplateExpression(node.iterable, scope)
126
+ const innerScope = new Set([...scope, node.itemName])
127
+
128
+ lines.push(`const ${anchorVar} = document.createComment("each");`)
129
+ lines.push(`const ${containerVar} = document.createDocumentFragment();`)
130
+ lines.push(`${containerVar}.appendChild(${anchorVar});`)
131
+ lines.push(`let ${nodesVar} = [];`)
132
+ lines.push(`let ${initialVar} = true;`)
133
+ lines.push(`effect(() => {`)
134
+ lines.push(` for (const n of ${nodesVar}) n.remove();`)
135
+ lines.push(` const frag = document.createDocumentFragment();`)
136
+ lines.push(` for (const ${node.itemName} of ${iterableExpr}) {`)
137
+ const childLines = compileChildrenIntoFragment(
138
+ node.children,
139
+ innerScope,
140
+ 'frag',
141
+ )
142
+ childLines.forEach((l) => lines.push(` ${l}`))
143
+ lines.push(` }`)
144
+ lines.push(` ${nodesVar} = Array.from(frag.childNodes);`)
145
+ lines.push(` if (${initialVar}) { ${containerVar}.appendChild(frag); }`)
146
+ lines.push(
147
+ ` else { ${anchorVar}.parentNode.insertBefore(frag, ${anchorVar}.nextSibling); }`,
148
+ )
149
+ lines.push(` ${initialVar} = false;`)
150
+ lines.push(`});`)
151
+
152
+ return containerVar
153
+ }
154
+
155
+ function isComponentTag(tag) {
156
+ return COMPONENT_TAG_PATTERN.test(tag)
157
+ }
158
+
159
+ function compileElement(node, lines, scope) {
160
+ if (isComponentTag(node.tag)) {
161
+ const varName = nextVar('component')
162
+ const tagLiteral = JSON.stringify(node.tag)
163
+
164
+ const propEntries = node.attributes.map((attr) => {
165
+ const expr = attr.dynamic
166
+ ? generateTemplateExpression(attr.value, scope)
167
+ : JSON.stringify(attr.value)
168
+ return `${JSON.stringify(attr.name)}: ${expr}`
169
+ })
170
+ const propsExpr = `{ ${propEntries.join(', ')} }`
171
+
172
+ lines.push(`let ${varName};`)
173
+ lines.push(`if (components[${tagLiteral}]) {`)
174
+ lines.push(
175
+ ` ${varName} = components[${tagLiteral}].mount(document, ${propsExpr}).node;`,
176
+ )
177
+ lines.push(`} else {`)
178
+ lines.push(
179
+ ` console.warn('Component "' + ${tagLiteral} + '" not found. Did you forget to restart tylix dev after creating it?');`,
180
+ )
181
+ lines.push(
182
+ ` ${varName} = document.createComment(${tagLiteral} + ' not found');`,
183
+ )
184
+ lines.push(`}`)
185
+ return varName
186
+ }
187
+
188
+ const varName = nextVar('el')
189
+ lines.push(
190
+ `const ${varName} = document.createElement(${JSON.stringify(node.tag)});`,
191
+ )
192
+
193
+ for (const attr of node.attributes) {
194
+ compileAttribute(varName, node.tag, attr, lines, scope)
195
+ }
196
+
197
+ for (const child of node.children) {
198
+ const childVar = compileNode(child, lines, scope)
199
+ lines.push(`${varName}.appendChild(${childVar});`)
200
+ }
201
+
202
+ return varName
203
+ }
204
+
205
+ // Attributes that reflect live user-editable DOM state -- setting
206
+ // them via setAttribute() only seeds the *initial* value; once the
207
+ // user interacts with the control, the live property diverges from
208
+ // the attribute and further setAttribute() calls stop being visible.
209
+ // These need the property set directly instead.
210
+ const LIVE_PROPERTY_ATTRS = new Set(['value', 'checked'])
211
+ const LIVE_PROPERTY_TAGS = new Set(['input', 'textarea', 'select'])
212
+
213
+ function compileAttribute(elVar, tag, attr, lines, scope) {
214
+ if (EVENT_ATTR_PREFIX.test(attr.name)) {
215
+ const eventName = attr.name.slice(2).toLowerCase()
216
+ if (!attr.dynamic) {
217
+ throw new Error(
218
+ `Event attribute "${attr.name}" must use {{ }} binding, got a static string.`,
219
+ )
220
+ }
221
+
222
+ // Templates reference the DOM event as either "$event" or the
223
+ // bare "event" -- both are treated as the same local so neither
224
+ // gets mistakenly prefixed with "instance.".
225
+ const scopeWithEvent = new Set([...scope, '$event', 'event'])
226
+
227
+ if (
228
+ attr.value.type === 'CallExpression' ||
229
+ attr.value.type === 'AssignmentExpression'
230
+ ) {
231
+ const expr = generateTemplateExpression(attr.value, scopeWithEvent)
232
+ lines.push(
233
+ `${elVar}.addEventListener(${JSON.stringify(eventName)}, ($event) => { const event = $event; ${expr}; });`,
234
+ )
235
+ return
236
+ }
237
+
238
+ const expr = generateTemplateExpression(attr.value, scopeWithEvent)
239
+ lines.push(
240
+ `${elVar}.addEventListener(${JSON.stringify(eventName)}, ($event) => { const event = $event; ${expr}($event); });`,
241
+ )
242
+ return
243
+ }
244
+ if (attr.dynamic) {
245
+ const expr = generateTemplateExpression(attr.value, scope)
246
+ const useProperty =
247
+ LIVE_PROPERTY_ATTRS.has(attr.name) && LIVE_PROPERTY_TAGS.has(tag)
248
+ if (useProperty) {
249
+ // Set the live DOM property, not the attribute, so re-renders
250
+ // after the user has typed (e.g. clearing the form on submit)
251
+ // actually update what's on screen.
252
+ lines.push(`effect(() => { ${elVar}.${attr.name} = ${expr}; });`)
253
+ } else {
254
+ lines.push(
255
+ `effect(() => { ${elVar}.setAttribute(${JSON.stringify(attr.name)}, ${expr}); });`,
256
+ )
257
+ }
258
+ return
259
+ }
260
+
261
+ lines.push(
262
+ `${elVar}.setAttribute(${JSON.stringify(attr.name)}, ${JSON.stringify(attr.value)});`,
263
+ )
264
+ }