solid-optimizer 1.0.0-next.6 → 1.0.0-next.7

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/src/nesting.ts ADDED
@@ -0,0 +1,325 @@
1
+ /**
2
+ * Keeps every template valid HTML.
3
+ *
4
+ * Solid's JSX transform puts an element and the elements written inside it
5
+ * into one HTML template. It rejects a template that a browser would parse
6
+ * into another tree, such as `<p><div></div></p>`, which parses as
7
+ * `<p></p><div></div><p></p>`. Before the passes, such an element is often
8
+ * apart from the template: `<p><Box /></p>` inserts the `<div>` that `Box`
9
+ * returns at runtime, which works. Inlining `Box`, resolving `<Show>`,
10
+ * unrolling `<For>`, or resolving `<Dynamic>` puts the `<div>` into the
11
+ * `<p>`'s template, and the build fails.
12
+ *
13
+ * This pass checks each template the way Solid does: it parses the
14
+ * template's tags as the body's `innerHTML` and compares the result. When
15
+ * the tree changes, the element that changes it is wrapped in `{}`. An
16
+ * element in an expression container starts its own template and is
17
+ * inserted at runtime, as it was before the pass.
18
+ */
19
+ import type { JSXChild, JSXElement, Node } from 'oxc-parser';
20
+ import type { DefaultTreeAdapterMap } from 'parse5';
21
+ import { parseFragment, parse as parseHTML, serialize } from 'parse5';
22
+ import { forEachChild, isIntrinsicTag } from './ast';
23
+ import type { PassContext } from './context';
24
+
25
+ const VOID_ELEMENTS = new Set([
26
+ 'area',
27
+ 'base',
28
+ 'br',
29
+ 'col',
30
+ 'embed',
31
+ 'hr',
32
+ 'img',
33
+ 'input',
34
+ 'keygen',
35
+ 'link',
36
+ 'meta',
37
+ 'param',
38
+ 'source',
39
+ 'track',
40
+ 'wbr',
41
+ ]);
42
+
43
+ // Solid's list of SVG tags, from dom-expressions. `a`, `script`, `style`, and
44
+ // `title` are in both namespaces, so a template rooted at one is HTML.
45
+ const SVG_ELEMENTS = new Set([
46
+ 'altGlyph',
47
+ 'altGlyphDef',
48
+ 'altGlyphItem',
49
+ 'animate',
50
+ 'animateColor',
51
+ 'animateMotion',
52
+ 'animateTransform',
53
+ 'circle',
54
+ 'clipPath',
55
+ 'cursor',
56
+ 'defs',
57
+ 'desc',
58
+ 'ellipse',
59
+ 'feBlend',
60
+ 'feColorMatrix',
61
+ 'feComponentTransfer',
62
+ 'feComposite',
63
+ 'feConvolveMatrix',
64
+ 'feDiffuseLighting',
65
+ 'feDisplacementMap',
66
+ 'feDistantLight',
67
+ 'feDropShadow',
68
+ 'feFlood',
69
+ 'feFuncA',
70
+ 'feFuncB',
71
+ 'feFuncG',
72
+ 'feFuncR',
73
+ 'feGaussianBlur',
74
+ 'feImage',
75
+ 'feMerge',
76
+ 'feMergeNode',
77
+ 'feMorphology',
78
+ 'feOffset',
79
+ 'fePointLight',
80
+ 'feSpecularLighting',
81
+ 'feSpotLight',
82
+ 'feTile',
83
+ 'feTurbulence',
84
+ 'filter',
85
+ 'font',
86
+ 'foreignObject',
87
+ 'g',
88
+ 'glyph',
89
+ 'glyphRef',
90
+ 'hkern',
91
+ 'image',
92
+ 'line',
93
+ 'linearGradient',
94
+ 'marker',
95
+ 'mask',
96
+ 'metadata',
97
+ 'mpath',
98
+ 'path',
99
+ 'pattern',
100
+ 'polygon',
101
+ 'polyline',
102
+ 'radialGradient',
103
+ 'rect',
104
+ 'set',
105
+ 'stop',
106
+ 'switch',
107
+ 'symbol',
108
+ 'text',
109
+ 'textPath',
110
+ 'tref',
111
+ 'tspan',
112
+ 'use',
113
+ 'view',
114
+ 'vkern',
115
+ ]);
116
+
117
+ type ParentNode = DefaultTreeAdapterMap['parentNode'];
118
+
119
+ function findElement(parent: ParentNode, name: string): ParentNode {
120
+ for (const child of parent.childNodes) {
121
+ if (child.nodeName === name && 'childNodes' in child) {
122
+ return child;
123
+ }
124
+ }
125
+ throw new Error(`[solid-optimizer] no <${name}> in an empty document`);
126
+ }
127
+
128
+ let body: ParentNode | undefined;
129
+
130
+ /** What a browser makes of `html` set as the body's `innerHTML`. */
131
+ function parseAsBody(html: string): string {
132
+ body ??= findElement(
133
+ findElement(parseHTML('<!DOCTYPE html><html><body></body></html>'), 'html'),
134
+ 'body',
135
+ );
136
+ return serialize(parseFragment(body, html, {}));
137
+ }
138
+
139
+ /** The tag of an intrinsic element, or `undefined` for a component or a namespaced tag. */
140
+ function readIntrinsicTag(element: JSXElement): string | undefined {
141
+ const name = element.openingElement.name;
142
+ return name.type === 'JSXIdentifier' && isIntrinsicTag(name.name) ? name.name : undefined;
143
+ }
144
+
145
+ /** A template element and the elements in the same template. */
146
+ interface TemplateNode {
147
+ readonly element: JSXElement;
148
+ readonly tag: string;
149
+ readonly children: TemplateNode[];
150
+ }
151
+
152
+ /**
153
+ * The template rooted at `element`. Elements inside fragments join it.
154
+ * Elements in expression containers or under a component start their own.
155
+ */
156
+ function collectTemplate(element: JSXElement, tag: string): TemplateNode {
157
+ const node: TemplateNode = { element, tag, children: [] };
158
+ addTemplateChildren(node, element.children);
159
+ return node;
160
+ }
161
+
162
+ function addTemplateChildren(node: TemplateNode, children: readonly JSXChild[]): void {
163
+ for (const child of children) {
164
+ if (child.type === 'JSXFragment') {
165
+ addTemplateChildren(node, child.children);
166
+ } else if (child.type === 'JSXElement') {
167
+ const tag = readIntrinsicTag(child);
168
+ if (tag !== undefined) {
169
+ node.children.push(collectTemplate(child, tag));
170
+ }
171
+ }
172
+ }
173
+ }
174
+
175
+ /**
176
+ * The tags of a template, without text or attributes. Elements not in
177
+ * `included` are left out with what they hold.
178
+ */
179
+ function writeTags(node: TemplateNode, included: ReadonlySet<TemplateNode>): string {
180
+ if (VOID_ELEMENTS.has(node.tag)) {
181
+ return `<${node.tag}>`;
182
+ }
183
+ let inner = '';
184
+ for (const child of node.children) {
185
+ if (included.has(child)) {
186
+ inner += writeTags(child, included);
187
+ }
188
+ }
189
+ return `<${node.tag}>${inner}</${node.tag}>`;
190
+ }
191
+
192
+ /**
193
+ * Table parts parse only inside a table, and SVG parts only inside an
194
+ * `<svg>`, so a template rooted at one is checked inside one, as Solid
195
+ * creates it.
196
+ */
197
+ function placeInContext(tag: string, html: string): string {
198
+ if (SVG_ELEMENTS.has(tag)) {
199
+ return `<svg>${html}</svg>`;
200
+ }
201
+ switch (tag) {
202
+ case 'td':
203
+ case 'th':
204
+ return `<table><tbody><tr>${html}</tr></tbody></table>`;
205
+ case 'tr':
206
+ return `<table><tbody>${html}</tbody></table>`;
207
+ case 'col':
208
+ return `<table><colgroup>${html}</colgroup></table>`;
209
+ case 'thead':
210
+ case 'tbody':
211
+ case 'tfoot':
212
+ case 'colgroup':
213
+ case 'caption':
214
+ return `<table>${html}</table>`;
215
+ default:
216
+ return html;
217
+ }
218
+ }
219
+
220
+ /** Whether a `<template>` in the template holds an element, which Solid rejects. */
221
+ function hasTemplateContent(node: TemplateNode, included: ReadonlySet<TemplateNode>): boolean {
222
+ for (const child of node.children) {
223
+ if (included.has(child) && (node.tag === 'template' || hasTemplateContent(child, included))) {
224
+ return true;
225
+ }
226
+ }
227
+ return false;
228
+ }
229
+
230
+ function isValidTemplate(root: TemplateNode, included: ReadonlySet<TemplateNode>): boolean {
231
+ if (hasTemplateContent(root, included)) {
232
+ return false;
233
+ }
234
+ const html = placeInContext(root.tag, writeTags(root, included));
235
+ return parseAsBody(html).toLowerCase() === html.toLowerCase();
236
+ }
237
+
238
+ function collectAll(node: TemplateNode, into: Set<TemplateNode>): Set<TemplateNode> {
239
+ into.add(node);
240
+ for (const child of node.children) {
241
+ collectAll(child, into);
242
+ }
243
+ return into;
244
+ }
245
+
246
+ /**
247
+ * Wraps the elements that make `root`'s template parse differently, and
248
+ * returns the wrapped elements, each the root of a template of its own.
249
+ */
250
+ function wrapInvalidElements(context: PassContext, root: TemplateNode): TemplateNode[] {
251
+ if (isValidTemplate(root, collectAll(root, new Set()))) {
252
+ return [];
253
+ }
254
+ // A template that is already wrong without its children is the source's own.
255
+ const included = new Set([root]);
256
+ if (!isValidTemplate(root, included)) {
257
+ return [];
258
+ }
259
+ // Add the elements one at a time, in source order, and keep apart each one
260
+ // that changes the parse. A kept-apart element takes what it holds along.
261
+ const wrapped: TemplateNode[] = [];
262
+ const pending: TemplateNode[] = [];
263
+ pushChildren(pending, root);
264
+ for (let node = pending.pop(); node; node = pending.pop()) {
265
+ included.add(node);
266
+ if (!isValidTemplate(root, included)) {
267
+ included.delete(node);
268
+ // Each brace sticks to its own element, so two wrapped neighbors read `}{`.
269
+ context.s.prependRight(node.element.start, '{');
270
+ context.s.appendLeft(node.element.end, '}');
271
+ wrapped.push(node);
272
+ continue;
273
+ }
274
+ pushChildren(pending, node);
275
+ }
276
+ return wrapped;
277
+ }
278
+
279
+ /** Pushes the children of `node` so that they pop in source order. */
280
+ function pushChildren(pending: TemplateNode[], node: TemplateNode): void {
281
+ for (let index = node.children.length - 1; index >= 0; index -= 1) {
282
+ pending.push(node.children[index]);
283
+ }
284
+ }
285
+
286
+ export function repairNesting(context: PassContext): boolean {
287
+ const roots: TemplateNode[] = [];
288
+ const visit = (node: Node, inTemplate: boolean): void => {
289
+ if (node.type === 'JSXElement') {
290
+ const tag = readIntrinsicTag(node);
291
+ if (tag !== undefined && !inTemplate) {
292
+ roots.push(collectTemplate(node, tag));
293
+ }
294
+ // An intrinsic element's children join its template. A component's
295
+ // children, an expression container, and an attribute value start over.
296
+ for (const child of node.children) {
297
+ visit(child, tag !== undefined);
298
+ }
299
+ for (const attribute of node.openingElement.attributes) {
300
+ visit(attribute, false);
301
+ }
302
+ return;
303
+ }
304
+ if (node.type === 'JSXFragment') {
305
+ for (const child of node.children) {
306
+ visit(child, inTemplate);
307
+ }
308
+ return;
309
+ }
310
+ forEachChild(node, (child) => {
311
+ visit(child, false);
312
+ });
313
+ };
314
+ visit(context.program, false);
315
+
316
+ let changed = false;
317
+ for (let root = roots.pop(); root; root = roots.pop()) {
318
+ const wrapped = wrapInvalidElements(context, root);
319
+ if (wrapped.length > 0) {
320
+ changed = true;
321
+ roots.push(...wrapped);
322
+ }
323
+ }
324
+ return changed;
325
+ }