@solidjs/html 2.0.0-beta.7 → 2.0.0-beta.9

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 CHANGED
@@ -2,26 +2,28 @@
2
2
 
3
3
  This sub module provides a Tagged Template Literal `html` method for Solid. This is useful to use Solid in non-compiled environments. This method can be used as replacement for JSX.
4
4
 
5
- `html` uses `${}` to escape into JavaScript expressions. Components are closed with `<//>`
5
+ `html` uses `${}` to escape into JavaScript expressions. Components are closed with `<//>`.
6
+
7
+ Since Solid 2.0, `html` is backed by [`sld-dom-expressions`](https://www.npmjs.com/package/sld-dom-expressions), an AST-based tagged-template runtime. Templates are parsed at runtime (no `new Function` / `eval`, so it is CSP-safe) and reactive bindings are installed against the resulting DOM.
6
8
 
7
9
  ```js
8
10
  // create an element with a title attribute
9
11
  html`<button title="My button">Click Me</button>`
10
12
 
11
- // create a component with a title prop
13
+ // create a component with a title prop (inline expression hole)
12
14
  html`<${Button} title="My button">Click me<//>`
13
15
 
14
16
  // create an element with dynamic attribute and spread
15
17
  html`<div title=${() => selectedClass()} ...${props} />`
16
18
  ```
17
19
 
18
- Using `html` is slightly less efficient than JSX(but more than HyperScript), requires a larger runtime that isn't treeshakeable, and cannot leverage expression analysis, so it requires manual wrapping of expressions and has a few other caveats (see below).
20
+ Using `html` is slightly less efficient than JSX, requires a larger runtime that isn't treeshakeable, and cannot leverage expression analysis, so it requires manual wrapping of expressions and has a few other caveats (see below).
19
21
 
20
22
  ## Example
21
23
 
22
24
  ```js
23
- import { render } from "solid-js/web";
24
- import html from "solid-js/html";
25
+ import { render } from "@solidjs/web";
26
+ import html from "@solidjs/html";
25
27
  import { createSignal } from "solid-js";
26
28
 
27
29
  function Button(props) {
@@ -38,6 +40,40 @@ function Counter() {
38
40
  render(Counter, document.getElementById("app"));
39
41
  ```
40
42
 
43
+ ## Component registry
44
+
45
+ Inline expression holes (`<${Component} />`) work without any setup, but the `sld` runtime also supports a named component registry. `html.define({ ... })` returns a new tag with the supplied components merged into the registry; capitalized tag names in the template are then looked up by name. The original `html` tag is unchanged.
46
+
47
+ ```js
48
+ import html from "@solidjs/html";
49
+ import { For, Show } from "solid-js";
50
+
51
+ const tpl = html.define({ For, Show });
52
+
53
+ function List(props) {
54
+ return tpl`
55
+ <Show when=${() => props.items.length > 0} fallback=${tpl`<p>No items</p>`}>
56
+ <ul>
57
+ <For each=${() => props.items}>
58
+ ${item => tpl`<li>${item.name}</li>`}
59
+ </For>
60
+ </ul>
61
+ </Show>
62
+ `;
63
+ }
64
+ ```
65
+
66
+ An unregistered capitalized tag name throws at template-construction time, which gives tooling (codemods, syntax highlighters) something concrete to key off.
67
+
68
+ ## Return shape
69
+
70
+ A `html\`...\`` expression returns a single node when the template resolves to one root, and an array of nodes when it resolves to many. Consumers that need to spread or iterate the result should normalize:
71
+
72
+ ```js
73
+ const result = html`<span/><span/>`;
74
+ const nodes = Array.isArray(result) ? result : [result];
75
+ ```
76
+
41
77
  ## Differences from JSX
42
78
 
43
79
  There are a few differences from Solid's JSX that are important to note.
package/dist/html.cjs CHANGED
@@ -2,564 +2,17 @@
2
2
 
3
3
  var web = require('@solidjs/web');
4
4
 
5
- const tagRE = /(?:<!--[\S\s]*?-->|<(?:"[^"]*"['"]*|'[^']*'['"]*|[^'">])+>)/g;
6
- const attrRE = /(?:\s(?<boolean>[^/\s><=]+?)(?=[\s/>]))|(?:(?<name>\S+?)(?:\s*=\s*(?:(['"])(?<quotedValue>[\s\S]*?)\3|(?<unquotedValue>[^\s>]+))))/g;
7
- const lookup = {
8
- area: true,
9
- base: true,
10
- br: true,
11
- col: true,
12
- embed: true,
13
- hr: true,
14
- img: true,
15
- input: true,
16
- keygen: true,
17
- link: true,
18
- menuitem: true,
19
- meta: true,
20
- param: true,
21
- source: true,
22
- track: true,
23
- wbr: true
24
- };
25
- function parseTag(tag) {
26
- const res = {
27
- type: 'tag',
28
- name: '',
29
- voidElement: false,
30
- attrs: [],
31
- children: []
32
- };
33
- const tagMatch = tag.match(/<\/?([^\s]+?)[/\s>]/);
34
- if (tagMatch) {
35
- res.name = tagMatch[1];
36
- if (lookup[tagMatch[1].toLowerCase()] || tag.charAt(tag.length - 2) === '/') {
37
- res.voidElement = true;
38
- }
39
- if (res.name.startsWith('!--')) {
40
- const endIndex = tag.indexOf('-->');
41
- return {
42
- type: 'comment',
43
- comment: endIndex !== -1 ? tag.slice(4, endIndex) : ''
44
- };
45
- }
46
- }
47
- const reg = new RegExp(attrRE);
48
- for (const match of tag.matchAll(reg)) {
49
- if ((match[1] || match[2]).startsWith('use:')) {
50
- res.attrs.push({
51
- type: 'directive',
52
- name: match[1] || match[2],
53
- value: match[4] || match[5] || ''
54
- });
55
- } else {
56
- res.attrs.push({
57
- type: 'attr',
58
- name: match[1] || match[2],
59
- value: match[4] || match[5] || ''
60
- });
61
- }
62
- }
63
- return res;
64
- }
65
- function pushTextNode(list, html, start) {
66
- const end = html.indexOf('<', start);
67
- const content = html.slice(start, end === -1 ? void 0 : end);
68
- if (!/^\s*$/.test(content)) {
69
- list.push({
70
- type: 'text',
71
- content: content
72
- });
73
- }
74
- }
75
- function pushCommentNode(list, tag) {
76
- const content = tag.replace('<!--', '').replace('-->', '');
77
- if (!/^\s*$/.test(content)) {
78
- list.push({
79
- type: 'comment',
80
- content: content
81
- });
82
- }
83
- }
84
- function parse(html) {
85
- const result = [];
86
- let current = void 0;
87
- let level = -1;
88
- const arr = [];
89
- const byTag = {};
90
- html.replace(tagRE, (tag, index) => {
91
- const isOpen = tag.charAt(1) !== '/';
92
- const isComment = tag.slice(0, 4) === '<!--';
93
- const start = index + tag.length;
94
- const nextChar = html.charAt(start);
95
- let parent = void 0;
96
- if (isOpen && !isComment) {
97
- level++;
98
- current = parseTag(tag);
99
- if (!current.voidElement && nextChar && nextChar !== '<') {
100
- pushTextNode(current.children, html, start);
101
- }
102
- byTag[current.tagName] = current;
103
- if (level === 0) {
104
- result.push(current);
105
- }
106
- parent = arr[level - 1];
107
- if (parent) {
108
- parent.children.push(current);
109
- }
110
- arr[level] = current;
111
- }
112
- if (isComment) {
113
- if (level < 0) {
114
- pushCommentNode(result, tag);
115
- } else {
116
- pushCommentNode(arr[level].children, tag);
117
- }
118
- }
119
- if (isComment || !isOpen || current.voidElement) {
120
- if (!isComment) {
121
- level--;
122
- }
123
- if (nextChar !== '<' && nextChar) {
124
- parent = level === -1 ? result : arr[level].children;
125
- pushTextNode(parent, html, start);
126
- }
127
- }
128
- });
129
- return result;
130
- }
131
- function attrString(attrs) {
132
- const buff = [];
133
- for (const attr of attrs) {
134
- buff.push(attr.name + '="' + attr.value.replace(/"/g, '&quot;') + '"');
135
- }
136
- if (!buff.length) {
137
- return '';
138
- }
139
- return ' ' + buff.join(' ');
140
- }
141
- function stringifier(buff, doc) {
142
- switch (doc.type) {
143
- case 'text':
144
- return buff + doc.content;
145
- case 'tag':
146
- buff += '<' + doc.name + (doc.attrs ? attrString(doc.attrs) : '') + (doc.voidElement ? '/>' : '>');
147
- if (doc.voidElement) {
148
- return buff;
149
- }
150
- return buff + doc.children.reduce(stringifier, '') + '</' + doc.name + '>';
151
- case 'comment':
152
- return buff += '<!--' + doc.content + '-->';
153
- }
154
- }
155
- function stringify(doc) {
156
- return doc.reduce(function (token, rootEl) {
157
- return token + stringifier('', rootEl);
158
- }, '');
159
- }
160
- const cache = new Map();
161
- const VOID_ELEMENTS = /^(?:area|base|br|col|embed|hr|img|input|keygen|link|menuitem|meta|param|source|track|wbr)$/i;
162
- const spaces = " \\f\\n\\r\\t";
163
- const almostEverything = "[^" + spaces + "\\/>\"'=]+";
164
- const attrName = "[ " + spaces + "]+" + almostEverything;
165
- const tagName = "<([A-Za-z$#]+[A-Za-z0-9:_-]*)((?:";
166
- const attrPartials = "(?:\\s*=\\s*(?:'[^']*?'|\"[^\"]*?\"|\\([^)]*?\\)|<[^>]*?>|" + almostEverything + "))?)";
167
- const attrSeeker = new RegExp(tagName + attrName + attrPartials + "+)([ " + spaces + "]*/?>)", "g");
168
- const findAttributes = new RegExp("(" + attrName + "\\s*=\\s*)(<!--#-->|['\"(]([\\w\\s]*<!--#-->[\\w\\s]*)*['\")])", "gi");
169
- const selfClosing = new RegExp(tagName + attrName + attrPartials + "*)([ " + spaces + "]*/>)", "g");
170
- const marker = "<!--#-->";
171
- const reservedNameSpaces = new Set(["class", "on", "style", "prop"]);
172
- function attrReplacer($0, $1, $2, $3) {
173
- return "<" + $1 + $2.replace(findAttributes, replaceAttributes) + $3;
174
- }
175
- function replaceAttributes($0, $1, $2) {
176
- return $1.replace(/<!--#-->/g, "###") + ($2[0] === '"' || $2[0] === "'" ? $2.replace(/<!--#-->/g, "###") : '"###"');
177
- }
178
- function fullClosing($0, $1, $2) {
179
- return VOID_ELEMENTS.test($1) ? $0 : "<" + $1 + $2 + "></" + $1 + ">";
180
- }
181
- function createHTML(r, {
182
- delegateEvents = true,
183
- functionBuilder = (...args) => new Function(...args)
184
- } = {}) {
185
- let uuid = 1;
186
- r.wrapProps = props => {
187
- const d = Object.getOwnPropertyDescriptors(props);
188
- for (const k in d) {
189
- if (typeof d[k].value === "function" && !d[k].value.length) r.dynamicProperty(props, k);
190
- }
191
- return props;
192
- };
193
- r.resolveFn = fn => typeof fn === "function" ? fn() : fn;
194
- function createTemplate(statics, opt) {
195
- let i = 0,
196
- markup = "";
197
- for (; i < statics.length - 1; i++) {
198
- markup = markup + statics[i] + "<!--#-->";
199
- }
200
- markup = markup + statics[i];
201
- const replaceList = [[selfClosing, fullClosing], [/<(<!--#-->)/g, "<###"], [/\.\.\.(<!--#-->)/g, "###"], [attrSeeker, attrReplacer], [/>\n+\s*/g, ">"], [/\n+\s*</g, "<"], [/\s+</g, " <"], [/>\s+/g, "> "]];
202
- markup = replaceList.reduce((acc, x) => {
203
- return acc.replace(x[0], x[1]);
204
- }, markup);
205
- const pars = parse(markup);
206
- const [html, code] = parseTemplate(pars, opt.funcBuilder),
207
- templates = [];
208
- for (let i = 0; i < html.length; i++) {
209
- templates.push(document.createElement("template"));
210
- templates[i].innerHTML = html[i];
211
- const nomarkers = templates[i].content.querySelectorAll("script,style");
212
- for (let j = 0; j < nomarkers.length; j++) {
213
- const d = nomarkers[j].firstChild?.data || "";
214
- if (d.indexOf(marker) > -1) {
215
- const parts = d.split(marker).reduce((memo, p, i) => {
216
- i && memo.push("");
217
- memo.push(p);
218
- return memo;
219
- }, []);
220
- nomarkers[i].firstChild.replaceWith(...parts);
221
- }
222
- }
223
- }
224
- templates[0].create = code;
225
- cache.set(statics, templates);
226
- return templates;
227
- }
228
- function parseKeyValue(node, tag, name, value, options) {
229
- let expr, parts, namespace;
230
- if (value === "###") {
231
- expr = `_$v`;
232
- options.counter++;
233
- } else {
234
- const chunks = value.split("###");
235
- options.counter = chunks.length - 1 + options.counter;
236
- expr = chunks.map((v, i) => i ? ` + _$v[${i - 1}] + "${v}"` : `"${v}"`).join("");
237
- }
238
- if ((parts = name.split(":")) && parts[1] && reservedNameSpaces.has(parts[0])) {
239
- name = parts[1];
240
- namespace = parts[0];
241
- }
242
- const isChildProp = r.ChildProperties.has(name);
243
- const isLockedDOMProperty = !!r.DOMWithState[node.name.toUpperCase()]?.[name];
244
- if (name === "style") {
245
- options.exprs.push(`r.style(${tag},${expr},_$p)`);
246
- } else if (name === "class") {
247
- options.exprs.push(`r.className(${tag},${expr},_$p)`);
248
- } else if (isChildProp || isLockedDOMProperty || namespace === "prop") {
249
- options.exprs.push(`${tag}.${name} = ${expr}`);
250
- } else {
251
- const ns = name.indexOf(":") > -1 && r.Namespaces[name.split(":")[0]];
252
- if (ns) options.exprs.push(`r.setAttributeNS(${tag},"${ns}","${name}",${expr})`);else options.exprs.push(`r.setAttribute(${tag},"${name}",${expr})`);
253
- }
254
- }
255
- function parseAttribute(node, tag, name, value, options) {
256
- if (name.slice(0, 2) === "on") {
257
- if (!name.includes(":")) {
258
- const lc = name.slice(2).toLowerCase();
259
- const delegate = delegateEvents && r.DelegatedEvents.has(lc);
260
- options.exprs.push(`r.addEventListener(${tag},"${lc}",exprs[${options.counter++}],${delegate})`);
261
- delegate && options.delegatedEvents.add(lc);
262
- } else {
263
- options.exprs.push(`${tag}.addEventListener("${name.slice(3)}",exprs[${options.counter++}])`);
264
- }
265
- } else if (name === "ref") {
266
- options.exprs.push(`r.ref(() => exprs[${options.counter++}], ${tag})`);
267
- } else {
268
- const childOptions = Object.assign({}, options, {
269
- exprs: []
270
- }),
271
- count = options.counter;
272
- parseKeyValue(node, tag, name, value, childOptions);
273
- options.decl.push(`_fn${count} = (_$v, _$p) => {\n${childOptions.exprs.join(";\n")};\n}`);
274
- if (value === "###") {
275
- options.exprs.push(`typeof exprs[${count}] === "function" ? r.effect(() => exprs[${count}](), _fn${count}) : _fn${count}(exprs[${count}])`);
276
- } else {
277
- let check = "";
278
- let list = "";
279
- let reactiveList = "";
280
- for (let i = count; i < childOptions.counter; i++) {
281
- if (i !== count) {
282
- check += " || ";
283
- list += ",";
284
- reactiveList += ",";
285
- }
286
- check += `typeof exprs[${i}] === "function"`;
287
- list += `exprs[${i}]`;
288
- reactiveList += `r.resolveFn(exprs[${i}])`;
289
- }
290
- options.exprs.push(check + ` ? r.effect(() => [${reactiveList}], _fn${count}) : _fn${count}([${list}])`);
291
- }
292
- options.counter = childOptions.counter;
293
- options.wrap = false;
294
- }
295
- }
296
- function processChildren(node, options) {
297
- const childOptions = Object.assign({}, options, {
298
- first: true,
299
- multi: false,
300
- parent: options.path
301
- });
302
- if (node.children.length > 1) {
303
- for (let i = 0; i < node.children.length; i++) {
304
- const child = node.children[i];
305
- if (child.type === "comment" && child.content === "#" || child.type === "tag" && child.name === "###") {
306
- childOptions.multi = true;
307
- break;
308
- }
309
- }
310
- }
311
- let i = 0;
312
- while (i < node.children.length) {
313
- const child = node.children[i];
314
- if (child.name === "###") {
315
- if (childOptions.multi) {
316
- node.children[i] = {
317
- type: "comment",
318
- content: "#"
319
- };
320
- i++;
321
- } else node.children.splice(i, 1);
322
- processComponent(child, childOptions);
323
- continue;
324
- }
325
- parseNode(child, childOptions);
326
- if (!childOptions.multi && child.type === "comment" && child.content === "#") node.children.splice(i, 1);else i++;
327
- }
328
- options.counter = childOptions.counter;
329
- options.templateId = childOptions.templateId;
330
- options.isImportNode = options.isImportNode || childOptions.isImportNode;
331
- }
332
- function processComponentProps(propGroups) {
333
- let result = [];
334
- for (const props of propGroups) {
335
- if (Array.isArray(props)) {
336
- if (!props.length) continue;
337
- result.push(`r.wrapProps({${props.join(",") || ""}})`);
338
- } else result.push(props);
339
- }
340
- return result.length > 1 ? `r.mergeProps(${result.join(",")})` : result[0];
341
- }
342
- function processComponent(node, options) {
343
- let props = [];
344
- const keys = Object.keys(node.attrs),
345
- propGroups = [props],
346
- componentIdentifier = options.counter++;
347
- for (let i = 0; i < keys.length; i++) {
348
- const {
349
- type,
350
- name,
351
- value
352
- } = node.attrs[i];
353
- if (type === "attr") {
354
- if (name === "###") {
355
- propGroups.push(`exprs[${options.counter++}]`);
356
- propGroups.push(props = []);
357
- } else if (value === "###") {
358
- props.push(`"${name}": exprs[${options.counter++}]`);
359
- } else props.push(`"${name}": "${value}"`);
360
- }
361
- }
362
- if (node.children.length === 1 && node.children[0].type === "comment" && node.children[0].content === "#") {
363
- props.push(`children: () => exprs[${options.counter++}]`);
364
- } else if (node.children.length) {
365
- const children = {
366
- type: "fragment",
367
- children: node.children
368
- },
369
- childOptions = Object.assign({}, options, {
370
- first: true,
371
- decl: [],
372
- exprs: [],
373
- parent: false
374
- });
375
- parseNode(children, childOptions);
376
- props.push(`children: () => { ${childOptions.exprs.join(";\n")}}`);
377
- options.templateId = childOptions.templateId;
378
- options.counter = childOptions.counter;
379
- }
380
- let tag;
381
- if (options.multi) {
382
- tag = `_$el${uuid++}`;
383
- options.decl.push(`${tag} = ${options.path}.${options.first ? "firstChild" : "nextSibling"}`);
384
- }
385
- if (options.parent) options.exprs.push(`r.insert(${options.parent}, r.createComponent(exprs[${componentIdentifier}],${processComponentProps(propGroups)})${tag ? `, ${tag}` : ""})`);else options.exprs.push(`${options.fragment ? "" : "return "}r.createComponent(exprs[${componentIdentifier}],${processComponentProps(propGroups)})`);
386
- options.path = tag;
387
- options.first = false;
388
- }
389
- function parseNode(node, options) {
390
- if (node.type === "fragment") {
391
- const parts = [];
392
- node.children.forEach(child => {
393
- if (child.type === "tag") {
394
- if (child.name === "###") {
395
- const childOptions = Object.assign({}, options, {
396
- first: true,
397
- fragment: true,
398
- decl: [],
399
- exprs: []
400
- });
401
- processComponent(child, childOptions);
402
- parts.push(childOptions.exprs[0]);
403
- options.counter = childOptions.counter;
404
- options.templateId = childOptions.templateId;
405
- return;
406
- }
407
- options.templateId++;
408
- const id = uuid;
409
- const childOptions = Object.assign({}, options, {
410
- first: true,
411
- decl: [],
412
- exprs: []
413
- });
414
- options.templateNodes.push([child]);
415
- parseNode(child, childOptions);
416
- parts.push(`function() { ${childOptions.decl.join(",\n") + ";\n" + childOptions.exprs.join(";\n") + `;\nreturn _$el${id};\n`}}()`);
417
- options.counter = childOptions.counter;
418
- options.templateId = childOptions.templateId;
419
- } else if (child.type === "text") {
420
- parts.push(`"${child.content}"`);
421
- } else if (child.type === "comment") {
422
- if (child.content === "#") parts.push(`exprs[${options.counter++}]`);else if (child.content) {
423
- for (let i = 0; i < child.content.split("###").length - 1; i++) {
424
- parts.push(`exprs[${options.counter++}]`);
425
- }
426
- }
427
- }
428
- });
429
- options.exprs.push(`return [${parts.join(", \n")}]`);
430
- } else if (node.type === "tag") {
431
- const tag = `_$el${uuid++}`;
432
- const topDecl = !options.decl.length;
433
- const templateId = options.templateId;
434
- options.decl.push(topDecl ? "" : `${tag} = ${options.path}.${options.first ? "firstChild" : "nextSibling"}`);
435
- options.isImportNode = node.name.includes("-") || node.attrs.some(e => e.name === "is") || (node.name === "img" || node.name === "iframe") && node.attrs.some(e => e.name === "loading" && e.value === "lazy");
436
- if (node.attrs.some(e => e.name === "###")) {
437
- const spreadArgs = [];
438
- let current = "";
439
- const newAttrs = [];
440
- for (let i = 0; i < node.attrs.length; i++) {
441
- const {
442
- type,
443
- name,
444
- value
445
- } = node.attrs[i];
446
- if (type === "attr") {
447
- if (value.includes("###")) {
448
- let count = options.counter++;
449
- current += `${name}: ${name !== "ref" ? `typeof exprs[${count}] === "function" ? exprs[${count}]() : ` : ""}exprs[${count}],`;
450
- } else if (name === "###") {
451
- if (current.length) {
452
- spreadArgs.push(`()=>({${current}})`);
453
- current = "";
454
- }
455
- spreadArgs.push(`exprs[${options.counter++}]`);
456
- } else {
457
- newAttrs.push(node.attrs[i]);
458
- }
459
- }
460
- }
461
- node.attrs = newAttrs;
462
- if (current.length) {
463
- spreadArgs.push(`()=>({${current}})`);
464
- }
465
- options.exprs.push(`r.spread(${tag},${spreadArgs.length === 1 ? `typeof ${spreadArgs[0]} === "function" ? r.mergeProps(${spreadArgs[0]}) : ${spreadArgs[0]}` : `r.mergeProps(${spreadArgs.join(",")})`},${!!node.children.length})`);
466
- } else {
467
- for (let i = 0; i < node.attrs.length; i++) {
468
- const {
469
- type,
470
- name,
471
- value
472
- } = node.attrs[i];
473
- if (type === "attr") {
474
- if (value.includes("###")) {
475
- node.attrs.splice(i, 1);
476
- i--;
477
- parseAttribute(node, tag, name, value, options);
478
- }
479
- }
480
- }
481
- }
482
- options.path = tag;
483
- options.first = false;
484
- processChildren(node, options);
485
- if (topDecl) {
486
- options.decl[0] = options.isImportNode ? `const ${tag} = document.importNode(tmpls[${templateId}].content.firstChild, true)` : `const ${tag} = tmpls[${templateId}].content.firstChild.cloneNode(true)`;
487
- }
488
- } else if (node.type === "text") {
489
- const tag = `_$el${uuid++}`;
490
- options.decl.push(`${tag} = ${options.path}.${options.first ? "firstChild" : "nextSibling"}`);
491
- options.path = tag;
492
- options.first = false;
493
- } else if (node.type === "comment") {
494
- const tag = `_$el${uuid++}`;
495
- options.decl.push(`${tag} = ${options.path}.${options.first ? "firstChild" : "nextSibling"}`);
496
- if (node.content === "#") {
497
- if (options.multi) {
498
- options.exprs.push(`r.insert(${options.parent}, exprs[${options.counter++}], ${tag})`);
499
- } else options.exprs.push(`r.insert(${options.parent}, exprs[${options.counter++}])`);
500
- }
501
- options.path = tag;
502
- options.first = false;
503
- }
504
- }
505
- function parseTemplate(nodes, funcBuilder) {
506
- const options = {
507
- path: "",
508
- decl: [],
509
- exprs: [],
510
- delegatedEvents: new Set(),
511
- counter: 0,
512
- first: true,
513
- multi: false,
514
- templateId: 0,
515
- templateNodes: []
516
- },
517
- id = uuid,
518
- origNodes = nodes;
519
- let toplevel;
520
- if (nodes.length > 1) {
521
- nodes = [{
522
- type: "fragment",
523
- children: nodes
524
- }];
525
- }
526
- if (nodes[0].name === "###") {
527
- toplevel = true;
528
- processComponent(nodes[0], options);
529
- } else parseNode(nodes[0], options);
530
- r.delegateEvents(Array.from(options.delegatedEvents));
531
- const templateNodes = [origNodes].concat(options.templateNodes);
532
- return [templateNodes.map(t => stringify(t)), funcBuilder("tmpls", "exprs", "r", options.decl.join(",\n") + ";\n" + options.exprs.join(";\n") + (toplevel ? "" : `;\nreturn _$el${id};\n`))];
533
- }
534
- function html(statics, ...args) {
535
- const templates = cache.get(statics) || createTemplate(statics, {
536
- funcBuilder: functionBuilder
537
- });
538
- return templates[0].create(templates, args, r);
539
- }
540
- return html;
541
- }
5
+ const e=e=>t(e)||e>=48&&e<=58||e===46||e===45,t=e=>e>=65&&e<=90||e>=97&&e<=122||e===95||e===36,n=e=>e>=9&&e<=13||e===32,r=(r,i)=>{let a=[],o=0,s=``,c=0;for(let l=0;l<r.length;l++){let u=r[l],d=u.length;for(c=0;c<d;)switch(o){case 0:{s=``;let e=u.indexOf(`<`,c);e===-1?(c<d&&a.push({type:6,value:u.slice(c)}),c=d):(e>c&&a.push({type:6,value:u.slice(c,e)}),u[e+1]===`!`&&u[e+2]===`-`&&u[e+3]===`-`?(o=3,c=e+4):(a.push({type:0}),o=1,c=e+1));break}case 1:{let r=u.charCodeAt(c);if(n(r))c++;else if(r===62)i.has(s)&&a[a.length-1]?.type!==2?o=2:(o=0,s=``),a.push({type:1}),c++;else if(r===61)a.push({type:4}),c++;else if(r===47)a.push({type:2}),c++;else if(r===34||r===39){let e=u[c],t=u.indexOf(e,c+1);if(t===-1)throw Error(`Unterminated string`);a.push({type:5,value:u.slice(c+1,t),quote:e}),c=t+1;}else if(t(r)){let t=c;for(;c<d&&e(u.charCodeAt(c));)c++;let n=u.slice(t,c);s===``&&(s=n),a.push({type:3,value:n});}else if(r===46&&u[c+1]===`.`&&u[c+2]===`.`)a.push({type:8}),c+=3;else throw Error(`Unexpected Character: ${u[c]}`);break}case 2:{let e=RegExp(`<\\s*/\\s*${s}\\s*>`,`g`);e.lastIndex=c;let t=e.exec(u);if(t){let e=t.index;e>c&&a.push({type:6,value:u.slice(c,e)}),o=0,c=e,s=``;}else a.push({type:6,value:u.slice(c)}),c=d;break}case 3:{let e=u.indexOf(`-->`,c);e===-1?c=d:(o=0,c=e+3);break}}l<r.length-1&&o!==3&&a.push({type:7,value:l});}return a},i=e=>{let t=e.charCodeAt(0);return t>=65&&t<=90},a=(e,t)=>{let n={type:0,children:[]},r=[n],a=0,o=e.length;for(;a<o;){let n=e[a],s=r[r.length-1];switch(n.type){case 6:{let t=n.value;if(t.trim()===``){let t=e[a-1]?.type,n=e[a+1]?.type;if(t===1||n===0){a++;continue}}s.children.push({type:3,value:t}),a++;continue}case 7:s.children.push({type:4,value:n.value}),a++;continue;case 0:{let n=e[++a];if(n.type===2){let n=e[++a],i=e[++a],o=r[r.length-1];if(r.length>1&&i.type===1&&(n?.type===3&&o.name===n.value||(n?.type===7||n.type===2)&&typeof o.name==`number`)){let e=r.pop();e?.type===1&&t.has(e.name)&&(e.children=[]),a++;continue}throw Error(`Mismatched closing tag.`)}if(n.type===3||n.type===7){let t=n.value,c={type:typeof t==`number`||i(t)?2:1,name:t,props:[],children:[]};for(s.children.push(c),a++;a<o;){let t=e[a];if(t.type===1||t.type===2)break;if(t.type===8){let t=e[a+1];if(t?.type===7)c.props.push({type:3,value:t.value}),a+=2;else throw Error(`Spread operator must be followed by an expression.`)}else if(t.type===3){let n=t.value;if(e[a+1]?.type===4){a+=2;let t=e[a];if(t.type===7)c.props.push({name:n,type:2,value:t.value}),a++;else if(t.type===5){let e=t.quote;c.props.push({name:n,value:t.value,quote:e,type:1}),a++;}else throw Error(`Attribute value must be an expression or a string.`)}else c.props.push({type:0,name:n,value:true}),a++;}else throw Error(`Invalid attribute.`)}let l=e[a];l.type===2?a+=2:l.type===1&&(a++,r.push(c));continue}}default:throw Error(`Unexpected token: ${JSON.stringify(n)}`)}}if(r.length>1)throw Error(`Unclosed tag found.`);return n},o=e=>e.length===1?e[0]:e;function s(e){let t=new WeakMap,n=document.createTreeWalker(document,129),i=t=>e.SVGElements.has(t)?document.createElementNS(`http://www.w3.org/2000/svg`,t):e.MathMLElements.has(t)?document.createElementNS(`http://www.w3.org/1998/Math/MathML`,t):document.createElement(t),s=e=>{let t=(t,...n)=>p(c(t),n,e);return t.components=e,t.sld=t,t.define=t=>s({...e,...t}),t},c=n=>{let i=t.get(n);return i||(i=a(r(n,e.RawTextElements),e.VoidElements),l(i),t.set(n,i)),i},l=e=>{if(e.type===0||e.type===2){if(e.children.some(e=>e.type===1)){let t=document.createElement(`template`);t.content.append(...e.children.map(d)),e.template=t;}e.children.forEach(l);}else e.type===1&&e.children.forEach(l);},u=document.createElement(`template`),d=e=>{switch(e.type){case 3:return u.innerHTML=e.value,document.createTextNode(u.content.textContent??``);case 4:return document.createComment(`+`);case 2:return document.createComment(e.name);case 1:let t=false,n=i(e.name);return e.props=e.props.filter(e=>e.type===1?e.name.startsWith(`prop:`)?true:(n.setAttribute(e.name,e.value),t):e.type===0?(n.setAttribute(e.name,``),t):e.type===3?(t=true,t):true),n.append(...e.children.map(d)),n}},f=(t,n,r)=>{switch(t.type){case 3:return t.value;case 4:return n[t.value];case 2:let a=typeof t.name==`string`?r[t.name]:n[t.name];if(a&&typeof a==`function`)return e.createComponent(a,m(t,n,r));throw Error(`Component "${t.name}" not found in registry`);case 1:let o=t.name,s=i(o),c=m(t,n,r);return e.spread(s,c,true),s}},p=(t,r,i)=>{if(!t.template)return o(t.children.map(e=>f(e,r,i)));let a=t.template.content.cloneNode(true);n.currentNode=a;let s=t=>{for(let a of t)if(a.type===1||a.type===4||a.type===2){let t=n.nextNode();if(a.type===4||a.type===2)e.insert(t.parentNode,f(a,r,i),t),n.currentNode=t;else {if(a.props.length){let n=m(a,r,i);e.spread(t,n,true);}s(a.children);}}};return s(t.children),a.childNodes.length===1?a.firstChild:Array.from(a.childNodes)},m=(t,n,r,i={})=>{for(let r of t.props)switch(r.type){case 0:i[r.name]=true;break;case 1:i[r.name]=r.value;break;case 2:h(i,r.name,n[r.value]);break;case 3:let t=n[r.value];if(!t||typeof t!=`object`)throw Error(`Can only spread objects`);i=e.mergeProps(i,t);break}return t.type===2&&t.children.length&&Object.defineProperty(i,`children`,{get(){return p(t,n,r)}}),i},h=(e,t,n)=>{typeof n==`function`&&n.length===0&&t!==`ref`&&!t.startsWith(`on`)?Object.defineProperty(e,t,{get(){return n()},enumerable:true}):e[t]=n;};return s({})}
542
6
 
543
- const html = createHTML({
544
- effect: web.effect,
545
- style: web.style,
7
+ const html = s({
546
8
  insert: web.insert,
547
- untrack: web.untrack,
548
9
  spread: web.spread,
549
10
  createComponent: web.createComponent,
550
- delegateEvents: web.delegateEvents,
551
- className: web.className,
552
11
  mergeProps: web.mergeProps,
553
- dynamicProperty: web.dynamicProperty,
554
- setAttribute: web.setAttribute,
555
- setAttributeNS: web.setAttributeNS,
556
- addEventListener: web.addEventListener,
557
- DOMWithState: web.DOMWithState,
558
- ChildProperties: web.ChildProperties,
559
- DelegatedEvents: web.DelegatedEvents,
560
12
  SVGElements: web.SVGElements,
561
13
  MathMLElements: web.MathMLElements,
562
- Namespaces: web.Namespaces
14
+ VoidElements: web.VoidElements,
15
+ RawTextElements: web.RawTextElements
563
16
  });
564
17
 
565
18
  module.exports = html;