@solidjs/html 2.0.0-rc.2 → 2.0.0-rc.21

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
@@ -4,7 +4,7 @@ This sub module provides a Tagged Template Literal `html` method for Solid. This
4
4
 
5
5
  `html` uses `${}` to escape into JavaScript expressions. Components are closed with `<//>`.
6
6
 
7
- Since Solid 2.0, `html` is backed by [`@dom-expressions/tagged-jsx`](https://www.npmjs.com/package/@dom-expressions/tagged-jsx), 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.
7
+ Since Solid 2.0, `html` is an AST-based tagged-template runtime in this package. Templates are parsed at runtime (no `new Function` / `eval`, so it is CSP-safe) and reactive bindings are installed against the resulting DOM.
8
8
 
9
9
  For editor support, the [Tagged JSX Tools VS Code extension](https://marketplace.visualstudio.com/items?itemName=DanielRKling.tagged-jsx-vscode) provides syntax highlighting, formatting, conversion commands, and TypeScript diagnostics for JSX inside tagged template literals.
10
10
 
@@ -92,14 +92,17 @@ html`<div id=${() => props.id}>${() => firstName() + lastName()}</div>`
92
92
 
93
93
  2. Events on components require explicit event in the arguments
94
94
 
95
- Solid's Tagged Template Literals automatically wraps functions passed to props of components with no arguments in getters so you need to provide one to prevent this. The same applies to render props like in the `<For>` component.
95
+ Solid's Tagged Template Literals automatically wrap functions with no arguments passed to props of components in getters, so you need to declare an argument to prevent this. That covers every prop, `onXxx` handlers and `ref` included; the same applies to render props like in the `<For>` component.
96
96
 
97
97
  ```js
98
- // good
99
- html`<${Button} onClick=${(e) => console.log("Hi")} />`;
98
+ // good: passed as a function
99
+ html`<${Button} onClick=${e => console.log("Hi")} />`;
100
100
 
101
- // bad
101
+ // bad: a getter, so `props.onClick` runs `console.log` and reads its result
102
102
  html`<${Button} onClick=${() => console.log("Hi")} />`;
103
+
104
+ // getter: `props.on` reads `key()`
105
+ html`<${Loading} on=${() => key()}>...<//>`;
103
106
  ```
104
107
 
105
108
  4. All refs are callback form
@@ -119,4 +122,13 @@ html`
119
122
  <div>1</div>
120
123
  <div>2</div>
121
124
  `
125
+ ```
126
+
127
+ 6. Only `onXxx` names are event handlers
128
+
129
+ On elements, camelCase `onXxx` names (`on` followed by an uppercase letter) are event handlers and are passed through as functions, as is `ref`. A lowercase `onclick` is a plain attribute, and a zero-argument function passed to it becomes a getter like any other attribute.
130
+
131
+ ```js
132
+ html`<button onClick=${() => save()} />`; // event handler
133
+ html`<button onclick=${() => code()} />`; // reactive `onclick` attribute
122
134
  ```
package/dist/html.js CHANGED
@@ -1,18 +1,550 @@
1
- import { RawTextElements, VoidElements, MathMLElements, SVGElements, claimElement, mergeProps, createComponent, spread, insert } from '@solidjs/web';
1
+ import { RawTextElements, spread, claimElement, createComponent, insert, mergeProps, SVGElements, MathMLElements, VoidElements } from '@solidjs/web';
2
2
 
3
- 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-2]?.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){let e=u.charCodeAt(c+1),t=u.slice(c+2).search(/\S/),n=e===47&&a[a.length-1]?.type===0&&t!==-1&&u[c+2+t]===`>`;e===47&&!n?o=4:e===42?o=5:(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 at ${l}:${c}`);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]} at ${l}:${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:case 4:case 5:{let e=o===4?`
4
- `:o===5?`*/`:`-->`,t=u.indexOf(e,c);t===-1?c=d:(o=o===3?0:1,c=t+e.length);break}}l<r.length-1&&(o===0||o===1||o===2)&&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 for <${o.name}>`)}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 in <${c.name}> 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 for "${n}" in <${c.name}> must be an expression or a string`)}else c.props.push({type:0,name:n,value:true}),a++;}else throw Error(`Invalid attribute in <${c.name}>`)}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)} after <${r[r.length-1].name}>`)}}if(r.length>1)throw Error(`Unclosed tag for <${r[r.length-1].name}>`);return n},o=e=>e.length===1?e[0]:e;function s(e){let t=new WeakMap,n=new Set(e.RawTextElements);n.delete(`template`);let i=document.createTreeWalker(document,129),s=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),c=e=>{let t=(t,...n)=>m(l(t),n,e);return t.components=e,t.jsx=t,t.define=t=>c({...e,...t}),t},l=i=>{let o=t.get(i);return o||(o=a(r(i,n),e.VoidElements),u(o,false),t.set(i,o)),o},u=(e,t)=>{if(e.type===1){if(!t){let n=document.createElement(`template`);n.content.appendChild(f(e)),e.template=n,t=true;}e.children.forEach(e=>u(e,t));}else e.type===2||e.type===0?e.children.forEach(e=>u(e,false)):e.type===3&&!t&&(d.innerHTML=e.value,e.value=d.content.textContent??``);},d=document.createElement(`template`),f=e=>{switch(e.type){case 3:return d.innerHTML=e.value,document.createTextNode(d.content.textContent??``);case 4:return document.createComment(`+`);case 2:return document.createComment(e.name);case 1:let t=false,n=s(e.name),r=e.name===`a`?`href`:e.name===`form`?`action`:void 0;return e.props=e.props.filter(i=>i.type===1?i.name.startsWith(`prop:`)?true:(n.setAttribute(i.name,i.value),!t&&i.name===r&&(e.claim=true),t):i.type===0?(n.setAttribute(i.name,``),!t&&i.name===r&&(e.claim=true),t):i.type===3?(t=true,t):true),(e.name===`template`?n.content:n).append(...e.children.map(f)),n}},p=(t,n,r)=>{switch(t.type){case 3:return t.value;case 4:return n[t.value];case 2:let i=typeof t.name==`string`?r[t.name]:n[t.name];if(i&&typeof i==`function`)return e.createComponent(i,h(t,n,r));throw Error(`Component "${t.name}" not found in registry`);case 1:let a=m(t,n,r),o=h(t,n,r);return e.spread(a,o,true),t.claim&&e.claimElement(a),a}},m=(t,n,r)=>{if(t.type!==1||!t.template)return o(t.children.map(e=>p(e,n,r)));let a=t.template.content.firstChild.cloneNode(true);i.currentNode=a;let s=(t,i)=>{for(let a of t)if(a.type===1||a.type===4||a.type===2){let t=i.nextNode();if(a.type===4||a.type===2)e.insert(t.parentNode,p(a,n,r),t),i.currentNode=t;else {if(a.props.length){let i=h(a,n,r);e.spread(t,i,true);}a.claim&&e.claimElement(t),s(a.children,a.name===`template`?document.createTreeWalker(t.content,129):i);}}};return s(t.children,t.name===`template`?document.createTreeWalker(a.content,129):i),a},h=(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:g(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 m(t,n,r)}}),i},g=(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 c({})}
3
+ const OPEN_TAG_TOKEN = 0;
4
+ const CLOSE_TAG_TOKEN = 1;
5
+ const SLASH_TOKEN = 2;
6
+ const IDENTIFIER_TOKEN = 3;
7
+ const EQUALS_TOKEN = 4;
8
+ const STRING_TOKEN = 5;
9
+ const TEXT_TOKEN = 6;
10
+ const EXPRESSION_TOKEN = 7;
11
+ const SPREAD_TOKEN = 8;
12
+ const isIdentifierChar = code => {
13
+ return isIdentifierStart(code) || code >= 48 && code <= 58 ||
14
+ code === 46 ||
15
+ code === 45
16
+ ;
17
+ };
18
+ const isIdentifierStart = code => {
19
+ return code >= 65 && code <= 90 ||
20
+ code >= 97 && code <= 122 ||
21
+ code === 95 ||
22
+ code === 36
23
+ ;
24
+ };
25
+ const isWhitespace = code => {
26
+ return code >= 9 && code <= 13 || code === 32;
27
+ };
28
+ const STATE_TEXT = 0;
29
+ const STATE_TAG = 1;
30
+ const STATE_RAW_TEXT = 2;
31
+ const STATE_COMMENT = 3;
32
+ const STATE_LINE_COMMENT = 4;
33
+ const STATE_BLOCK_COMMENT = 5;
34
+ const STATE_BRACED_COMMENT = 6;
35
+ const tokenize = (strings, rawTextElements) => {
36
+ const tokens = [];
37
+ let state = STATE_TEXT;
38
+ let lastTagName = "";
39
+ let cursor = 0;
40
+ for (let i = 0; i < strings.length; i++) {
41
+ const str = strings[i];
42
+ const len = str.length;
43
+ cursor = 0;
44
+ while (cursor < len) {
45
+ switch (state) {
46
+ case STATE_TEXT:
47
+ {
48
+ lastTagName = "";
49
+ const nextTag = str.indexOf("<", cursor);
50
+ const nextBracedComment = str.indexOf("{/*", cursor);
51
+ const nextComment = nextBracedComment !== -1 && (nextTag === -1 || nextBracedComment < nextTag) ? nextBracedComment : -1;
52
+ if (nextComment !== -1) {
53
+ if (nextComment > cursor) tokens.push({
54
+ type: TEXT_TOKEN,
55
+ value: str.slice(cursor, nextComment)
56
+ });
57
+ state = STATE_BRACED_COMMENT;
58
+ cursor = nextComment + 3;
59
+ } else if (nextTag === -1) {
60
+ if (cursor < len) tokens.push({
61
+ type: TEXT_TOKEN,
62
+ value: str.slice(cursor)
63
+ });
64
+ cursor = len;
65
+ } else {
66
+ if (nextTag > cursor) tokens.push({
67
+ type: TEXT_TOKEN,
68
+ value: str.slice(cursor, nextTag)
69
+ });
70
+ if (str[nextTag + 1] === "!" && str[nextTag + 2] === "-" && str[nextTag + 3] === "-") {
71
+ state = STATE_COMMENT;
72
+ cursor = nextTag + 4;
73
+ } else {
74
+ tokens.push({
75
+ type: OPEN_TAG_TOKEN
76
+ });
77
+ state = STATE_TAG;
78
+ cursor = nextTag + 1;
79
+ }
80
+ }
81
+ break;
82
+ }
83
+ case STATE_TAG:
84
+ {
85
+ const code = str.charCodeAt(cursor);
86
+ if (isWhitespace(code)) {
87
+ cursor++;
88
+ } else if (code === 62) {
89
+ if (rawTextElements.has(lastTagName) && tokens[tokens.length - 1]?.type !== SLASH_TOKEN && tokens[tokens.length - 2]?.type !== SLASH_TOKEN) {
90
+ state = STATE_RAW_TEXT;
91
+ } else {
92
+ state = STATE_TEXT;
93
+ lastTagName = "";
94
+ }
95
+ tokens.push({
96
+ type: CLOSE_TAG_TOKEN
97
+ });
98
+ cursor++;
99
+ } else if (code === 61) {
100
+ tokens.push({
101
+ type: EQUALS_TOKEN
102
+ });
103
+ cursor++;
104
+ } else if (code === 47) {
105
+ const next = str.charCodeAt(cursor + 1);
106
+ const nextNonWhitespace = str.slice(cursor + 2).search(/\S/);
107
+ const isShorthandClosingTag = next === 47 && tokens[tokens.length - 1]?.type === OPEN_TAG_TOKEN && nextNonWhitespace !== -1 && str[cursor + 2 + nextNonWhitespace] === ">";
108
+ if (next === 47 && !isShorthandClosingTag) {
109
+ state = STATE_LINE_COMMENT;
110
+ } else if (next === 42) {
111
+ state = STATE_BLOCK_COMMENT;
112
+ } else {
113
+ tokens.push({
114
+ type: SLASH_TOKEN
115
+ });
116
+ cursor++;
117
+ }
118
+ } else if (code === 34 || code === 39) {
119
+ const char = str[cursor];
120
+ const endQuoteIndex = str.indexOf(char, cursor + 1);
121
+ if (endQuoteIndex === -1) {
122
+ throw new Error(`Unterminated string at ${i}:${cursor}`);
123
+ }
124
+ tokens.push({
125
+ type: STRING_TOKEN,
126
+ value: str.slice(cursor + 1, endQuoteIndex),
127
+ quote: char
128
+ });
129
+ cursor = endQuoteIndex + 1;
130
+ } else if (isIdentifierStart(code)) {
131
+ const start = cursor;
132
+ while (cursor < len && isIdentifierChar(str.charCodeAt(cursor))) cursor++;
133
+ const value = str.slice(start, cursor);
134
+ if (tokens[tokens.length - 1]?.type === OPEN_TAG_TOKEN) {
135
+ lastTagName = value;
136
+ }
137
+ tokens.push({
138
+ type: IDENTIFIER_TOKEN,
139
+ value
140
+ });
141
+ } else if (code === 46 && str[cursor + 1] === "." && str[cursor + 2] === ".") {
142
+ tokens.push({
143
+ type: SPREAD_TOKEN
144
+ });
145
+ cursor += 3;
146
+ } else {
147
+ throw new Error(`Unexpected Character: ${str[cursor]} at ${i}:${cursor}`);
148
+ }
149
+ break;
150
+ }
151
+ case STATE_RAW_TEXT:
152
+ {
153
+ const closeTagRegex = new RegExp(`<\\s*/\\s*${lastTagName}\\s*>`, "g");
154
+ closeTagRegex.lastIndex = cursor;
155
+ const match = closeTagRegex.exec(str);
156
+ if (match) {
157
+ const endOfRawIdx = match.index;
158
+ if (endOfRawIdx > cursor) {
159
+ tokens.push({
160
+ type: TEXT_TOKEN,
161
+ value: str.slice(cursor, endOfRawIdx)
162
+ });
163
+ }
164
+ state = STATE_TEXT;
165
+ cursor = endOfRawIdx;
166
+ lastTagName = "";
167
+ } else {
168
+ tokens.push({
169
+ type: TEXT_TOKEN,
170
+ value: str.slice(cursor)
171
+ });
172
+ cursor = len;
173
+ }
174
+ break;
175
+ }
176
+ case STATE_COMMENT:
177
+ case STATE_BRACED_COMMENT:
178
+ case STATE_LINE_COMMENT:
179
+ case STATE_BLOCK_COMMENT:
180
+ {
181
+ const commentEnd = state === STATE_LINE_COMMENT ? "\n" : state === STATE_BLOCK_COMMENT ? "*/" : state === STATE_BRACED_COMMENT ? "*/}" : "-->";
182
+ const commentEndIndex = str.indexOf(commentEnd, cursor);
183
+ if (commentEndIndex === -1) {
184
+ cursor = len;
185
+ } else {
186
+ state = state === STATE_COMMENT || state === STATE_BRACED_COMMENT ? STATE_TEXT : STATE_TAG;
187
+ cursor = commentEndIndex + commentEnd.length;
188
+ }
189
+ break;
190
+ }
191
+ }
192
+ }
193
+ if (i < strings.length - 1) {
194
+ if (state === STATE_TEXT || state === STATE_TAG || state === STATE_RAW_TEXT) {
195
+ tokens.push({
196
+ type: EXPRESSION_TOKEN,
197
+ value: i
198
+ });
199
+ }
200
+ }
201
+ }
202
+ return tokens;
203
+ };
5
204
 
6
- const html = s({
7
- insert,
8
- spread,
9
- createComponent,
10
- mergeProps,
11
- claimElement,
12
- SVGElements,
13
- MathMLElements,
14
- VoidElements,
15
- RawTextElements
16
- });
205
+ const isComponentNode = name => {
206
+ const char = name.charCodeAt(0);
207
+ return char >= 65 && char <= 90
208
+ ;
209
+ };
210
+ const ROOT_NODE = 0;
211
+ const ELEMENT_NODE = 1;
212
+ const COMPONENT_NODE = 2;
213
+ const TEXT_NODE = 3;
214
+ const EXPRESSION_NODE = 4;
215
+ const BOOLEAN_PROP = 0;
216
+ const STATIC_PROP = 1;
217
+ const EXPRESSION_PROP = 2;
218
+ const SPREAD_PROP = 3;
219
+ const parse = (tokens, voidElements) => {
220
+ const root = {
221
+ type: ROOT_NODE,
222
+ children: []
223
+ };
224
+ const stack = [root];
225
+ let pos = 0;
226
+ const len = tokens.length;
227
+ while (pos < len) {
228
+ const token = tokens[pos];
229
+ const parent = stack[stack.length - 1];
230
+ switch (token.type) {
231
+ case TEXT_TOKEN:
232
+ {
233
+ const value = token.value;
234
+ if (value.trim() === "") {
235
+ const prevType = tokens[pos - 1]?.type;
236
+ const nextType = tokens[pos + 1]?.type;
237
+ if (prevType === CLOSE_TAG_TOKEN || nextType === OPEN_TAG_TOKEN) {
238
+ pos++;
239
+ continue;
240
+ }
241
+ }
242
+ parent.children.push({
243
+ type: TEXT_NODE,
244
+ value
245
+ });
246
+ pos++;
247
+ continue;
248
+ }
249
+ case EXPRESSION_TOKEN:
250
+ {
251
+ parent.children.push({
252
+ type: EXPRESSION_NODE,
253
+ value: token.value
254
+ });
255
+ pos++;
256
+ continue;
257
+ }
258
+ case OPEN_TAG_TOKEN:
259
+ {
260
+ const nextToken = tokens[++pos];
261
+ if (nextToken.type === SLASH_TOKEN) {
262
+ const nameToken = tokens[++pos];
263
+ const closeToken = tokens[++pos];
264
+ const currentParent = stack[stack.length - 1];
265
+ if (stack.length > 1 && closeToken.type === CLOSE_TAG_TOKEN && (nameToken?.type === IDENTIFIER_TOKEN && currentParent.name === nameToken.value || (nameToken?.type === EXPRESSION_TOKEN || nameToken.type === SLASH_TOKEN) && typeof currentParent.name === "number")) {
266
+ const node = stack.pop();
267
+ if (node?.type === ELEMENT_NODE && voidElements.has(node.name)) {
268
+ node.children = [];
269
+ }
270
+ pos++;
271
+ continue;
272
+ }
273
+ throw new Error(`Mismatched closing tag for <${currentParent.name}>`);
274
+ }
275
+ if (nextToken.type === IDENTIFIER_TOKEN || nextToken.type === EXPRESSION_TOKEN) {
276
+ const tagName = nextToken.value;
277
+ const node = {
278
+ type: typeof tagName === "number" || isComponentNode(tagName) ? COMPONENT_NODE : ELEMENT_NODE,
279
+ name: tagName,
280
+ props: [],
281
+ children: []
282
+ };
283
+ parent.children.push(node);
284
+ pos++;
285
+ while (pos < len) {
286
+ const attrToken = tokens[pos];
287
+ if (attrToken.type === CLOSE_TAG_TOKEN || attrToken.type === SLASH_TOKEN) {
288
+ break;
289
+ }
290
+ if (attrToken.type === SPREAD_TOKEN) {
291
+ const expr = tokens[pos + 1];
292
+ if (expr?.type === EXPRESSION_TOKEN) {
293
+ node.props.push({
294
+ type: SPREAD_PROP,
295
+ value: expr.value
296
+ });
297
+ pos += 2;
298
+ } else {
299
+ throw new Error(`Spread operator in <${node.name}> must be followed by an expression`);
300
+ }
301
+ } else if (attrToken.type === IDENTIFIER_TOKEN) {
302
+ const name = attrToken.value;
303
+ const next = tokens[pos + 1];
304
+ if (next?.type === EQUALS_TOKEN) {
305
+ pos += 2;
306
+ const valToken = tokens[pos];
307
+ if (valToken.type === EXPRESSION_TOKEN) {
308
+ node.props.push({
309
+ name,
310
+ type: EXPRESSION_PROP,
311
+ value: valToken.value
312
+ });
313
+ pos++;
314
+ } else if (valToken.type === STRING_TOKEN) {
315
+ const quote = valToken.quote;
316
+ node.props.push({
317
+ name,
318
+ value: valToken.value,
319
+ quote,
320
+ type: STATIC_PROP
321
+ });
322
+ pos++;
323
+ } else {
324
+ throw new Error(`Attribute value for "${name}" in <${node.name}> must be an expression or a string`);
325
+ }
326
+ } else {
327
+ node.props.push({
328
+ type: BOOLEAN_PROP,
329
+ name,
330
+ value: true
331
+ });
332
+ pos++;
333
+ }
334
+ } else {
335
+ throw new Error(`Invalid attribute in <${node.name}>`);
336
+ }
337
+ }
338
+ const endToken = tokens[pos];
339
+ if (endToken.type === SLASH_TOKEN) {
340
+ pos += 2;
341
+ } else if (endToken.type === CLOSE_TAG_TOKEN) {
342
+ pos++;
343
+ stack.push(node);
344
+ }
345
+ continue;
346
+ }
347
+ }
348
+ default:
349
+ throw new Error(`Unexpected token: ${JSON.stringify(token)} after <${stack[stack.length - 1].name}>`);
350
+ }
351
+ }
352
+ if (stack.length > 1) {
353
+ throw new Error(`Unclosed tag for <${stack[stack.length - 1].name}>`);
354
+ }
355
+ return root;
356
+ };
357
+
358
+ const flat = arr => {
359
+ return arr.length === 1 ? arr[0] : arr;
360
+ };
361
+ function createHtml() {
362
+ const cache = new WeakMap();
363
+ const rawTextElements = new Set(RawTextElements);
364
+ rawTextElements.delete("template");
365
+ const walker = document.createTreeWalker(document, 129);
366
+ const createElement = name => {
367
+ return SVGElements.has(name) ? document.createElementNS("http://www.w3.org/2000/svg", name) : MathMLElements.has(name) ? document.createElementNS("http://www.w3.org/1998/Math/MathML", name) : document.createElement(name);
368
+ };
369
+ const createTaggedJSX = components => {
370
+ const tag = (strings, ...values) => {
371
+ const root = getCachedRoot(strings);
372
+ return renderChildren(root, values, components);
373
+ };
374
+ tag.components = components;
375
+ tag.jsx = tag;
376
+ tag.define = newComponents => {
377
+ return createTaggedJSX({
378
+ ...components,
379
+ ...newComponents
380
+ });
381
+ };
382
+ return tag;
383
+ };
384
+ const getCachedRoot = strings => {
385
+ let root = cache.get(strings);
386
+ if (!root) {
387
+ root = parse(tokenize(strings, rawTextElements), VoidElements);
388
+ buildTemplate(root, false);
389
+ cache.set(strings, root);
390
+ }
391
+ return root;
392
+ };
393
+ const buildTemplate = (node, insideTemplate) => {
394
+ if (node.type === ELEMENT_NODE) {
395
+ if (!insideTemplate) {
396
+ const template = document.createElement("template");
397
+ template.content.appendChild(buildNodes(node));
398
+ node.template = template;
399
+ insideTemplate = true;
400
+ }
401
+ node.children.forEach(child => buildTemplate(child, insideTemplate));
402
+ } else if (node.type === COMPONENT_NODE || node.type === ROOT_NODE) {
403
+ if (node.type === COMPONENT_NODE) decodeStaticProps(node);
404
+ node.children.forEach(child => buildTemplate(child, false));
405
+ } else if (node.type === TEXT_NODE && !insideTemplate) {
406
+ textTemplate.innerHTML = node.value;
407
+ node.value = textTemplate.content.textContent ?? "";
408
+ }
409
+ };
410
+ const textTemplate = document.createElement("template");
411
+ const decodeStaticProps = node => {
412
+ for (const prop of node.props) {
413
+ if (prop.type !== STATIC_PROP || !prop.value.includes("&")) continue;
414
+ textTemplate.innerHTML = `<i a="${prop.value.replace(/"/g, "&quot;")}"></i>`;
415
+ prop.value = textTemplate.content.firstChild.getAttribute("a");
416
+ }
417
+ };
418
+ const buildNodes = node => {
419
+ switch (node.type) {
420
+ case TEXT_NODE:
421
+ textTemplate.innerHTML = node.value;
422
+ return document.createTextNode(textTemplate.content.textContent ?? "");
423
+ case EXPRESSION_NODE:
424
+ return document.createComment("+");
425
+ case COMPONENT_NODE:
426
+ return document.createComment(node.name);
427
+ case ELEMENT_NODE:
428
+ let hasSpread = false;
429
+ const elem = createElement(node.name);
430
+ const claimAttr = node.name === "a" ? "href" : node.name === "form" ? "action" : undefined;
431
+ decodeStaticProps(node);
432
+ node.props = node.props.filter(prop => {
433
+ if (prop.type === STATIC_PROP) {
434
+ if (prop.name.startsWith("prop:")) return true;
435
+ elem.setAttribute(prop.name, prop.value);
436
+ if (!hasSpread && prop.name === claimAttr) node.claim = true;
437
+ return hasSpread;
438
+ } else if (prop.type === BOOLEAN_PROP) {
439
+ elem.setAttribute(prop.name, "");
440
+ if (!hasSpread && prop.name === claimAttr) node.claim = true;
441
+ return hasSpread;
442
+ } else if (prop.type === SPREAD_PROP) {
443
+ hasSpread = true;
444
+ return hasSpread;
445
+ }
446
+ return true;
447
+ });
448
+ const childRoot = node.name === "template" ? elem.content : elem;
449
+ childRoot.append(...node.children.map(buildNodes));
450
+ return elem;
451
+ }
452
+ };
453
+ const renderNode = (node, values, components) => {
454
+ switch (node.type) {
455
+ case TEXT_NODE:
456
+ return node.value;
457
+ case EXPRESSION_NODE:
458
+ return values[node.value];
459
+ case COMPONENT_NODE:
460
+ const component = typeof node.name === "string" ? components[node.name] : values[node.name];
461
+ if (component && typeof component === "function") {
462
+ return createComponent(component, gatherProps(node, values, components));
463
+ } else {
464
+ throw new Error(`Component "${node.name}" not found in registry`);
465
+ }
466
+ case ELEMENT_NODE:
467
+ const element = renderChildren(node, values, components);
468
+ const props = gatherProps(node, values, components);
469
+ spread(element, props, true);
470
+ if (node.claim) claimElement(element);
471
+ return element;
472
+ }
473
+ };
474
+ const renderChildren = (node, values, components) => {
475
+ if (node.type !== ELEMENT_NODE || !node.template) {
476
+ return flat(node.children.map(n => renderNode(n, values, components)));
477
+ }
478
+ const element = node.template.content.firstChild.cloneNode(true);
479
+ walker.currentNode = element;
480
+ const walkNodes = (nodes, walker) => {
481
+ for (const node of nodes) {
482
+ if (node.type === ELEMENT_NODE || node.type === EXPRESSION_NODE || node.type === COMPONENT_NODE) {
483
+ const domNode = walker.nextNode();
484
+ if (node.type === EXPRESSION_NODE || node.type === COMPONENT_NODE) {
485
+ insert(domNode.parentNode, renderNode(node, values, components), domNode);
486
+ walker.currentNode = domNode;
487
+ } else {
488
+ if (node.props.length) {
489
+ const props = gatherProps(node, values, components);
490
+ spread(domNode, props, true);
491
+ }
492
+ if (node.claim) claimElement(domNode);
493
+ walkNodes(node.children, node.name === "template" ? document.createTreeWalker(domNode.content, 129) : walker);
494
+ }
495
+ }
496
+ }
497
+ };
498
+ walkNodes(node.children, node.name === "template" ? document.createTreeWalker(element.content, 129) : walker);
499
+ return element;
500
+ };
501
+ const gatherProps = (node, values, components, props = {}) => {
502
+ const sources = [];
503
+ let own = props;
504
+ for (const prop of node.props) {
505
+ switch (prop.type) {
506
+ case BOOLEAN_PROP:
507
+ own[prop.name] = true;
508
+ break;
509
+ case STATIC_PROP:
510
+ own[prop.name] = prop.value;
511
+ break;
512
+ case EXPRESSION_PROP:
513
+ applyGetter(own, prop.name, values[prop.value], node.type === COMPONENT_NODE);
514
+ break;
515
+ case SPREAD_PROP:
516
+ const spreadValue = values[prop.value];
517
+ if (!spreadValue || typeof spreadValue !== "object") throw new Error("Can only spread objects");
518
+ sources.push(own, spreadValue);
519
+ own = {};
520
+ break;
521
+ }
522
+ }
523
+ if (node.type === COMPONENT_NODE && node.children.length) {
524
+ Object.defineProperty(own, "children", {
525
+ get() {
526
+ return renderChildren(node, values, components);
527
+ }
528
+ });
529
+ }
530
+ if (sources.length === 0) return own;
531
+ sources.push(own);
532
+ return mergeProps(...sources);
533
+ };
534
+ const applyGetter = (props, name, value, component) => {
535
+ if (typeof value === "function" && value.length === 0 && (component || name !== "ref" && !/^on[A-Z]/.test(name))) {
536
+ Object.defineProperty(props, name, {
537
+ get() {
538
+ return value();
539
+ },
540
+ enumerable: true
541
+ });
542
+ } else {
543
+ props[name] = value;
544
+ }
545
+ };
546
+ return createTaggedJSX({});
547
+ }
548
+ const html = createHtml();
17
549
 
18
550
  export { html as default };