@hidemikimura/vanji 0.0.0-stage → 0.1.1
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/CHANGELOG.md +14 -0
- package/LICENSE +21 -0
- package/README.md +256 -2
- package/compiler/ast.js +48 -0
- package/compiler/index.d.ts +21 -0
- package/compiler/index.js +155 -0
- package/compiler/list.js +195 -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 +62 -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 +280 -0
- package/src/signals.js +287 -0
package/compiler/list.js
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
// Fast lists: `${each(items, row => html`<one element>…`, { key })}` compiled into a row record
|
|
2
|
+
// factory for src/list.js. Returns null when the row cannot be compiled this way; the generic each()
|
|
3
|
+
// then handles it (same behaviour, a scope per row).
|
|
4
|
+
import { hasFnOrTemplate, walk, IDENT } from './ast.js';
|
|
5
|
+
|
|
6
|
+
const prop = p => (IDENT.test(p) ? `.${p}` : `[${JSON.stringify(p)}]`);
|
|
7
|
+
|
|
8
|
+
/** `sel() === row.key` (either side), optionally as the test of `? a : b` with plain branches: the signal name. */
|
|
9
|
+
function selectorOf(e, rowName, keyProp, isHtmlTag, calls) {
|
|
10
|
+
if (!rowName || !keyProp) return null;
|
|
11
|
+
let test = e;
|
|
12
|
+
if (e.type === 'ConditionalExpression') {
|
|
13
|
+
for (const b of [e.consequent, e.alternate]) if (calls(b) || hasFnOrTemplate(b, isHtmlTag)) return null;
|
|
14
|
+
test = e.test;
|
|
15
|
+
}
|
|
16
|
+
// only ===: the list finds rows with Map lookups, which compare strictly
|
|
17
|
+
if (test.type !== 'BinaryExpression' || test.operator !== '===') return null;
|
|
18
|
+
const sig = n => (n.type === 'CallExpression' && !n.arguments.length && n.callee.type === 'Identifier' ? n.callee.name : null);
|
|
19
|
+
const isKey = n =>
|
|
20
|
+
n.type === 'MemberExpression' && !n.computed && n.object.type === 'Identifier' && n.object.name === rowName && n.property.name === keyProp;
|
|
21
|
+
if (sig(test.left) && isKey(test.right)) return sig(test.left);
|
|
22
|
+
if (sig(test.right) && isKey(test.left)) return sig(test.right);
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function emitList(call, parent, marker, api, err) {
|
|
27
|
+
const { source, parseTemplate, layout, register, use, isHtmlTag, isEach, isWhen, calls } = api;
|
|
28
|
+
const [items, row, opts] = call.arguments;
|
|
29
|
+
if (row.type !== 'ArrowFunctionExpression' || row.async || !row.params.length || row.params.length > 2) return null;
|
|
30
|
+
// (item) or (item, index): no defaults or rest (the generic each() handles those)
|
|
31
|
+
if (/^(AssignmentPattern|RestElement)$/.test(row.params[0].type) || (row.params[1] && row.params[1].type !== 'Identifier')) return null;
|
|
32
|
+
if (!isHtmlTag(row.body)) return null;
|
|
33
|
+
|
|
34
|
+
// { key: 'id' } or { key: item => … }
|
|
35
|
+
let key = 'undefined', keyProp = null;
|
|
36
|
+
if (opts) {
|
|
37
|
+
for (const p of opts.properties) {
|
|
38
|
+
if (p.type !== 'Property' || p.computed || (p.key.name || p.key.value) !== 'key') return null;
|
|
39
|
+
if (p.value.type === 'Literal' && typeof p.value.value === 'string') keyProp = p.value.value;
|
|
40
|
+
key = source(p.value);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const t = parseTemplate(row.body);
|
|
45
|
+
if (t.kind & 1 || t.roots[0].type !== 'el') return null;
|
|
46
|
+
const { decls, binds } = layout(t, '_$$el');
|
|
47
|
+
// holes with nested templates, functions or directives need a scope per row: generic each()
|
|
48
|
+
for (const b of binds) {
|
|
49
|
+
if (b.type === 'attr' && (b.a.name[0] === '@' || b.a.name === 'ref')) continue;
|
|
50
|
+
const holes = b.type === 'text' ? [b.index] : b.a.parts.filter(p => typeof p !== 'string').map(p => p.hole);
|
|
51
|
+
for (const i of holes) if (isEach(t.exprs[i]) || isWhen(t.exprs[i]) || hasFnOrTemplate(t.exprs[i], isHtmlTag)) return null;
|
|
52
|
+
}
|
|
53
|
+
const rowParam = source(row.params[0]);
|
|
54
|
+
const rowName = row.params[0].type === 'Identifier' ? row.params[0].name : null;
|
|
55
|
+
const idxParam = row.params[1] ? source(row.params[1]) : null;
|
|
56
|
+
const params = `(${rowParam}${idxParam ? `, ${idxParam}` : ''})`;
|
|
57
|
+
const bindRow = `const ${rowParam} = _$$v${idxParam ? `, ${idxParam} = _$$i` : ''};`;
|
|
58
|
+
|
|
59
|
+
const hoisted = [], fields = [], initial = [], patches = [], selPatches = [], dyn = [], sigs = new Set(), events = {};
|
|
60
|
+
// do the branches of a selection (`sel() === row.key ? a : b`) mention the row or the index?
|
|
61
|
+
// (conservative: any identifier of that name; the test itself reads only the key)
|
|
62
|
+
const names = new Set([rowName, row.params[1] && row.params[1].name].filter(Boolean));
|
|
63
|
+
const readsRow = e => {
|
|
64
|
+
if (e.type !== 'ConditionalExpression') return false;
|
|
65
|
+
let found = false;
|
|
66
|
+
for (const branch of [e.consequent, e.alternate])
|
|
67
|
+
walk(branch, n => {
|
|
68
|
+
if (found) return false;
|
|
69
|
+
if (n.type === 'Identifier' && names.has(n.name)) found = true;
|
|
70
|
+
});
|
|
71
|
+
return found;
|
|
72
|
+
};
|
|
73
|
+
let uid = 0;
|
|
74
|
+
const fn = body => {
|
|
75
|
+
const name = `_$$f${uid++}`;
|
|
76
|
+
hoisted.push(`const ${name} = ${params} => (${body});`);
|
|
77
|
+
return name;
|
|
78
|
+
};
|
|
79
|
+
// an element reachable at any time: its element path, or a reference kept on the row
|
|
80
|
+
const keep = (v, path, safe) => {
|
|
81
|
+
if (safe) return path.replace(/^\$/, () => '_$$r.el');
|
|
82
|
+
const q = `q${uid++}`;
|
|
83
|
+
fields.push(`${q}: ${v}`);
|
|
84
|
+
return `_$$r.${q}`;
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
for (const b of binds) {
|
|
88
|
+
const exprs = t.exprs;
|
|
89
|
+
if (b.type === 'attr' && b.a.name[0] === '@') {
|
|
90
|
+
const name = b.a.name, [type, ...mods] = name.slice(1).split('.');
|
|
91
|
+
if (mods.length)
|
|
92
|
+
err(`Unknown modifier ".${mods[0]}" in "${name}"`, 'Event modifiers are not supported: call e.preventDefault() / e.stopPropagation() in the handler.');
|
|
93
|
+
// every event type: one capture listener on the list's parent (src/list.js)
|
|
94
|
+
const h = fn(source(exprs[b.a.parts[0].hole]));
|
|
95
|
+
(events[type] ||= []).push(`[_$$r => ${keep(b.el, b.path, b.safe)}, ${h}]`);
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
if (b.type === 'attr' && b.a.name === 'ref') {
|
|
99
|
+
// in the row's scope, so what it creates (effects, cleanups) lives as long as the row
|
|
100
|
+
dyn.push(`(${source(exprs[b.a.parts[0].hole])})(${b.el});`);
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
// the value of this binding as an expression of the row, and how it behaves
|
|
104
|
+
const holes = b.type === 'text' ? [b.index] : b.a.parts.filter(p => typeof p !== 'string').map(p => p.hole);
|
|
105
|
+
let mode = 'memo', selects = false, onlySelect = true;
|
|
106
|
+
for (const i of holes) {
|
|
107
|
+
const e = exprs[i];
|
|
108
|
+
const s = selectorOf(e, rowName, keyProp, isHtmlTag, calls);
|
|
109
|
+
if (s) {
|
|
110
|
+
sigs.add(s);
|
|
111
|
+
selects = true;
|
|
112
|
+
if (readsRow(e)) onlySelect = false;
|
|
113
|
+
} else {
|
|
114
|
+
onlySelect = false;
|
|
115
|
+
if (calls(e)) mode = 'dyn';
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
// where the patch goes: u (the item or index changed) and/or s (a selection signal changed).
|
|
119
|
+
// A binding made only of `sig() === row.key ? a : b` with branches that do not read the row
|
|
120
|
+
// cannot change with the item (same key), so it is left out of u.
|
|
121
|
+
const patchTo = code => {
|
|
122
|
+
if (selects) selPatches.push(code);
|
|
123
|
+
if (!(selects && onlySelect)) patches.push(code);
|
|
124
|
+
};
|
|
125
|
+
let value;
|
|
126
|
+
if (b.type === 'attr' && !(b.a.parts.length === 1 && typeof b.a.parts[0] !== 'string'))
|
|
127
|
+
value = b.a.parts.map(p => (typeof p === 'string' ? JSON.stringify(p) : `${use('str')}(${source(exprs[p.hole])})`)).join(' + ');
|
|
128
|
+
else value = source(exprs[holes[0]]);
|
|
129
|
+
|
|
130
|
+
if (mode === 'dyn') {
|
|
131
|
+
// re-evaluated by an effect of the row (and when the item is replaced)
|
|
132
|
+
const f = `${fn(value)}(_$$r.v, _$$r.i)`;
|
|
133
|
+
if (b.type === 'text') dyn.push(`${use('insert')}(${b.parent}, () => ${f}${b.marker ? `, ${b.marker}` : ''});`);
|
|
134
|
+
else {
|
|
135
|
+
const name = b.a.name;
|
|
136
|
+
let set;
|
|
137
|
+
if (name[0] === '.') set = `${b.el}${prop(name.slice(1))} = ${f};`;
|
|
138
|
+
else if (name[0] === '?') set = `${b.el}.toggleAttribute(${JSON.stringify(name.slice(1))}, !!${f});`;
|
|
139
|
+
else set = `${use('setAttr')}(${b.el}, ${JSON.stringify(name)}, ${f});`;
|
|
140
|
+
dyn.push(`${use('effect')}(() => { ${set} });`);
|
|
141
|
+
}
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// memo: the last value is kept on the row; written now, and again when it changes
|
|
146
|
+
const p = `p${uid++}`;
|
|
147
|
+
fields.push(`${p}: (${value})`);
|
|
148
|
+
if (b.type === 'text' && b.marker === null) {
|
|
149
|
+
// from its first update on, the row keeps the text node and writes new strings to it directly
|
|
150
|
+
const at = keep(b.parent, b.path, b.safe), x = `x${uid++}`;
|
|
151
|
+
fields.push(`${x}: null`);
|
|
152
|
+
initial.push(`${use('text')}(${b.parent}, _$$r.${p});`);
|
|
153
|
+
patchTo(
|
|
154
|
+
`if (_$$r.${p} !== (_$$t = (${value}))) { _$$r.${p} = _$$t; ` +
|
|
155
|
+
`if (_$$r.${x} !== null && typeof _$$t === 'string') _$$r.${x}.data = _$$t; else _$$r.${x} = ${use('textNode')}(${at}, _$$t); }`
|
|
156
|
+
);
|
|
157
|
+
} else if (b.type === 'text') {
|
|
158
|
+
const n = `n${uid++}`, m = `m${uid++}`;
|
|
159
|
+
fields.push(`${n}: undefined`, `${m}: ${b.marker}`);
|
|
160
|
+
initial.push(`_$$r.${n} = ${use('place')}(${b.parent}, _$$r.${p}, undefined, ${b.marker});`);
|
|
161
|
+
patchTo(`if (_$$r.${p} !== (_$$t = (${value}))) { _$$r.${p} = _$$t; _$$r.${n} = ${use('place')}(_$$r.${m}.parentNode, _$$t, _$$r.${n}, _$$r.${m}); }`);
|
|
162
|
+
} else {
|
|
163
|
+
const at = keep(b.el, b.path, b.safe), name = b.a.name;
|
|
164
|
+
let now, later;
|
|
165
|
+
if (name[0] === '.') {
|
|
166
|
+
now = `${b.el}${prop(name.slice(1))} = _$$r.${p};`;
|
|
167
|
+
later = `${at}${prop(name.slice(1))} = _$$t;`;
|
|
168
|
+
} else if (name[0] === '?') {
|
|
169
|
+
const n = JSON.stringify(name.slice(1));
|
|
170
|
+
now = `if (_$$r.${p}) ${b.el}.toggleAttribute(${n}, true);`;
|
|
171
|
+
later = `${at}.toggleAttribute(${n}, !!_$$t);`;
|
|
172
|
+
} else if (name === 'class') {
|
|
173
|
+
now = `if (_$$r.${p} != null && _$$r.${p} !== '') ${b.el}.setAttribute("class", _$$r.${p});`;
|
|
174
|
+
later = `${use('setAttr')}(${at}, "class", _$$t);`;
|
|
175
|
+
} else {
|
|
176
|
+
now = `${use('setAttr')}(${b.el}, ${JSON.stringify(name)}, _$$r.${p});`;
|
|
177
|
+
later = `${use('setAttr')}(${at}, ${JSON.stringify(name)}, _$$t);`;
|
|
178
|
+
}
|
|
179
|
+
initial.push(now);
|
|
180
|
+
patchTo(`if (_$$r.${p} !== (_$$t = (${value}))) { _$$r.${p} = _$$t; ${later} }`);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const create =
|
|
185
|
+
`(_$$el, _$$v, _$$i) => { ${bindRow} ${decls.length ? `const ${decls.join(', ')};` : ''} ` +
|
|
186
|
+
`const _$$r = { el: _$$el, v: _$$v, i: _$$i, s: null, h: 0${fields.map(f => `, ${f}`).join('')} }; ` +
|
|
187
|
+
`${initial.join(' ')} ${dyn.length ? `${use('rowScope')}(_$$r, () => { ${dyn.join(' ')} });` : ''} return _$$r; }`;
|
|
188
|
+
const patch = patches.length ? `(_$$r, _$$v, _$$i) => { ${bindRow} let _$$t; ${patches.join(' ')} }` : '() => {}';
|
|
189
|
+
const x = sigs.size ? `[${[...sigs].map(s => `() => ${s}()`).join(', ')}]` : 'null';
|
|
190
|
+
const sel = selPatches.length ? `(_$$r) => { const ${rowParam} = _$$r.v${idxParam ? `, ${idxParam} = _$$r.i` : ''}; let _$$t; ${selPatches.join(' ')} }` : 'null';
|
|
191
|
+
const ev = Object.keys(events).length ? `{ ${Object.entries(events).map(([k, v]) => `${JSON.stringify(k)}: [${v.join(', ')}]`).join(', ')} }` : 'null';
|
|
192
|
+
const spec = `{ t: ${register(t)}, k: ${key}, c: ${create}, u: ${patch}, s: ${sel}, x: ${x}, e: ${ev}, ix: ${!!idxParam} }`;
|
|
193
|
+
const specCode = hoisted.length ? `(() => { ${hoisted.join(' ')} return ${spec}; })()` : spec;
|
|
194
|
+
return `${use('list')}(${parent}, ${marker || 'null'}, () => (${source(items)}), ${specCode});`;
|
|
195
|
+
}
|
|
@@ -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
|
+
}
|