@sigil-dev/compiler 0.9.26 → 0.9.28

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.
@@ -1,355 +1,356 @@
1
- import { types as t } from "@babel/core";
2
- import { isImportRead, isStoreRead } from "../util/props.ts";
3
-
4
- export const ATTR_MAP: Record<string, string> = {
5
- class: "className",
6
- for: "htmlFor",
7
- };
8
-
9
- /**
10
- * The names the compiler treats as reactive in one file.
11
- *
12
- * A `Set` of signal names, plus `reactiveFns`: same-file functions that read
13
- * one (see `collectReactiveFns`). Kept on the same object so the many
14
- * `containsSignal(expr, signals)` call sites need no new argument.
15
- */
16
- export class SignalScope extends Set<string> {
17
- readonly reactiveFns = new Set<string>();
18
- override clear(): void {
19
- super.clear();
20
- this.reactiveFns.clear();
21
- }
22
- }
23
-
24
- export function containsSignal(
25
- expr: t.Expression | t.Node,
26
- signals: Set<string>,
27
- asCallee = false,
28
- ): boolean {
29
- if (!expr) return false;
30
- if (t.isIdentifier(expr)) return signals.has(expr.name);
31
- if (t.isCallExpression(expr)) {
32
- if (isStoreRead(expr)) return true;
33
- // `label()` where label reads a signal inside its body
34
- if (
35
- t.isIdentifier(expr.callee) &&
36
- (signals as Partial<SignalScope>).reactiveFns?.has(expr.callee.name)
37
- ) {
38
- return true;
39
- }
40
- return (
41
- containsSignal(expr.callee as t.Expression, signals, true) ||
42
- expr.arguments.some((a) => containsSignal(a as t.Expression, signals))
43
- );
44
- }
45
- // a read on an imported store; `utils.format` as a callee is not one
46
- if (!asCallee && isImportRead(expr)) return true;
47
- if (t.isBinaryExpression(expr)) {
48
- return (
49
- containsSignal(expr.left as t.Expression, signals) ||
50
- containsSignal(expr.right, signals)
51
- );
52
- }
53
- if (t.isMemberExpression(expr)) {
54
- return containsSignal(expr.object as t.Expression, signals);
55
- }
56
- if (t.isLogicalExpression(expr)) {
57
- return (
58
- containsSignal(expr.left as t.Expression, signals) ||
59
- containsSignal(expr.right as t.Expression, signals)
60
- );
61
- }
62
- if (t.isConditionalExpression(expr)) {
63
- return (
64
- containsSignal(expr.test as t.Expression, signals) ||
65
- containsSignal(expr.consequent as t.Expression, signals) ||
66
- containsSignal(expr.alternate as t.Expression, signals)
67
- );
68
- }
69
- if (t.isUnaryExpression(expr)) {
70
- return containsSignal(expr.argument as t.Expression, signals);
71
- }
72
- if (t.isTemplateLiteral(expr)) {
73
- return expr.expressions.some((e) =>
74
- containsSignal(e as t.Expression, signals),
75
- );
76
- }
77
- // ── additions ──
78
- if (t.isArrayExpression(expr)) {
79
- return expr.elements.some(
80
- (e) => e !== null && containsSignal(e as t.Expression, signals),
81
- );
82
- }
83
- if (t.isObjectExpression(expr)) {
84
- return expr.properties.some((p) => {
85
- if (t.isObjectProperty(p)) {
86
- const computedKey = p.computed
87
- ? containsSignal(p.key as t.Expression, signals)
88
- : false;
89
- return computedKey || containsSignal(p.value as t.Expression, signals);
90
- }
91
- if (t.isSpreadElement(p)) return containsSignal(p.argument, signals);
92
- return false;
93
- });
94
- }
95
- if (t.isSequenceExpression(expr)) {
96
- return expr.expressions.some((e) => containsSignal(e, signals));
97
- }
98
- if (t.isAssignmentExpression(expr)) {
99
- return containsSignal(expr.right, signals);
100
- }
101
- if (t.isSpreadElement(expr)) {
102
- return containsSignal(expr.argument, signals);
103
- }
104
- // ArrowFunction/Function — don't traverse, signals inside are captured
105
- // not reactive at the call site (onclick={() => count()} is fine as-is)
106
- if (t.isArrowFunctionExpression(expr) || t.isFunctionExpression(expr)) {
107
- return false;
108
- }
109
- // Babel represents ?. as distinct node types not in t.is* guards
110
- if (t.isOptionalMemberExpression(expr)) {
111
- return containsSignal((expr as any).object, signals);
112
- }
113
- if (t.isOptionalCallExpression(expr)) {
114
- const n = expr as any;
115
- return (
116
- containsSignal(n.callee, signals) ||
117
- n.arguments.some((a: t.Node) => containsSignal(a, signals))
118
- );
119
- }
120
- return false;
121
- }
122
-
123
- export function isPrimitive(expr: t.Expression): boolean {
124
- if (t.isCallExpression(expr) && t.isIdentifier(expr.callee)) return true;
125
- if (t.isBinaryExpression(expr)) return true;
126
- if (t.isTemplateLiteral(expr)) return true;
127
- if (t.isIdentifier(expr)) return true;
128
- // user().name is a MemberExpression after state handler rewrites user → user()
129
- if (t.isMemberExpression(expr)) return true;
130
- return false;
131
- }
132
-
133
- /**
134
- * Generate createElement call. In hydrate mode, claims from node pool.
135
- * When parentVar is provided, passes it to claim() for SPA fallback (append on create).
136
- */
137
- export function getCreateElement(
138
- tag: string,
139
- hydrate: boolean,
140
- nodesVar = "__nodes",
141
- parentVar?: string,
142
- ): t.Expression {
143
- if (hydrate) {
144
- const args: t.Expression[] = [t.identifier(nodesVar), t.stringLiteral(tag)];
145
- if (parentVar) {
146
- args.push(t.identifier(parentVar));
147
- }
148
- return t.callExpression(t.identifier("claim"), args);
149
- }
150
- return t.callExpression(
151
- t.memberExpression(t.identifier("document"), t.identifier("createElement")),
152
- [t.stringLiteral(tag)],
153
- );
154
- }
155
-
156
- /**
157
- * Generate createTextNode call. In hydrate mode, claims from node pool.
158
- * When parentVar is provided, passes it to claimText() for SPA fallback.
159
- */
160
- export function getCreateText(
161
- hydrate: boolean,
162
- nodesVar = "__nodes",
163
- parentVar?: string,
164
- ): t.Expression {
165
- if (hydrate) {
166
- const args: t.Expression[] = [t.identifier(nodesVar)];
167
- if (parentVar) {
168
- args.push(t.identifier(parentVar));
169
- }
170
- return t.callExpression(t.identifier("claimText"), args);
171
- }
172
- return t.callExpression(
173
- t.memberExpression(
174
- t.identifier("document"),
175
- t.identifier("createTextNode"),
176
- ),
177
- [t.stringLiteral("")],
178
- );
179
- }
180
-
181
- /**
182
- * Generate `const <nodesVar> = Array.from(el.childNodes)` for hydration scope.
183
- * Returns the generated variable name for use by children.
184
- */
185
- export function buildHydrationScope(
186
- parentVar: string,
187
- statements: t.Statement[],
188
- nodesVar: string,
189
- ): void {
190
- statements.push(
191
- t.variableDeclaration("const", [
192
- t.variableDeclarator(
193
- t.identifier(nodesVar),
194
- t.callExpression(
195
- t.memberExpression(t.identifier("Array"), t.identifier("from")),
196
- [
197
- t.memberExpression(
198
- t.identifier(parentVar),
199
- t.identifier("childNodes"),
200
- ),
201
- ],
202
- ),
203
- ),
204
- ]),
205
- );
206
- }
207
-
208
- /** Text that takes no space before it: closing punctuation. */
209
- const NO_SPACE_BEFORE =
210
- /^[.,;:!?)\]}%\u2019\u201d\u00bb\u2026\u3001\u3002\u300d\u300f\uff09\uff0c\uff0e\uff1a\uff1b\uff01\uff1f]/;
211
- /** Text that takes no space after it: opening brackets and quotes. */
212
- const NO_SPACE_AFTER = /[(\[{\u2018\u201c\u00ab\u300c\u300e\uff08\/]$/;
213
- /** Japanese and Chinese run words together, so a line break there is no space. */
214
- const CJK =
215
- /[\u3000-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff00-\uffef]/;
216
-
217
- /** The sibling an inline neighbour is: an element or an expression, past comments. */
218
- function neighbour(
219
- siblings: readonly t.Node[],
220
- from: number,
221
- step: 1 | -1,
222
- ): t.Node | null {
223
- for (let i = from + step; i >= 0 && i < siblings.length; i += step) {
224
- const n = siblings[i] as t.Node;
225
- if (t.isJSXExpressionContainer(n) && t.isJSXEmptyExpression(n.expression))
226
- continue;
227
- return n;
228
- }
229
- return null;
230
- }
231
- /** Elements that sit in a line of text, where HTML renders a line break between two of them as a space. */
232
- const INLINE = new Set([
233
- "a",
234
- "abbr",
235
- "b",
236
- "bdi",
237
- "bdo",
238
- "cite",
239
- "code",
240
- "data",
241
- "dfn",
242
- "em",
243
- "i",
244
- "kbd",
245
- "mark",
246
- "q",
247
- "s",
248
- "samp",
249
- "small",
250
- "span",
251
- "strong",
252
- "sub",
253
- "sup",
254
- "time",
255
- "u",
256
- "var",
257
- ]);
258
- const isInline = (n: t.Node | null) =>
259
- n !== null &&
260
- t.isJSXElement(n) &&
261
- t.isJSXIdentifier(n.openingElement.name) &&
262
- INLINE.has(n.openingElement.name.name);
263
-
264
- const isNode = (n: t.Node | null) =>
265
- n !== null &&
266
- (t.isJSXElement(n) ||
267
- t.isJSXFragment(n) ||
268
- t.isJSXExpressionContainer(n) ||
269
- t.isJSXSpreadChild(n));
270
-
271
- /**
272
- * The text a JSXText child renders, or null when nothing is left. Whitespace
273
- * that doesn't touch a line break is kept, so `Hello <b>big</b> world` keeps
274
- * both spaces. Lines that are only whitespace vanish, the remaining lines
275
- * join with one space, and the whitespace at the start and end of an
276
- * element's content goes, so indentation never becomes text.
277
- *
278
- * Unlike React's rule, a line break between text and an element or
279
- * expression next to it reads as a space, the way it does in HTML:
280
- *
281
- * loaded from
282
- * <a href="…">sekai.best</a>.
283
- *
284
- * is "loaded from sekai.best." with no {" "}. No space goes before closing
285
- * punctuation (</a>⏎.), after an opening bracket or quote, or next to
286
- * Japanese and Chinese text. Pass the parent's children as `siblings` to get
287
- * this; without them (a <script>'s text) the line breaks just go.
288
- *
289
- * Every mode (ssr, hydrate, dom) must go through this: if they disagree,
290
- * server HTML and client-rendered pages show different text.
291
- */
292
- export function jsxText(
293
- child: t.JSXText,
294
- siblings?: readonly t.Node[],
295
- ): string | null {
296
- const lines = child.value.split(/\r\n|\n|\r/);
297
- let lastNonEmpty = 0;
298
- for (let i = 0; i < lines.length; i++) {
299
- if (/[^ \t]/.test(lines[i] as string)) lastNonEmpty = i;
300
- }
301
- let out = "";
302
- for (let i = 0; i < lines.length; i++) {
303
- let line = (lines[i] as string).replace(/\t/g, " ");
304
- if (i !== 0) line = line.replace(/^ +/, "");
305
- if (i !== lines.length - 1) line = line.replace(/ +$/, "");
306
- if (!line) continue;
307
- out += i === lastNonEmpty ? line : `${line} `;
308
- }
309
- if (!out) {
310
- // a line break between two inline elements is a space, as in HTML:
311
- // <a href="…">three.js</a>
312
- // <span>by the three.js authors</span>
313
- // Between anything else (blocks, components) it is indentation.
314
- if (siblings && /[\r\n]/.test(child.value)) {
315
- const at = siblings.indexOf(child);
316
- if (
317
- isInline(neighbour(siblings, at, -1)) &&
318
- isInline(neighbour(siblings, at, 1))
319
- )
320
- return " ";
321
- }
322
- return null;
323
- }
324
- if (!siblings) return out;
325
-
326
- const at = siblings.indexOf(child);
327
- // a line break before the text, after an element or expression
328
- if (
329
- /^[ \t]*[\r\n]/.test(child.value) &&
330
- isNode(neighbour(siblings, at, -1))
331
- ) {
332
- if (!NO_SPACE_BEFORE.test(out) && !CJK.test(out[0] as string))
333
- out = ` ${out}`;
334
- }
335
- // a line break after the text, before an element or expression
336
- if (/[\r\n][ \t]*$/.test(child.value) && isNode(neighbour(siblings, at, 1))) {
337
- if (!NO_SPACE_AFTER.test(out) && !CJK.test(out.at(-1) as string))
338
- out = `${out} `;
339
- }
340
- return out;
341
- }
342
-
343
- /** JSX that runs when the expression is evaluated (not inside a function). */
344
- export function hasJSX(expr: t.Node): boolean {
345
- if (t.isJSXElement(expr) || t.isJSXFragment(expr)) return true;
346
- if (t.isConditionalExpression(expr))
347
- return hasJSX(expr.consequent) || hasJSX(expr.alternate);
348
- if (t.isLogicalExpression(expr))
349
- return hasJSX(expr.left) || hasJSX(expr.right);
350
- if (t.isParenthesizedExpression(expr) || t.isTSAsExpression(expr))
351
- return hasJSX(expr.expression);
352
- if (t.isArrayExpression(expr))
353
- return expr.elements.some((e) => e !== null && hasJSX(e));
354
- return false;
355
- }
1
+ import { types as t } from "@babel/core";
2
+ import { isImportRead } from "../util/props.ts";
3
+ import { STATE_READS } from "../util/state-imports.ts";
4
+
5
+ export const ATTR_MAP: Record<string, string> = {
6
+ class: "className",
7
+ for: "htmlFor",
8
+ };
9
+
10
+ /**
11
+ * The names the compiler treats as reactive in one file.
12
+ *
13
+ * A `Set` of signal names, plus `reactiveFns`: same-file functions that read
14
+ * one (see `collectReactiveFns`). Kept on the same object so the many
15
+ * `containsSignal(expr, signals)` call sites need no new argument.
16
+ */
17
+ export class SignalScope extends Set<string> {
18
+ readonly reactiveFns = new Set<string>();
19
+ override clear(): void {
20
+ super.clear();
21
+ this.reactiveFns.clear();
22
+ }
23
+ }
24
+
25
+ export function containsSignal(
26
+ expr: t.Expression | t.Node,
27
+ signals: Set<string>,
28
+ asCallee = false,
29
+ ): boolean {
30
+ if (!expr) return false;
31
+ if (t.isIdentifier(expr)) return signals.has(expr.name);
32
+ if (t.isCallExpression(expr)) {
33
+ if (STATE_READS.has(expr)) return true;
34
+ // `label()` where label reads a signal inside its body
35
+ if (
36
+ t.isIdentifier(expr.callee) &&
37
+ (signals as Partial<SignalScope>).reactiveFns?.has(expr.callee.name)
38
+ ) {
39
+ return true;
40
+ }
41
+ return (
42
+ containsSignal(expr.callee as t.Expression, signals, true) ||
43
+ expr.arguments.some((a) => containsSignal(a as t.Expression, signals))
44
+ );
45
+ }
46
+ // a read on an imported store; `utils.format` as a callee is not one
47
+ if (!asCallee && isImportRead(expr)) return true;
48
+ if (t.isBinaryExpression(expr)) {
49
+ return (
50
+ containsSignal(expr.left as t.Expression, signals) ||
51
+ containsSignal(expr.right, signals)
52
+ );
53
+ }
54
+ if (t.isMemberExpression(expr)) {
55
+ return containsSignal(expr.object as t.Expression, signals);
56
+ }
57
+ if (t.isLogicalExpression(expr)) {
58
+ return (
59
+ containsSignal(expr.left as t.Expression, signals) ||
60
+ containsSignal(expr.right as t.Expression, signals)
61
+ );
62
+ }
63
+ if (t.isConditionalExpression(expr)) {
64
+ return (
65
+ containsSignal(expr.test as t.Expression, signals) ||
66
+ containsSignal(expr.consequent as t.Expression, signals) ||
67
+ containsSignal(expr.alternate as t.Expression, signals)
68
+ );
69
+ }
70
+ if (t.isUnaryExpression(expr)) {
71
+ return containsSignal(expr.argument as t.Expression, signals);
72
+ }
73
+ if (t.isTemplateLiteral(expr)) {
74
+ return expr.expressions.some((e) =>
75
+ containsSignal(e as t.Expression, signals),
76
+ );
77
+ }
78
+ // ── additions ──
79
+ if (t.isArrayExpression(expr)) {
80
+ return expr.elements.some(
81
+ (e) => e !== null && containsSignal(e as t.Expression, signals),
82
+ );
83
+ }
84
+ if (t.isObjectExpression(expr)) {
85
+ return expr.properties.some((p) => {
86
+ if (t.isObjectProperty(p)) {
87
+ const computedKey = p.computed
88
+ ? containsSignal(p.key as t.Expression, signals)
89
+ : false;
90
+ return computedKey || containsSignal(p.value as t.Expression, signals);
91
+ }
92
+ if (t.isSpreadElement(p)) return containsSignal(p.argument, signals);
93
+ return false;
94
+ });
95
+ }
96
+ if (t.isSequenceExpression(expr)) {
97
+ return expr.expressions.some((e) => containsSignal(e, signals));
98
+ }
99
+ if (t.isAssignmentExpression(expr)) {
100
+ return containsSignal(expr.right, signals);
101
+ }
102
+ if (t.isSpreadElement(expr)) {
103
+ return containsSignal(expr.argument, signals);
104
+ }
105
+ // ArrowFunction/Function — don't traverse, signals inside are captured
106
+ // not reactive at the call site (onclick={() => count()} is fine as-is)
107
+ if (t.isArrowFunctionExpression(expr) || t.isFunctionExpression(expr)) {
108
+ return false;
109
+ }
110
+ // Babel represents ?. as distinct node types not in t.is* guards
111
+ if (t.isOptionalMemberExpression(expr)) {
112
+ return containsSignal((expr as any).object, signals);
113
+ }
114
+ if (t.isOptionalCallExpression(expr)) {
115
+ const n = expr as any;
116
+ return (
117
+ containsSignal(n.callee, signals) ||
118
+ n.arguments.some((a: t.Node) => containsSignal(a, signals))
119
+ );
120
+ }
121
+ return false;
122
+ }
123
+
124
+ export function isPrimitive(expr: t.Expression): boolean {
125
+ if (t.isCallExpression(expr) && t.isIdentifier(expr.callee)) return true;
126
+ if (t.isBinaryExpression(expr)) return true;
127
+ if (t.isTemplateLiteral(expr)) return true;
128
+ if (t.isIdentifier(expr)) return true;
129
+ // user().name is a MemberExpression after state handler rewrites user → user()
130
+ if (t.isMemberExpression(expr)) return true;
131
+ return false;
132
+ }
133
+
134
+ /**
135
+ * Generate createElement call. In hydrate mode, claims from node pool.
136
+ * When parentVar is provided, passes it to claim() for SPA fallback (append on create).
137
+ */
138
+ export function getCreateElement(
139
+ tag: string,
140
+ hydrate: boolean,
141
+ nodesVar = "__nodes",
142
+ parentVar?: string,
143
+ ): t.Expression {
144
+ if (hydrate) {
145
+ const args: t.Expression[] = [t.identifier(nodesVar), t.stringLiteral(tag)];
146
+ if (parentVar) {
147
+ args.push(t.identifier(parentVar));
148
+ }
149
+ return t.callExpression(t.identifier("claim"), args);
150
+ }
151
+ return t.callExpression(
152
+ t.memberExpression(t.identifier("document"), t.identifier("createElement")),
153
+ [t.stringLiteral(tag)],
154
+ );
155
+ }
156
+
157
+ /**
158
+ * Generate createTextNode call. In hydrate mode, claims from node pool.
159
+ * When parentVar is provided, passes it to claimText() for SPA fallback.
160
+ */
161
+ export function getCreateText(
162
+ hydrate: boolean,
163
+ nodesVar = "__nodes",
164
+ parentVar?: string,
165
+ ): t.Expression {
166
+ if (hydrate) {
167
+ const args: t.Expression[] = [t.identifier(nodesVar)];
168
+ if (parentVar) {
169
+ args.push(t.identifier(parentVar));
170
+ }
171
+ return t.callExpression(t.identifier("claimText"), args);
172
+ }
173
+ return t.callExpression(
174
+ t.memberExpression(
175
+ t.identifier("document"),
176
+ t.identifier("createTextNode"),
177
+ ),
178
+ [t.stringLiteral("")],
179
+ );
180
+ }
181
+
182
+ /**
183
+ * Generate `const <nodesVar> = Array.from(el.childNodes)` for hydration scope.
184
+ * Returns the generated variable name for use by children.
185
+ */
186
+ export function buildHydrationScope(
187
+ parentVar: string,
188
+ statements: t.Statement[],
189
+ nodesVar: string,
190
+ ): void {
191
+ statements.push(
192
+ t.variableDeclaration("const", [
193
+ t.variableDeclarator(
194
+ t.identifier(nodesVar),
195
+ t.callExpression(
196
+ t.memberExpression(t.identifier("Array"), t.identifier("from")),
197
+ [
198
+ t.memberExpression(
199
+ t.identifier(parentVar),
200
+ t.identifier("childNodes"),
201
+ ),
202
+ ],
203
+ ),
204
+ ),
205
+ ]),
206
+ );
207
+ }
208
+
209
+ /** Text that takes no space before it: closing punctuation. */
210
+ const NO_SPACE_BEFORE =
211
+ /^[.,;:!?)\]}%\u2019\u201d\u00bb\u2026\u3001\u3002\u300d\u300f\uff09\uff0c\uff0e\uff1a\uff1b\uff01\uff1f]/;
212
+ /** Text that takes no space after it: opening brackets and quotes. */
213
+ const NO_SPACE_AFTER = /[(\[{\u2018\u201c\u00ab\u300c\u300e\uff08\/]$/;
214
+ /** Japanese and Chinese run words together, so a line break there is no space. */
215
+ const CJK =
216
+ /[\u3000-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff00-\uffef]/;
217
+
218
+ /** The sibling an inline neighbour is: an element or an expression, past comments. */
219
+ function neighbour(
220
+ siblings: readonly t.Node[],
221
+ from: number,
222
+ step: 1 | -1,
223
+ ): t.Node | null {
224
+ for (let i = from + step; i >= 0 && i < siblings.length; i += step) {
225
+ const n = siblings[i] as t.Node;
226
+ if (t.isJSXExpressionContainer(n) && t.isJSXEmptyExpression(n.expression))
227
+ continue;
228
+ return n;
229
+ }
230
+ return null;
231
+ }
232
+ /** Elements that sit in a line of text, where HTML renders a line break between two of them as a space. */
233
+ const INLINE = new Set([
234
+ "a",
235
+ "abbr",
236
+ "b",
237
+ "bdi",
238
+ "bdo",
239
+ "cite",
240
+ "code",
241
+ "data",
242
+ "dfn",
243
+ "em",
244
+ "i",
245
+ "kbd",
246
+ "mark",
247
+ "q",
248
+ "s",
249
+ "samp",
250
+ "small",
251
+ "span",
252
+ "strong",
253
+ "sub",
254
+ "sup",
255
+ "time",
256
+ "u",
257
+ "var",
258
+ ]);
259
+ const isInline = (n: t.Node | null) =>
260
+ n !== null &&
261
+ t.isJSXElement(n) &&
262
+ t.isJSXIdentifier(n.openingElement.name) &&
263
+ INLINE.has(n.openingElement.name.name);
264
+
265
+ const isNode = (n: t.Node | null) =>
266
+ n !== null &&
267
+ (t.isJSXElement(n) ||
268
+ t.isJSXFragment(n) ||
269
+ t.isJSXExpressionContainer(n) ||
270
+ t.isJSXSpreadChild(n));
271
+
272
+ /**
273
+ * The text a JSXText child renders, or null when nothing is left. Whitespace
274
+ * that doesn't touch a line break is kept, so `Hello <b>big</b> world` keeps
275
+ * both spaces. Lines that are only whitespace vanish, the remaining lines
276
+ * join with one space, and the whitespace at the start and end of an
277
+ * element's content goes, so indentation never becomes text.
278
+ *
279
+ * Unlike React's rule, a line break between text and an element or
280
+ * expression next to it reads as a space, the way it does in HTML:
281
+ *
282
+ * loaded from
283
+ * <a href="…">sekai.best</a>.
284
+ *
285
+ * is "loaded from sekai.best." with no {" "}. No space goes before closing
286
+ * punctuation (</a>⏎.), after an opening bracket or quote, or next to
287
+ * Japanese and Chinese text. Pass the parent's children as `siblings` to get
288
+ * this; without them (a <script>'s text) the line breaks just go.
289
+ *
290
+ * Every mode (ssr, hydrate, dom) must go through this: if they disagree,
291
+ * server HTML and client-rendered pages show different text.
292
+ */
293
+ export function jsxText(
294
+ child: t.JSXText,
295
+ siblings?: readonly t.Node[],
296
+ ): string | null {
297
+ const lines = child.value.split(/\r\n|\n|\r/);
298
+ let lastNonEmpty = 0;
299
+ for (let i = 0; i < lines.length; i++) {
300
+ if (/[^ \t]/.test(lines[i] as string)) lastNonEmpty = i;
301
+ }
302
+ let out = "";
303
+ for (let i = 0; i < lines.length; i++) {
304
+ let line = (lines[i] as string).replace(/\t/g, " ");
305
+ if (i !== 0) line = line.replace(/^ +/, "");
306
+ if (i !== lines.length - 1) line = line.replace(/ +$/, "");
307
+ if (!line) continue;
308
+ out += i === lastNonEmpty ? line : `${line} `;
309
+ }
310
+ if (!out) {
311
+ // a line break between two inline elements is a space, as in HTML:
312
+ // <a href="…">three.js</a>
313
+ // <span>by the three.js authors</span>
314
+ // Between anything else (blocks, components) it is indentation.
315
+ if (siblings && /[\r\n]/.test(child.value)) {
316
+ const at = siblings.indexOf(child);
317
+ if (
318
+ isInline(neighbour(siblings, at, -1)) &&
319
+ isInline(neighbour(siblings, at, 1))
320
+ )
321
+ return " ";
322
+ }
323
+ return null;
324
+ }
325
+ if (!siblings) return out;
326
+
327
+ const at = siblings.indexOf(child);
328
+ // a line break before the text, after an element or expression
329
+ if (
330
+ /^[ \t]*[\r\n]/.test(child.value) &&
331
+ isNode(neighbour(siblings, at, -1))
332
+ ) {
333
+ if (!NO_SPACE_BEFORE.test(out) && !CJK.test(out[0] as string))
334
+ out = ` ${out}`;
335
+ }
336
+ // a line break after the text, before an element or expression
337
+ if (/[\r\n][ \t]*$/.test(child.value) && isNode(neighbour(siblings, at, 1))) {
338
+ if (!NO_SPACE_AFTER.test(out) && !CJK.test(out.at(-1) as string))
339
+ out = `${out} `;
340
+ }
341
+ return out;
342
+ }
343
+
344
+ /** JSX that runs when the expression is evaluated (not inside a function). */
345
+ export function hasJSX(expr: t.Node): boolean {
346
+ if (t.isJSXElement(expr) || t.isJSXFragment(expr)) return true;
347
+ if (t.isConditionalExpression(expr))
348
+ return hasJSX(expr.consequent) || hasJSX(expr.alternate);
349
+ if (t.isLogicalExpression(expr))
350
+ return hasJSX(expr.left) || hasJSX(expr.right);
351
+ if (t.isParenthesizedExpression(expr) || t.isTSAsExpression(expr))
352
+ return hasJSX(expr.expression);
353
+ if (t.isArrayExpression(expr))
354
+ return expr.elements.some((e) => e !== null && hasJSX(e));
355
+ return false;
356
+ }