clarusjs 0.2.0 → 0.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 +0 -10
- package/dist/compiler/emit-client.js +88 -17
- package/dist/compiler/emit-server.js +30 -24
- package/dist/compiler/html-expr.d.ts +29 -0
- package/dist/compiler/html-expr.js +85 -0
- package/dist/compiler/ir.d.ts +38 -0
- package/dist/compiler/ir.js +144 -32
- package/dist/compiler/parse.d.ts +34 -0
- package/dist/compiler/parse.js +199 -4
- package/dist/compiler/script.d.ts +17 -2
- package/dist/compiler/script.js +66 -6
- package/dist/runtime/attrs.d.ts +5 -0
- package/dist/runtime/attrs.js +56 -0
- package/dist/runtime/dom.d.ts +61 -5
- package/dist/runtime/dom.js +257 -17
- package/dist/runtime/html.d.ts +10 -0
- package/dist/runtime/html.js +30 -0
- package/dist/runtime/index.d.ts +4 -2
- package/dist/runtime/index.js +4 -2
- package/dist/runtime/loader.d.ts +7 -2
- package/dist/runtime/loader.js +125 -28
- package/dist/runtime/serialize.d.ts +8 -0
- package/dist/runtime/serialize.js +93 -0
- package/dist/runtime/server.d.ts +9 -4
- package/dist/runtime/server.js +13 -24
- package/dist/runtime/signals.d.ts +12 -0
- package/dist/runtime/signals.js +44 -1
- package/dist/vite/plugin.js +30 -3
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -53,16 +53,6 @@ export default defineConfig({ plugins: [clarusjs()] })
|
|
|
53
53
|
- `vite build` writes a static site to `dist/client/`: one HTML file per page, plus JavaScript only for components
|
|
54
54
|
with a `<script>` (the counter above). The `<h1>` ships no JavaScript at all.
|
|
55
55
|
|
|
56
|
-
## Exports
|
|
57
|
-
|
|
58
|
-
| Import | What |
|
|
59
|
-
|---|---|
|
|
60
|
-
| `clarusjs/vite` | the Vite plugin |
|
|
61
|
-
| `clarusjs/compiler` | `compile()`, for tools |
|
|
62
|
-
| `clarusjs/runtime` | browser runtime used by compiled components (signals, attach) |
|
|
63
|
-
| `clarusjs/runtime/server` | server helpers used by compiled components |
|
|
64
|
-
| `clarusjs/server` | `createHandler()`, the `fetch(Request)` handler |
|
|
65
|
-
|
|
66
56
|
## Links
|
|
67
57
|
|
|
68
58
|
- Repository and design: [github.com/forinda/clarusjs](https://github.com/forinda/clarusjs)
|
|
@@ -1,34 +1,105 @@
|
|
|
1
|
+
import { attrValueExpr, componentCall, htmlExpr, tagArg, walk, whichExpr } from './html-expr.js';
|
|
1
2
|
import { rewriteClient, rewriteClientExpr, wrapExpr } from './script.js';
|
|
2
|
-
import { indentScript, inputsLine } from './shared.js';
|
|
3
|
+
import { indentScript, inputsLine, renderName } from './shared.js';
|
|
3
4
|
export function emitClient(ir) {
|
|
4
5
|
if (!ir.stateful)
|
|
5
6
|
return 'export {}\n';
|
|
6
7
|
const kinds = new Set(ir.signals.values());
|
|
7
|
-
const
|
|
8
|
+
const all = walk(ir.nodes);
|
|
9
|
+
const hasHoles = all.some((n) => n.kind === 'hole' && n.reactive);
|
|
10
|
+
const hasBlocks = all.some((n) => n.kind === 'if' && n.block >= 0);
|
|
11
|
+
const hasFors = all.some((n) => n.kind === 'for' && n.block >= 0);
|
|
12
|
+
const hasRegions = all.some((n) => n.kind === 'component' && n.region >= 0);
|
|
13
|
+
const rendersHtml = hasBlocks || hasFors || hasRegions;
|
|
8
14
|
const used = [
|
|
9
15
|
kinds.has('state') && 'state',
|
|
10
16
|
kinds.has('derived') && 'derived',
|
|
11
|
-
|
|
12
|
-
|
|
17
|
+
kinds.has('shared') && 'shared',
|
|
18
|
+
hasHoles && 'holes as __cl_holes',
|
|
19
|
+
hasHoles && 'text as __cl_text',
|
|
13
20
|
ir.events.length > 0 && 'on as __cl_on',
|
|
21
|
+
all.some((n) => n.kind === 'attr' && n.reactive) && 'attr as __cl_attr',
|
|
22
|
+
hasBlocks && 'block as __cl_block',
|
|
23
|
+
hasFors && 'forBlock as __cl_for',
|
|
24
|
+
hasRegions && 'region as __cl_region',
|
|
25
|
+
// Branch and row HTML is rendered in the browser with the same helpers as on the server.
|
|
26
|
+
rendersHtml && 'escape as __cl_escape',
|
|
27
|
+
rendersHtml && all.some((n) => n.kind === 'attr') && 'attrHtml as __cl_attrHtml',
|
|
28
|
+
rendersHtml && hasBlocks && 'blockHtml as __cl_blockHtml',
|
|
29
|
+
rendersHtml && hasFors && 'forHtml as __cl_forHtml',
|
|
30
|
+
hasRegions && 'regionHtml as __cl_regionHtml',
|
|
14
31
|
].filter(Boolean);
|
|
15
32
|
let out = used.length ? `import { ${used.join(', ')} } from 'clarusjs/runtime'\n` : '';
|
|
16
|
-
|
|
33
|
+
// Child components render in the browser too (in branches, rows and regions): import their server render
|
|
34
|
+
// functions through the plugin's ?render query.
|
|
35
|
+
const usedComponents = new Set(all.flatMap((n) => (n.kind === 'component' ? [n.name] : [])));
|
|
36
|
+
for (const imp of ir.imports) {
|
|
37
|
+
if (usedComponents.has(imp.name))
|
|
38
|
+
out += `import { render as ${renderName(imp.name)} } from '${imp.from}?render'\n`;
|
|
39
|
+
}
|
|
40
|
+
for (const line of ir.scriptImports)
|
|
41
|
+
out += `${line}\n`;
|
|
42
|
+
out += `\nexport function attach(__cl_root, __cl_props = {}, __cl_state) {\n`;
|
|
17
43
|
out += inputsLine(ir);
|
|
18
44
|
if (ir.script)
|
|
19
|
-
out += indentScript(rewriteClient(ir.script, ir.signals));
|
|
20
|
-
const
|
|
21
|
-
if (
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
45
|
+
out += indentScript(rewriteClient(ir.script, ir.signals, { stateFromServer: true }));
|
|
46
|
+
const lines = wiring(ir, ir.nodes, undefined, '__cl_root', ir.signals, 0);
|
|
47
|
+
if (lines.length)
|
|
48
|
+
out += '\n' + lines.map((l) => ` ${l}\n`).join('');
|
|
49
|
+
return out + '}\n';
|
|
50
|
+
}
|
|
51
|
+
/** Rewrites expressions for the browser: reads of `signals` become `.get()`. */
|
|
52
|
+
function rewriter(signals) {
|
|
53
|
+
return {
|
|
54
|
+
expr: (e) => rewriteClientExpr(e, signals),
|
|
55
|
+
without: (names) => rewriter(new Map([...signals].filter(([name]) => !names.includes(name)))),
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Code that wires one scope: the top level, an @if branch, a @for row or @empty content. Holes, attributes and
|
|
60
|
+
* events directly in `nodes` are wired here; nested blocks and lists get their own calls, whose branches and rows
|
|
61
|
+
* wire themselves. `ctx` names the island (top level) or the row range the scope's markers are looked up in.
|
|
62
|
+
*/
|
|
63
|
+
function wiring(ir, nodes, scope, ctx, signals, depth) {
|
|
64
|
+
const rw = rewriter(signals);
|
|
65
|
+
const lines = [];
|
|
66
|
+
const holes = nodes.filter((n) => n.kind === 'hole' && n.reactive);
|
|
67
|
+
if (holes.length)
|
|
68
|
+
lines.push(`const __cl_h = __cl_holes(${ctx})`);
|
|
69
|
+
for (const h of [...holes].sort((a, b) => a.index - b.index))
|
|
70
|
+
lines.push(`__cl_text(__cl_h[${h.index}], () => ${wrapExpr(rw.expr(h.expr))})`);
|
|
71
|
+
for (const a of nodes) {
|
|
72
|
+
if (a.kind === 'attr' && a.reactive)
|
|
73
|
+
lines.push(`__cl_attr(${ctx}, ${a.index}, ${JSON.stringify(a.name)}, () => ${attrValueExpr(a.value, rw.expr)}${tagArg(a)})`);
|
|
25
74
|
}
|
|
26
|
-
for (const e of ir.events) {
|
|
27
|
-
const body = rewriteClient(e.handler,
|
|
75
|
+
for (const e of ir.events.filter((ev) => ev.scope === scope)) {
|
|
76
|
+
const body = rewriteClient(e.handler, signals).trim();
|
|
28
77
|
const end = body.includes('//') ? '\n ' : ' '; // a trailing line comment must not swallow the closing `})`
|
|
29
|
-
|
|
78
|
+
lines.push(`__cl_on(${ctx}, ${e.index}, ${JSON.stringify(e.type)}, ($event) => { ${body}${end}})`);
|
|
30
79
|
}
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
80
|
+
const fn = (args, inner) => inner.length ? `(${args}) => {\n${inner.map((l) => ` ${l}`).join('\n')}\n }` : `(${args}) => {}`;
|
|
81
|
+
for (const n of nodes) {
|
|
82
|
+
if (n.kind === 'component' && n.region >= 0) {
|
|
83
|
+
const content = [...n.children, ...n.fills.flatMap((f) => f.nodes)];
|
|
84
|
+
lines.push(`__cl_region(${ctx}, ${n.region}, () => ${componentCall(n, rw)}, ${fn('', wiring(ir, content, `c${n.region}`, ctx, signals, depth))})`);
|
|
85
|
+
}
|
|
86
|
+
if (n.kind === 'if' && n.block >= 0) {
|
|
87
|
+
const branches = n.branches.map((b, i) => ` { html: () => ${htmlExpr(b.nodes, rw)}, wire: ${fn('', wiring(ir, b.nodes, `${n.block}.${i}`, ctx, signals, depth))} },`);
|
|
88
|
+
lines.push(`__cl_block(${ctx}, ${n.block}, () => ${whichExpr(n, rw)}, [\n${branches.join('\n')}\n ])`);
|
|
89
|
+
}
|
|
90
|
+
if (n.kind === 'for' && n.block >= 0) {
|
|
91
|
+
// In row HTML `item` and `$index` are plain values; while wiring a row they are that row's signals.
|
|
92
|
+
const rowCtx = `__cl_c${depth + 1}`;
|
|
93
|
+
const loop = [n.item, '$index'];
|
|
94
|
+
const rowSignals = new Map([...signals, ...loop.map((name) => [name, 'state'])]);
|
|
95
|
+
const plain = rw.without(loop);
|
|
96
|
+
const key = n.track === null ? '$index' : wrapExpr(plain.expr(n.track));
|
|
97
|
+
const row = `{\n html: (${n.item}, $index) => ${htmlExpr(n.nodes, plain)},\n wire: ${fn(`${rowCtx}, ${n.item}, $index`, wiring(ir, n.nodes, `f${n.block}`, rowCtx, rowSignals, depth + 1))},\n }`;
|
|
98
|
+
const empty = n.empty
|
|
99
|
+
? `{\n html: () => ${htmlExpr(n.empty, rw)},\n wire: ${fn(rowCtx, wiring(ir, n.empty, `f${n.block}e`, rowCtx, signals, depth + 1))},\n }`
|
|
100
|
+
: 'null';
|
|
101
|
+
lines.push(`__cl_for(${ctx}, ${n.block}, () => ${wrapExpr(rw.expr(n.list))}, (${n.item}, $index) => ${key}, ${row}, ${empty})`);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return lines;
|
|
34
105
|
}
|
|
@@ -1,41 +1,47 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { htmlExpr, walk } from './html-expr.js';
|
|
2
|
+
import { rewriteServer } from './script.js';
|
|
2
3
|
import { indentScript, inputsLine, renderName } from './shared.js';
|
|
3
4
|
export function emitServer(ir, clientUrl) {
|
|
4
|
-
const
|
|
5
|
+
const all = walk(ir.nodes);
|
|
6
|
+
const runtime = [
|
|
7
|
+
'escape as __cl_escape',
|
|
8
|
+
ir.stateful && 'island as __cl_island',
|
|
9
|
+
all.some((n) => n.kind === 'attr') && 'attr as __cl_attrHtml',
|
|
10
|
+
all.some((n) => n.kind === 'if' && n.block >= 0) && 'blockHtml as __cl_blockHtml',
|
|
11
|
+
all.some((n) => n.kind === 'for' && n.block >= 0) && 'forHtml as __cl_forHtml',
|
|
12
|
+
all.some((n) => n.kind === 'component' && n.region >= 0) && 'regionHtml as __cl_regionHtml',
|
|
13
|
+
].filter(Boolean).join(', ');
|
|
5
14
|
let out = `import { ${runtime} } from 'clarusjs/runtime/server'\n`;
|
|
6
15
|
for (const imp of ir.imports)
|
|
7
16
|
out += `import { render as ${renderName(imp.name)} } from '${imp.from}'\n`;
|
|
17
|
+
for (const line of ir.scriptImports)
|
|
18
|
+
out += `${line}\n`;
|
|
8
19
|
const html = htmlExpr(ir.nodes);
|
|
9
20
|
const props = `{ ${ir.inputs.map((i) => i.name).join(', ')} }`.replace('{ }', '{}');
|
|
10
|
-
out += `\nexport function render(__cl_props = {},
|
|
21
|
+
out += `\nexport function render(__cl_props = {}, __cl_slots, __cl_opts) {\n`;
|
|
11
22
|
if (ir.stateful)
|
|
12
|
-
out += ` if (
|
|
13
|
-
else
|
|
14
|
-
out +=
|
|
23
|
+
out += ` if (__cl_slots !== undefined) throw new Error(${JSON.stringify(`[clarusjs] <${ir.name}> does not accept children yet`)})\n`;
|
|
24
|
+
else {
|
|
25
|
+
out += unknownSlotCheck(ir);
|
|
26
|
+
out += ` if (__cl_opts?.attach) throw new Error(${JSON.stringify(`[clarusjs] <${ir.name}> has no <script>, so attach="`)} + __cl_opts.attach + '" does nothing')\n`;
|
|
27
|
+
}
|
|
15
28
|
out += inputsLine(ir);
|
|
16
29
|
if (ir.script)
|
|
17
30
|
out += indentScript(rewriteServer(ir.script));
|
|
18
31
|
out += ir.stateful
|
|
19
|
-
? ` return __cl_island(${JSON.stringify(ir.name)}, ${JSON.stringify(clientUrl)}, ${props}, ${html})\n`
|
|
32
|
+
? ` return __cl_island(${JSON.stringify(ir.name)}, ${JSON.stringify(clientUrl)}, ${props}, ${html}, ${stateArg(ir)}, __cl_opts?.attach)\n`
|
|
20
33
|
: ` return ${html}\n`;
|
|
21
34
|
return out + '}\n';
|
|
22
35
|
}
|
|
23
|
-
/**
|
|
24
|
-
function
|
|
25
|
-
const
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
return '(__cl_slot ?? "")';
|
|
30
|
-
if (n.kind === 'component') {
|
|
31
|
-
const props = n.props.map((p) => `${p.name}: ${wrapExpr(p.expr)}`).join(', ');
|
|
32
|
-
return n.children.length ? `${renderName(n.name)}({ ${props} }, ${htmlExpr(n.children)})` : `${renderName(n.name)}({ ${props} })`;
|
|
33
|
-
}
|
|
34
|
-
const value = `__cl_escape(${wrapExpr(n.expr)})`;
|
|
35
|
-
return n.reactive ? `"<!--[${n.index}-->" + ${value} + "<!--]-->"` : value;
|
|
36
|
-
});
|
|
37
|
-
return parts.length ? parts.join(' + ') : '""';
|
|
36
|
+
/** Content for a slot this component doesn't have is an error (at render, so a build fails naming it). */
|
|
37
|
+
function unknownSlotCheck(ir) {
|
|
38
|
+
const known = [...new Set(walk(ir.nodes).flatMap((n) => (n.kind === 'slot' ? [n.name] : [])))];
|
|
39
|
+
const noDefault = JSON.stringify(`[clarusjs] <${ir.name}> has no <slot /> for the content passed to it`);
|
|
40
|
+
const noNamed = JSON.stringify(`[clarusjs] <${ir.name}> has no slot "`);
|
|
41
|
+
return ` for (const __cl_k in __cl_slots) if (!${JSON.stringify(known)}.includes(__cl_k)) throw new Error(__cl_k === "default" ? ${noDefault} : ${noNamed} + __cl_k + '"')\n`;
|
|
38
42
|
}
|
|
39
|
-
|
|
40
|
-
|
|
43
|
+
/** The component's state() values after its script ran: the island's starting point in the browser. */
|
|
44
|
+
function stateArg(ir) {
|
|
45
|
+
const names = [...ir.signals].filter(([, kind]) => kind === 'state').map(([name]) => name);
|
|
46
|
+
return names.length ? `{ ${names.join(', ')} }` : 'undefined';
|
|
41
47
|
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { IRNode } from './ir.ts';
|
|
2
|
+
/**
|
|
3
|
+
* How a template expression becomes code. On the server it is used as written; in the browser signal reads become
|
|
4
|
+
* `.get()`. Inside a @for row's HTML, the row's `item` and `$index` are plain parameters, hence `without()`.
|
|
5
|
+
*/
|
|
6
|
+
export type Rewriter = {
|
|
7
|
+
expr(e: string): string;
|
|
8
|
+
without(names: string[]): Rewriter;
|
|
9
|
+
};
|
|
10
|
+
export declare const asWritten: Rewriter;
|
|
11
|
+
export declare function htmlExpr(nodes: IRNode[], rw?: Rewriter): string;
|
|
12
|
+
/** `render_child({ props }, { slots })` for a component node. */
|
|
13
|
+
export declare function componentCall(n: Extract<IRNode, {
|
|
14
|
+
kind: 'component';
|
|
15
|
+
}>, rw: Rewriter): string;
|
|
16
|
+
/** Index of the branch an @if picks: `(a ? 0 : b ? 1 : 2)`, or -1 when nothing matches and there is no @else. */
|
|
17
|
+
export declare function whichExpr(n: Extract<IRNode, {
|
|
18
|
+
kind: 'if';
|
|
19
|
+
}>, rw: Rewriter): string;
|
|
20
|
+
/** JS expression for an attribute's value: the bound expression, or the parts joined (null/undefined join as ''). */
|
|
21
|
+
export declare function attrValueExpr(value: Extract<IRNode, {
|
|
22
|
+
kind: 'attr';
|
|
23
|
+
}>['value'], rewrite: (e: string) => string): string;
|
|
24
|
+
/** The element's tag, passed only for attributes whose meaning depends on it (SVG animation values). */
|
|
25
|
+
export declare function tagArg(n: Extract<IRNode, {
|
|
26
|
+
kind: 'attr';
|
|
27
|
+
}>): string;
|
|
28
|
+
/** Every node, including those inside @if branches, @for bodies and component children. */
|
|
29
|
+
export declare function walk(nodes: IRNode[]): IRNode[];
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { renderName } from './shared.js';
|
|
2
|
+
import { wrapExpr } from './script.js';
|
|
3
|
+
export const asWritten = { expr: (e) => e, without: () => asWritten };
|
|
4
|
+
export function htmlExpr(nodes, rw = asWritten) {
|
|
5
|
+
const parts = nodes.map((n) => {
|
|
6
|
+
if (n.kind === 'static')
|
|
7
|
+
return JSON.stringify(n.html);
|
|
8
|
+
if (n.kind === 'slot')
|
|
9
|
+
return `(__cl_slots?.[${JSON.stringify(n.name)}] ?? ${n.fallback.length ? `(${htmlExpr(n.fallback, rw)})` : '""'})`;
|
|
10
|
+
if (n.kind === 'attr')
|
|
11
|
+
return `__cl_attrHtml(${JSON.stringify(n.name)}, ${attrValueExpr(n.value, rw.expr)}${tagArg(n)})`;
|
|
12
|
+
if (n.kind === 'if') {
|
|
13
|
+
if (n.block === -1) {
|
|
14
|
+
// Outside islands: a plain choice, no markers.
|
|
15
|
+
const last = n.branches[n.branches.length - 1];
|
|
16
|
+
let expr = last.cond === null ? `(${htmlExpr(last.nodes, rw)})` : '""';
|
|
17
|
+
const conditional = last.cond === null ? n.branches.slice(0, -1) : n.branches;
|
|
18
|
+
for (const b of [...conditional].reverse())
|
|
19
|
+
expr = `(${wrapExpr(rw.expr(b.cond))} ? (${htmlExpr(b.nodes, rw)}) : ${expr})`;
|
|
20
|
+
return expr;
|
|
21
|
+
}
|
|
22
|
+
const branches = n.branches.map((b) => `() => ${htmlExpr(b.nodes, rw)}`).join(', ');
|
|
23
|
+
return `__cl_blockHtml(${n.block}, ${whichExpr(n, rw)}, [${branches}])`;
|
|
24
|
+
}
|
|
25
|
+
if (n.kind === 'for') {
|
|
26
|
+
const list = wrapExpr(rw.expr(n.list));
|
|
27
|
+
const row = `(${n.item}, $index) => ${htmlExpr(n.nodes, rw.without([n.item, '$index']))}`;
|
|
28
|
+
const empty = n.empty ? `() => ${htmlExpr(n.empty, rw)}` : 'null';
|
|
29
|
+
if (n.block >= 0)
|
|
30
|
+
return `__cl_forHtml(${n.block}, ${list}, ${row}, ${empty})`;
|
|
31
|
+
// Outside islands: a plain loop, no markers.
|
|
32
|
+
return `((__cl_l) => __cl_l.length ? __cl_l.map(${row}).join("") : ${n.empty ? `(${htmlExpr(n.empty, rw)})` : '""'})([...(${list} ?? [])])`;
|
|
33
|
+
}
|
|
34
|
+
if (n.kind === 'component') {
|
|
35
|
+
const call = componentCall(n, rw);
|
|
36
|
+
return n.region >= 0 ? `__cl_regionHtml(${n.region}, () => ${call})` : call;
|
|
37
|
+
}
|
|
38
|
+
const value = `__cl_escape(${wrapExpr(rw.expr(n.expr))})`;
|
|
39
|
+
return n.reactive ? `"<!--[${n.index}-->" + ${value} + "<!--]-->"` : value;
|
|
40
|
+
});
|
|
41
|
+
return parts.length ? parts.join(' + ') : '""';
|
|
42
|
+
}
|
|
43
|
+
/** `render_child({ props }, { slots })` for a component node. */
|
|
44
|
+
export function componentCall(n, rw) {
|
|
45
|
+
const props = n.props.map((p) => `${p.name}: ${wrapExpr(rw.expr(p.expr))}`).join(', ');
|
|
46
|
+
const slots = [
|
|
47
|
+
...(n.children.length ? [`"default": ${htmlExpr(n.children, rw)}`] : []),
|
|
48
|
+
...n.fills.map((f) => `${JSON.stringify(f.name)}: ${htmlExpr(f.nodes, rw)}`),
|
|
49
|
+
];
|
|
50
|
+
const slotsArg = slots.length ? `{ ${slots.join(', ')} }` : undefined;
|
|
51
|
+
if (n.attach)
|
|
52
|
+
return `${renderName(n.name)}({ ${props} }, ${slotsArg ?? 'undefined'}, { attach: ${JSON.stringify(n.attach)} })`;
|
|
53
|
+
return slotsArg ? `${renderName(n.name)}({ ${props} }, ${slotsArg})` : `${renderName(n.name)}({ ${props} })`;
|
|
54
|
+
}
|
|
55
|
+
/** Index of the branch an @if picks: `(a ? 0 : b ? 1 : 2)`, or -1 when nothing matches and there is no @else. */
|
|
56
|
+
export function whichExpr(n, rw) {
|
|
57
|
+
let expr = n.branches[n.branches.length - 1].cond === null ? String(n.branches.length - 1) : '-1';
|
|
58
|
+
for (let i = n.branches.length - 1; i >= 0; i--) {
|
|
59
|
+
const cond = n.branches[i].cond;
|
|
60
|
+
if (cond !== null)
|
|
61
|
+
expr = `${wrapExpr(rw.expr(cond))} ? ${i} : ${expr}`;
|
|
62
|
+
}
|
|
63
|
+
return `(${expr})`;
|
|
64
|
+
}
|
|
65
|
+
/** JS expression for an attribute's value: the bound expression, or the parts joined (null/undefined join as ''). */
|
|
66
|
+
export function attrValueExpr(value, rewrite) {
|
|
67
|
+
if ('expr' in value)
|
|
68
|
+
return `(${rewrite(value.expr)})`;
|
|
69
|
+
return `[${value.parts.map((p) => (typeof p === 'string' ? JSON.stringify(p) : `(${rewrite(p.expr)})`)).join(', ')}].join("")`;
|
|
70
|
+
}
|
|
71
|
+
/** The element's tag, passed only for attributes whose meaning depends on it (SVG animation values). */
|
|
72
|
+
export function tagArg(n) {
|
|
73
|
+
return ['to', 'from', 'values', 'by'].includes(n.name.toLowerCase()) ? `, ${JSON.stringify(n.tag)}` : '';
|
|
74
|
+
}
|
|
75
|
+
/** Every node, including those inside @if branches, @for bodies and component children. */
|
|
76
|
+
export function walk(nodes) {
|
|
77
|
+
return nodes.flatMap((n) => [
|
|
78
|
+
n,
|
|
79
|
+
...(n.kind === 'if' ? n.branches.flatMap((b) => walk(b.nodes))
|
|
80
|
+
: n.kind === 'for' ? [...walk(n.nodes), ...walk(n.empty ?? [])]
|
|
81
|
+
: n.kind === 'component' ? [...walk(n.children), ...n.fills.flatMap((f) => walk(f.nodes))]
|
|
82
|
+
: n.kind === 'slot' ? walk(n.fallback)
|
|
83
|
+
: []),
|
|
84
|
+
]);
|
|
85
|
+
}
|
package/dist/compiler/ir.d.ts
CHANGED
|
@@ -16,13 +16,50 @@ export type IRNode = {
|
|
|
16
16
|
expr: string;
|
|
17
17
|
}[];
|
|
18
18
|
children: IRNode[];
|
|
19
|
+
fills: {
|
|
20
|
+
name: string;
|
|
21
|
+
nodes: IRNode[];
|
|
22
|
+
}[];
|
|
23
|
+
region: number;
|
|
24
|
+
attach?: string;
|
|
19
25
|
} | {
|
|
20
26
|
kind: 'slot';
|
|
27
|
+
name: string;
|
|
28
|
+
fallback: IRNode[];
|
|
29
|
+
} | {
|
|
30
|
+
kind: 'attr';
|
|
31
|
+
name: string;
|
|
32
|
+
value: {
|
|
33
|
+
expr: string;
|
|
34
|
+
} | {
|
|
35
|
+
parts: (string | {
|
|
36
|
+
expr: string;
|
|
37
|
+
})[];
|
|
38
|
+
};
|
|
39
|
+
reactive: boolean;
|
|
40
|
+
index: number;
|
|
41
|
+
tag: string;
|
|
42
|
+
} | {
|
|
43
|
+
kind: 'if';
|
|
44
|
+
branches: {
|
|
45
|
+
cond: string | null;
|
|
46
|
+
nodes: IRNode[];
|
|
47
|
+
}[];
|
|
48
|
+
block: number;
|
|
49
|
+
} | {
|
|
50
|
+
kind: 'for';
|
|
51
|
+
item: string;
|
|
52
|
+
list: string;
|
|
53
|
+
track: string | null;
|
|
54
|
+
nodes: IRNode[];
|
|
55
|
+
empty: IRNode[] | null;
|
|
56
|
+
block: number;
|
|
21
57
|
};
|
|
22
58
|
export type IREvent = {
|
|
23
59
|
index: number;
|
|
24
60
|
type: string;
|
|
25
61
|
handler: string;
|
|
62
|
+
scope?: string;
|
|
26
63
|
};
|
|
27
64
|
export type ComponentIR = {
|
|
28
65
|
file: string;
|
|
@@ -30,6 +67,7 @@ export type ComponentIR = {
|
|
|
30
67
|
inputs: InputDecl[];
|
|
31
68
|
imports: ImportDecl[];
|
|
32
69
|
script?: string;
|
|
70
|
+
scriptImports: string[];
|
|
33
71
|
signals: Signals;
|
|
34
72
|
stateful: boolean;
|
|
35
73
|
nodes: IRNode[];
|
package/dist/compiler/ir.js
CHANGED
|
@@ -1,21 +1,28 @@
|
|
|
1
1
|
// Syntax tree → IR: static HTML chunks, holes (reactive or not), child components, events. Build-time checks live here.
|
|
2
2
|
import { ClarusError } from './errors.js';
|
|
3
|
-
import { analyzeScript, checkExpr, checkHandler, referencesNames, scriptNames } from './script.js';
|
|
3
|
+
import { analyzeScript, checkExpr, checkHandler, referencesNames, scriptNames, splitImports } from './script.js';
|
|
4
|
+
const ATTACH_MODES = ['load', 'idle', 'visible', 'interaction'];
|
|
4
5
|
const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
|
|
5
6
|
export function lower(parsed, file, source) {
|
|
6
7
|
const fail = (text, at) => { throw new ClarusError(text, file, source, at); };
|
|
7
8
|
const stateful = !!parsed.script;
|
|
8
|
-
const
|
|
9
|
+
const split = parsed.script ? splitImports(parsed.script.code, file, source, parsed.script.start) : { imports: [], body: '' };
|
|
10
|
+
const signals = parsed.script ? analyzeScript(split.body, file, source, parsed.script.start) : new Map();
|
|
9
11
|
// A hole is reactive if it reads anything the script declares: a signal directly, or a function/value that may read one.
|
|
10
12
|
// text()'s effect tracks the real dependencies, so over-marking only costs a pair of comment markers.
|
|
11
13
|
const scriptScope = parsed.script ? new Set([...signals.keys(), ...scriptNames(parsed.script.code)]) : new Set();
|
|
12
14
|
const components = new Set(parsed.imports.map((i) => i.name));
|
|
13
15
|
const nodes = [];
|
|
14
16
|
let out = nodes; // where lowering writes; switched while lowering a component's children
|
|
15
|
-
let slotCount = 0;
|
|
16
17
|
const events = [];
|
|
17
18
|
let holeCount = 0;
|
|
18
19
|
let eventElementCount = 0;
|
|
20
|
+
let attrElementCount = 0;
|
|
21
|
+
let blockCount = 0;
|
|
22
|
+
let forCount = 0;
|
|
23
|
+
let regionCount = 0;
|
|
24
|
+
let loopNames = new Set(); // @for item and $index names in scope: they make holes inside rows reactive
|
|
25
|
+
let scopeKey; // the @if branch being lowered, for events
|
|
19
26
|
const emitStatic = (html) => {
|
|
20
27
|
const last = out[out.length - 1];
|
|
21
28
|
if (last?.kind === 'static')
|
|
@@ -31,66 +38,170 @@ export function lower(parsed, file, source) {
|
|
|
31
38
|
function visit(node, rawText) {
|
|
32
39
|
if (node.type === 'text')
|
|
33
40
|
return emitStatic(node.value);
|
|
41
|
+
if (node.type === 'fill')
|
|
42
|
+
return fail('@slot only works directly inside a component tag', node.start);
|
|
43
|
+
if (node.type === 'if') {
|
|
44
|
+
const block = stateful ? blockCount++ : -1;
|
|
45
|
+
const parent = out;
|
|
46
|
+
const parentScope = scopeKey;
|
|
47
|
+
const branches = node.branches.map((b, i) => {
|
|
48
|
+
if (b.cond !== null)
|
|
49
|
+
checkExpr(b.cond, file, source, b.condStart);
|
|
50
|
+
const branchNodes = [];
|
|
51
|
+
out = branchNodes;
|
|
52
|
+
if (stateful)
|
|
53
|
+
scopeKey = `${block}.${i}`;
|
|
54
|
+
b.children.forEach((child) => visit(child, rawText));
|
|
55
|
+
return { cond: b.cond, nodes: branchNodes };
|
|
56
|
+
});
|
|
57
|
+
out = parent;
|
|
58
|
+
scopeKey = parentScope;
|
|
59
|
+
out.push({ kind: 'if', branches, block });
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
if (node.type === 'for') {
|
|
63
|
+
checkExpr(node.list, file, source, node.headStart);
|
|
64
|
+
if (node.track !== null)
|
|
65
|
+
checkExpr(node.track, file, source, node.headStart);
|
|
66
|
+
const block = stateful ? forCount++ : -1;
|
|
67
|
+
const parent = out;
|
|
68
|
+
const parentScope = scopeKey;
|
|
69
|
+
const parentLoop = loopNames;
|
|
70
|
+
const lowerInto = (children, key, names) => {
|
|
71
|
+
const list = [];
|
|
72
|
+
out = list;
|
|
73
|
+
loopNames = names;
|
|
74
|
+
if (stateful)
|
|
75
|
+
scopeKey = key;
|
|
76
|
+
children.forEach((child) => visit(child, rawText));
|
|
77
|
+
return list;
|
|
78
|
+
};
|
|
79
|
+
const nodes = lowerInto(node.children, `f${block}`, new Set([...parentLoop, node.item, '$index']));
|
|
80
|
+
const empty = node.empty ? lowerInto(node.empty, `f${block}e`, parentLoop) : null;
|
|
81
|
+
out = parent;
|
|
82
|
+
scopeKey = parentScope;
|
|
83
|
+
loopNames = parentLoop;
|
|
84
|
+
out.push({ kind: 'for', item: node.item, list: node.list, track: node.track, nodes, empty, block });
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
if (node.type === 'raw')
|
|
88
|
+
return emitStatic(node.value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>'));
|
|
34
89
|
if (node.type === 'expr') {
|
|
35
90
|
checkExpr(node.expr, file, source, node.start);
|
|
36
|
-
const reactive = referencesNames(node.expr, scriptScope);
|
|
91
|
+
const reactive = stateful && (referencesNames(node.expr, scriptScope) || referencesNames(node.expr, loopNames));
|
|
37
92
|
if (reactive && rawText)
|
|
38
93
|
fail(`reactive {{ }} inside <${rawText}> is not supported yet (it cannot hold update markers)`, node.start);
|
|
39
94
|
out.push({ kind: 'hole', expr: node.expr, reactive, index: reactive ? holeCount++ : -1 });
|
|
40
95
|
return;
|
|
41
96
|
}
|
|
42
97
|
if (components.has(node.tag)) {
|
|
43
|
-
if (stateful)
|
|
44
|
-
fail('components inside a stateful component are not supported yet', node.start);
|
|
45
98
|
const props = [];
|
|
99
|
+
let attach;
|
|
46
100
|
for (const a of node.attrs) {
|
|
47
101
|
if (a.kind === 'prop') {
|
|
48
102
|
checkExpr(a.expr, file, source, a.start);
|
|
49
103
|
props.push({ name: a.name, expr: a.expr });
|
|
50
104
|
}
|
|
105
|
+
else if (a.kind === 'static' && a.name === 'attach') {
|
|
106
|
+
// When the island's code loads in the browser (see runtime/loader.ts).
|
|
107
|
+
if (typeof a.value !== 'string' || !ATTACH_MODES.includes(a.value))
|
|
108
|
+
fail(`attach must be one of ${ATTACH_MODES.join(', ')}`, a.start);
|
|
109
|
+
attach = a.value;
|
|
110
|
+
}
|
|
51
111
|
else
|
|
52
|
-
fail(`component <${node.tag}> only takes [prop] bindings`, a.start);
|
|
112
|
+
fail(`component <${node.tag}> only takes [prop] bindings and attach="…"`, a.start);
|
|
53
113
|
}
|
|
54
|
-
//
|
|
55
|
-
const
|
|
56
|
-
const
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
114
|
+
// Content is rendered here, in this component's scope, and handed to the child for its slots.
|
|
115
|
+
const hasContent = node.children.some((c) => c.type !== 'text' || c.value.trim());
|
|
116
|
+
const readsState = props.some((p) => referencesNames(p.expr, scriptScope) || referencesNames(p.expr, loopNames));
|
|
117
|
+
const region = stateful && (hasContent || readsState) ? regionCount++ : -1;
|
|
118
|
+
const parentScope = scopeKey;
|
|
119
|
+
if (region >= 0)
|
|
120
|
+
scopeKey = `c${region}`;
|
|
121
|
+
const lowerList = (list) => {
|
|
122
|
+
const nodes_ = [];
|
|
123
|
+
const parent = out;
|
|
124
|
+
out = nodes_;
|
|
125
|
+
list.forEach((child) => visit(child, rawText));
|
|
126
|
+
out = parent;
|
|
127
|
+
return nodes_;
|
|
128
|
+
};
|
|
129
|
+
const fills = [];
|
|
130
|
+
for (const child of node.children) {
|
|
131
|
+
if (child.type !== 'fill')
|
|
132
|
+
continue;
|
|
133
|
+
if (fills.some((f) => f.name === child.name))
|
|
134
|
+
fail(`slot "${child.name}" is filled twice`, child.start);
|
|
135
|
+
fills.push({ name: child.name, nodes: lowerList(child.children) });
|
|
136
|
+
}
|
|
137
|
+
const rest = node.children.filter((c) => c.type !== 'fill');
|
|
138
|
+
// Whitespace around @slot blocks is not content for the default slot.
|
|
139
|
+
const children = rest.every((c) => c.type === 'text' && !c.value.trim()) ? [] : lowerList(rest);
|
|
140
|
+
scopeKey = parentScope;
|
|
141
|
+
out.push({ kind: 'component', name: node.tag, props, children, fills, region, ...(attach ? { attach } : {}) });
|
|
61
142
|
return;
|
|
62
143
|
}
|
|
63
144
|
if (node.tag === 'slot') {
|
|
64
145
|
if (stateful)
|
|
65
146
|
fail('<slot /> is only supported in components without <script>', node.start);
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
147
|
+
let name = 'default';
|
|
148
|
+
for (const a of node.attrs) {
|
|
149
|
+
if (a.kind === 'static' && a.name === 'name' && typeof a.value === 'string' && a.value)
|
|
150
|
+
name = a.value;
|
|
151
|
+
else
|
|
152
|
+
fail('<slot> only takes name="…"', a.start);
|
|
153
|
+
}
|
|
154
|
+
// Fallback content belongs to this component: its holes read this component's inputs.
|
|
155
|
+
const fallback = [];
|
|
156
|
+
const parent = out;
|
|
157
|
+
out = fallback;
|
|
158
|
+
node.children.forEach((child) => visit(child, rawText));
|
|
159
|
+
out = parent;
|
|
160
|
+
out.push({ kind: 'slot', name, fallback });
|
|
73
161
|
return;
|
|
74
162
|
}
|
|
75
|
-
|
|
163
|
+
emitStatic(`<${node.tag}`);
|
|
76
164
|
const elementEvents = node.attrs.filter((a) => a.kind === 'event');
|
|
165
|
+
const dynamic = [];
|
|
77
166
|
for (const a of node.attrs) {
|
|
78
167
|
if (a.kind === 'static')
|
|
79
|
-
|
|
80
|
-
else if (a.kind === '
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
fail('event bindings need a <script> with state; this component is static', a.start);
|
|
84
|
-
else
|
|
168
|
+
emitStatic(a.value === true ? ` ${a.name}` : ` ${a.name}="${a.value}"`);
|
|
169
|
+
else if (a.kind === 'event') {
|
|
170
|
+
if (!stateful)
|
|
171
|
+
fail('event bindings need a <script> with state; this component is static', a.start);
|
|
85
172
|
checkHandler(a.expr, file, source, a.start);
|
|
173
|
+
}
|
|
174
|
+
else {
|
|
175
|
+
if (/^on/i.test(a.name))
|
|
176
|
+
fail(`use (${a.name.slice(2).toLowerCase()}) for events, not an ${a.name} attribute`, a.start);
|
|
177
|
+
// srcdoc is a whole HTML document: binding data into it is HTML injection, so it stays static.
|
|
178
|
+
if (a.name.toLowerCase() === 'srcdoc')
|
|
179
|
+
fail('srcdoc cannot be bound; write it as a static attribute', a.start);
|
|
180
|
+
const exprs = a.kind === 'prop' ? [{ expr: a.expr, start: a.start }] : a.parts.filter((p) => typeof p !== 'string');
|
|
181
|
+
for (const e of exprs)
|
|
182
|
+
checkExpr(e.expr, file, source, e.start);
|
|
183
|
+
const reactive = stateful && exprs.some((e) => referencesNames(e.expr, scriptScope) || referencesNames(e.expr, loopNames));
|
|
184
|
+
const value = a.kind === 'prop' ? { expr: a.expr } : { parts: a.parts.map((p) => (typeof p === 'string' ? p : { expr: p.expr })) };
|
|
185
|
+
const node_ = { kind: 'attr', name: a.name, value, reactive, index: -1, tag: node.tag };
|
|
186
|
+
if (reactive)
|
|
187
|
+
dynamic.push(node_);
|
|
188
|
+
out.push(node_);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
// One marker per element for its reactive attributes, one for its events.
|
|
192
|
+
if (dynamic.length) {
|
|
193
|
+
const index = attrElementCount++;
|
|
194
|
+
for (const d of dynamic)
|
|
195
|
+
d.index = index;
|
|
196
|
+
emitStatic(` data-cl-a="${index}"`);
|
|
86
197
|
}
|
|
87
198
|
if (elementEvents.length) {
|
|
88
199
|
const index = eventElementCount++;
|
|
89
|
-
|
|
200
|
+
emitStatic(` data-cl-e="${index}"`);
|
|
90
201
|
for (const a of elementEvents)
|
|
91
|
-
events.push({ index, type: a.name, handler: a.kind === 'event' ? a.expr : '' });
|
|
202
|
+
events.push({ index, type: a.name, handler: a.kind === 'event' ? a.expr : '', scope: scopeKey });
|
|
92
203
|
}
|
|
93
|
-
emitStatic(
|
|
204
|
+
emitStatic('>');
|
|
94
205
|
node.children.forEach((child) => visit(child, RAW_TEXT.has(node.tag) ? node.tag : rawText));
|
|
95
206
|
if (!VOID.has(node.tag))
|
|
96
207
|
emitStatic(`</${node.tag}>`);
|
|
@@ -101,7 +212,8 @@ export function lower(parsed, file, source) {
|
|
|
101
212
|
name: file.split('/').pop().replace(/\.clarus$/, ''),
|
|
102
213
|
inputs: parsed.inputs,
|
|
103
214
|
imports: parsed.imports,
|
|
104
|
-
script: parsed.script
|
|
215
|
+
script: parsed.script ? split.body : undefined,
|
|
216
|
+
scriptImports: split.imports,
|
|
105
217
|
signals,
|
|
106
218
|
stateful,
|
|
107
219
|
nodes,
|