@hidemikimura/vanji 0.0.0-stage → 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.
- package/LICENSE +21 -0
- package/README.md +245 -2
- package/compiler/ast.js +48 -0
- package/compiler/index.d.ts +21 -0
- package/compiler/index.js +155 -0
- package/compiler/list.js +163 -0
- package/compiler/parse-html.js +278 -0
- package/compiler/template.js +391 -0
- package/compiler/vite.d.ts +31 -0
- package/compiler/vite.js +35 -0
- package/llms.txt +143 -0
- package/package.json +61 -4
- package/skills/vanji/SKILL.md +231 -0
- package/skills/vanji/references/patterns.md +241 -0
- package/src/dev.js +3 -0
- package/src/dom.js +308 -0
- package/src/index.d.ts +85 -0
- package/src/index.js +17 -0
- package/src/internal.js +4 -0
- package/src/list.js +272 -0
- package/src/signals.js +287 -0
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
// Strict, small HTML parser for html`` templates (build time only).
|
|
2
|
+
// Holes are encoded in the source string as \u0001<index>\u0002.
|
|
3
|
+
|
|
4
|
+
export const HO = '\u0001';
|
|
5
|
+
export const HC = '\u0002';
|
|
6
|
+
const HOLE_RE = /\u0001(\d+)\u0002/g;
|
|
7
|
+
|
|
8
|
+
const VOID = new Set('area base br col embed hr img input link meta source track wbr'.split(' '));
|
|
9
|
+
const RAW = new Set('script style textarea title'.split(' '));
|
|
10
|
+
const KEEP_WS = new Set('pre textarea'.split(' '));
|
|
11
|
+
const CLOSES_P = new Set(
|
|
12
|
+
('address article aside blockquote details div dl fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 ' +
|
|
13
|
+
'header hgroup hr main menu nav ol p pre section table ul').split(' ')
|
|
14
|
+
);
|
|
15
|
+
const P_SCOPE = new Set('button td th caption table object svg foreignobject template'.split(' '));
|
|
16
|
+
const TABLE_KIDS = new Set('caption colgroup thead tbody tfoot script style template'.split(' '));
|
|
17
|
+
const SVG_ONLY = new Set(
|
|
18
|
+
('circle clipPath defs desc ellipse filter foreignObject g image line linearGradient marker mask metadata ' +
|
|
19
|
+
'path pattern polygon polyline radialGradient rect stop symbol text textPath tspan use animate ' +
|
|
20
|
+
'animateMotion animateTransform set').split(' ')
|
|
21
|
+
);
|
|
22
|
+
|
|
23
|
+
export const isSvgOnly = tag => SVG_ONLY.has(tag) || /^fe[A-Z]/.test(tag);
|
|
24
|
+
|
|
25
|
+
export class TemplateError extends Error {
|
|
26
|
+
constructor(message, hint) {
|
|
27
|
+
super(message);
|
|
28
|
+
this.hint = hint;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const fail = (message, hint) => {
|
|
33
|
+
throw new TemplateError(message, hint);
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
// "a\u00010\u0002b" -> ['a', {hole: 0}, 'b']
|
|
37
|
+
const splitHoles = s => {
|
|
38
|
+
const parts = [];
|
|
39
|
+
let last = 0, m;
|
|
40
|
+
HOLE_RE.lastIndex = 0;
|
|
41
|
+
while ((m = HOLE_RE.exec(s))) {
|
|
42
|
+
if (m.index > last) parts.push(s.slice(last, m.index));
|
|
43
|
+
parts.push({ hole: +m[1] });
|
|
44
|
+
last = m.index + m[0].length;
|
|
45
|
+
}
|
|
46
|
+
if (last < s.length) parts.push(s.slice(last));
|
|
47
|
+
return parts;
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
const show = s => s.replace(HOLE_RE, '${…}');
|
|
51
|
+
|
|
52
|
+
export function parseHTML(src) {
|
|
53
|
+
const rootNode = { type: 'root', tag: '#root', children: [] };
|
|
54
|
+
const stack = [rootNode];
|
|
55
|
+
let i = 0;
|
|
56
|
+
const top = () => stack[stack.length - 1];
|
|
57
|
+
const near = () => `near: ${JSON.stringify(show(src.slice(Math.max(0, i - 20), i + 40)).trim())}`;
|
|
58
|
+
const error = (msg, hint) => fail(`${msg} (${near()})`, hint);
|
|
59
|
+
|
|
60
|
+
const pushText = raw => {
|
|
61
|
+
for (const part of splitHoles(raw)) {
|
|
62
|
+
const kids = top().children;
|
|
63
|
+
if (typeof part === 'string') {
|
|
64
|
+
const last = kids[kids.length - 1];
|
|
65
|
+
if (last && last.type === 'text') last.value += part;
|
|
66
|
+
else kids.push({ type: 'text', value: part });
|
|
67
|
+
} else kids.push({ type: 'hole', index: part.hole });
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
const checkNesting = lower => {
|
|
72
|
+
const ptag = top().tag.toLowerCase();
|
|
73
|
+
if (lower === 'html' || lower === 'head' || lower === 'body')
|
|
74
|
+
error(`<${lower}> cannot be used inside a template`, 'Render into document.body with mount() instead.');
|
|
75
|
+
if (ptag === 'table' && !TABLE_KIDS.has(lower))
|
|
76
|
+
error(
|
|
77
|
+
`<${lower}> cannot be a direct child of <table>`,
|
|
78
|
+
'Wrap rows in <tbody> (browsers insert it implicitly, which breaks compiled templates).'
|
|
79
|
+
);
|
|
80
|
+
if ((ptag === 'tbody' || ptag === 'thead' || ptag === 'tfoot') && !/^(tr|template|script)$/.test(lower))
|
|
81
|
+
error(`<${lower}> cannot be a direct child of <${ptag}>`, 'Only <tr> is allowed here.');
|
|
82
|
+
if (ptag === 'tr' && !/^(td|th|template|script)$/.test(lower))
|
|
83
|
+
error(`<${lower}> cannot be a direct child of <tr>`, 'Only <td> / <th> are allowed here.');
|
|
84
|
+
for (let s = stack.length - 1; s > 0; s--) {
|
|
85
|
+
const t = stack[s].tag.toLowerCase();
|
|
86
|
+
if (t === lower && (lower === 'a' || lower === 'button' || lower === 'form'))
|
|
87
|
+
error(
|
|
88
|
+
`<${lower}> cannot be nested inside another <${lower}>`,
|
|
89
|
+
'Browsers re-parent this markup; restructure the template.'
|
|
90
|
+
);
|
|
91
|
+
if (t === 'p' && CLOSES_P.has(lower))
|
|
92
|
+
error(
|
|
93
|
+
`<${lower}> cannot be inside <p>`,
|
|
94
|
+
'Browsers close the <p> automatically here. Use <div> instead of <p> as the container.'
|
|
95
|
+
);
|
|
96
|
+
if (P_SCOPE.has(t)) break;
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
while (i < src.length) {
|
|
101
|
+
if (src.startsWith('<!--', i)) {
|
|
102
|
+
const end = src.indexOf('-->', i + 4);
|
|
103
|
+
if (end < 0) error('Unclosed HTML comment');
|
|
104
|
+
i = end + 3;
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
if (src[i] === '<' && src[i + 1] === '/') {
|
|
108
|
+
const m = /<\/([^\s>]*)\s*>/y;
|
|
109
|
+
m.lastIndex = i;
|
|
110
|
+
const r = m.exec(src);
|
|
111
|
+
if (!r) error('Malformed closing tag');
|
|
112
|
+
const name = r[1];
|
|
113
|
+
const open = top();
|
|
114
|
+
if (open.type === 'root') error(`Unexpected closing tag </${show(name)}>`);
|
|
115
|
+
if (open.tag.toLowerCase() !== name.toLowerCase())
|
|
116
|
+
error(
|
|
117
|
+
`</${show(name)}> does not match <${open.tag}>`,
|
|
118
|
+
`Close <${open.tag}> explicitly. Every non-void element needs a closing tag (or write <${open.tag} />).`
|
|
119
|
+
);
|
|
120
|
+
stack.pop();
|
|
121
|
+
i += r[0].length;
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
if (src[i] === '<' && src[i + 1] === HO)
|
|
125
|
+
error(
|
|
126
|
+
'Dynamic tag names are not supported',
|
|
127
|
+
'Choose between templates in JS instead: ${cond ? html`<a>…</a>` : html`<b>…</b>`}'
|
|
128
|
+
);
|
|
129
|
+
if (src[i] === '<' && src[i + 1] === '!') error('<!…> declarations are not supported in templates');
|
|
130
|
+
if (src[i] === '<' && /[a-zA-Z]/.test(src[i + 1] || '')) {
|
|
131
|
+
const nameRe = /<([a-zA-Z][^\s/>\u0001]*)/y;
|
|
132
|
+
nameRe.lastIndex = i;
|
|
133
|
+
const tag = nameRe.exec(src)[1];
|
|
134
|
+
const lower = tag.toLowerCase();
|
|
135
|
+
checkNesting(lower);
|
|
136
|
+
i += tag.length + 1;
|
|
137
|
+
const el = { type: 'el', tag, attrs: [], children: [] };
|
|
138
|
+
let selfClose = false;
|
|
139
|
+
for (;;) {
|
|
140
|
+
while (/\s/.test(src[i] || '')) i++;
|
|
141
|
+
if (i >= src.length) error(`<${tag}> tag is not terminated`);
|
|
142
|
+
if (src[i] === '>') {
|
|
143
|
+
i++;
|
|
144
|
+
break;
|
|
145
|
+
}
|
|
146
|
+
if (src[i] === '/') {
|
|
147
|
+
if (src[i + 1] === '>') {
|
|
148
|
+
selfClose = true;
|
|
149
|
+
i += 2;
|
|
150
|
+
break;
|
|
151
|
+
}
|
|
152
|
+
i++;
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
if (src[i] === HO)
|
|
156
|
+
error('A hole cannot be used as an attribute name or spread', 'Write each attribute explicitly: name=${value}');
|
|
157
|
+
const attrRe = /[^\s=>/\u0001]+/y;
|
|
158
|
+
attrRe.lastIndex = i;
|
|
159
|
+
const am = attrRe.exec(src);
|
|
160
|
+
if (!am) error('Malformed attribute');
|
|
161
|
+
const name = am[0];
|
|
162
|
+
i += name.length;
|
|
163
|
+
if (src[i] === HO) error('A hole cannot be part of an attribute name');
|
|
164
|
+
let j = i;
|
|
165
|
+
while (/\s/.test(src[j] || '')) j++;
|
|
166
|
+
let parts = null;
|
|
167
|
+
if (src[j] === '=') {
|
|
168
|
+
j++;
|
|
169
|
+
while (/\s/.test(src[j] || '')) j++;
|
|
170
|
+
let value;
|
|
171
|
+
const q = src[j];
|
|
172
|
+
if (q === '"' || q === "'") {
|
|
173
|
+
const end = src.indexOf(q, j + 1);
|
|
174
|
+
if (end < 0) error(`Unclosed quote in attribute "${name}"`);
|
|
175
|
+
value = src.slice(j + 1, end);
|
|
176
|
+
j = end + 1;
|
|
177
|
+
} else {
|
|
178
|
+
const vr = /[^\s>]+/y;
|
|
179
|
+
vr.lastIndex = j;
|
|
180
|
+
const vm = vr.exec(src);
|
|
181
|
+
if (!vm) error(`Attribute "${name}" has no value`);
|
|
182
|
+
value = vm[0];
|
|
183
|
+
if (value.endsWith('/') && src[j + value.length] === '>') value = value.slice(0, -1);
|
|
184
|
+
j += value.length;
|
|
185
|
+
}
|
|
186
|
+
parts = splitHoles(value);
|
|
187
|
+
i = j;
|
|
188
|
+
}
|
|
189
|
+
el.attrs.push({ name, parts });
|
|
190
|
+
}
|
|
191
|
+
top().children.push(el);
|
|
192
|
+
if (selfClose || VOID.has(lower)) continue;
|
|
193
|
+
if (RAW.has(lower)) {
|
|
194
|
+
const closeRe = new RegExp(`</${lower}\\s*>`, 'ig');
|
|
195
|
+
closeRe.lastIndex = i;
|
|
196
|
+
const cm = closeRe.exec(src);
|
|
197
|
+
if (!cm) error(`<${tag}> is not closed`);
|
|
198
|
+
const text = src.slice(i, cm.index);
|
|
199
|
+
if (text.includes(HO))
|
|
200
|
+
error(
|
|
201
|
+
`Holes are not supported inside <${tag}>`,
|
|
202
|
+
lower === 'textarea' ? 'Bind the property instead: <textarea .value=${text}></textarea>' : undefined
|
|
203
|
+
);
|
|
204
|
+
if (text) el.children.push({ type: 'text', value: text });
|
|
205
|
+
i = cm.index + cm[0].length;
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
stack.push(el);
|
|
209
|
+
continue;
|
|
210
|
+
}
|
|
211
|
+
// text up to the next thing that starts a tag
|
|
212
|
+
let end = i + 1;
|
|
213
|
+
while (end < src.length && !(src[end] === '<' && /[a-zA-Z/!\u0001]/.test(src[end + 1] || ''))) end++;
|
|
214
|
+
const text = src.slice(i, end);
|
|
215
|
+
const ptag = top().tag.toLowerCase();
|
|
216
|
+
if (/^(table|tbody|thead|tfoot|tr)$/.test(ptag) && text.replace(HOLE_RE, '').trim())
|
|
217
|
+
error(`Text cannot be a direct child of <${ptag}>`, 'Put the text inside a <td>.');
|
|
218
|
+
pushText(text);
|
|
219
|
+
i = end;
|
|
220
|
+
}
|
|
221
|
+
if (stack.length > 1) {
|
|
222
|
+
i = src.length;
|
|
223
|
+
error(`<${top().tag}> is not closed`, `Add </${top().tag}>. Every non-void element needs a closing tag.`);
|
|
224
|
+
}
|
|
225
|
+
normalize(rootNode, false);
|
|
226
|
+
return rootNode;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// Whitespace: a run containing a newline is removed next to a tag / template edge,
|
|
230
|
+
// and becomes a single space anywhere else. <pre> and <textarea> are left untouched.
|
|
231
|
+
function normalize(parent, keep) {
|
|
232
|
+
const kids = parent.children;
|
|
233
|
+
const raw = parent.type === 'el' && RAW.has(parent.tag.toLowerCase());
|
|
234
|
+
const out = [];
|
|
235
|
+
for (let k = 0; k < kids.length; k++) {
|
|
236
|
+
const n = kids[k];
|
|
237
|
+
if (n.type === 'text' && !keep && !raw) {
|
|
238
|
+
const prevHole = kids[k - 1] && kids[k - 1].type === 'hole';
|
|
239
|
+
const nextHole = kids[k + 1] && kids[k + 1].type === 'hole';
|
|
240
|
+
let v = n.value;
|
|
241
|
+
if (/^\s*$/.test(v)) {
|
|
242
|
+
if (v.includes('\n')) v = prevHole && nextHole ? ' ' : '';
|
|
243
|
+
} else {
|
|
244
|
+
v = v
|
|
245
|
+
.replace(/^\s*\n\s*/, prevHole ? ' ' : '')
|
|
246
|
+
.replace(/\s*\n\s*$/, nextHole ? ' ' : '')
|
|
247
|
+
.replace(/\s*\n\s*/g, ' ');
|
|
248
|
+
}
|
|
249
|
+
if (!v) continue;
|
|
250
|
+
n.value = v;
|
|
251
|
+
}
|
|
252
|
+
if (n.type === 'el') normalize(n, keep || KEEP_WS.has(n.tag.toLowerCase()));
|
|
253
|
+
out.push(n);
|
|
254
|
+
}
|
|
255
|
+
parent.children = out;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const escAttr = s => s.replace(/"/g, '"');
|
|
259
|
+
|
|
260
|
+
/** Serialize the static part. Holes between siblings become `<!>` markers. */
|
|
261
|
+
export function serialize(node) {
|
|
262
|
+
if (node.type === 'text') return node.value;
|
|
263
|
+
if (node.type === 'hole') return '<!>';
|
|
264
|
+
if (node.type === 'root') return node.children.map(serialize).join('');
|
|
265
|
+
let s = `<${node.tag}`;
|
|
266
|
+
for (const a of node.attrs) {
|
|
267
|
+
if (a.dynamic) continue;
|
|
268
|
+
s += ` ${a.name}`;
|
|
269
|
+
if (a.parts) s += `="${escAttr(a.parts.join(''))}"`;
|
|
270
|
+
}
|
|
271
|
+
s += '>';
|
|
272
|
+
const lower = node.tag.toLowerCase();
|
|
273
|
+
if (VOID.has(lower)) return s;
|
|
274
|
+
const kids = node.children;
|
|
275
|
+
if (KEEP_WS.has(lower) && kids[0] && kids[0].type === 'text' && kids[0].value[0] === '\n') s += '\n';
|
|
276
|
+
if (!(kids.length === 1 && kids[0].type === 'hole')) s += kids.map(serialize).join('');
|
|
277
|
+
return `${s}</${node.tag}>`;
|
|
278
|
+
}
|
|
@@ -0,0 +1,391 @@
|
|
|
1
|
+
// Turns one html`` template into "clone the static HTML + walk to the dynamic nodes + bind".
|
|
2
|
+
import { parseHTML, serialize, isSvgOnly, TemplateError, HO, HC } from './parse-html.js';
|
|
3
|
+
import { walk, isFn, hasCall, hasFnOrTemplate, arrowBody, IDENT } from './ast.js';
|
|
4
|
+
import { emitList } from './list.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* @param {{ code: string, id: string, use: (name: string) => string, isHtmlTag: Function, isEach: Function,
|
|
8
|
+
* isWhen: Function, templates: Map<string, object>, handled: Set<object>, fail: Function }} ctx
|
|
9
|
+
*/
|
|
10
|
+
export function createTemplateCompiler(ctx) {
|
|
11
|
+
const { code, use, isHtmlTag, isEach, isWhen, templates, handled, reads } = ctx;
|
|
12
|
+
const calls = n => hasCall(n, isHtmlTag, reads);
|
|
13
|
+
const generated = new Map();
|
|
14
|
+
|
|
15
|
+
const isComponentCall = n =>
|
|
16
|
+
n.type === 'CallExpression' && !n.optional && n.callee.type === 'Identifier' && /^[A-Z]/.test(n.callee.name);
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Source of `node` with nested html`` compiled, component calls wrapped (`Card(x)` -> `_$c(Card, x)`)
|
|
20
|
+
* and the item / index of a live each() row read through its getter (`r.n` -> `_$$it().n`).
|
|
21
|
+
*/
|
|
22
|
+
const source = node => {
|
|
23
|
+
const reps = [];
|
|
24
|
+
walk(node, n => {
|
|
25
|
+
if (isHtmlTag(n) || isComponentCall(n) || reads.has(n)) {
|
|
26
|
+
reps.push(n);
|
|
27
|
+
return false;
|
|
28
|
+
}
|
|
29
|
+
});
|
|
30
|
+
reps.sort((a, b) => a.start - b.start);
|
|
31
|
+
let out = '', pos = node.start;
|
|
32
|
+
for (const r of reps) {
|
|
33
|
+
out += code.slice(pos, r.start);
|
|
34
|
+
if (isHtmlTag(r)) out += genTemplate(r);
|
|
35
|
+
else if (reads.has(r)) out += reads.get(r);
|
|
36
|
+
else {
|
|
37
|
+
const args = r.arguments.map(a => (a.type === 'SpreadElement' ? `...${source(a.argument)}` : source(a)));
|
|
38
|
+
out += `${use('c')}(${[r.callee.name, ...args].join(', ')})`;
|
|
39
|
+
}
|
|
40
|
+
pos = r.end;
|
|
41
|
+
}
|
|
42
|
+
out += code.slice(pos, node.end);
|
|
43
|
+
return node.type === 'SequenceExpression' ? `(${out})` : out;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
function genTemplate(tpl) {
|
|
47
|
+
let out = generated.get(tpl);
|
|
48
|
+
if (out === undefined) generated.set(tpl, (out = genTemplateUncached(tpl)));
|
|
49
|
+
return out;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Parse and validate a template: { tree, roots, exprs, kind, err }. */
|
|
53
|
+
function parseTemplate(tpl) {
|
|
54
|
+
const at = { line: tpl.loc.start.line, column: tpl.loc.start.column };
|
|
55
|
+
const err = (message, hint, node) =>
|
|
56
|
+
ctx.fail(message, hint, node ? { line: node.loc.start.line, column: node.loc.start.column } : at);
|
|
57
|
+
const quasis = tpl.quasi.quasis;
|
|
58
|
+
const exprs = tpl.quasi.expressions;
|
|
59
|
+
let src = '';
|
|
60
|
+
quasis.forEach((q, i) => {
|
|
61
|
+
if (q.value.cooked == null) err('Invalid escape sequence in template');
|
|
62
|
+
src += q.value.cooked;
|
|
63
|
+
if (i < exprs.length) src += HO + i + HC;
|
|
64
|
+
});
|
|
65
|
+
let tree;
|
|
66
|
+
try {
|
|
67
|
+
tree = parseHTML(src);
|
|
68
|
+
} catch (e) {
|
|
69
|
+
if (e instanceof TemplateError) err(e.message, e.hint);
|
|
70
|
+
throw e;
|
|
71
|
+
}
|
|
72
|
+
exprs.forEach(expr =>
|
|
73
|
+
walk(expr, n => {
|
|
74
|
+
if (isFn(n)) return false;
|
|
75
|
+
if (n.type === 'AwaitExpression' || n.type === 'YieldExpression')
|
|
76
|
+
err(
|
|
77
|
+
`"${n.type === 'AwaitExpression' ? 'await' : 'yield'}" cannot be used directly inside a template hole`,
|
|
78
|
+
'Assign the result to a variable before the template.',
|
|
79
|
+
n
|
|
80
|
+
);
|
|
81
|
+
})
|
|
82
|
+
);
|
|
83
|
+
const roots = tree.children;
|
|
84
|
+
// holes at the root: the template returns an array (nodes and the holes' parts), see genTemplateUncached
|
|
85
|
+
const rootHoles = roots.some(n => n.type === 'hole');
|
|
86
|
+
let kind = roots.length === 1 && !rootHoles ? 0 : 1;
|
|
87
|
+
const rootEls = roots.filter(n => n.type === 'el');
|
|
88
|
+
if (rootEls.length && rootEls.every(n => isSvgOnly(n.tag))) kind |= 2;
|
|
89
|
+
else if (rootEls.some(n => isSvgOnly(n.tag)))
|
|
90
|
+
err('SVG and HTML elements cannot be mixed at the template root', 'Wrap SVG content in <svg>.');
|
|
91
|
+
|
|
92
|
+
const markDynamic = el => {
|
|
93
|
+
let dyn = false;
|
|
94
|
+
for (const a of el.attrs) {
|
|
95
|
+
const special = /^[@.?]/.test(a.name) || a.name === 'ref';
|
|
96
|
+
const hasHole = a.parts && a.parts.some(p => typeof p !== 'string');
|
|
97
|
+
if (special && !(a.parts && a.parts.length === 1 && hasHole))
|
|
98
|
+
err(`"${a.name}" must be bound to exactly one hole`, `Write ${a.name}=\${value} (no quotes mixing text and holes).`);
|
|
99
|
+
a.dynamic = !!hasHole;
|
|
100
|
+
dyn ||= a.dynamic;
|
|
101
|
+
}
|
|
102
|
+
if (el.tag.includes('-')) kind |= 4;
|
|
103
|
+
if (el.tag.toLowerCase() === 'template' && el.children.length) {
|
|
104
|
+
let holes = false;
|
|
105
|
+
walk({ type: 'x', c: el.children }, n => {
|
|
106
|
+
if (n.type === 'hole' || (n.type === 'el' && n.attrs.some(a => a.parts && a.parts.some(p => typeof p !== 'string'))))
|
|
107
|
+
holes = true;
|
|
108
|
+
});
|
|
109
|
+
if (holes) err('Holes are not supported inside a nested <template> element');
|
|
110
|
+
}
|
|
111
|
+
for (const c of el.children) {
|
|
112
|
+
if (c.type === 'hole') dyn = true;
|
|
113
|
+
else if (c.type === 'el') dyn = markDynamic(c) || dyn;
|
|
114
|
+
}
|
|
115
|
+
return (el.dyn = dyn);
|
|
116
|
+
};
|
|
117
|
+
for (const n of roots) if (n.type === 'el') markDynamic(n);
|
|
118
|
+
return { tree, roots, exprs, kind, err, rootHoles };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Where the dynamic parts are. `decls` reach them right after cloning (firstChild / nextSibling);
|
|
123
|
+
* `path` is an element-only path from the root ("$"), still valid after holes were filled when
|
|
124
|
+
* `safe` (no hole precedes it among its parent's children).
|
|
125
|
+
*/
|
|
126
|
+
function layout(t, root) {
|
|
127
|
+
const decls = [], binds = [];
|
|
128
|
+
let uid = 0;
|
|
129
|
+
// <select .value> / .selectedIndex only take effect once the options exist: bind them after the children
|
|
130
|
+
const late = (el, a) => el.tag.toLowerCase() === 'select' && (a.name === '.value' || a.name === '.selectedIndex');
|
|
131
|
+
const visitEl = (el, v, path, safe) => {
|
|
132
|
+
for (const a of el.attrs) if (a.dynamic && !late(el, a)) binds.push({ type: 'attr', el: v, a, path, safe });
|
|
133
|
+
visitKids(el, v, path, safe);
|
|
134
|
+
for (const a of el.attrs) if (a.dynamic && late(el, a)) binds.push({ type: 'attr', el: v, a, path, safe });
|
|
135
|
+
};
|
|
136
|
+
const visitKids = (parent, v, path, safe) => {
|
|
137
|
+
const kids = parent.children;
|
|
138
|
+
if (parent.type === 'el' && kids.length === 1 && kids[0].type === 'hole') {
|
|
139
|
+
binds.push({ type: 'text', parent: v, marker: null, index: kids[0].index, path, safe });
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
let prev = '', prevEl = null, holeBefore = false;
|
|
143
|
+
kids.forEach((c, k) => {
|
|
144
|
+
const access = k === 0 ? `${v}.firstChild` : `${prev}.nextSibling`;
|
|
145
|
+
const elPath = c.type === 'el' ? (prevEl === null ? `${path}.firstElementChild` : `${prevEl}.nextElementSibling`) : null;
|
|
146
|
+
if (c.type === 'hole' || (c.type === 'el' && c.dyn)) {
|
|
147
|
+
const name = `_$$e${uid++}`;
|
|
148
|
+
decls.push(`${name} = ${access}`);
|
|
149
|
+
prev = name;
|
|
150
|
+
if (c.type === 'hole') {
|
|
151
|
+
binds.push({ type: 'text', parent: v, marker: name, index: c.index, path, safe });
|
|
152
|
+
holeBefore = true;
|
|
153
|
+
} else visitEl(c, name, elPath, safe && !holeBefore);
|
|
154
|
+
} else prev = access;
|
|
155
|
+
if (elPath) prevEl = elPath;
|
|
156
|
+
});
|
|
157
|
+
};
|
|
158
|
+
if (t.kind & 1) visitKids(t.tree, root, null, false);
|
|
159
|
+
else if (t.roots[0].type === 'el' && t.roots[0].dyn) visitEl(t.roots[0], root, '$', true);
|
|
160
|
+
return { decls, binds };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** The `_tmpl$N` factory for a parsed template (identical templates share one). */
|
|
164
|
+
function register(t) {
|
|
165
|
+
const html = serialize(t.tree);
|
|
166
|
+
const key = t.kind + html;
|
|
167
|
+
let tmpl = templates.get(key);
|
|
168
|
+
if (!tmpl) templates.set(key, (tmpl = { name: `_tmpl$${templates.size}`, html, kind: t.kind }));
|
|
169
|
+
return tmpl.name;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const api = { source, parseTemplate, layout, register, use, isHtmlTag, isEach, isWhen, handled, reads, calls };
|
|
173
|
+
|
|
174
|
+
function genTemplateUncached(tpl) {
|
|
175
|
+
const t = parseTemplate(tpl);
|
|
176
|
+
const { exprs, err } = t;
|
|
177
|
+
const { decls, binds } = layout(t, '_$$r');
|
|
178
|
+
const stmts = [];
|
|
179
|
+
const src = i => source(exprs[i]);
|
|
180
|
+
// reactive body of a hole, or null when the hole is static
|
|
181
|
+
const dynBody = i => {
|
|
182
|
+
const b = arrowBody(exprs[i]);
|
|
183
|
+
if (b) return `(${source(b)})`;
|
|
184
|
+
return calls(exprs[i]) ? `(${src(i)})` : null;
|
|
185
|
+
};
|
|
186
|
+
const noDirective = (i, where) => {
|
|
187
|
+
const e = exprs[i];
|
|
188
|
+
if (isEach(e) || isWhen(e))
|
|
189
|
+
err(`${e.callee.name || e.callee.property.name}() can only be used as content, not in ${where}`, 'Write it between tags: html`<ul>${each(…)}</ul>`.', e);
|
|
190
|
+
};
|
|
191
|
+
|
|
192
|
+
// Holes of a live each() row that read only its item / index (no other call): one effect per template
|
|
193
|
+
// re-evaluates them all and writes the ones that changed, instead of an effect per hole.
|
|
194
|
+
const readsRow = e => {
|
|
195
|
+
let found = false;
|
|
196
|
+
walk(e, n => {
|
|
197
|
+
if (found || isFn(n) || isHtmlTag(n)) return false;
|
|
198
|
+
if (reads.has(n)) found = true;
|
|
199
|
+
});
|
|
200
|
+
return found;
|
|
201
|
+
};
|
|
202
|
+
const rowOnly = i => {
|
|
203
|
+
const e = exprs[i];
|
|
204
|
+
return readsRow(e) && !hasCall(e, isHtmlTag) && !hasFnOrTemplate(e, isHtmlTag) && !isEach(e) && !isWhen(e);
|
|
205
|
+
};
|
|
206
|
+
const group = [], groupVars = [];
|
|
207
|
+
const memo = (value, write) => {
|
|
208
|
+
const k = group.length, pv = `_$$g${k}`;
|
|
209
|
+
groupVars.push(pv);
|
|
210
|
+
group.push(`if (${pv} !== (_$$t = (${value}))) { ${pv} = _$$t; ${write} }`);
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
const parts = new Map(); // root hole index -> its part in the returned array
|
|
214
|
+
for (const b of binds) {
|
|
215
|
+
if (b.type === 'text' && t.rootHoles && b.parent === '_$$r') {
|
|
216
|
+
// a root hole cannot insert into the fragment (it is emptied when inserted somewhere): it becomes
|
|
217
|
+
// a part of the returned array, resolved by whoever renders the array (src/dom.js memo / nodes)
|
|
218
|
+
const e = exprs[b.index];
|
|
219
|
+
let part;
|
|
220
|
+
if (isEach(e)) part = genericEach(e, api, err);
|
|
221
|
+
else if (isWhen(e)) part = whenCall(e, api, err);
|
|
222
|
+
else {
|
|
223
|
+
const body = dynBody(b.index);
|
|
224
|
+
part = body ? `${use('memo')}(() => ${body})` : `${use('nodes')}(${src(b.index)})`;
|
|
225
|
+
}
|
|
226
|
+
parts.set(b.index, part);
|
|
227
|
+
continue;
|
|
228
|
+
}
|
|
229
|
+
if (b.type === 'text') {
|
|
230
|
+
const e = exprs[b.index], at = b.marker ? `, ${b.marker}` : '';
|
|
231
|
+
if (isEach(e)) stmts.push(emitEach(e, b.parent, b.marker, api, err));
|
|
232
|
+
else if (isWhen(e)) stmts.push(`${use('insert')}(${b.parent}, ${whenCall(e, api, err)}${at});`);
|
|
233
|
+
else if (rowOnly(b.index)) {
|
|
234
|
+
if (b.marker === null) memo(src(b.index), `${use('text')}(${b.parent}, _$$t);`);
|
|
235
|
+
else {
|
|
236
|
+
const n = `_$$n${groupVars.length}`;
|
|
237
|
+
groupVars.push(n);
|
|
238
|
+
memo(src(b.index), `${n} = ${use('place')}(${b.parent}, _$$t, ${n}, ${b.marker});`);
|
|
239
|
+
}
|
|
240
|
+
} else {
|
|
241
|
+
const body = dynBody(b.index);
|
|
242
|
+
stmts.push(`${use('insert')}(${b.parent}, ${body ? `() => ${body}` : src(b.index)}${at});`);
|
|
243
|
+
}
|
|
244
|
+
continue;
|
|
245
|
+
}
|
|
246
|
+
const { el: v, a } = b, name = a.name;
|
|
247
|
+
const single = a.parts.length === 1 ? a.parts[0].hole : -1;
|
|
248
|
+
if (single >= 0) noDirective(single, `"${name}"`);
|
|
249
|
+
if (name[0] === '@') {
|
|
250
|
+
const [type, ...mods] = name.slice(1).split('.');
|
|
251
|
+
if (mods.length)
|
|
252
|
+
err(`Unknown modifier ".${mods[0]}" in "${name}"`, 'Event modifiers are not supported: call e.preventDefault() / e.stopPropagation() in the handler.');
|
|
253
|
+
stmts.push(`${v}.addEventListener(${JSON.stringify(type)}, ${src(single)});`);
|
|
254
|
+
} else if (name === 'ref') {
|
|
255
|
+
stmts.push(`(${src(single)})(${v});`);
|
|
256
|
+
} else if (name[0] === '.') {
|
|
257
|
+
// a property gets the value as is (a function stays a function); it is reactive when it calls one
|
|
258
|
+
const p = name.slice(1), target = IDENT.test(p) ? `${v}.${p}` : `${v}[${JSON.stringify(p)}]`;
|
|
259
|
+
if (rowOnly(single)) memo(src(single), `${target} = _$$t;`);
|
|
260
|
+
else if (calls(exprs[single])) stmts.push(`${use('effect')}(() => { ${target} = (${src(single)}); });`);
|
|
261
|
+
else stmts.push(`${target} = ${src(single)};`);
|
|
262
|
+
} else if (name[0] === '?') {
|
|
263
|
+
const n = JSON.stringify(name.slice(1)), body = dynBody(single);
|
|
264
|
+
if (rowOnly(single)) memo(src(single), `${v}.toggleAttribute(${n}, !!_$$t);`);
|
|
265
|
+
else if (body) stmts.push(`${use('effect')}(() => { ${v}.toggleAttribute(${n}, !!${body}); });`);
|
|
266
|
+
else stmts.push(`${use('bool')}(${v}, ${n}, ${src(single)});`);
|
|
267
|
+
} else if (single >= 0) {
|
|
268
|
+
const n = JSON.stringify(name), body = dynBody(single);
|
|
269
|
+
if (rowOnly(single)) memo(src(single), `${use('setAttr')}(${v}, ${n}, _$$t);`);
|
|
270
|
+
else if (body) stmts.push(`${use('effect')}(() => { ${use('setAttr')}(${v}, ${n}, ${body}); });`);
|
|
271
|
+
else stmts.push(`${use('attr')}(${v}, ${n}, ${src(single)});`);
|
|
272
|
+
} else {
|
|
273
|
+
// class="a ${x} b"
|
|
274
|
+
const holes = a.parts.filter(p => typeof p !== 'string').map(p => p.hole);
|
|
275
|
+
if (holes.some(rowOnly) && holes.every(i => rowOnly(i) || !dynBody(i))) {
|
|
276
|
+
const value = a.parts.map(p => (typeof p === 'string' ? JSON.stringify(p) : `${use('str')}(${src(p.hole)})`)).join(' + ');
|
|
277
|
+
memo(value, `${use('setAttr')}(${v}, ${JSON.stringify(name)}, _$$t);`);
|
|
278
|
+
continue;
|
|
279
|
+
}
|
|
280
|
+
let dyn = false;
|
|
281
|
+
const pieces = a.parts.map(p => {
|
|
282
|
+
if (typeof p === 'string') return JSON.stringify(p);
|
|
283
|
+
noDirective(p.hole, `"${name}"`);
|
|
284
|
+
const body = dynBody(p.hole);
|
|
285
|
+
if (body) dyn = true;
|
|
286
|
+
return `${use('str')}(${body || src(p.hole)})`;
|
|
287
|
+
});
|
|
288
|
+
const set = `${use('setAttr')}(${v}, ${JSON.stringify(name)}, ${pieces.join(' + ')});`;
|
|
289
|
+
stmts.push(dyn ? `${use('effect')}(() => { ${set} });` : set);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
if (group.length)
|
|
294
|
+
stmts.push(`let ${groupVars.join(', ')}; ${use('effect')}(() => { let _$$t; ${group.join(' ')} });`);
|
|
295
|
+
const name = register(t);
|
|
296
|
+
if (t.rootHoles) {
|
|
297
|
+
const items = t.roots.map((n, k) => (n.type === 'hole' ? parts.get(n.index) : `_$$r.childNodes[${k}]`));
|
|
298
|
+
return `(() => { const _$$r = ${name}()${decls.map(d => `, ${d}`).join('')}; ${stmts.join(' ')} return [${items.join(', ')}]; })()`;
|
|
299
|
+
}
|
|
300
|
+
if (!stmts.length) return `${name}()`;
|
|
301
|
+
return `(() => { const _$$r = ${name}()${decls.map(d => `, ${d}`).join('')}; ${stmts.join(' ')} return _$$r; })()`;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
return { genTemplate, source };
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** `${each(items, row, { key })}`: a fast list when the row can be compiled, else the generic each(). */
|
|
308
|
+
function emitEach(e, parent, marker, api, err) {
|
|
309
|
+
checkEach(e, api, err);
|
|
310
|
+
const fast = emitList(e, parent, marker, api, err);
|
|
311
|
+
if (fast) return fast;
|
|
312
|
+
return `${api.use('insert')}(${parent}, ${genericEach(e, api, err)}${marker ? `, ${marker}` : ''});`;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function checkEach(e, api, err) {
|
|
316
|
+
api.handled.add(e);
|
|
317
|
+
const [items, row, opts, extra] = e.arguments;
|
|
318
|
+
if (!items || !row) err("each() needs items and a row function: each(items, row => html`…`, { key: 'id' })", undefined, e);
|
|
319
|
+
if (extra || (opts && opts.type !== 'ObjectExpression'))
|
|
320
|
+
err(
|
|
321
|
+
'each() takes (items, row, { key }): the key moved into the options',
|
|
322
|
+
"Write each(todos(), t => html`<li>…</li>`, { key: 'id' }) or { key: t => t.id }.",
|
|
323
|
+
e
|
|
324
|
+
);
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** The generic each() call (a scope per row, rows of any shape). */
|
|
328
|
+
function genericEach(e, api, err) {
|
|
329
|
+
checkEach(e, api, err);
|
|
330
|
+
const { source, use } = api;
|
|
331
|
+
const [items, row, opts] = e.arguments;
|
|
332
|
+
const inline = row.type === 'ArrowFunctionExpression' || row.type === 'FunctionExpression';
|
|
333
|
+
// flags: 1 = an index parameter (row.length misses defaults and rest), 2 = live row (see liveRow)
|
|
334
|
+
const ix = inline && (row.params.length > 1 || row.params.some(p => p.type === 'RestElement'));
|
|
335
|
+
const live = inline && liveRow(row, api.reads);
|
|
336
|
+
const flags = (ix ? 1 : 0) | (live ? 2 : 0);
|
|
337
|
+
let rowSrc = source(row);
|
|
338
|
+
if (live) {
|
|
339
|
+
const names = ['_$$it', '_$$ix'].slice(0, row.params.length);
|
|
340
|
+
const body = row.body.type === 'BlockStatement' ? source(row.body) : `(${source(row.body)})`;
|
|
341
|
+
rowSrc = row.type === 'ArrowFunctionExpression' ? `(${names.join(', ')}) => ${body}` : `function (${names.join(', ')}) ${body}`;
|
|
342
|
+
}
|
|
343
|
+
return `${use('each')}(() => (${source(items)}), ${rowSrc}${opts || flags ? `, ${opts ? source(opts) : 'undefined'}` : ''}${flags ? `, ${flags}` : ''})`;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* A live row keeps its DOM while its key stays: its item / index parameters are read through
|
|
348
|
+
* getters (`r.n` -> `_$$it().n`), so holes that use them update in place. Only for plain identifier
|
|
349
|
+
* parameters that the row never re-declares or assigns; otherwise the row is created again instead.
|
|
350
|
+
*/
|
|
351
|
+
function liveRow(row, reads) {
|
|
352
|
+
if (row.async || row.generator || row.params.length > 2 || row.params.some(p => p.type !== 'Identifier')) return false;
|
|
353
|
+
const names = new Map(row.params.map((p, k) => [p.name, k ? '_$$ix()' : '_$$it()']));
|
|
354
|
+
let ok = true;
|
|
355
|
+
const refs = [];
|
|
356
|
+
const visit = (n, parent, key) => {
|
|
357
|
+
if (!ok || !n || typeof n.type !== 'string') return;
|
|
358
|
+
if (n.type === 'Identifier' && names.has(n.name)) {
|
|
359
|
+
const declared =
|
|
360
|
+
((parent.type === 'VariableDeclarator' || parent.type === 'FunctionDeclaration' || parent.type === 'ClassDeclaration' || parent.type === 'FunctionExpression' || parent.type === 'ClassExpression') && key === 'id') ||
|
|
361
|
+
key === 'params' || parent.type === 'CatchClause' || parent.type === 'AssignmentPattern' || parent.type === 'RestElement' || parent.type === 'ArrayPattern' ||
|
|
362
|
+
(parent.type === 'Property' && key === 'value' && parent.__pattern);
|
|
363
|
+
const assigned = (parent.type === 'AssignmentExpression' && key === 'left') || parent.type === 'UpdateExpression';
|
|
364
|
+
if (declared || assigned) ok = false; // re-declared or assigned: keep the plain value (row is recreated)
|
|
365
|
+
else if ((parent.type === 'MemberExpression' && key === 'property' && !parent.computed) || (parent.type === 'Property' && key === 'key' && !parent.computed) ||
|
|
366
|
+
(parent.type === 'MethodDefinition' && key === 'key') || parent.type === 'LabeledStatement' || parent.type === 'BreakStatement' || parent.type === 'ContinueStatement') {
|
|
367
|
+
// a property name or a label, not a reference
|
|
368
|
+
} else refs.push([n, parent]);
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
371
|
+
if (n.type === 'ObjectPattern') for (const p of n.properties) p.__pattern = true;
|
|
372
|
+
for (const k in n) {
|
|
373
|
+
if (k === '__pattern') continue;
|
|
374
|
+
const v = n[k];
|
|
375
|
+
if (Array.isArray(v)) for (const c of v) visit(c, n, k);
|
|
376
|
+
else if (v && typeof v.type === 'string') visit(v, n, k);
|
|
377
|
+
}
|
|
378
|
+
};
|
|
379
|
+
visit(row.body, row, 'body');
|
|
380
|
+
if (!ok) return false;
|
|
381
|
+
for (const [n, parent] of refs)
|
|
382
|
+
reads.set(n, parent.type === 'Property' && parent.shorthand ? `${n.name}: ${names.get(n.name)}` : names.get(n.name));
|
|
383
|
+
return true;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/** `when(cond, yes, no)` with every argument as a function. */
|
|
387
|
+
function whenCall(e, api, err) {
|
|
388
|
+
api.handled.add(e);
|
|
389
|
+
if (!e.arguments.length) err('when() needs a condition: when(cond, yes, no?)', undefined, e);
|
|
390
|
+
return `${api.use('when')}(${e.arguments.map(a => `() => (${api.source(a)})`).join(', ')})`;
|
|
391
|
+
}
|