@oxy.so/bloom-language-codemod 0.0.0-stage → 0.2.0

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.
@@ -0,0 +1,4454 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.cleanJsxText = cleanJsxText;
37
+ exports.transformSource = transformSource;
38
+ /**
39
+ * The codemod: one source file's JSX regions rewritten as language chains.
40
+ *
41
+ * A region is a JSX element the codemod converts whole, with everything
42
+ * inside it: React Native's `View` and `Pressable` (a stack), Bloom's `Text`
43
+ * (`@oxy.so/bloom/typography`) and Bloom's icons. A child it cannot convert
44
+ * stays JSX inside the chain (`Embed`), and its own children are regions of
45
+ * their own. An element that cannot convert stays as it is and is reported
46
+ * with every reason. A region is placed back in its JSX with `toElement()`.
47
+ *
48
+ * Nothing is guessed: each utility lands through the className table
49
+ * (`resolve.ts`), each prop through the short list below, and anything else
50
+ * is a reason.
51
+ */
52
+ const node_fs_1 = require("node:fs");
53
+ const node_path_1 = require("node:path");
54
+ const recast = __importStar(require("recast"));
55
+ const babelTs = __importStar(require("recast/parsers/babel-ts"));
56
+ const components_1 = require("./components");
57
+ const resolve_1 = require("./resolve");
58
+ const style_1 = require("./style");
59
+ const table_1 = require("./table");
60
+ const n = recast.types.namedTypes;
61
+ const spec = JSON.parse((0, node_fs_1.readFileSync)((0, node_path_1.join)(table_1.LANGUAGE_PACKAGE, 'spec/language.json'), 'utf8'));
62
+ /** The roles the universal `.role()` takes, each React Native's `accessibilityRole` of its name. */
63
+ const ROLES = new Set(spec.enums.role);
64
+ /** A React Native `fontWeight` as the spec's weight of that value (`'700'` is `bold`). */
65
+ const WEIGHT_BY_VALUE = {
66
+ ...Object.fromEntries(Object.entries(spec.scales.weight).map(([name, value]) => [value, name])),
67
+ bold: 'bold',
68
+ normal: 'regular',
69
+ };
70
+ /** What a scroll view's content view takes: the layout of one view. */
71
+ const CONTENT_VIEW = new Set(spec.contentView.modifiers);
72
+ /** The modifiers each constructor's node takes: its own, and the universal ones unless it opts out. */
73
+ const NODE_MODIFIERS = new Map();
74
+ for (const node of Object.values(spec.nodes)) {
75
+ if (typeof node === 'string')
76
+ continue;
77
+ const taken = new Set([
78
+ ...(node.modifiers ?? []),
79
+ ...(node.universal === false ? [] : spec.universal),
80
+ ]);
81
+ for (const constructor of node.constructors ?? [])
82
+ NODE_MODIFIERS.set(constructor, taken);
83
+ }
84
+ /** React Native's `accessibilityLiveRegion` values, each the language's `.liveRegion()` of its name. */
85
+ const LIVE_REGIONS = new Set(spec.enums.liveRegion);
86
+ /** An opacity (`0.7`) as the opacity token of its value (`'70'`): a `TouchableOpacity`'s `activeOpacity`. */
87
+ const OPACITY_TOKEN = new Map(Object.entries(spec.scales.opacity)
88
+ .filter(([name]) => name !== '$comment')
89
+ .map(([name, value]) => [value, name]));
90
+ /** A hit slop in points (`8`) as the hit slop token of its value (`'md'`); a name of Bloom's (`tokens.hitSlop.md`) as itself. */
91
+ const HIT_SLOP = Object.fromEntries(Object.entries(spec.scales.hitSlop).filter(([name]) => name !== '$comment'));
92
+ const HIT_SLOP_TOKEN = new Map(Object.entries(HIT_SLOP).map(([name, value]) => [value, name]));
93
+ /** One side's slop: a static number, or Bloom's `tokens.hitSlop.<name>`, as its token. */
94
+ function hitSlopToken(value) {
95
+ const number = staticNumber(value);
96
+ if (number !== undefined)
97
+ return HIT_SLOP_TOKEN.get(number);
98
+ const expression = n.JSXExpressionContainer.check(value) ? value.expression : value;
99
+ if (n.MemberExpression.check(expression) &&
100
+ !expression.computed &&
101
+ n.Identifier.check(expression.property) &&
102
+ n.MemberExpression.check(expression.object) &&
103
+ n.Identifier.check(expression.object.property) &&
104
+ expression.object.property.name === 'hitSlop' &&
105
+ expression.property.name in HIT_SLOP)
106
+ return expression.property.name;
107
+ return undefined;
108
+ }
109
+ /**
110
+ * React Native's `hitSlop` as `.hitSlop()` calls: one slop is one call; an
111
+ * object of static sides is a call per pair of equal opposite sides (or per
112
+ * side), only the sides it names. Undefined when any side is no token.
113
+ */
114
+ function hitSlopCalls(value) {
115
+ const one = hitSlopToken(value);
116
+ if (one !== undefined)
117
+ return [[one]];
118
+ const object = n.JSXExpressionContainer.check(value) ? value.expression : value;
119
+ if (!n.ObjectExpression.check(object))
120
+ return undefined;
121
+ const sides = {};
122
+ for (const property of object.properties) {
123
+ if (!(n.ObjectProperty.check(property) || n.Property.check(property)) ||
124
+ property.computed ||
125
+ !n.Identifier.check(property.key) ||
126
+ !['top', 'bottom', 'left', 'right'].includes(property.key.name))
127
+ return undefined;
128
+ const token = hitSlopToken(property.value);
129
+ if (token === undefined)
130
+ return undefined;
131
+ sides[property.key.name] = token;
132
+ }
133
+ const { top, bottom, left, right } = sides;
134
+ if (top !== undefined && top === bottom && bottom === left && left === right)
135
+ return [[top]];
136
+ const calls = [];
137
+ const pair = (edge, a, b, sideA, sideB) => {
138
+ if (a !== undefined && a === b)
139
+ calls.push([edge, a]);
140
+ else {
141
+ if (a !== undefined)
142
+ calls.push([sideA, a]);
143
+ if (b !== undefined)
144
+ calls.push([sideB, b]);
145
+ }
146
+ };
147
+ pair('vertical', top, bottom, 'top', 'bottom');
148
+ pair('horizontal', left, right, 'left', 'right');
149
+ return calls;
150
+ }
151
+ /** The roles the theme's palette paints (the surface fill is the surface's: `useSurfaceFill()`). */
152
+ const PALETTE = Object.entries(spec.colors).filter((entry) => Array.isArray(entry[1]) && entry[1][1] !== null);
153
+ /** A Bloom theme colour (`theme.colors.textSecondary`) as the role painted from it (`muted`). */
154
+ const ROLE_OF_THEME_COLOR = new Map();
155
+ for (const [role, entry] of PALETTE)
156
+ if (!ROLE_OF_THEME_COLOR.has(entry[0]))
157
+ ROLE_OF_THEME_COLOR.set(entry[0], role);
158
+ /** Each canonical colour token, as `useColorTokens()` names it (`mutedForeground`), as the role painted from it. */
159
+ const ROLE_OF_COLOR_TOKEN = new Map();
160
+ for (const [role, entry] of PALETTE) {
161
+ const token = entry[1].replace(/-([a-z0-9])/g, (_, c) => c.toUpperCase());
162
+ if (!ROLE_OF_COLOR_TOKEN.has(token))
163
+ ROLE_OF_COLOR_TOKEN.set(token, role);
164
+ }
165
+ const ICON_SIZES = Object.entries(spec.scales.iconSize);
166
+ /** A glyph size in points (`28`) as the icon size token of its value (`'xl'`), a named rung over a numeric one. */
167
+ const ICON_SIZE_TOKEN = new Map();
168
+ for (const [name, size] of ICON_SIZES)
169
+ if (typeof size === 'number' && (!/^\d/.test(name) || !ICON_SIZE_TOKEN.has(size)))
170
+ ICON_SIZE_TOKEN.set(size, name);
171
+ const RAMP = new Set(Object.keys(spec.typeRamp).filter((k) => !k.startsWith('$')));
172
+ /** A content container's padding key as the edge of its content margin. */
173
+ const CONTENT_EDGE = {
174
+ padding: 'all',
175
+ paddingHorizontal: 'horizontal',
176
+ paddingVertical: 'vertical',
177
+ paddingTop: 'top',
178
+ paddingBottom: 'bottom',
179
+ paddingStart: 'leading',
180
+ paddingEnd: 'trailing',
181
+ paddingLeft: 'left',
182
+ paddingRight: 'right',
183
+ };
184
+ /** React Native's `pointerEvents` as the language's hit testing (`auto` is the default, left as JSX). */
185
+ const HIT_TESTING = {
186
+ none: false,
187
+ 'box-none': 'children',
188
+ 'box-only': 'self',
189
+ };
190
+ /**
191
+ * What `defineTokens` takes as a colour (the language's `isAppColorValue`): a
192
+ * hex of 3, 4, 6 or 8 digits, an `rgb()` or `rgba()` of numbers, or a CSS
193
+ * colour name both platforms paint (the spec's `appColorName`).
194
+ */
195
+ const HEX = /^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
196
+ const RGB = /^rgb\(\s*\d{1,3}\s*(?:,\s*\d{1,3}\s*){2}\)$|^rgba\(\s*\d{1,3}\s*(?:,\s*\d{1,3}\s*){2},\s*(?:0|1|0?\.\d+)\s*\)$/;
197
+ const COLOR_NAMES = new Set(spec.enums.appColorName);
198
+ const isAppColorValue = (value) => HEX.test(value) || RGB.test(value) || COLOR_NAMES.has(value);
199
+ /** A colour written out as its token's name: `hex` and its digits, a colour name itself, an rgb()'s numbers joined. */
200
+ const appColorName = (value) => HEX.test(value)
201
+ ? `hex${value.slice(1)}`
202
+ : COLOR_NAMES.has(value)
203
+ ? value
204
+ : value.replace(/[^\w]+/g, '_').replace(/_$/, '');
205
+ /** Bloom's colour scope: inside it, a theme read outside it is another scheme's colour. */
206
+ const COLOR_SCOPE = '@oxy.so/bloom/theme#BloomColorScope';
207
+ /** The parameter of a list's row that hands a named row function its argument. */
208
+ const ROW_INFO = 'info';
209
+ const isCarried = (value) => typeof value === 'object' && 'hole' in value && 'node' in value;
210
+ /** A value of the codemod's own (a style object literal never has a `$` key). */
211
+ const isTagged = (value) => typeof value === 'object' && '$' in value && !isCarried(value);
212
+ const isAbsent = (value) => isTagged(value) && value.$ === 'absent';
213
+ /** Whether an expression holds JSX anywhere (an element is no string, number or flag). */
214
+ function hasJsx(expression) {
215
+ let found = false;
216
+ recast.visit(expression, {
217
+ visitJSXElement() {
218
+ found = true;
219
+ return false;
220
+ },
221
+ visitJSXFragment() {
222
+ found = true;
223
+ return false;
224
+ },
225
+ });
226
+ return found;
227
+ }
228
+ const LANGUAGE_MODULE = '@oxy.so/bloom-language';
229
+ /** Bloom's floating action button. */
230
+ const FAB_MODULE = '@oxy.so/bloom/fab';
231
+ /** Bloom's dropdown menu and its parts. */
232
+ const DROPDOWN = '@oxy.so/bloom/dropdown-menu';
233
+ const SCREEN_KEY = '@oxy.so/bloom/screen#Screen';
234
+ /**
235
+ * Bloom's `PressableScale`: a Pressable that eases to a smaller scale under a
236
+ * press, its className on the node that scales. The language's parity pairs it
237
+ * with a pressable stack's `.pressScale()` (parity/pieces.cases.tsx).
238
+ */
239
+ function isPressableScale(source) {
240
+ return source.module === '@oxy.so/bloom/pressable-scale' && source.imported === 'PressableScale';
241
+ }
242
+ /** The import that names an element, by kind. */
243
+ function kindOf(source) {
244
+ if (!source)
245
+ return undefined;
246
+ if (source.module === 'react-native') {
247
+ if (source.imported === 'View')
248
+ return 'view';
249
+ if (source.imported === 'Pressable')
250
+ return 'pressable';
251
+ // A TouchableOpacity is a pressable whose press fades it: `.pressFade()`.
252
+ if (source.imported === 'TouchableOpacity')
253
+ return 'pressable';
254
+ if (source.imported === 'Text')
255
+ return 'rnText';
256
+ if (source.imported === 'Image')
257
+ return 'rnImage';
258
+ return undefined;
259
+ }
260
+ if (source.module === '@oxy.so/bloom/typography' &&
261
+ (source.imported === 'Text' || components_1.TEXT_STYLES[source.imported]))
262
+ return 'bloomText';
263
+ if (source.module === '@oxy.so/bloom/button' && source.imported === 'Button')
264
+ return 'button';
265
+ if (isPressableScale(source))
266
+ return 'pressable';
267
+ if ((0, components_1.ruleFor)(source.module, source.imported))
268
+ return 'component';
269
+ if (components_1.KEPT[`${source.module}#${source.imported}`] || components_1.REMOVED[`${source.module}#${source.imported}`])
270
+ return 'kept';
271
+ if ((source.module === '@oxy.so/bloom/icons' || source.module.startsWith('@oxy.so/bloom/icons/')) &&
272
+ /^(Ri|Si)[A-Z0-9]\w*$|Icon$/.test(source.imported) &&
273
+ source.module !== '@oxy.so/bloom/icons/shared')
274
+ return 'icon';
275
+ return undefined;
276
+ }
277
+ /** React's JSX text rule: lines trimmed and joined, an empty result is no child. */
278
+ function cleanJsxText(value) {
279
+ const lines = value.split(/\r\n|\n|\r/);
280
+ let lastNonEmpty = 0;
281
+ lines.forEach((line, i) => {
282
+ if (/[^ \t]/.test(line))
283
+ lastNonEmpty = i;
284
+ });
285
+ let out = '';
286
+ lines.forEach((line, i) => {
287
+ let trimmed = line.replace(/\t/g, ' ');
288
+ if (i !== 0)
289
+ trimmed = trimmed.replace(/^[ ]+/, '');
290
+ if (i !== lines.length - 1)
291
+ trimmed = trimmed.replace(/[ ]+$/, '');
292
+ if (trimmed) {
293
+ if (i !== lastNonEmpty)
294
+ trimmed += ' ';
295
+ out += trimmed;
296
+ }
297
+ });
298
+ return out;
299
+ }
300
+ /**
301
+ * A condition read without a call: names, properties, literals and their
302
+ * comparisons, negations and logic, so reading it again reads the same.
303
+ */
304
+ function isPlainRead(node) {
305
+ if (n.Identifier.check(node) || n.Literal.check(node) || n.StringLiteral.check(node))
306
+ return true;
307
+ if (n.NumericLiteral.check(node) || n.BooleanLiteral.check(node) || n.NullLiteral.check(node))
308
+ return true;
309
+ if (n.MemberExpression.check(node) || n.OptionalMemberExpression.check(node))
310
+ return isPlainRead(node.object) && (!node.computed || isPlainRead(node.property));
311
+ if (n.UnaryExpression.check(node))
312
+ return node.operator === '!' && isPlainRead(node.argument);
313
+ if (n.BinaryExpression.check(node) || n.LogicalExpression.check(node))
314
+ return isPlainRead(node.left) && isPlainRead(node.right);
315
+ return false;
316
+ }
317
+ /** A condition that is a boolean by its form, so `c && x` never renders a value of `c`. */
318
+ function isBooleanForm(node) {
319
+ if (n.BooleanLiteral.check(node))
320
+ return true;
321
+ if (n.UnaryExpression.check(node) && node.operator === '!')
322
+ return true;
323
+ if (n.BinaryExpression.check(node) &&
324
+ ['===', '!==', '==', '!=', '<', '>', '<=', '>=', 'in', 'instanceof'].includes(node.operator))
325
+ return true;
326
+ if (n.LogicalExpression.check(node) && node.operator !== '??')
327
+ return isBooleanForm(node.left) && isBooleanForm(node.right);
328
+ if (n.CallExpression.check(node) &&
329
+ n.Identifier.check(node.callee) &&
330
+ node.callee.name === 'Boolean')
331
+ return true;
332
+ return false;
333
+ }
334
+ function jsxName(node) {
335
+ const name = node.openingElement.name;
336
+ return n.JSXIdentifier.check(name) ? name.name : undefined;
337
+ }
338
+ function staticString(value) {
339
+ if (!value)
340
+ return undefined;
341
+ if (n.StringLiteral.check(value) || n.Literal.check(value))
342
+ return typeof value.value === 'string' ? value.value : undefined;
343
+ if (n.JSXExpressionContainer.check(value))
344
+ return staticString(value.expression);
345
+ if (n.TemplateLiteral.check(value) && value.expressions.length === 0)
346
+ return value.quasis.map((q) => q.value.cooked).join('');
347
+ return undefined;
348
+ }
349
+ function staticNumber(value) {
350
+ if (n.JSXExpressionContainer.check(value))
351
+ return staticNumber(value.expression);
352
+ if (n.NumericLiteral.check(value))
353
+ return value.value;
354
+ if (n.Literal.check(value) && typeof value.value === 'number')
355
+ return value.value;
356
+ return undefined;
357
+ }
358
+ /** The expression of an attribute value, or a string literal's node. */
359
+ function attributeExpression(value) {
360
+ if (n.JSXExpressionContainer.check(value))
361
+ return value.expression;
362
+ return value;
363
+ }
364
+ /** Code without its block comments: a name in a comment is no binding. */
365
+ const uncommented = (code) => code.replace(/\/\*[\s\S]*?\*\//g, '');
366
+ const quote = (text) => `'${text.replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/\n/g, '\\n')}'`;
367
+ /** An argument as code; points computed at render are their carried value (`carry`). */
368
+ function printArg(arg, carry) {
369
+ if (typeof arg === 'string')
370
+ return quote(arg);
371
+ if (typeof arg === 'number' || typeof arg === 'boolean')
372
+ return String(arg);
373
+ if ((0, table_1.isPoints)(arg))
374
+ return carry(arg);
375
+ const entries = Object.entries(arg).map(([k, v]) => `${/^[A-Za-z_$][\w$]*$/.test(k) ? k : quote(k)}: ${(0, table_1.isPoints)(v) ? carry(v) : quote(v)}`);
376
+ return `{ ${entries.join(', ')} }`;
377
+ }
378
+ const printMod = (mod, carry) => `.${mod.name}(${mod.args.map((arg) => printArg(arg, carry)).join(', ')})`;
379
+ /** The points an argument carries: itself, or an object's values (`{ width: itemSize }`). */
380
+ const pointsOf = (arg) => (0, table_1.isPoints)(arg)
381
+ ? [arg]
382
+ : typeof arg === 'object' && arg !== null && !('$' in arg) && !('hole' in arg)
383
+ ? Object.values(arg).filter(table_1.isPoints)
384
+ : [];
385
+ /** Transforms one file's source. */
386
+ function transformSource(source, options) {
387
+ const ast = recast.parse(source, { parser: babelTs });
388
+ const sources = new Map();
389
+ const declared = new Set();
390
+ recast.visit(ast, {
391
+ visitImportDeclaration(path) {
392
+ const module = String(path.node.source.value);
393
+ for (const specifier of path.node.specifiers ?? []) {
394
+ const local = specifier.local?.name;
395
+ declared.add(local);
396
+ if (n.ImportSpecifier.check(specifier))
397
+ sources.set(local, { module, imported: specifier.imported.name });
398
+ else if (n.ImportDefaultSpecifier.check(specifier) &&
399
+ module.startsWith('@oxy.so/bloom/icons/'))
400
+ sources.set(local, { module, imported: module.slice('@oxy.so/bloom/icons/'.length) });
401
+ }
402
+ return false;
403
+ },
404
+ visitIdentifier(path) {
405
+ declared.add(path.node.name);
406
+ this.traverse(path);
407
+ },
408
+ });
409
+ /** The language names the file already imports, by their local name (`Embed`, `toElement`). */
410
+ const importedLanguage = new Map();
411
+ for (const [local, source] of sources)
412
+ if (source.module === LANGUAGE_MODULE || source.module === `${LANGUAGE_MODULE}/router`)
413
+ importedLanguage.set(source.imported, local);
414
+ /** A language name: the file's own import of it, else one added, aliased when the file already uses the name. */
415
+ const usedLanguage = new Map();
416
+ const lang = (name) => {
417
+ const imported = importedLanguage.get(name);
418
+ if (imported)
419
+ return imported;
420
+ let local = usedLanguage.get(name);
421
+ if (!local) {
422
+ local = declared.has(name) ? `L${name}` : name;
423
+ usedLanguage.set(name, local);
424
+ }
425
+ return local;
426
+ };
427
+ /** Module-level `const styles = StyleSheet.create({...})`, by name: each style's object literal. */
428
+ const styleSheets = new Map();
429
+ const styleSheetLocal = [...sources].find(([, s]) => s.module === 'react-native' && s.imported === 'StyleSheet')?.[0];
430
+ for (const statement of ast.program.body) {
431
+ const declaration = n.ExportNamedDeclaration.check(statement)
432
+ ? statement.declaration
433
+ : statement;
434
+ if (!n.VariableDeclaration.check(declaration) || declaration.kind !== 'const')
435
+ continue;
436
+ for (const declarator of declaration.declarations) {
437
+ const init = declarator.init;
438
+ if (!styleSheetLocal ||
439
+ !n.Identifier.check(declarator.id) ||
440
+ !n.CallExpression.check(init) ||
441
+ !n.MemberExpression.check(init.callee) ||
442
+ !n.Identifier.check(init.callee.object) ||
443
+ init.callee.object.name !== styleSheetLocal ||
444
+ !n.Identifier.check(init.callee.property) ||
445
+ init.callee.property.name !== 'create' ||
446
+ !n.ObjectExpression.check(init.arguments[0]))
447
+ continue;
448
+ const sheet = new Map();
449
+ for (const property of init.arguments[0].properties)
450
+ if ((n.ObjectProperty.check(property) || n.Property.check(property)) &&
451
+ n.Identifier.check(property.key))
452
+ sheet.set(property.key.name, property.value);
453
+ styleSheets.set(declarator.id.name, sheet);
454
+ }
455
+ }
456
+ /**
457
+ * Each `theme.colors.key` (`theme` from Bloom's `useTheme()`) and `colors.key`
458
+ * (`const { colors } = useTheme()`) in the file, as the role painted from that
459
+ * theme colour, resolved through the scope it is read in.
460
+ */
461
+ const themeRoles = new Map();
462
+ const useColorTokensLocals = new Set([...sources]
463
+ .filter(([, s]) => s.module === '@oxy.so/bloom/theme' && s.imported === 'useColorTokens')
464
+ .map(([local]) => local));
465
+ /** The theme reads that are `useColorTokens()`'s (`colorTokens.border`), not `useTheme()`'s. */
466
+ const colorTokenReads = new Set();
467
+ const useThemeLocals = new Set([...sources]
468
+ .filter(([, s]) => s.module === '@oxy.so/bloom/theme' && s.imported === 'useTheme')
469
+ .map(([local]) => local));
470
+ /**
471
+ * The scope that declares `name` where `path` reads it. ast-types cannot scan
472
+ * every pattern Babel parses (an array pattern's hole, `const [, b] = …`):
473
+ * a scope it cannot scan is no known binding.
474
+ */
475
+ const scopeOf = (path, name) => {
476
+ try {
477
+ return path.scope?.lookup(name);
478
+ }
479
+ catch {
480
+ return undefined;
481
+ }
482
+ };
483
+ /** What `name` is bound to where `path` reads it: Bloom's theme, its colours, or neither. */
484
+ const boundTo = (path, name) => {
485
+ const bindings = scopeOf(path, name)?.getBindings()[name];
486
+ if (bindings?.length !== 1)
487
+ return undefined;
488
+ // `const theme = useTheme()`, or `const { colors } = useTheme()` (the property's value is the binding).
489
+ let at = bindings[0];
490
+ while (at && !n.VariableDeclarator.check(at.node))
491
+ at = at.parent;
492
+ const init = at?.node.init;
493
+ if (!init ||
494
+ !n.CallExpression.check(init) ||
495
+ !n.Identifier.check(init.callee) ||
496
+ at.parent?.node.kind !== 'const')
497
+ return undefined;
498
+ // `const colorTokens = useColorTokens()`: the theme's canonical colours by token.
499
+ if (useColorTokensLocals.has(init.callee.name))
500
+ return n.Identifier.check(at.node.id) && at.node.id.name === name ? 'tokens' : undefined;
501
+ if (!useThemeLocals.has(init.callee.name))
502
+ return undefined;
503
+ if (n.Identifier.check(at.node.id) && at.node.id.name === name)
504
+ return 'theme';
505
+ if (n.ObjectPattern.check(at.node.id) &&
506
+ at.node.id.properties.some((p) => (n.ObjectProperty.check(p) || n.Property.check(p)) &&
507
+ !p.computed &&
508
+ n.Identifier.check(p.key) &&
509
+ p.key.name === 'colors' &&
510
+ n.Identifier.check(p.value) &&
511
+ p.value.name === name))
512
+ return 'colors';
513
+ return undefined;
514
+ };
515
+ /** Each `styles.x` read where `styles` is the module's StyleSheet (not a name that shadows it). */
516
+ const moduleStyleReads = new Set();
517
+ if (useThemeLocals.size > 0 || useColorTokensLocals.size > 0 || styleSheets.size > 0)
518
+ recast.visit(ast, {
519
+ visitMemberExpression(path) {
520
+ const { object, property, computed } = path.node;
521
+ if (n.Identifier.check(object) &&
522
+ styleSheets.has(object.name) &&
523
+ scopeOf(path, object.name)?.isGlobal)
524
+ moduleStyleReads.add(path.node);
525
+ if (!computed && n.Identifier.check(property)) {
526
+ const role = ROLE_OF_THEME_COLOR.get(property.name);
527
+ const colorsOf = n.MemberExpression.check(object) &&
528
+ !object.computed &&
529
+ n.Identifier.check(object.property) &&
530
+ object.property.name === 'colors' &&
531
+ n.Identifier.check(object.object) &&
532
+ boundTo(path, object.object.name) === 'theme';
533
+ const colors = n.Identifier.check(object) && boundTo(path, object.name) === 'colors';
534
+ if (role && (colorsOf || colors))
535
+ themeRoles.set(path.node, role);
536
+ const token = ROLE_OF_COLOR_TOKEN.get(property.name);
537
+ if (token && n.Identifier.check(object) && boundTo(path, object.name) === 'tokens') {
538
+ themeRoles.set(path.node, token);
539
+ colorTokenReads.add(path.node);
540
+ }
541
+ }
542
+ this.traverse(path);
543
+ },
544
+ });
545
+ /** A className chosen at runtime, by its expression: both branches' classes, which the parity's stylesheet holds. */
546
+ const choiceClasses = new Map();
547
+ /**
548
+ * Each `insets.top` (`bottom`, `left`, `right`) where `insets` is a `const`
549
+ * holding `useSafeAreaInsets()` (react-native-safe-area-context): the device's
550
+ * inset on that side, which `.safeAreaPadding(side)` pads by.
551
+ */
552
+ const insetReads = new Map();
553
+ recast.visit(ast, {
554
+ visitMemberExpression(path) {
555
+ const { object, property } = path.node;
556
+ const side = !path.node.computed && n.Identifier.check(property) ? property.name : '';
557
+ if (n.Identifier.check(object) && ['top', 'bottom', 'left', 'right'].includes(side)) {
558
+ const bindings = scopeOf(path, object.name)?.getBindings()[object.name];
559
+ let at = bindings?.length === 1 ? bindings[0] : undefined;
560
+ while (at && !n.VariableDeclarator.check(at.node))
561
+ at = at.parent;
562
+ const init = at?.node.init;
563
+ const callee = n.CallExpression.check(init) ? init.callee : undefined;
564
+ const source = n.Identifier.check(callee) ? sources.get(callee.name) : undefined;
565
+ if (at?.parent?.node.kind === 'const' &&
566
+ n.Identifier.check(at.node.id) &&
567
+ init.arguments.length === 0 &&
568
+ source?.module === 'react-native-safe-area-context' &&
569
+ source.imported === 'useSafeAreaInsets')
570
+ insetReads.set(path.node, side);
571
+ }
572
+ this.traverse(path);
573
+ },
574
+ });
575
+ /**
576
+ * Each identifier read whose binding is inside a function (a prop, a local, a
577
+ * hook's result): what the view works out as it renders, never a module's constant.
578
+ */
579
+ const renderReads = new Set();
580
+ recast.visit(ast, {
581
+ visitIdentifier(path) {
582
+ const parent = path.parent?.node;
583
+ const named = (n.MemberExpression.check(parent) && parent.property === path.node && !parent.computed) ||
584
+ ((n.ObjectProperty.check(parent) || n.Property.check(parent)) &&
585
+ parent.key === path.node &&
586
+ !parent.computed);
587
+ if (!named && scopeOf(path, path.node.name)?.isGlobal === false)
588
+ renderReads.add(path.node);
589
+ this.traverse(path);
590
+ },
591
+ });
592
+ /** An expression of numbers alone: reads, arithmetic, `Math`'s functions, a plain choice between two. */
593
+ const numberForm = (node) => {
594
+ if (n.NumericLiteral.check(node))
595
+ return true;
596
+ if (n.Identifier.check(node))
597
+ return node.name !== 'undefined';
598
+ if (n.MemberExpression.check(node))
599
+ return ((n.Identifier.check(node.object) || n.MemberExpression.check(node.object)) &&
600
+ numberForm(node.object) &&
601
+ (!node.computed || numberForm(node.property)));
602
+ if (n.BinaryExpression.check(node))
603
+ return (['+', '-', '*', '/'].includes(node.operator) &&
604
+ numberForm(node.left) &&
605
+ numberForm(node.right));
606
+ if (n.UnaryExpression.check(node))
607
+ return node.operator === '-' && numberForm(node.argument);
608
+ if (n.TSNonNullExpression.check(node))
609
+ return numberForm(node.expression);
610
+ if (n.ConditionalExpression.check(node))
611
+ return ((isPlainRead(node.test) || isBooleanForm(node.test)) &&
612
+ numberForm(node.consequent) &&
613
+ numberForm(node.alternate));
614
+ return (n.CallExpression.check(node) &&
615
+ n.MemberExpression.check(node.callee) &&
616
+ n.Identifier.check(node.callee.object) &&
617
+ node.callee.object.name === 'Math' &&
618
+ !renderReads.has(node.callee.object) &&
619
+ node.arguments.every(numberForm));
620
+ };
621
+ /**
622
+ * A number the view computes as it renders (`itemSize`, `insets.top + 8`,
623
+ * `SIZES[size] / 2`): a number form that reads something bound in the
624
+ * component. A number written out, or one of module constants alone, is a token.
625
+ */
626
+ const computedAtRender = (node) => {
627
+ if (n.NumericLiteral.check(node) || !numberForm(node))
628
+ return false;
629
+ let reads = false;
630
+ recast.visit(node, {
631
+ visitIdentifier(path) {
632
+ if (renderReads.has(path.node))
633
+ reads = true;
634
+ return false;
635
+ },
636
+ });
637
+ return reads;
638
+ };
639
+ /**
640
+ * A padding by the device's inset, as `.safeAreaPadding(side)`: `paddingTop:
641
+ * insets.top`, or `insets.top + 24` with a padding of the space token beyond it
642
+ * on the same view (a top or bottom one: the language adds them).
643
+ */
644
+ const insetPadding = (key, value) => {
645
+ const side = {
646
+ paddingTop: 'top',
647
+ paddingBottom: 'bottom',
648
+ paddingLeft: 'left',
649
+ paddingRight: 'right',
650
+ }[key];
651
+ if (!side)
652
+ return undefined;
653
+ const sum = n.BinaryExpression.check(value) && value.operator === '+' ? value : undefined;
654
+ const inset = sum ? sum.left : value;
655
+ if (insetReads.get(inset) !== side)
656
+ return undefined;
657
+ if (!sum)
658
+ return [{ name: 'safeAreaPadding', args: [side] }];
659
+ const beyond = n.NumericLiteral.check(sum.right) ? components_1.SPACE[String(sum.right.value)] : undefined;
660
+ if (beyond === undefined || (side !== 'top' && side !== 'bottom'))
661
+ return undefined;
662
+ return [
663
+ { name: 'safeAreaPadding', args: [side] },
664
+ { name: 'padding', args: [side, beyond] },
665
+ ];
666
+ };
667
+ /**
668
+ * Each read of a `const` holding Bloom's `useSurfaceFill()`: the fill of the
669
+ * surface around the component, the language's `surfaceFill` role.
670
+ */
671
+ const surfaceReads = new Set();
672
+ recast.visit(ast, {
673
+ visitIdentifier(path) {
674
+ const bindings = renderReads.has(path.node)
675
+ ? scopeOf(path, path.node.name)?.getBindings()[path.node.name]
676
+ : undefined;
677
+ let at = bindings?.length === 1 ? bindings[0] : undefined;
678
+ while (at && !n.VariableDeclarator.check(at.node))
679
+ at = at.parent;
680
+ const init = at?.node.init;
681
+ const callee = n.CallExpression.check(init) ? init.callee : undefined;
682
+ const source = n.Identifier.check(callee) ? sources.get(callee.name) : undefined;
683
+ if (at?.parent?.node.kind === 'const' &&
684
+ n.Identifier.check(at.node.id) &&
685
+ at.node.id !== path.node &&
686
+ source?.module === '@oxy.so/bloom/styles' &&
687
+ source.imported === 'useSurfaceFill' &&
688
+ init.arguments.length === 0)
689
+ surfaceReads.add(path.node);
690
+ this.traverse(path);
691
+ },
692
+ });
693
+ /** Each `{name}` in a JSX attribute where `name` is a `const`: its initialiser (a Button's ink held in a variable). */
694
+ const constInits = new Map();
695
+ recast.visit(ast, {
696
+ visitJSXAttribute(path) {
697
+ const expression = n.JSXExpressionContainer.check(path.node.value)
698
+ ? path.node.value.expression
699
+ : undefined;
700
+ if (n.Identifier.check(expression)) {
701
+ const bindings = scopeOf(path, expression.name)?.getBindings()[expression.name];
702
+ let at = bindings?.length === 1 ? bindings[0] : undefined;
703
+ while (at && !n.VariableDeclarator.check(at.node))
704
+ at = at.parent;
705
+ if (at?.parent?.node.kind === 'const' && n.Identifier.check(at.node.id) && at.node.init)
706
+ constInits.set(expression, at.node.init);
707
+ }
708
+ this.traverse(path);
709
+ },
710
+ });
711
+ /**
712
+ * A colour as the role it is painted from: a theme colour read from
713
+ * `useTheme()`, a choice of them by a plain condition (`undefined` for none),
714
+ * or a `const` holding one.
715
+ */
716
+ /** The `const` reads `roleOf` followed: the before side writes their initialiser in their place. */
717
+ const roleConstReads = new Set();
718
+ const roleOf = (expression) => {
719
+ const role = themeRoles.get(expression);
720
+ if (role)
721
+ return role;
722
+ if (n.Identifier.check(expression) && expression.name === 'undefined')
723
+ return { $: 'absent' };
724
+ if (n.Identifier.check(expression) && constInits.has(expression)) {
725
+ const held = roleOf(constInits.get(expression));
726
+ if (held !== undefined)
727
+ roleConstReads.add(expression);
728
+ return held;
729
+ }
730
+ if (n.ConditionalExpression.check(expression) &&
731
+ (isPlainRead(expression.test) || isBooleanForm(expression.test))) {
732
+ const then = roleOf(expression.consequent);
733
+ const otherwise = roleOf(expression.alternate);
734
+ if (then !== undefined && otherwise !== undefined)
735
+ return { $: 'choose', test: { node: expression.test, hole: 'condition' }, then, otherwise };
736
+ }
737
+ // Bloom's `withAlpha(colors.primary, 0.1)` or `tokenAlpha(tokens.primary, 0.1)`: the role at
738
+ // that opacity token, `'primary/10'` (the web paints it from the language's ink sheet).
739
+ const callee = n.CallExpression.check(expression) ? expression.callee : undefined;
740
+ const alpha = n.Identifier.check(callee) ? sources.get(callee.name) : undefined;
741
+ if (alpha?.module === '@oxy.so/bloom/theme' &&
742
+ (alpha.imported === 'withAlpha' || alpha.imported === 'tokenAlpha') &&
743
+ expression.arguments.length === 2) {
744
+ const role = roleOf(expression.arguments[0]);
745
+ const opacity = OPACITY_TOKEN.get(staticNumber(expression.arguments[1]));
746
+ if (typeof role === 'string' && !role.includes('/') && opacity !== undefined)
747
+ return `${role}/${opacity}`;
748
+ }
749
+ return undefined;
750
+ };
751
+ /**
752
+ * A colour as a modifier's value: a theme colour as its role (outside a
753
+ * colour scope, where the role would paint the scope's scheme), a colour
754
+ * written out as an app colour, or a plain choice between them
755
+ * (`empty ? theme.colors.background : '#000000'`).
756
+ */
757
+ const inkOf = (node, expression) => {
758
+ if (n.ConditionalExpression.check(expression) &&
759
+ (isPlainRead(expression.test) || isBooleanForm(expression.test))) {
760
+ const then = inkOf(node, expression.consequent);
761
+ const otherwise = inkOf(node, expression.alternate);
762
+ return then === undefined || otherwise === undefined
763
+ ? undefined
764
+ : { $: 'choose', test: { node: expression.test, hole: 'condition' }, then, otherwise };
765
+ }
766
+ const role = roleOf(expression);
767
+ if (typeof role === 'string')
768
+ return insideOf(node, [COLOR_SCOPE]) ? undefined : role;
769
+ const value = staticString(expression);
770
+ if (value === undefined || !isAppColorValue(value) || colorConstants.has(appColorName(value)))
771
+ return undefined;
772
+ return { $: 'appColor', color: { name: appColorName(value), value } };
773
+ };
774
+ /** A language view placed as an element: `toElement(view)`, as a file partly in the language writes it. */
775
+ const isToElement = (expression) => {
776
+ const callee = n.CallExpression.check(expression) ? expression.callee : undefined;
777
+ const source = n.Identifier.check(callee) ? sources.get(callee.name) : undefined;
778
+ return source?.module === LANGUAGE_MODULE && source.imported === 'toElement';
779
+ };
780
+ /**
781
+ * Each `{name}` in JSX where `name` is a `const` holding an element
782
+ * (`const header = <PageHeader … />`, or `toElement(Header(…))`).
783
+ */
784
+ const elementReads = new Set();
785
+ recast.visit(ast, {
786
+ visitJSXExpressionContainer(path) {
787
+ const { expression } = path.node;
788
+ const bindings = n.Identifier.check(expression)
789
+ ? scopeOf(path, expression.name)?.getBindings()[expression.name]
790
+ : undefined;
791
+ let at = bindings?.length === 1 ? bindings[0] : undefined;
792
+ while (at && !n.VariableDeclarator.check(at.node))
793
+ at = at.parent;
794
+ if (at?.parent?.node.kind === 'const' &&
795
+ n.Identifier.check(at.node.id) &&
796
+ (n.JSXElement.check(at.node.init) ||
797
+ n.JSXFragment.check(at.node.init) ||
798
+ isToElement(at.node.init)))
799
+ elementReads.add(expression);
800
+ this.traverse(path);
801
+ },
802
+ });
803
+ /**
804
+ * Module-level `const NAME = 'text'` (no type annotation, so a colour's type is
805
+ * the literal `defineTokens` takes), by name: a colour the codemod reads in the file.
806
+ */
807
+ const colorConstants = new Map();
808
+ for (const statement of ast.program.body) {
809
+ const declaration = n.ExportNamedDeclaration.check(statement)
810
+ ? statement.declaration
811
+ : statement;
812
+ if (!n.VariableDeclaration.check(declaration) || declaration.kind !== 'const')
813
+ continue;
814
+ for (const declarator of declaration.declarations) {
815
+ const value = staticString(declarator.init);
816
+ if (n.Identifier.check(declarator.id) &&
817
+ !declarator.id.typeAnnotation &&
818
+ n.StringLiteral.check(declarator.init) &&
819
+ value !== undefined)
820
+ colorConstants.set(declarator.id.name, { value, statement });
821
+ }
822
+ }
823
+ /** Each name that reads a string constant of the module's (not a name that shadows it). */
824
+ const colorConstantReads = new Set();
825
+ if (colorConstants.size > 0)
826
+ recast.visit(ast, {
827
+ visitIdentifier(path) {
828
+ if (colorConstants.has(path.node.name) && scopeOf(path, path.node.name)?.isGlobal)
829
+ colorConstantReads.add(path.node);
830
+ this.traverse(path);
831
+ },
832
+ });
833
+ /** The local name of the file's app colour table, free in the file. */
834
+ let appColorTable = 'appColors';
835
+ for (let i = 2; declared.has(appColorTable); i++)
836
+ appColorTable = `appColors${i}`;
837
+ /** The app colours the converted regions paint with, by token name: the file's table. */
838
+ const appColors = new Map();
839
+ /** A `style` whose objects are the parity's before side, where `styles.x` is not in scope. */
840
+ const styleLiterals = new Map();
841
+ /** Each shorthand property's value (`{ width }`), which shares its key's place in the source. */
842
+ const shorthandValues = new Set();
843
+ recast.visit(ast, {
844
+ visitObjectProperty(path) {
845
+ if (path.node.shorthand)
846
+ shorthandValues.add(path.node.value);
847
+ this.traverse(path);
848
+ },
849
+ });
850
+ /** Points a style's chain draws without carrying them (a half-square radius's side): holes on the before side. */
851
+ const heldPoints = new Set();
852
+ /**
853
+ * Module-level `const NAME = { … }` (a style held in a constant, `satisfies`
854
+ * or `as` a type left out), by name: read as a StyleSheet's style is.
855
+ */
856
+ const styleConstants = new Map();
857
+ for (const statement of ast.program.body) {
858
+ const declaration = n.ExportNamedDeclaration.check(statement)
859
+ ? statement.declaration
860
+ : statement;
861
+ if (!n.VariableDeclaration.check(declaration) || declaration.kind !== 'const')
862
+ continue;
863
+ for (const declarator of declaration.declarations) {
864
+ let init = declarator.init;
865
+ while (init && (init.type === 'TSSatisfiesExpression' || init.type === 'TSAsExpression'))
866
+ init = init.expression;
867
+ if (n.Identifier.check(declarator.id) && n.ObjectExpression.check(init))
868
+ styleConstants.set(declarator.id.name, init);
869
+ }
870
+ }
871
+ /** Each name that reads a module style constant (not a name that shadows it): the constant's object. */
872
+ const styleConstantReads = new Map();
873
+ if (styleConstants.size > 0)
874
+ recast.visit(ast, {
875
+ visitIdentifier(path) {
876
+ const parent = path.parent?.node;
877
+ const declares = n.VariableDeclarator.check(parent) && parent.id === path.node;
878
+ if (!declares &&
879
+ styleConstants.has(path.node.name) &&
880
+ scopeOf(path, path.node.name)?.isGlobal)
881
+ styleConstantReads.set(path.node, styleConstants.get(path.node.name));
882
+ this.traverse(path);
883
+ },
884
+ });
885
+ /** Bloom's `tokens` (`@oxy.so/bloom/styles`), by its local name in the file. */
886
+ const bloomTokens = [...sources].find(([, s]) => s.module === '@oxy.so/bloom/styles' && s.imported === 'tokens')?.[0];
887
+ /** Bloom's scales the language holds, by their name in `tokens`. */
888
+ const TOKEN_SCALES = {
889
+ space: spec.scales.space,
890
+ borderRadius: spec.scales.corner,
891
+ fontSize: spec.scales.fontSize,
892
+ };
893
+ /** `tokens.space.sm` (`tokens.borderRadius.xs`, `tokens.fontSize._2xl`): the rung's points, the spec's own. */
894
+ const bloomTokenNumber = (node) => {
895
+ const scale = node?.object;
896
+ if (!bloomTokens ||
897
+ !n.MemberExpression.check(node) ||
898
+ node.computed ||
899
+ !n.MemberExpression.check(scale) ||
900
+ scale.computed ||
901
+ !n.Identifier.check(scale.object) ||
902
+ scale.object.name !== bloomTokens ||
903
+ !n.Identifier.check(scale.property) ||
904
+ !n.Identifier.check(node.property))
905
+ return undefined;
906
+ const value = TOKEN_SCALES[scale.property.name]?.[node.property.name.replace(/^_/, '')];
907
+ return typeof value === 'number' ? value : undefined;
908
+ };
909
+ /** React Native's `StyleSheet.absoluteFill`, read from the module's `StyleSheet`. */
910
+ const isAbsoluteFill = (node) => !!styleSheetLocal &&
911
+ n.MemberExpression.check(node) &&
912
+ !node.computed &&
913
+ n.Identifier.check(node.object) &&
914
+ node.object.name === styleSheetLocal &&
915
+ n.Identifier.check(node.property) &&
916
+ node.property.name === 'absoluteFill';
917
+ /** Bloom's `fontFamilyStyle` (`@oxy.so/bloom/typography`), by its local name in the file. */
918
+ const fontFamilyStyleLocal = [...sources].find(([, s]) => s.module === '@oxy.so/bloom/typography' && s.imported === 'fontFamilyStyle')?.[0];
919
+ /**
920
+ * A spread a style reads: `StyleSheet.absoluteFill`'s edges, and Bloom's
921
+ * `fontFamilyStyle('mono' | 'display')`, the face the language's
922
+ * `.font('mono')` and `.font('display')` set (the same family on every platform).
923
+ */
924
+ const spreadOf = (node) => {
925
+ if (isAbsoluteFill(node))
926
+ return { classes: style_1.ABSOLUTE_FILL.classes, mods: [], literal: style_1.ABSOLUTE_FILL.literal };
927
+ if (fontFamilyStyleLocal &&
928
+ n.CallExpression.check(node) &&
929
+ n.Identifier.check(node.callee) &&
930
+ node.callee.name === fontFamilyStyleLocal &&
931
+ node.arguments.length === 1 &&
932
+ n.StringLiteral.check(node.arguments[0]) &&
933
+ spec.enums.fontFamily.includes(node.arguments[0].value))
934
+ return { classes: [], mods: [{ name: 'font', args: [node.arguments[0].value] }] };
935
+ return undefined;
936
+ };
937
+ /** No style: a branch of a choice that adds none. */
938
+ const noStyle = (node) => n.NullLiteral.check(node) ||
939
+ (n.BooleanLiteral.check(node) && !node.value) ||
940
+ (n.Identifier.check(node) && node.name === 'undefined');
941
+ /**
942
+ * A list part chosen by a plain condition: `test && style` or `test ? a : b`,
943
+ * its branches (null where it adds no style).
944
+ */
945
+ function styleBranches(part) {
946
+ const plain = (test) => isPlainRead(test) || isBooleanForm(test);
947
+ if (n.LogicalExpression.check(part) && part.operator === '&&' && plain(part.left))
948
+ return { test: part.left, branches: [part.right, null] };
949
+ if (n.ConditionalExpression.check(part) && plain(part.test))
950
+ return {
951
+ test: part.test,
952
+ branches: [
953
+ noStyle(part.consequent) ? null : part.consequent,
954
+ noStyle(part.alternate) ? null : part.alternate,
955
+ ],
956
+ };
957
+ return undefined;
958
+ }
959
+ /** A static style (an object literal, a module StyleSheet's style, or a list of them) as utilities. */
960
+ function staticStyle(expression, read,
961
+ /** A Pressable's style function's `pressed`: what it adds is the pressed variant (`active:`). */
962
+ pressed) {
963
+ const parts = n.ArrayExpression.check(expression)
964
+ ? expression.elements
965
+ : [expression];
966
+ const classes = [];
967
+ const mods = [];
968
+ let choice;
969
+ // A StyleSheet's style is its literal on the before side; an inline object stays as written.
970
+ const literals = new Map();
971
+ for (const part of parts) {
972
+ // A style chosen by a plain condition (`!focused && styles.dim`, `compact ? A : B`): each
973
+ // branch's utilities, chosen as a className is (`dynamic-className`).
974
+ const chosen = styleBranches(part);
975
+ if (chosen && pressed && n.Identifier.check(chosen.test) && chosen.test.name === pressed) {
976
+ const [whenPressed, otherwise] = chosen.branches;
977
+ const style = whenPressed && !otherwise ? staticStyle(whenPressed, read) : undefined;
978
+ if (!style?.ok || style.mods.length || style.choice)
979
+ return {
980
+ ok: false,
981
+ subject: 'style',
982
+ why: 'a pressed style that is more than utilities added while pressed',
983
+ };
984
+ classes.push(...style.classes.map((name) => `active:${name}`));
985
+ continue;
986
+ }
987
+ if (chosen) {
988
+ // Inside a style function a choice reads its parameter, which the chain has no name for.
989
+ if (pressed)
990
+ return {
991
+ ok: false,
992
+ subject: 'style',
993
+ why: 'a pressed style chosen with another condition (`pressed || locked`)',
994
+ };
995
+ if (choice)
996
+ return { ok: false, subject: 'style', why: 'a style with two choices' };
997
+ const [whenTrue, whenFalse] = chosen.branches.map((branch) => branch ? staticStyle(branch, read) : { ok: true, classes: [], mods: [] });
998
+ if (!whenTrue.ok)
999
+ return whenTrue;
1000
+ if (!whenFalse.ok)
1001
+ return whenFalse;
1002
+ if (whenTrue.mods.length || whenFalse.mods.length || whenTrue.choice || whenFalse.choice)
1003
+ return {
1004
+ ok: false,
1005
+ subject: 'style',
1006
+ why: 'a style chosen at runtime whose branches write more than utilities',
1007
+ };
1008
+ choice = { test: chosen.test, whenTrue: whenTrue.classes, whenFalse: whenFalse.classes };
1009
+ continue;
1010
+ }
1011
+ // React Native's own fill, pinned to every edge: its declarations, written out on the before side.
1012
+ if (isAbsoluteFill(part)) {
1013
+ classes.push(...style_1.ABSOLUTE_FILL.classes);
1014
+ literals.set(part, `{ ${style_1.ABSOLUTE_FILL.literal} }`);
1015
+ continue;
1016
+ }
1017
+ let object = part;
1018
+ // A module constant holding a style is its object, written out on the before side.
1019
+ if (styleConstantReads.has(part)) {
1020
+ const style = (0, style_1.styleUtilities)(styleConstantReads.get(part), {
1021
+ read,
1022
+ spreadOf,
1023
+ numberOf: bloomTokenNumber,
1024
+ });
1025
+ if (!style.ok)
1026
+ return style;
1027
+ classes.push(...style.classes);
1028
+ mods.push(...style.mods);
1029
+ literals.set(part, style.literal);
1030
+ continue;
1031
+ }
1032
+ const referenced = n.MemberExpression.check(part) &&
1033
+ !part.computed &&
1034
+ n.Identifier.check(part.object) &&
1035
+ n.Identifier.check(part.property);
1036
+ if (referenced) {
1037
+ const { object: sheet, property } = part;
1038
+ object = moduleStyleReads.has(part)
1039
+ ? styleSheets.get(sheet.name)?.get(property.name)
1040
+ : undefined;
1041
+ }
1042
+ const style = object
1043
+ ? (0, style_1.styleUtilities)(object, {
1044
+ read,
1045
+ spreadOf,
1046
+ numberOf: bloomTokenNumber,
1047
+ computed: computedAtRender,
1048
+ })
1049
+ : undefined;
1050
+ if (!style)
1051
+ return { ok: false, subject: 'style', why: 'a style the codemod cannot read' };
1052
+ if (!style.ok)
1053
+ return style;
1054
+ classes.push(...style.classes);
1055
+ mods.push(...style.mods);
1056
+ for (const side of style.held)
1057
+ heldPoints.add(side);
1058
+ if (referenced)
1059
+ literals.set(part, style.literal);
1060
+ }
1061
+ for (const [part, literal] of literals)
1062
+ styleLiterals.set(part, literal);
1063
+ return { ok: true, classes, mods, choice };
1064
+ }
1065
+ /**
1066
+ * A Bloom component's static `style` as its node's box, for a component
1067
+ * that draws its `style` on its outer view, where the language draws a
1068
+ * node's box: each declaration through the className table as a View's
1069
+ * (`padding: 16` is `.padding('lg')`, `gap: 12` `.spacing('md')`,
1070
+ * `flexDirection: 'row'` `.axis('horizontal')`), every modifier one the node
1071
+ * takes. A colour, a variant or a value no token writes is a reason.
1072
+ */
1073
+ function componentStyle(expression, node) {
1074
+ const reason = (subject, why) => ({
1075
+ reasons: [{ subject, code: `${node}:style`, why }],
1076
+ });
1077
+ const style = staticStyle(expression, () => undefined);
1078
+ if (!style.ok)
1079
+ return reason(style.subject, style.why);
1080
+ const resolution = (0, resolve_1.resolveClassName)(style.classes.join(' '), 'view', options.table, {
1081
+ overridden: options.overridden,
1082
+ });
1083
+ if (!resolution.ok)
1084
+ return { reasons: [...resolution.reasons] };
1085
+ if (resolution.value.variants.length)
1086
+ return reason('style', 'a style with a variant');
1087
+ const mods = [
1088
+ ...(resolution.value.axis === 'row' ? [{ name: 'axis', args: ['horizontal'] }] : []),
1089
+ ...resolution.value.mods,
1090
+ ...style.mods.map(({ mod }) => mod),
1091
+ ];
1092
+ const taken = NODE_MODIFIERS.get(node);
1093
+ const outside = mods.find((mod) => !taken?.has(mod.name));
1094
+ if (outside)
1095
+ return reason('style', `a style that is \`.${outside.name}()\`, which ${node} does not take`);
1096
+ return { mods: mods.map((mod) => ({ name: mod.name, args: [...mod.args] })) };
1097
+ }
1098
+ /** Each element's nearest enclosing element in the file. */
1099
+ const enclosing = new Map();
1100
+ recast.visit(ast, {
1101
+ visitJSXElement(path) {
1102
+ let at = path.parent;
1103
+ while (at && !n.JSXElement.check(at.node))
1104
+ at = at.parent;
1105
+ if (at)
1106
+ enclosing.set(path.node, at.node);
1107
+ this.traverse(path);
1108
+ },
1109
+ });
1110
+ /** Whether a Bloom component's element is around `node` in the file. */
1111
+ function insideBloomComponent(node) {
1112
+ for (let at = enclosing.get(node); at; at = enclosing.get(at)) {
1113
+ const local = jsxName(at);
1114
+ if (local && sources.get(local)?.module.startsWith('@oxy.so/bloom/'))
1115
+ return true;
1116
+ }
1117
+ return false;
1118
+ }
1119
+ /** The first element around `node` (in the file) drawn by one of `components` (`module#export`). */
1120
+ function insideOf(node, components) {
1121
+ for (let at = enclosing.get(node); at; at = enclosing.get(at)) {
1122
+ const local = jsxName(at);
1123
+ const source = local ? sources.get(local) : undefined;
1124
+ if (source && components.includes(`${source.module}#${source.imported}`))
1125
+ return local;
1126
+ }
1127
+ return undefined;
1128
+ }
1129
+ /**
1130
+ * Each screen: a module-level function component whose every return is a
1131
+ * Bloom Screen becomes `screen(function …)`, each Screen its body's root.
1132
+ * `screen()` wraps the whole component, so its branches (a loading, an
1133
+ * error, the content) each return their content and chrome. A component is
1134
+ * a function declaration (exported or not) or a `const` holding an arrow or
1135
+ * a function expression, named with a capital, not async, with no return
1136
+ * type; a `const` or a declaration whose name is read becomes
1137
+ * `const Name = screen(function Name …)`, so its name is never read before
1138
+ * the module has defined it.
1139
+ */
1140
+ const screenRoutes = new Map();
1141
+ /** Where each screen's function is declared: the statement that holds it, and its name. */
1142
+ const screenDeclarations = new Map();
1143
+ /** The Screens of a component whose name is read before it is declared. */
1144
+ const earlyScreens = new Map();
1145
+ const isScreenElement = (node) => {
1146
+ const local = n.JSXElement.check(node) ? jsxName(node) : undefined;
1147
+ const source = local ? sources.get(local) : undefined;
1148
+ return source?.module === '@oxy.so/bloom/screen' && source.imported === 'Screen';
1149
+ };
1150
+ const peeled = new Map();
1151
+ function peelScreen(node) {
1152
+ if (peeled.has(node))
1153
+ return peeled.get(node);
1154
+ let result;
1155
+ if (isScreenElement(node))
1156
+ result = { screen: node, mods: [] };
1157
+ else if (n.JSXElement.check(node)) {
1158
+ const children = node.children.filter((child) => !(n.JSXText.check(child) && !child.value.trim()));
1159
+ const inner = children.length === 1 ? peelScreen(children[0]) : undefined;
1160
+ if (inner && 'mods' in inner) {
1161
+ const wrapper = screenWrapper(node);
1162
+ result =
1163
+ 'mod' in wrapper
1164
+ ? { screen: inner.screen, mods: [...inner.mods, wrapper.mod] }
1165
+ : { screen: inner.screen, reason: wrapper.reason };
1166
+ }
1167
+ else
1168
+ result = inner;
1169
+ }
1170
+ peeled.set(node, result);
1171
+ return result;
1172
+ }
1173
+ /** The one element a wrapper around a route's Screen holds. */
1174
+ const peelChild = (node) => node.children.find((child) => n.JSXElement.check(child));
1175
+ /** One element around a route's Screen as its screen modifier, or why it is none. */
1176
+ function screenWrapper(node) {
1177
+ const local = jsxName(node) ?? 'an element';
1178
+ const source = sources.get(local);
1179
+ const reason = (why) => ({
1180
+ reason: {
1181
+ subject: 'Screen',
1182
+ code: 'screen:wrapped',
1183
+ why: `inside \`${local}\`: ${why}`,
1184
+ },
1185
+ });
1186
+ const attributes = node.openingElement.attributes.filter((a) => n.JSXAttribute.check(a));
1187
+ if (attributes.length !== node.openingElement.attributes.length)
1188
+ return reason('spread props: the codemod cannot see what they set');
1189
+ const named = new Map(attributes.map((a) => [a.name.name, a.value]));
1190
+ const only = (...names) => [...named.keys()].every((name) => names.includes(name));
1191
+ if (source?.module === '@oxy.so/bloom/theme' && source.imported === 'BloomColorScope') {
1192
+ const asChild = named.get('asChild');
1193
+ const mode = named.get('mode');
1194
+ if (!only('asChild', 'mode') || !named.has('asChild') || !named.has('mode'))
1195
+ return reason('a colour scope is `.colorScope(mode)` when it takes only `mode` and `asChild` (a preset, a seed or its own view are its own)');
1196
+ const bare = asChild === null ||
1197
+ (n.JSXExpressionContainer.check(asChild) &&
1198
+ n.BooleanLiteral.check(asChild.expression) &&
1199
+ asChild.expression.value === true);
1200
+ if (!bare)
1201
+ return reason('a colour scope that is no `asChild` draws a view of its own');
1202
+ const scheme = staticString(mode);
1203
+ if (scheme !== undefined && scheme !== 'light' && scheme !== 'dark')
1204
+ return reason(`a scheme \`${scheme}\` that is neither light nor dark`);
1205
+ return {
1206
+ mod: {
1207
+ name: 'colorScope',
1208
+ args: [scheme ?? { node: attributeExpression(mode), hole: 'string' }],
1209
+ },
1210
+ };
1211
+ }
1212
+ if (source?.module === 'react-native' && source.imported === 'KeyboardAvoidingView') {
1213
+ if (!only('style', 'behavior'))
1214
+ return reason('a keyboard avoiding view with props `.keyboardAvoiding()` does not draw');
1215
+ const style = named.get('style');
1216
+ const fill = style ? staticStyle(attributeExpression(style), () => undefined) : undefined;
1217
+ const filled = fill?.ok && fill.classes.length === 0 && fill.mods.length === 1
1218
+ ? fill.mods[0]?.mod
1219
+ : undefined;
1220
+ if (filled?.name !== 'grow' && filled?.name !== 'flex')
1221
+ return reason('a style other than a fill `.keyboardAvoiding()` draws (React Native’s `flex: 1`, or a flex token)');
1222
+ const behavior = attributeExpression(named.get('behavior'));
1223
+ if (!isKeyboardBehavior(behavior))
1224
+ return reason("a behavior other than React Native’s (`Platform.OS === 'ios' ? 'padding' : 'height'`)");
1225
+ keyboardBehaviors.add(behavior);
1226
+ return {
1227
+ mod: { name: 'keyboardAvoiding', args: filled.name === 'flex' ? [...filled.args] : [] },
1228
+ };
1229
+ }
1230
+ if (source && /Provider$/.test(local) && !source.module.startsWith('react-native')) {
1231
+ if (named.size > 0)
1232
+ return reason('a provider with props: `.provider()` draws one with none');
1233
+ return { mod: { name: 'provider', args: [{ $: 'component', name: local }] } };
1234
+ }
1235
+ return reason('`screen()` wraps the whole component, so what is around the Screen would draw inside it (a colour scope, a keyboard avoiding view and an app’s provider are screen modifiers)');
1236
+ }
1237
+ /** `Platform.OS === 'ios' ? 'padding' : 'height'`, React Native's behavior, as a route writes it. */
1238
+ const isKeyboardBehavior = (expression) => {
1239
+ if (!n.ConditionalExpression.check(expression))
1240
+ return false;
1241
+ const { test, consequent, alternate } = expression;
1242
+ const platform = n.BinaryExpression.check(test) && test.operator === '===' ? test.left : undefined;
1243
+ return (n.MemberExpression.check(platform) &&
1244
+ n.Identifier.check(platform.object) &&
1245
+ sources.get(platform.object.name)?.module === 'react-native' &&
1246
+ sources.get(platform.object.name)?.imported === 'Platform' &&
1247
+ n.Identifier.check(platform.property) &&
1248
+ platform.property.name === 'OS' &&
1249
+ staticString(test.right) === 'ios' &&
1250
+ staticString(consequent) === 'padding' &&
1251
+ staticString(alternate) === 'height');
1252
+ };
1253
+ /** The behaviors a converted keyboard avoiding view wrote: the parity's before side writes React Native's own `Platform`. */
1254
+ const keyboardBehaviors = new Set();
1255
+ /** Each route's Screen: the return around it, and the screen modifiers what is around it draws. */
1256
+ const screenOuter = new Map();
1257
+ /** Where each module-level name is read outside a function, before its own statement. */
1258
+ const readsBefore = (name, statement) => {
1259
+ let early = false;
1260
+ recast.visit(ast, {
1261
+ visitFunction: () => false,
1262
+ visitIdentifier(path) {
1263
+ if (path.node.name === name && path.node.start < statement.start)
1264
+ early = true;
1265
+ this.traverse(path);
1266
+ },
1267
+ });
1268
+ return early;
1269
+ };
1270
+ for (const statement of ast.program.body) {
1271
+ const declaration = n.ExportDefaultDeclaration.check(statement) || n.ExportNamedDeclaration.check(statement)
1272
+ ? statement.declaration
1273
+ : statement;
1274
+ let fn;
1275
+ let name;
1276
+ if (n.FunctionDeclaration.check(declaration)) {
1277
+ fn = declaration;
1278
+ name = declaration.id?.name;
1279
+ }
1280
+ else if (n.VariableDeclaration.check(declaration) &&
1281
+ declaration.kind === 'const' &&
1282
+ declaration.declarations.length === 1) {
1283
+ const declarator = declaration.declarations[0];
1284
+ if (n.Identifier.check(declarator.id) &&
1285
+ !declarator.id.typeAnnotation &&
1286
+ (n.ArrowFunctionExpression.check(declarator.init) ||
1287
+ (n.FunctionExpression.check(declarator.init) && !declarator.init.id))) {
1288
+ fn = declarator.init;
1289
+ name = declarator.id.name;
1290
+ }
1291
+ }
1292
+ if (!fn || !name || !/^[A-Z]/.test(name) || fn.async || fn.generator || fn.returnType)
1293
+ continue;
1294
+ const returned = [];
1295
+ if (!n.BlockStatement.check(fn.body))
1296
+ returned.push(fn.body);
1297
+ else
1298
+ recast.visit(fn.body, {
1299
+ visitFunction: () => false,
1300
+ visitReturnStatement(path) {
1301
+ returned.push(path.node.argument);
1302
+ return false;
1303
+ },
1304
+ });
1305
+ const screens = returned.map(peelScreen);
1306
+ if (!returned.length || !screens.every((p) => p !== undefined))
1307
+ continue;
1308
+ // A Screen inside an element that is no screen modifier stays JSX, with what keeps it.
1309
+ const kept = screens.find((p) => 'reason' in p);
1310
+ if (kept) {
1311
+ for (const p of screens)
1312
+ earlyScreens.set(p.screen, 'reason' in p ? p.reason : kept.reason);
1313
+ continue;
1314
+ }
1315
+ if (readsBefore(name, statement)) {
1316
+ for (const { screen: node } of screens)
1317
+ earlyScreens.set(node, {
1318
+ subject: 'Screen',
1319
+ code: 'screen:read-early',
1320
+ why: `\`${name}\` is read before its declaration, where \`const ${name} = screen(…)\` is not yet defined`,
1321
+ });
1322
+ continue;
1323
+ }
1324
+ returned.forEach((outer, i) => {
1325
+ const { screen, mods } = screens[i];
1326
+ screenRoutes.set(screen, fn);
1327
+ if (outer !== screen)
1328
+ screenOuter.set(screen, { outer, mods });
1329
+ });
1330
+ screenDeclarations.set(fn, { statement, name });
1331
+ }
1332
+ /**
1333
+ * Why a Screen that is no screen's return stays JSX: what is around it, or
1334
+ * the component's other returns. `screen()` wraps the whole component, so a
1335
+ * view beside the Screen or around it would draw inside it.
1336
+ */
1337
+ const screenPlaces = new Map(earlyScreens);
1338
+ recast.visit(ast, {
1339
+ visitJSXElement(path) {
1340
+ const node = path.node;
1341
+ if (isScreenElement(node) && !screenRoutes.has(node) && !earlyScreens.has(node)) {
1342
+ // Past what its screen modifiers draw (a colour scope, a keyboard avoiding view, a provider).
1343
+ let at = path;
1344
+ while (n.JSXElement.check(at.parent?.node) &&
1345
+ peelScreen(at.parent.node)?.screen === node &&
1346
+ 'mods' in peelScreen(at.parent.node))
1347
+ at = at.parent;
1348
+ const outer = at.node;
1349
+ const parent = at.parent?.node;
1350
+ const name = (element) => `\`${jsxName(element) ?? 'an element'}\``;
1351
+ const beside = n.JSXFragment.check(parent)
1352
+ ? parent.children.filter((child) => child !== outer && n.JSXElement.check(child))
1353
+ : [];
1354
+ const wrapper = n.JSXElement.check(parent) ? screenWrapper(parent) : undefined;
1355
+ screenPlaces.set(node, wrapper && 'reason' in wrapper
1356
+ ? wrapper.reason
1357
+ : beside.length
1358
+ ? {
1359
+ subject: 'Screen',
1360
+ code: 'screen:beside',
1361
+ why: `beside ${beside.map(name).join(', ')}: \`screen()\` wraps the whole component, so a view beside the Screen would draw inside it (one that draws nothing, a head element, moves into the Screen by hand)`,
1362
+ }
1363
+ : {
1364
+ subject: 'Screen',
1365
+ code: 'screen:returns',
1366
+ why: 'a return of its component that is no Screen (`null`, another view, a choice): `screen()` would draw a Screen around it',
1367
+ });
1368
+ }
1369
+ this.traverse(path);
1370
+ },
1371
+ });
1372
+ /**
1373
+ * An icon's fill as the chain paints it: a Bloom theme colour read from
1374
+ * `useTheme()` is its role, and a static colour (a literal, or a module
1375
+ * constant) an app colour, the same colour in both schemes. Anything else is a reason.
1376
+ */
1377
+ function iconFill(node, fill) {
1378
+ const reason = (code, why) => ({ reason: { subject: 'fill', code, why } });
1379
+ const expression = attributeExpression(fill);
1380
+ const role = themeRoles.get(expression);
1381
+ if (role) {
1382
+ const scope = insideOf(node, [COLOR_SCOPE]);
1383
+ return scope
1384
+ ? reason('icon-fill:color-scope', `a theme colour read outside the ${scope} the icon is drawn in, where the role paints the scope's scheme`)
1385
+ : { role };
1386
+ }
1387
+ const constant = n.Identifier.check(expression) && colorConstantReads.has(expression)
1388
+ ? expression.name
1389
+ : undefined;
1390
+ const value = constant ? colorConstants.get(constant)?.value : staticString(fill);
1391
+ if (value !== undefined) {
1392
+ if (!isAppColorValue(value))
1393
+ return reason('icon-fill:not-a-colour', 'a colour the platforms do not paint alike (`currentColor`, an `hsl()`, a name only one knows): an app colour is a hex, an `rgb()` or `rgba()` of numbers, or a CSS colour name');
1394
+ const name = constant ?? appColorName(value);
1395
+ if (!constant && colorConstants.has(name))
1396
+ return reason('icon-fill', `a colour whose token name the file declares (\`${name}\`)`);
1397
+ return { color: constant ? { name, value, constant, read: expression } : { name, value } };
1398
+ }
1399
+ // `x.colors.key` or `colors.key` with no role, or not bound to `useTheme()` where it is read.
1400
+ const object = n.MemberExpression.check(expression) ? expression.object : undefined;
1401
+ const themed = object &&
1402
+ !expression.computed &&
1403
+ n.Identifier.check(expression.property) &&
1404
+ ((n.Identifier.check(object) && object.name === 'colors') ||
1405
+ (n.MemberExpression.check(object) &&
1406
+ !object.computed &&
1407
+ n.Identifier.check(object.property) &&
1408
+ object.property.name === 'colors'));
1409
+ if (themed && !ROLE_OF_THEME_COLOR.has(expression.property.name))
1410
+ return reason('icon-fill:no-role', `a theme colour no language role paints (\`${expression.property.name}\`)`);
1411
+ if (themed)
1412
+ return reason('icon-fill:theme-handed-in', 'a theme colour read from a theme handed in (a prop, a parameter), not from `useTheme()` here: the scheme it was read in may not be the one the icon is drawn in');
1413
+ return reason('icon-fill', 'a fill set at runtime, or read from outside the file');
1414
+ }
1415
+ const results = new Map();
1416
+ const classes = new Set();
1417
+ let candidates = 0;
1418
+ const counted = new Set();
1419
+ const unconverted = [];
1420
+ const convertedNodes = new Set();
1421
+ const convertedLocals = new Set();
1422
+ /** The text style a Bloom typography component draws its Text in. */
1423
+ function textStyleOf(local) {
1424
+ const source = sources.get(local);
1425
+ return source?.module === '@oxy.so/bloom/typography' ? components_1.TEXT_STYLES[source.imported] : undefined;
1426
+ }
1427
+ function elementOf(node) {
1428
+ const local = jsxName(node);
1429
+ if (!local)
1430
+ return undefined;
1431
+ const kind = kindOf(sources.get(local));
1432
+ return kind ? { kind, local } : undefined;
1433
+ }
1434
+ /** Converts one element, children included; a child that cannot convert is embedded. */
1435
+ function convert(node) {
1436
+ const cached = results.get(node);
1437
+ if (cached)
1438
+ return cached;
1439
+ const element = elementOf(node);
1440
+ let result;
1441
+ if (!element)
1442
+ result = {
1443
+ reasons: [{ subject: jsxName(node) ?? 'element', code: 'not-a-candidate', why: '' }],
1444
+ };
1445
+ else {
1446
+ if (!counted.has(node)) {
1447
+ counted.add(node);
1448
+ candidates++;
1449
+ }
1450
+ result = convertCandidate(node, element.kind, element.local);
1451
+ }
1452
+ results.set(node, result);
1453
+ return result;
1454
+ }
1455
+ function convertCandidate(node, kind, local) {
1456
+ if (kind === 'rnImage')
1457
+ return {
1458
+ reasons: [
1459
+ {
1460
+ subject: 'Image',
1461
+ code: 'react-native-image',
1462
+ why: 'React Native’s Image: the language’s Image is Bloom’s BloomImage (expo-image on a device)',
1463
+ },
1464
+ ],
1465
+ };
1466
+ if (kind === 'button')
1467
+ return convertButton(node);
1468
+ if (kind === 'kept' && screenRoutes.has(node))
1469
+ return convertScreen(node);
1470
+ if (kind === 'kept' && sources.get(local)?.module === FAB_MODULE)
1471
+ return convertFab(node);
1472
+ if (kind === 'kept' && sources.get(local)?.module === DROPDOWN)
1473
+ return convertDropdownMenu(node);
1474
+ if (kind === 'kept') {
1475
+ const source = sources.get(local);
1476
+ const removed = components_1.REMOVED[`${source.module}#${source.imported}`];
1477
+ return {
1478
+ reasons: [
1479
+ removed
1480
+ ? {
1481
+ subject: local,
1482
+ code: `removed:${source.imported}`,
1483
+ why: `removed in Bloom 22: use ${removed}`,
1484
+ }
1485
+ : (screenPlaces.get(node) ?? {
1486
+ subject: local,
1487
+ code: `kept:${source.imported}`,
1488
+ why: components_1.KEPT[`${source.module}#${source.imported}`],
1489
+ }),
1490
+ ],
1491
+ };
1492
+ }
1493
+ if (kind === 'component') {
1494
+ const source = sources.get(local);
1495
+ const rule = (0, components_1.ruleFor)(source.module, source.imported);
1496
+ // A part converts with its compound element (`convertParts`), never alone.
1497
+ if (rule.partOf)
1498
+ return {
1499
+ reasons: [
1500
+ {
1501
+ subject: local,
1502
+ code: `${rule.node}:part`,
1503
+ why: `a part of \`${rule.partOf.split('#')[1]}\`, converted only with it, which stays JSX here`,
1504
+ },
1505
+ ],
1506
+ };
1507
+ return rule.shell ? convertShell(node, rule, rule.shell) : convertComponent(node, rule);
1508
+ }
1509
+ const reasons = [];
1510
+ const fail = (subject, code, why) => reasons.push({ subject, code, why });
1511
+ const props = [];
1512
+ let key = null;
1513
+ let className = '';
1514
+ /** A className chosen at runtime: its condition and the other branch's classes. */
1515
+ let other;
1516
+ let numberOfLines;
1517
+ let variant;
1518
+ let size;
1519
+ /** The utilities a static `style` writes, read with the className. */
1520
+ const styleClasses = [];
1521
+ const styleMods = [];
1522
+ let styleChoice;
1523
+ /** An icon's `width`, `height` and `fill`. */
1524
+ const iconProps = new Map();
1525
+ /** A TouchableOpacity: its press fades it (`.pressFade()`), at its `activeOpacity` token. */
1526
+ const fades = kind === 'pressable' &&
1527
+ sources.get(local)?.imported === 'TouchableOpacity';
1528
+ let fade;
1529
+ for (const attribute of node.openingElement.attributes) {
1530
+ if (!n.JSXAttribute.check(attribute) || !n.JSXIdentifier.check(attribute.name)) {
1531
+ fail('{...spread}', 'spread', 'spread props: the codemod cannot see what they set');
1532
+ continue;
1533
+ }
1534
+ const name = attribute.name.name;
1535
+ const value = attribute.value;
1536
+ if (value === null || value === undefined) {
1537
+ if (kind === 'pressable' && name === 'disabled')
1538
+ props.push({ name: 'disabled', args: [] });
1539
+ else
1540
+ fail(name, `prop:${name}`, 'a boolean prop the codemod does not map');
1541
+ continue;
1542
+ }
1543
+ const expression = attributeExpression(value);
1544
+ if (name === 'key') {
1545
+ key = { node: expression, hole: 'key', attribute };
1546
+ continue;
1547
+ }
1548
+ if (name === 'className') {
1549
+ const text = staticString(value);
1550
+ const choice = text === undefined ? classNameChoice(expression) : undefined;
1551
+ if (text !== undefined)
1552
+ className = text;
1553
+ else if (choice) {
1554
+ className = choice.whenTrue;
1555
+ other = { test: { node: choice.test, hole: 'condition' }, className: choice.whenFalse };
1556
+ choiceClasses.set(expression, `${choice.whenTrue} ${choice.whenFalse}`);
1557
+ }
1558
+ else
1559
+ fail('className', 'dynamic-className', 'a className built at runtime other than one of two static strings by a plain condition');
1560
+ continue;
1561
+ }
1562
+ if (name === 'testID') {
1563
+ props.push({
1564
+ name: 'testID',
1565
+ args: [staticString(value) ?? { node: expression, hole: 'string' }],
1566
+ });
1567
+ continue;
1568
+ }
1569
+ if (name === 'accessibilityLabel' && kind !== 'icon') {
1570
+ props.push({
1571
+ name: 'label',
1572
+ args: [staticString(value) ?? { node: expression, hole: 'string' }],
1573
+ });
1574
+ continue;
1575
+ }
1576
+ if (kind !== 'icon' && name === 'accessibilityHint') {
1577
+ props.push({
1578
+ name: 'hint',
1579
+ args: [staticString(value) ?? { node: expression, hole: 'string' }],
1580
+ });
1581
+ continue;
1582
+ }
1583
+ if (kind === 'pressable' && (name === 'onPress' || name === 'onLongPress')) {
1584
+ props.push({ name, args: [{ node: expression, hole: 'handler' }] });
1585
+ continue;
1586
+ }
1587
+ if (kind === 'pressable' && name === 'disabled') {
1588
+ props.push({ name: 'disabled', args: [{ node: expression, hole: 'boolean' }] });
1589
+ continue;
1590
+ }
1591
+ if (fades && name === 'activeOpacity') {
1592
+ const token = OPACITY_TOKEN.get(staticNumber(value));
1593
+ if (token === undefined)
1594
+ fail(name, 'prop:activeOpacity', 'an activeOpacity that is no opacity token, or set at runtime');
1595
+ else
1596
+ fade = token;
1597
+ continue;
1598
+ }
1599
+ if (kind !== 'icon' && name === 'accessibilityLiveRegion') {
1600
+ const region = staticString(value);
1601
+ if (region !== undefined && LIVE_REGIONS.has(region))
1602
+ props.push({ name: 'liveRegion', args: [region] });
1603
+ else
1604
+ fail(name, 'prop:accessibilityLiveRegion', 'a live region set at runtime');
1605
+ continue;
1606
+ }
1607
+ if (kind !== 'icon' && name === 'accessibilityState') {
1608
+ props.push({ name: 'accessibilityState', args: [{ node: expression, hole: 'state' }] });
1609
+ continue;
1610
+ }
1611
+ if (kind !== 'icon' && name === 'accessibilityValue') {
1612
+ props.push({ name: 'accessibilityValue', args: [{ node: expression, hole: 'state' }] });
1613
+ continue;
1614
+ }
1615
+ // The escape hatches, on the view's outermost box as React Native's own.
1616
+ if (kind !== 'icon' && (name === 'ref' || name === 'onLayout')) {
1617
+ props.push({ name, args: [{ node: expression, hole: 'handler' }] });
1618
+ continue;
1619
+ }
1620
+ if (kind !== 'icon' && name === 'hitSlop') {
1621
+ const calls = hitSlopCalls(value);
1622
+ if (calls === undefined)
1623
+ fail(name, 'prop:hitSlop', 'a hit slop whose sides are no hit slop tokens, or set at runtime');
1624
+ else
1625
+ for (const args of calls)
1626
+ props.push({ name: 'hitSlop', args });
1627
+ continue;
1628
+ }
1629
+ if ((kind === 'bloomText' || kind === 'rnText') && name === 'numberOfLines') {
1630
+ numberOfLines = staticNumber(value) ?? { node: expression, hole: 'number' };
1631
+ continue;
1632
+ }
1633
+ if (kind === 'bloomText' && name === 'variant') {
1634
+ const text = staticString(value);
1635
+ if (text === undefined || !RAMP.has(text))
1636
+ fail('variant', 'variant', 'a variant that is no type-ramp step, or set at runtime');
1637
+ else
1638
+ variant = text;
1639
+ continue;
1640
+ }
1641
+ if (name === 'style' && kind !== 'icon') {
1642
+ // A theme colour read from `useTheme()` here is its role, as an icon's fill is.
1643
+ const read = (key, read) => {
1644
+ const inset = insetPadding(key, read);
1645
+ if (inset)
1646
+ return inset;
1647
+ // The surface fill, read where the component is: the same surface the view sits on unless
1648
+ // a Bloom component between them (a Card, a Surface) publishes one of its own.
1649
+ if (surfaceReads.has(read) && !insideBloomComponent(node)) {
1650
+ if (key === 'backgroundColor')
1651
+ return { name: 'background', args: ['surfaceFill'] };
1652
+ if (key === 'color' && (kind === 'bloomText' || kind === 'rnText'))
1653
+ return { name: 'foreground', args: ['surfaceFill'] };
1654
+ }
1655
+ if (kind === 'bloomText' || kind === 'rnText') {
1656
+ const text = (0, style_1.textDeclaration)(key, read);
1657
+ if (text)
1658
+ return text;
1659
+ }
1660
+ // A role, or a role at an opacity (`withAlpha(colors.primary, 0.1)`).
1661
+ const role = roleOf(read);
1662
+ if (typeof role !== 'string' || insideOf(node, [COLOR_SCOPE]))
1663
+ return undefined;
1664
+ if (key === 'backgroundColor')
1665
+ return { name: 'background', args: [role] };
1666
+ if (key === 'color' && (kind === 'bloomText' || kind === 'rnText'))
1667
+ return { name: 'foreground', args: [role] };
1668
+ return undefined;
1669
+ };
1670
+ // A Pressable's style of its press state (`({ pressed }) => [base, pressed && dim]`): `.when('pressed')`.
1671
+ const fn = kind === 'pressable' &&
1672
+ n.ArrowFunctionExpression.check(expression) &&
1673
+ expression.params.length === 1 &&
1674
+ n.ObjectPattern.check(expression.params[0]) &&
1675
+ !n.BlockStatement.check(expression.body)
1676
+ ? expression
1677
+ : undefined;
1678
+ const pressedProperty = fn?.params[0].properties.find((p) => (n.ObjectProperty.check(p) || n.Property.check(p)) &&
1679
+ n.Identifier.check(p.key) &&
1680
+ p.key.name === 'pressed' &&
1681
+ n.Identifier.check(p.value));
1682
+ const style = fn && pressedProperty && fn.params[0].properties.length === 1
1683
+ ? staticStyle(fn.body, read, pressedProperty.value.name)
1684
+ : staticStyle(expression, read);
1685
+ if (style.ok) {
1686
+ styleClasses.push(...style.classes);
1687
+ styleMods.push(...style.mods);
1688
+ styleChoice = style.choice;
1689
+ }
1690
+ else
1691
+ fail(style.subject, 'style', style.why);
1692
+ continue;
1693
+ }
1694
+ // What takes touches: `none` nothing (SwiftUI's `allowsHitTesting(false)`), `box-none` what is inside only, `box-only` the view only.
1695
+ if (name === 'pointerEvents' && (kind === 'view' || kind === 'pressable')) {
1696
+ const hitTesting = hitTestingOf(attributeExpression(value));
1697
+ if (hitTesting !== undefined)
1698
+ props.push({ name: 'allowsHitTesting', args: [hitTesting] });
1699
+ else
1700
+ fail(name, 'prop:pointerEvents', 'a pointerEvents set at runtime');
1701
+ continue;
1702
+ }
1703
+ if (name === 'accessibilityRole' && kind !== 'icon') {
1704
+ const role = staticString(value);
1705
+ if (role !== undefined && ROLES.has(role))
1706
+ props.push({ name: 'role', args: [role] });
1707
+ else
1708
+ fail(name, 'role', 'a role the language does not take, or set at runtime');
1709
+ continue;
1710
+ }
1711
+ if (kind === 'icon' && name === 'size') {
1712
+ size = value;
1713
+ continue;
1714
+ }
1715
+ if (kind === 'icon' && (name === 'width' || name === 'height' || name === 'fill')) {
1716
+ iconProps.set(name, value);
1717
+ continue;
1718
+ }
1719
+ fail(name, `prop:${name}`, `the prop \`${name}\` has no mapping`);
1720
+ }
1721
+ // A style chosen by a condition is the className choice it writes: what each branch adds.
1722
+ if (styleChoice) {
1723
+ if (other)
1724
+ fail('style', 'dynamic-className', 'a className and a style both chosen at runtime');
1725
+ else {
1726
+ other = {
1727
+ test: { node: styleChoice.test, hole: 'condition' },
1728
+ className: [className, ...styleChoice.whenFalse].filter(Boolean).join(' '),
1729
+ };
1730
+ className = [className, ...styleChoice.whenTrue].filter(Boolean).join(' ');
1731
+ }
1732
+ }
1733
+ for (const token of `${className} ${other?.className ?? ''}`.split(/\s+/).filter(Boolean))
1734
+ classes.add(token);
1735
+ if (styleClasses.length) {
1736
+ className = [className, ...styleClasses].filter(Boolean).join(' ');
1737
+ if (other)
1738
+ other.className = [other.className, ...styleClasses].filter(Boolean).join(' ');
1739
+ }
1740
+ if (kind === 'icon') {
1741
+ if (className || other)
1742
+ fail('className', 'icon-className', 'a className on an icon');
1743
+ const mods = [];
1744
+ // A width and a height of one number are the glyph's side, as `size` is.
1745
+ const width = iconProps.get('width');
1746
+ const height = iconProps.get('height');
1747
+ if (width !== undefined || height !== undefined) {
1748
+ const side = staticNumber(width);
1749
+ if (size !== undefined || side === undefined || staticNumber(height) !== side)
1750
+ fail('width', 'icon-size', 'a width and a height that are not one static side');
1751
+ else
1752
+ size = width;
1753
+ }
1754
+ if (size !== undefined) {
1755
+ // A rung by name, or a number of points that is a rung's (Bloom draws a number as its side).
1756
+ const named = staticString(size);
1757
+ const number = staticNumber(size);
1758
+ const rung = ICON_SIZES.find(([k, v]) => k === named || v === number);
1759
+ if (!rung)
1760
+ fail('size', 'icon-size', 'an icon size that is no icon rung, or set at runtime');
1761
+ else
1762
+ mods.push({ name: 'size', args: [rung[0]] });
1763
+ }
1764
+ if (node.children.some((c) => !(n.JSXText.check(c) && cleanJsxText(c.value) === '')))
1765
+ fail('children', 'icon-children', 'an icon with children');
1766
+ const fill = iconProps.get('fill');
1767
+ let color;
1768
+ if (fill !== undefined) {
1769
+ const ink = iconFill(node, fill);
1770
+ if ('role' in ink)
1771
+ mods.push({ name: 'foreground', args: [ink.role] });
1772
+ else if ('color' in ink)
1773
+ color = ink.color;
1774
+ else
1775
+ reasons.push(ink.reason);
1776
+ }
1777
+ else {
1778
+ // A bare Bloom icon paints primary; Icon(X) paints the ink around it.
1779
+ mods.push(...options.table.bareIcon);
1780
+ }
1781
+ if (reasons.length)
1782
+ return { reasons };
1783
+ return { ir: { type: 'icon', component: local, mods, key, ...(color && { color }) } };
1784
+ }
1785
+ const isText = kind === 'bloomText' || kind === 'rnText';
1786
+ // Bloom's typography components (`Muted`, `H2`) are its Text in a text style.
1787
+ const textStyle = textStyleOf(local);
1788
+ if (textStyle && (className || other))
1789
+ fail('className', 'text-style-className', 'a className on a typography component drops its own style');
1790
+ const host = isText ? 'text' : kind;
1791
+ const resolveOptions = {
1792
+ overridden: options.overridden,
1793
+ styleMods,
1794
+ styleClasses: new Set(styleClasses),
1795
+ };
1796
+ let resolution = (0, resolve_1.resolveClassName)(className, host, options.table, resolveOptions);
1797
+ if (!resolution.ok)
1798
+ reasons.push(...resolution.reasons);
1799
+ // The other branch resolves alike: the same modifiers, only their values differing, or a variant of each.
1800
+ let choice = null;
1801
+ if (other) {
1802
+ const otherwise = (0, resolve_1.resolveClassName)(other.className, host, options.table, resolveOptions);
1803
+ if (!otherwise.ok)
1804
+ reasons.push(...otherwise.reasons);
1805
+ else if (resolution.ok) {
1806
+ const mods = sameShape(resolution.value, otherwise.value);
1807
+ const only = mods ? undefined : branchesOnly(resolution.value, otherwise.value);
1808
+ if (mods)
1809
+ choice = { test: other.test, mods };
1810
+ else if (only) {
1811
+ choice = { test: other.test, only };
1812
+ resolution = { ok: true, value: { ...resolution.value, mods: only.both } };
1813
+ }
1814
+ else
1815
+ fail('className', 'dynamic-className', 'a className whose two branches differ in their layout axis or variants, or add a modifier a variant cannot change');
1816
+ }
1817
+ }
1818
+ if (isText) {
1819
+ const runs = [];
1820
+ for (const child of node.children) {
1821
+ if (n.JSXText.check(child)) {
1822
+ const text = cleanJsxText(child.value);
1823
+ if (text)
1824
+ runs.push({ type: 'string', value: text });
1825
+ }
1826
+ else if (n.JSXExpressionContainer.check(child)) {
1827
+ if (n.JSXEmptyExpression.check(child.expression))
1828
+ fail('{/* */}', 'comment', 'a JSX comment (kept only in JSX)');
1829
+ else if (n.StringLiteral.check(child.expression))
1830
+ runs.push({ type: 'string', value: child.expression.value });
1831
+ else
1832
+ runs.push({ type: 'expr', value: { node: child.expression, hole: 'text' } });
1833
+ }
1834
+ else if (n.JSXElement.check(child)) {
1835
+ const inner = convert(child);
1836
+ const innerKind = elementOf(child)?.kind;
1837
+ // A span is the same Text as its parent: Bloom's in Bloom's, React Native's in React Native's.
1838
+ const span = jsxName(child);
1839
+ if ('ir' in inner && innerKind === kind && !(span && textStyleOf(span)))
1840
+ runs.push(inner.ir);
1841
+ else
1842
+ fail(jsxName(child) ?? 'element', 'text-child', 'an element inside a Text that is no convertible Text');
1843
+ }
1844
+ else
1845
+ fail('child', 'text-child', 'a child inside a Text the codemod does not map');
1846
+ }
1847
+ if (!resolution.ok || reasons.length)
1848
+ return { reasons };
1849
+ const resolved = resolution.value;
1850
+ const fontMods = textStyle ? [{ name: 'textStyle', args: [textStyle] }] : [];
1851
+ if (variant) {
1852
+ if ([...resolved.mods, ...choiceMods(choice)].some((m) => m.name === 'font' || m.name === 'weight'))
1853
+ return {
1854
+ reasons: [
1855
+ { subject: 'variant', code: 'conflict', why: 'a variant and a className font' },
1856
+ ],
1857
+ };
1858
+ const [family, weight] = [
1859
+ variant.replace(/-(regular|medium|semibold|bold)$/, ''),
1860
+ variant.split('-').pop(),
1861
+ ];
1862
+ fontMods.push({ name: 'font', args: [family] });
1863
+ if (weight !== 'regular')
1864
+ fontMods.push({ name: 'weight', args: [weight] });
1865
+ }
1866
+ if (numberOfLines !== undefined)
1867
+ props.push({ name: 'lines', args: [numberOfLines] });
1868
+ return {
1869
+ ir: {
1870
+ type: 'text',
1871
+ raw: kind === 'rnText',
1872
+ resolved: { ...resolved, mods: [...resolved.mods, ...fontMods] },
1873
+ choice: choice && 'mods' in choice
1874
+ ? { ...choice, mods: [...choice.mods, ...fontMods] }
1875
+ : choice,
1876
+ props,
1877
+ key,
1878
+ runs,
1879
+ },
1880
+ };
1881
+ }
1882
+ // A stack: View or Pressable. A Pressable with no press is still a focusable pressable; a stack with none is a View.
1883
+ if (kind === 'pressable' &&
1884
+ !props.some((p) => p.name === 'onPress' || p.name === 'onLongPress'))
1885
+ fail('Pressable', 'pressable-without-press', 'a Pressable with no onPress or onLongPress stays a focusable pressable');
1886
+ const children = [];
1887
+ for (const child of node.children) {
1888
+ if (n.JSXText.check(child)) {
1889
+ if (cleanJsxText(child.value))
1890
+ fail('text', 'raw-text', 'text directly inside a View');
1891
+ }
1892
+ else if (n.JSXExpressionContainer.check(child)) {
1893
+ if (n.JSXEmptyExpression.check(child.expression)) {
1894
+ const comment = commentOf(child);
1895
+ if (comment)
1896
+ children.push(comment);
1897
+ else
1898
+ fail('{/* */}', 'comment', 'a line comment in JSX (only a block comment moves)');
1899
+ continue;
1900
+ }
1901
+ children.push(expressionChild(child.expression));
1902
+ }
1903
+ else if (n.JSXElement.check(child)) {
1904
+ const inner = convert(child);
1905
+ children.push('ir' in inner ? inner.ir : { type: 'embed', content: { node: child, hole: 'element' } });
1906
+ }
1907
+ else if (n.JSXFragment.check(child)) {
1908
+ children.push({ type: 'embed', content: { node: child, hole: 'element' } });
1909
+ }
1910
+ else
1911
+ fail('child', 'child', 'a child the codemod does not map');
1912
+ }
1913
+ if (!resolution.ok || reasons.length)
1914
+ return { reasons };
1915
+ if (isPressableScale(sources.get(local)))
1916
+ props.push({ name: 'pressScale', args: [] });
1917
+ if (fades)
1918
+ props.push({ name: 'pressFade', args: fade === undefined ? [] : [fade] });
1919
+ return { ir: { type: 'stack', resolved: resolution.value, choice, props, key, children } };
1920
+ }
1921
+ /**
1922
+ * A route's Screen by `SCREEN`: its one child is the body's root, and several
1923
+ * (a fragment's, a comment or a condition among them) a `Group` of them, which
1924
+ * draws no view of its own; its props are the root's screen modifiers, with no
1925
+ * header `.header(false)`.
1926
+ */
1927
+ function convertScreen(node) {
1928
+ const inner = convertComponent(node, components_1.SCREEN);
1929
+ if (!('ir' in inner) || inner.ir.type !== 'component')
1930
+ return inner;
1931
+ const { args } = inner.ir;
1932
+ const only = args.length === 1 ? args[0] : undefined;
1933
+ const view = only && isTagged(only) && only.$ === 'view' ? only.view : undefined;
1934
+ if (!args.some((arg) => isTagged(arg) && arg.$ === 'view' && arg.view.type !== 'comment'))
1935
+ return {
1936
+ reasons: [
1937
+ {
1938
+ subject: 'children',
1939
+ code: 'screen:children',
1940
+ why: 'a screen with no content: the body’s root is a view',
1941
+ },
1942
+ ],
1943
+ };
1944
+ const root = view && view.type !== 'cond' && view.type !== 'comment'
1945
+ ? view
1946
+ : { type: 'component', node: 'Group', within: undefined, args, props: [], key: null };
1947
+ const props = inner.ir.props;
1948
+ if (!props.some((prop) => prop.name === 'header'))
1949
+ props.unshift({ name: 'header', args: [false] });
1950
+ props.push(...(screenOuter.get(node)?.mods ?? []));
1951
+ return { ir: { type: 'screen', content: root, props } };
1952
+ }
1953
+ /**
1954
+ * A className that is one of two static strings by one condition:
1955
+ * `test ? 'a' : 'b'` (a branch of `''`, `undefined` or `null` writes no
1956
+ * class), or a template literal holding one such choice of strings. The
1957
+ * condition is a plain read (no call), since the chain reads it once per
1958
+ * value it chooses.
1959
+ */
1960
+ function classNameChoice(expression) {
1961
+ const template = n.TemplateLiteral.check(expression) && expression.expressions.length === 1;
1962
+ const choice = template ? expression.expressions[0] : expression;
1963
+ if (!n.ConditionalExpression.check(choice) || !isPlainRead(choice.test))
1964
+ return undefined;
1965
+ // Outside a template an absent branch is no className; inside one it would be the word.
1966
+ const branch = (node) => !template &&
1967
+ (n.NullLiteral.check(node) || (n.Identifier.check(node) && node.name === 'undefined'))
1968
+ ? ''
1969
+ : staticString(node);
1970
+ const [whenTrue, whenFalse] = [branch(choice.consequent), branch(choice.alternate)];
1971
+ if (whenTrue === undefined || whenFalse === undefined)
1972
+ return undefined;
1973
+ if (!template)
1974
+ return { test: choice.test, whenTrue, whenFalse };
1975
+ const [head, tail] = expression.quasis.map((q) => q.value.cooked);
1976
+ return {
1977
+ test: choice.test,
1978
+ whenTrue: head + whenTrue + tail,
1979
+ whenFalse: head + whenFalse + tail,
1980
+ };
1981
+ }
1982
+ /** The modifiers a choice writes besides the chain's. */
1983
+ function choiceMods(choice) {
1984
+ if (!choice)
1985
+ return [];
1986
+ return 'mods' in choice ? choice.mods : [...choice.only.whenTrue, ...choice.only.whenFalse];
1987
+ }
1988
+ /**
1989
+ * Each branch's own modifiers over those both write, when the branches lay
1990
+ * out on one axis with the same variants, and what each adds alone is what
1991
+ * a variant under the app's condition changes. Both branches resolved with
1992
+ * no two classes setting one thing, so a modifier one branch adds sets
1993
+ * nothing the other modifiers set: the variant adds it, overriding nothing.
1994
+ */
1995
+ function branchesOnly(chain, other) {
1996
+ if (chain.axis !== other.axis || (0, table_1.modKey)(chain.variants) !== (0, table_1.modKey)(other.variants))
1997
+ return undefined;
1998
+ const rest = other.mods.map(table_1.modKey);
1999
+ const both = [];
2000
+ const whenTrue = [];
2001
+ for (const mod of chain.mods) {
2002
+ const at = rest.indexOf((0, table_1.modKey)(mod));
2003
+ if (at < 0)
2004
+ whenTrue.push(mod);
2005
+ else {
2006
+ both.push(mod);
2007
+ rest[at] = '';
2008
+ }
2009
+ }
2010
+ const whenFalse = other.mods.filter((_, i) => rest[i] !== '');
2011
+ return [...whenTrue, ...whenFalse].every(resolve_1.heldVariantChanges)
2012
+ ? { both, whenTrue, whenFalse }
2013
+ : undefined;
2014
+ }
2015
+ /**
2016
+ * The other branch's modifiers when they are the chain's, one for one, with
2017
+ * arguments of the same kinds (the same axis and variants too); else undefined.
2018
+ */
2019
+ function sameShape(chain, other) {
2020
+ const same = chain.axis === other.axis &&
2021
+ (0, table_1.modKey)(chain.variants) === (0, table_1.modKey)(other.variants) &&
2022
+ chain.mods.length === other.mods.length &&
2023
+ chain.mods.every((mod, i) => {
2024
+ const at = other.mods[i];
2025
+ return (mod.name === at.name &&
2026
+ mod.args.length === at.args.length &&
2027
+ mod.args.every((arg, j) => typeof arg === typeof at.args[j] && typeof arg !== 'object'));
2028
+ });
2029
+ return same ? other.mods : undefined;
2030
+ }
2031
+ /**
2032
+ * A shell around one input, as the input's node: the input by its own rule
2033
+ * (its shell is this one, so its context is), the glyphs beside it as the
2034
+ * node's `icon` and `trailingIcon`, and the shell's props joined to the input's.
2035
+ */
2036
+ function convertShell(node, rule, shell) {
2037
+ const fail = (subject, why) => ({
2038
+ reasons: [{ subject, code: `${rule.node}:${subject}`, why }],
2039
+ });
2040
+ const named = (child) => {
2041
+ const local = n.JSXElement.check(child) ? jsxName(child) : undefined;
2042
+ const source = local ? sources.get(local) : undefined;
2043
+ return source ? `${source.module}#${source.imported}` : undefined;
2044
+ };
2045
+ const children = node.children.filter((c) => !(n.JSXText.check(c) && cleanJsxText(c.value) === ''));
2046
+ const at = children.findIndex((child) => named(child) === shell.input);
2047
+ const input = children[at];
2048
+ const [inputSource] = shell.input.split('#');
2049
+ const inputRule = (0, components_1.ruleFor)(inputSource, shell.input.slice(inputSource.length + 1));
2050
+ if (!input || !inputRule || at > 1 || children.length > at + 2)
2051
+ return fail('children', 'a shell holds its input, a glyph before it and one after');
2052
+ // The shell's own props and its key.
2053
+ const own = [];
2054
+ let key = null;
2055
+ for (const attribute of node.openingElement.attributes) {
2056
+ if (!n.JSXAttribute.check(attribute) || !n.JSXIdentifier.check(attribute.name))
2057
+ return fail('{...spread}', 'spread props: the codemod cannot see what they set');
2058
+ const name = attribute.name.name;
2059
+ if (name === 'key' && attribute.value) {
2060
+ key = { node: attributeExpression(attribute.value), hole: 'key', attribute };
2061
+ continue;
2062
+ }
2063
+ const prop = rule.props?.[name];
2064
+ const values = prop ? valuesOf(prop.form, attribute.value ?? null, prop.map) : undefined;
2065
+ if (!prop || !values)
2066
+ return fail(name, `the shell's \`${name}\` (or its form here) has no mapping`);
2067
+ own.push({ name: prop.modifier, args: values });
2068
+ }
2069
+ // Its glyphs: a TextFieldIcon before the input is the node's icon, one after its trailing icon.
2070
+ for (const [index, child] of children.entries()) {
2071
+ if (index === at)
2072
+ continue;
2073
+ if (named(child) !== shell.icon)
2074
+ return fail('children', 'a shell child that is no glyph');
2075
+ const position = index < at ? 'leading' : 'trailing';
2076
+ let icon;
2077
+ for (const attribute of child.openingElement.attributes) {
2078
+ const plain = n.JSXAttribute.check(attribute) && n.JSXIdentifier.check(attribute.name);
2079
+ const name = plain ? attribute.name.name : '{...spread}';
2080
+ const value = plain ? attribute.value : null;
2081
+ if (name === 'icon')
2082
+ icon = valuesOf('icon', value)?.[0];
2083
+ else if (name !== 'position' || staticString(value) !== position)
2084
+ return fail(name, `a glyph's \`${name}\` (or its form here) has no mapping`);
2085
+ }
2086
+ if (!icon)
2087
+ return fail('icon', 'a glyph that is no Bloom icon');
2088
+ own.push({ name: position === 'leading' ? 'icon' : 'trailingIcon', args: [icon] });
2089
+ }
2090
+ // The input by its own rule: its shell is this one, so the shell's context is its own.
2091
+ const inner = convertComponent(input, inputRule, false);
2092
+ if (!('ir' in inner) || inner.ir.type !== 'component')
2093
+ return inner;
2094
+ const props = inner.ir.props;
2095
+ const twice = own.find((prop) => props.some((p) => p.name === prop.name));
2096
+ if (twice)
2097
+ return fail(twice.name, 'set on the shell and on its input');
2098
+ if (inner.ir.key)
2099
+ return fail('key', 'a key on the input inside a shell');
2100
+ // The input converts with its shell, as one node.
2101
+ if (!counted.has(input)) {
2102
+ counted.add(input);
2103
+ candidates++;
2104
+ }
2105
+ const ir = { ...inner.ir, props: [...props, ...own], key };
2106
+ results.set(input, { ir });
2107
+ return { ir };
2108
+ }
2109
+ /** A Bloom component the language draws as a node of its own, by its rule (`components.ts`). */
2110
+ function convertComponent(node, rule,
2111
+ /** Whether the rule's `outside` applies: not to an input converted with its own shell. */
2112
+ checkOutside = true) {
2113
+ const reasons = [];
2114
+ const unmapped = (name) => reasons.push({
2115
+ subject: name,
2116
+ code: `${rule.node}:${name}`,
2117
+ why: `${rule.node}'s \`${name}\` (or its form here) has no mapping`,
2118
+ });
2119
+ const around = rule.outside && checkOutside ? insideOf(node, rule.outside) : undefined;
2120
+ if (around)
2121
+ reasons.push({
2122
+ subject: around,
2123
+ code: `${rule.node}:inside-${around}`,
2124
+ why: `inside a ${around}, whose context the Bloom component reads and the language's node does not`,
2125
+ });
2126
+ let key = null;
2127
+ /** Each prop's attribute value (`null` when it is bare). */
2128
+ const given = new Map();
2129
+ for (const attribute of node.openingElement.attributes) {
2130
+ if (!n.JSXAttribute.check(attribute) || !n.JSXIdentifier.check(attribute.name)) {
2131
+ reasons.push({
2132
+ subject: '{...spread}',
2133
+ code: 'spread',
2134
+ why: 'spread props: the codemod cannot see what they set',
2135
+ });
2136
+ continue;
2137
+ }
2138
+ const name = attribute.name.name;
2139
+ if (name === 'key' && attribute.value)
2140
+ key = { node: attributeExpression(attribute.value), hole: 'key', attribute };
2141
+ else
2142
+ given.set(name, attribute.value ?? null);
2143
+ }
2144
+ const args = [];
2145
+ const consumed = new Set();
2146
+ let textChildren = false;
2147
+ /** The props of an object given as one value, each under its own name or the key beside its form. */
2148
+ const optionsOf = (options) => {
2149
+ const entries = [];
2150
+ for (const [name, entry] of Object.entries(options)) {
2151
+ consumed.add(name);
2152
+ if (!given.has(name))
2153
+ continue;
2154
+ const [key, form] = typeof entry === 'string' ? [name, entry] : entry;
2155
+ const value = valuesOf(form, given.get(name));
2156
+ // A bare flag is `true` in an object.
2157
+ if (value?.length === 0 && (form === 'flag' || form === 'mark'))
2158
+ entries.push([key, true]);
2159
+ else if (value?.length !== 1)
2160
+ unmapped(name);
2161
+ else
2162
+ entries.push([key, value[0]]);
2163
+ }
2164
+ return entries;
2165
+ };
2166
+ for (const param of rule.params ?? []) {
2167
+ if ('binding' in param) {
2168
+ const [valueProp, setters] = param.binding;
2169
+ const setProps = typeof setters === 'string' ? [setters] : setters;
2170
+ consumed.add(valueProp);
2171
+ for (const name of setProps)
2172
+ consumed.add(name);
2173
+ const value = given.get(valueProp);
2174
+ // One setter: two would be Bloom's choice between them, which the binding does not carry.
2175
+ const named = setProps.filter((name) => given.has(name));
2176
+ const set = named.length === 1 ? given.get(named[0]) : undefined;
2177
+ if (!value || !set)
2178
+ unmapped(valueProp);
2179
+ else
2180
+ args.push({
2181
+ $: 'binding',
2182
+ binding: [
2183
+ { node: attributeExpression(value), hole: param.hole },
2184
+ { node: attributeExpression(set), hole: 'handler' },
2185
+ ],
2186
+ });
2187
+ }
2188
+ else if ('options' in param) {
2189
+ const entries = optionsOf(param.options);
2190
+ args.push(entries.length ? { $: 'options', entries } : { $: 'absent' });
2191
+ }
2192
+ else if ('label' in param) {
2193
+ // Its glyphs and its label, as the node reads them from its content.
2194
+ textChildren = true;
2195
+ const glyph = (prop) => {
2196
+ if (!prop || !given.has(prop))
2197
+ return null;
2198
+ consumed.add(prop);
2199
+ const value = valuesOf('icon', given.get(prop));
2200
+ if (value?.length !== 1) {
2201
+ unmapped(prop);
2202
+ return null;
2203
+ }
2204
+ const { name } = value[0];
2205
+ return { $: 'view', view: { type: 'icon', component: name, mods: [], key: null } };
2206
+ };
2207
+ /** A view in the glyph's slot: one of the element props naming it, and no glyph beside it. */
2208
+ const slotView = (props = [], icon) => {
2209
+ const named = props.filter((prop) => given.has(prop));
2210
+ for (const prop of named)
2211
+ consumed.add(prop);
2212
+ if (named.length === 0)
2213
+ return icon;
2214
+ const value = named.length === 1 && !icon
2215
+ ? valuesOf('view', given.get(named[0]))
2216
+ : undefined;
2217
+ if (value?.length !== 1) {
2218
+ unmapped(named[0]);
2219
+ return icon;
2220
+ }
2221
+ return value[0];
2222
+ };
2223
+ const leading = slotView(param.label.leadingViews, glyph(param.label.leading));
2224
+ const text = textOf(node.children);
2225
+ const trailing = slotView(param.label.trailingViews, glyph(param.label.trailing));
2226
+ if (leading)
2227
+ args.push(leading);
2228
+ if (text !== undefined)
2229
+ args.push({
2230
+ $: 'view',
2231
+ view: {
2232
+ type: 'text',
2233
+ raw: false,
2234
+ resolved: { axis: 'column', mods: [], variants: [] },
2235
+ choice: null,
2236
+ props: [],
2237
+ key: null,
2238
+ runs: [
2239
+ typeof text === 'string'
2240
+ ? { type: 'string', value: text }
2241
+ : { type: 'expr', value: text },
2242
+ ],
2243
+ },
2244
+ });
2245
+ else if (node.children.some((c) => !(n.JSXText.check(c) && cleanJsxText(c.value) === '')))
2246
+ unmapped('children');
2247
+ if (trailing)
2248
+ args.push(trailing);
2249
+ }
2250
+ else if ('text' in param) {
2251
+ textChildren = true;
2252
+ const children = param.text === true ? node.children : innerChildren(node.children, param.text);
2253
+ const text = children && textOf(children);
2254
+ if (text === undefined)
2255
+ unmapped('children');
2256
+ else
2257
+ args.push(text);
2258
+ }
2259
+ else {
2260
+ consumed.add(param.prop);
2261
+ if (!given.has(param.prop)) {
2262
+ if (param.optional)
2263
+ args.push({ $: 'absent' });
2264
+ else
2265
+ unmapped(param.prop);
2266
+ continue;
2267
+ }
2268
+ const value = valuesOf(param.form, given.get(param.prop));
2269
+ if (value?.length !== 1)
2270
+ unmapped(param.prop);
2271
+ else
2272
+ args.push(value[0]);
2273
+ }
2274
+ }
2275
+ const props = [];
2276
+ if (rule.gather) {
2277
+ const entries = optionsOf(rule.gather.props);
2278
+ if (entries.length)
2279
+ props.push({ name: rule.gather.modifier, args: [{ $: 'options', entries }] });
2280
+ }
2281
+ /** A binding that ends the chain (`.presented()`), written after every other modifier. */
2282
+ let last;
2283
+ // A prop that is another's modifier's next argument (or its close handler) is read with it.
2284
+ for (const prop of Object.values(rule.props ?? {})) {
2285
+ if (prop.with && given.has(prop.with[0]))
2286
+ consumed.add(prop.with[0]);
2287
+ if (prop.closedBy && given.has(prop.closedBy))
2288
+ consumed.add(prop.closedBy);
2289
+ for (const option of Object.keys(prop.options ?? {}))
2290
+ if (given.has(option))
2291
+ consumed.add(option);
2292
+ }
2293
+ /** Its `style`, the node's box: chained after its own modifiers. */
2294
+ const styled = [];
2295
+ for (const [name, value] of given) {
2296
+ if (consumed.has(name))
2297
+ continue;
2298
+ const differs = rule.differs?.[name];
2299
+ if (differs) {
2300
+ reasons.push({ subject: name, code: `${rule.node}:${name}`, why: differs });
2301
+ continue;
2302
+ }
2303
+ const prop = rule.props?.[name];
2304
+ if (prop?.form === 'className') {
2305
+ const text = value ? staticString(value) : undefined;
2306
+ const view = text === undefined ? undefined : contentViewOf(text);
2307
+ if (!view)
2308
+ unmapped(name);
2309
+ else if ('reasons' in view)
2310
+ reasons.push(...view.reasons);
2311
+ else
2312
+ props.push({ name: prop.modifier, args: [view] });
2313
+ continue;
2314
+ }
2315
+ if (prop?.form === 'style') {
2316
+ const box = value ? componentStyle(attributeExpression(value), rule.node) : undefined;
2317
+ if (!box)
2318
+ unmapped(name);
2319
+ else if ('reasons' in box)
2320
+ reasons.push(...box.reasons);
2321
+ else
2322
+ styled.push(...box.mods);
2323
+ continue;
2324
+ }
2325
+ if (prop?.form === 'fill') {
2326
+ const ink = value ? fillOf(node, attributeExpression(value)) : undefined;
2327
+ if (ink === undefined)
2328
+ unmapped(name);
2329
+ else
2330
+ props.push({ name: prop.modifier, args: [ink] });
2331
+ continue;
2332
+ }
2333
+ if (prop?.form === 'reselect') {
2334
+ const handlers = value ? reselectOf(attributeExpression(value)) : undefined;
2335
+ if (!handlers)
2336
+ unmapped(name);
2337
+ else
2338
+ props.push(...handlers);
2339
+ continue;
2340
+ }
2341
+ if (prop?.form === 'textStyle') {
2342
+ const text = value ? partTextStyleOf(attributeExpression(value)) : undefined;
2343
+ if (text)
2344
+ props.push(...text);
2345
+ else
2346
+ unmapped(name);
2347
+ continue;
2348
+ }
2349
+ if (prop?.form === 'contentStyle') {
2350
+ const margins = value ? contentStyleOf(attributeExpression(value)) : undefined;
2351
+ if (margins)
2352
+ props.push(...margins);
2353
+ else
2354
+ unmapped(name);
2355
+ continue;
2356
+ }
2357
+ if (prop?.marks) {
2358
+ // A static string naming the bare modifier, or none.
2359
+ const text = staticString(value);
2360
+ const mark = text === undefined ? undefined : prop.marks[text];
2361
+ if (mark === undefined)
2362
+ unmapped(name);
2363
+ else if (mark)
2364
+ props.push({ name: prop.modifier, args: [] });
2365
+ continue;
2366
+ }
2367
+ const values = prop ? valuesOf(prop.form, value, prop.map, prop.unset) : undefined;
2368
+ if (!prop || !values) {
2369
+ unmapped(name);
2370
+ continue;
2371
+ }
2372
+ if (prop.with && given.has(prop.with[0])) {
2373
+ const next = valuesOf(prop.with[1], given.get(prop.with[0]));
2374
+ if (next?.length !== 1)
2375
+ unmapped(prop.with[0]);
2376
+ else
2377
+ values.push(next[0]);
2378
+ }
2379
+ if (prop.closedBy) {
2380
+ // The value and the close handler, one binding: setting it false calls the handler.
2381
+ const close = given.has(prop.closedBy)
2382
+ ? actionOf(attributeExpression(given.get(prop.closedBy)))
2383
+ : undefined;
2384
+ if (values.length !== 1 || !close)
2385
+ unmapped(name);
2386
+ else
2387
+ last = {
2388
+ name: prop.modifier,
2389
+ args: [{ $: 'binding', binding: [values[0], close] }],
2390
+ };
2391
+ continue;
2392
+ }
2393
+ if (prop.options) {
2394
+ // Its options object, each prop given by its key.
2395
+ const entries = [];
2396
+ for (const [option, [key, form, map]] of Object.entries(prop.options)) {
2397
+ if (!given.has(option))
2398
+ continue;
2399
+ const value = valuesOf(form, given.get(option), map);
2400
+ if (value?.length !== 1)
2401
+ unmapped(option);
2402
+ else
2403
+ entries.push([key, value[0]]);
2404
+ }
2405
+ if (entries.length)
2406
+ values.push({ $: 'options', entries });
2407
+ }
2408
+ if (prop.key) {
2409
+ // One object for the modifier: each prop its key.
2410
+ const entry = [prop.key, values[0]];
2411
+ const joined = props.find((mod) => mod.name === prop.modifier);
2412
+ const object = joined?.args[0];
2413
+ if (values.length !== 1)
2414
+ unmapped(name);
2415
+ else if (object && isTagged(object) && object.$ === 'options')
2416
+ joined.args[0] = { $: 'options', entries: [...object.entries, entry] };
2417
+ else
2418
+ props.push({ name: prop.modifier, args: [{ $: 'options', entries: [entry] }] });
2419
+ continue;
2420
+ }
2421
+ props.push({ name: prop.modifier, args: [...values, ...(prop.args ?? [])] });
2422
+ }
2423
+ if (last)
2424
+ props.push(last);
2425
+ // A next argument (or a close handler) given without its modifier's prop.
2426
+ for (const [name, prop] of Object.entries(rule.props ?? {})) {
2427
+ if (prop.with && given.has(prop.with[0]) && !given.has(name))
2428
+ unmapped(prop.with[0]);
2429
+ if (prop.closedBy && given.has(prop.closedBy) && !given.has(name))
2430
+ unmapped(prop.closedBy);
2431
+ for (const option of Object.keys(prop.options ?? {}))
2432
+ if (given.has(option) && !given.has(name))
2433
+ unmapped(option);
2434
+ }
2435
+ /** Its parts, each converted with it. */
2436
+ const parts = new Map();
2437
+ if (rule.parts) {
2438
+ const converted = convertParts(node.children, rule.parts, parts);
2439
+ if ('reasons' in converted)
2440
+ reasons.push(...converted.reasons);
2441
+ else
2442
+ args.push(...converted.views.map((view) => ({ $: 'view', view })));
2443
+ }
2444
+ else if (rule.children) {
2445
+ // A fragment's children are the element's own, where the fragment is.
2446
+ const children = rule.fragments
2447
+ ? node.children.flatMap((child) => n.JSXFragment.check(child) ? child.children : [child])
2448
+ : node.children;
2449
+ for (const child of children) {
2450
+ const view = childView(child);
2451
+ if (view === null)
2452
+ continue;
2453
+ if (view === undefined)
2454
+ unmapped('children');
2455
+ else
2456
+ args.push({ $: 'view', view });
2457
+ }
2458
+ }
2459
+ else if (!textChildren &&
2460
+ node.children.some((c) => !(n.JSXText.check(c) && cleanJsxText(c.value) === '')))
2461
+ unmapped('children');
2462
+ for (const name of rule.always ?? [])
2463
+ props.push({ name, args: [] });
2464
+ props.push(...styled);
2465
+ // An optional argument left out at the end (children included) is no argument.
2466
+ while (args.length > 0 && isAbsent(args[args.length - 1]))
2467
+ args.pop();
2468
+ if (reasons.length)
2469
+ return { reasons };
2470
+ for (const [element, ir] of parts)
2471
+ results.set(element, { ir });
2472
+ return {
2473
+ ir: {
2474
+ type: 'component',
2475
+ node: rule.node,
2476
+ within: rule.within ??
2477
+ Object.entries(rule.props ?? {}).find(([name, prop]) => prop.within && given.has(name))?.[1].within,
2478
+ args,
2479
+ props,
2480
+ key,
2481
+ },
2482
+ };
2483
+ }
2484
+ /**
2485
+ * The children of a compound element as its parts (`module#export`), each
2486
+ * by its own rule: an element, a comment, or a `.map()` whose function
2487
+ * returns one (its array carried). Each part converted is added to `converted`.
2488
+ */
2489
+ function convertParts(children, parts, converted) {
2490
+ const reasons = [];
2491
+ const views = [];
2492
+ const names = parts.map((part) => `\`${part.split('#')[1]}\``).join(', ');
2493
+ const part = (element) => {
2494
+ const local = n.JSXElement.check(element) ? jsxName(element) : undefined;
2495
+ const source = local ? sources.get(local) : undefined;
2496
+ const rule = source && parts.includes(`${source.module}#${source.imported}`)
2497
+ ? (0, components_1.ruleFor)(source.module, source.imported)
2498
+ : undefined;
2499
+ if (!rule) {
2500
+ reasons.push({
2501
+ subject: local ?? 'children',
2502
+ code: 'not-a-part',
2503
+ why: `a child that is none of its parts (${names})`,
2504
+ });
2505
+ return undefined;
2506
+ }
2507
+ if (!counted.has(element)) {
2508
+ counted.add(element);
2509
+ candidates++;
2510
+ }
2511
+ const result = convertComponent(element, rule);
2512
+ if (!('ir' in result) || result.ir.type !== 'component') {
2513
+ if ('reasons' in result)
2514
+ reasons.push(...result.reasons);
2515
+ return undefined;
2516
+ }
2517
+ const ir = { ...result.ir, part: true };
2518
+ converted.set(element, ir);
2519
+ return ir;
2520
+ };
2521
+ for (const child of children) {
2522
+ if (n.JSXText.check(child) && !cleanJsxText(child.value))
2523
+ continue;
2524
+ const expression = n.JSXExpressionContainer.check(child) ? child.expression : undefined;
2525
+ if (expression && n.JSXEmptyExpression.check(expression)) {
2526
+ const comment = commentOf(child);
2527
+ if (comment)
2528
+ views.push(comment);
2529
+ else
2530
+ reasons.push({
2531
+ subject: '{/* */}',
2532
+ code: 'comment',
2533
+ why: 'a line comment in JSX (only a block comment moves)',
2534
+ });
2535
+ continue;
2536
+ }
2537
+ const map = expression ? mapOf(expression) : undefined;
2538
+ const body = part(map ? map.body : expression ? undefined : child);
2539
+ if (!body)
2540
+ continue;
2541
+ views.push(map
2542
+ ? { type: 'map', items: { node: map.items, hole: 'items' }, params: map.params, body }
2543
+ : body);
2544
+ }
2545
+ return reasons.length ? { reasons } : { views };
2546
+ }
2547
+ /** `items.map((item) => <Element />)`: its array, its function's parameters and the element it returns. */
2548
+ function mapOf(expression) {
2549
+ if (!n.CallExpression.check(expression) || expression.arguments.length !== 1)
2550
+ return undefined;
2551
+ const { callee } = expression;
2552
+ const fn = expression.arguments[0];
2553
+ if (!n.MemberExpression.check(callee) ||
2554
+ callee.computed ||
2555
+ !n.Identifier.check(callee.property) ||
2556
+ callee.property.name !== 'map' ||
2557
+ !n.ArrowFunctionExpression.check(fn) ||
2558
+ !n.JSXElement.check(fn.body))
2559
+ return undefined;
2560
+ return { items: callee.object, params: fn.params, body: fn.body };
2561
+ }
2562
+ /** The children of an element's one child, when it is `component` (`module#export`) with no props. */
2563
+ function innerChildren(children, component) {
2564
+ const given = children.filter((c) => !(n.JSXText.check(c) && cleanJsxText(c.value) === ''));
2565
+ const only = given.length === 1 && n.JSXElement.check(given[0]) ? given[0] : null;
2566
+ const source = only ? sources.get(jsxName(only) ?? '') : undefined;
2567
+ return source &&
2568
+ `${source.module}#${source.imported}` === component &&
2569
+ only.openingElement.attributes.length === 0
2570
+ ? only.children
2571
+ : undefined;
2572
+ }
2573
+ /**
2574
+ * A prop's value in a rule's form, as the modifier's arguments (none for a
2575
+ * bare flag), or undefined when the value is in a form the rule does not take.
2576
+ */
2577
+ function valuesOf(form, value, map, unset) {
2578
+ if (value === null)
2579
+ // A bare prop is `true`.
2580
+ return form === 'flag' || form === 'mark'
2581
+ ? []
2582
+ : form === 'boolean'
2583
+ ? [true]
2584
+ : form === 'literal' && map?.true !== undefined
2585
+ ? [map.true]
2586
+ : undefined;
2587
+ const expression = attributeExpression(value);
2588
+ if (n.JSXEmptyExpression.check(expression))
2589
+ return undefined;
2590
+ switch (form) {
2591
+ case 'string': {
2592
+ const text = staticString(value);
2593
+ if (text !== undefined)
2594
+ return [text];
2595
+ return hasJsx(expression) ? undefined : [{ node: expression, hole: 'string' }];
2596
+ }
2597
+ case 'token': {
2598
+ // Tokens chosen by a plain condition (`sensitive ? 'error' : 'default'`) are that choice;
2599
+ // none is a branch only where the modifier takes `undefined` (`unset`).
2600
+ if (n.ConditionalExpression.check(expression) &&
2601
+ (isPlainRead(expression.test) || isBooleanForm(expression.test))) {
2602
+ const branch = (node) => unset && noStyle(node) && !n.BooleanLiteral.check(node)
2603
+ ? { $: 'absent' }
2604
+ : valuesOf('token', node, map)?.[0];
2605
+ const then = branch(expression.consequent);
2606
+ const otherwise = branch(expression.alternate);
2607
+ return then === undefined || otherwise === undefined
2608
+ ? undefined
2609
+ : [
2610
+ {
2611
+ $: 'choose',
2612
+ test: { node: expression.test, hole: 'condition' },
2613
+ then,
2614
+ otherwise,
2615
+ },
2616
+ ];
2617
+ }
2618
+ // A token is a static string, or a static number of points (`spacing={12}`).
2619
+ const number = staticNumber(value);
2620
+ const text = staticString(value) ?? (number === undefined ? undefined : String(number));
2621
+ if (text === undefined)
2622
+ return undefined;
2623
+ const token = map ? map[text] : text;
2624
+ return token === undefined ? undefined : [token];
2625
+ }
2626
+ case 'flag':
2627
+ case 'boolean':
2628
+ if (n.BooleanLiteral.check(expression))
2629
+ return [expression.value];
2630
+ return hasJsx(expression) ? undefined : [{ node: expression, hole: 'boolean' }];
2631
+ case 'mark':
2632
+ return n.BooleanLiteral.check(expression) && expression.value ? [] : undefined;
2633
+ case 'empty':
2634
+ return n.ObjectExpression.check(expression) && expression.properties.length === 0
2635
+ ? []
2636
+ : undefined;
2637
+ case 'number': {
2638
+ const number = staticNumber(value);
2639
+ if (number !== undefined)
2640
+ return [number];
2641
+ return hasJsx(expression) || n.StringLiteral.check(expression)
2642
+ ? undefined
2643
+ : [{ node: expression, hole: 'number' }];
2644
+ }
2645
+ case 'handler':
2646
+ // `null` is a handler's own value (a header's `onBack={null}` shows no back button).
2647
+ if (n.NullLiteral.check(expression))
2648
+ return [{ $: 'null' }];
2649
+ return n.ArrowFunctionExpression.check(expression) ||
2650
+ n.FunctionExpression.check(expression) ||
2651
+ n.Identifier.check(expression) ||
2652
+ n.MemberExpression.check(expression) ||
2653
+ n.CallExpression.check(expression)
2654
+ ? [{ node: expression, hole: 'handler' }]
2655
+ : undefined;
2656
+ case 'content':
2657
+ return n.JSXElement.check(expression) || n.JSXFragment.check(expression)
2658
+ ? valuesOf('view', value, map)
2659
+ : valuesOf('string', value, map);
2660
+ case 'view': {
2661
+ if (n.StringLiteral.check(expression) || n.TemplateLiteral.check(expression))
2662
+ return undefined;
2663
+ const view = n.JSXElement.check(expression) ? elementView(expression) : null;
2664
+ if (view)
2665
+ return [{ $: 'view', view }];
2666
+ if (n.JSXFragment.check(expression))
2667
+ return [
2668
+ { $: 'view', view: { type: 'embed', content: { node: expression, hole: 'element' } } },
2669
+ ];
2670
+ return [{ $: 'view', view: expressionChild(expression) }];
2671
+ }
2672
+ case 'icon':
2673
+ return n.Identifier.check(expression) && kindOf(sources.get(expression.name)) === 'icon'
2674
+ ? [{ $: 'icon', name: expression.name }]
2675
+ : undefined;
2676
+ case 'literal': {
2677
+ const token = n.BooleanLiteral.check(expression)
2678
+ ? map?.[String(expression.value)]
2679
+ : undefined;
2680
+ return token === undefined ? undefined : [token];
2681
+ }
2682
+ case 'refresh':
2683
+ return refreshOf(expression);
2684
+ case 'items':
2685
+ // Data carried as it is, the elements inside it (a row's trailing button) included.
2686
+ return n.JSXElement.check(expression) ||
2687
+ n.JSXFragment.check(expression) ||
2688
+ n.StringLiteral.check(expression)
2689
+ ? undefined
2690
+ : [{ node: expression, hole: 'items' }];
2691
+ case 'element':
2692
+ return elementPropOf(expression);
2693
+ case 'row': {
2694
+ const row = rowOf(expression);
2695
+ return row === undefined ? undefined : [row];
2696
+ }
2697
+ case 'placement':
2698
+ return placementOf(value);
2699
+ }
2700
+ }
2701
+ /**
2702
+ * An element prop as a view: an element converted; a fragment, a language
2703
+ * view's element, a `const` holding an element, or what a render function
2704
+ * returns (`renderEmpty()`, a lowercase callee: a component is never called)
2705
+ * drawn as it is; an element or none chosen by a plain condition (`loading ?
2706
+ * <Spinner /> : null`) as that choice.
2707
+ */
2708
+ function elementPropOf(expression) {
2709
+ if (n.JSXElement.check(expression))
2710
+ return [{ $: 'view', view: elementView(expression) }];
2711
+ if (n.ConditionalExpression.check(expression) &&
2712
+ (isPlainRead(expression.test) || isBooleanForm(expression.test))) {
2713
+ const branch = (node) => noStyle(node) ? { $: 'null' } : elementPropOf(node)?.[0];
2714
+ const then = branch(expression.consequent);
2715
+ const otherwise = branch(expression.alternate);
2716
+ if (then === undefined || otherwise === undefined)
2717
+ return undefined;
2718
+ return [{ $: 'choose', test: { node: expression.test, hole: 'condition' }, then, otherwise }];
2719
+ }
2720
+ const rendered = n.CallExpression.check(expression) &&
2721
+ n.Identifier.check(expression.callee) &&
2722
+ /^[a-z]/.test(expression.callee.name);
2723
+ return n.JSXFragment.check(expression) ||
2724
+ isToElement(expression) ||
2725
+ elementReads.has(expression) ||
2726
+ rendered
2727
+ ? [{ $: 'view', view: { type: 'embed', content: { node: expression, hole: 'element' } } }]
2728
+ : undefined;
2729
+ }
2730
+ /**
2731
+ * Bloom's responsive placement as `.presentAt(base, tiers)`: a static token,
2732
+ * or an object literal of static tokens with its `base` and any of the
2733
+ * breakpoints, each tier written as Bloom reads it over the base.
2734
+ */
2735
+ function placementOf(value) {
2736
+ const text = staticString(value);
2737
+ if (text !== undefined) {
2738
+ const token = components_1.DIALOG_PLACEMENT[text];
2739
+ return token === undefined ? undefined : [token];
2740
+ }
2741
+ const object = attributeExpression(value);
2742
+ if (!n.ObjectExpression.check(object))
2743
+ return undefined;
2744
+ let base;
2745
+ const tiers = [];
2746
+ for (const property of object.properties) {
2747
+ if (!(n.ObjectProperty.check(property) || n.Property.check(property)) ||
2748
+ property.computed ||
2749
+ !n.Identifier.check(property.key))
2750
+ return undefined;
2751
+ const token = components_1.DIALOG_PLACEMENT[staticString(property.value) ?? ''];
2752
+ const key = property.key.name;
2753
+ if (token === undefined)
2754
+ return undefined;
2755
+ if (key === 'base')
2756
+ base = token;
2757
+ else if (components_1.PLACEMENT_TIERS.includes(key))
2758
+ tiers.push([key, token]);
2759
+ else
2760
+ return undefined;
2761
+ }
2762
+ // An object is drawn as an object (`{ base, ...tiers }`), its tiers none or more.
2763
+ return base === undefined ? undefined : [base, { $: 'options', entries: tiers }];
2764
+ }
2765
+ /**
2766
+ * A handler Bloom calls with no arguments, as a function of none: an arrow of
2767
+ * no parameters as it is (it ignores what it is called with), a name or a
2768
+ * member called with none (`() => onClose()`). Anything else may read an argument.
2769
+ */
2770
+ function actionOf(expression) {
2771
+ if (n.ArrowFunctionExpression.check(expression) && expression.params.length === 0)
2772
+ return { node: expression, hole: 'handler' };
2773
+ if (n.Identifier.check(expression) || n.MemberExpression.check(expression))
2774
+ return { node: expression, hole: 'action' };
2775
+ return undefined;
2776
+ }
2777
+ /**
2778
+ * A part's label style (a tab's `textStyle`), an object literal of a
2779
+ * `fontSize` and `lineHeight` of the spec's tokens and a `fontWeight`, as
2780
+ * `.font()`, `.leading()` and `.weight()`; a weight chosen by a plain
2781
+ * condition (`open ? '700' : '500'`) is the weight it chooses.
2782
+ */
2783
+ function partTextStyleOf(expression) {
2784
+ if (!n.ObjectExpression.check(expression))
2785
+ return undefined;
2786
+ const weightOf = (node) => {
2787
+ const text = staticString(node) ?? (n.NumericLiteral.check(node) ? String(node.value) : undefined);
2788
+ if (text !== undefined)
2789
+ return WEIGHT_BY_VALUE[text];
2790
+ if (n.ConditionalExpression.check(node) &&
2791
+ (isPlainRead(node.test) || isBooleanForm(node.test))) {
2792
+ const then = weightOf(node.consequent);
2793
+ const otherwise = weightOf(node.alternate);
2794
+ return then === undefined || otherwise === undefined
2795
+ ? undefined
2796
+ : { $: 'choose', test: { node: node.test, hole: 'condition' }, then, otherwise };
2797
+ }
2798
+ return undefined;
2799
+ };
2800
+ const mods = [];
2801
+ for (const property of expression.properties) {
2802
+ if (!(n.ObjectProperty.check(property) || n.Property.check(property)) ||
2803
+ property.computed ||
2804
+ !n.Identifier.check(property.key))
2805
+ return undefined;
2806
+ const key = property.key.name;
2807
+ if (key === 'fontWeight') {
2808
+ const weight = weightOf(property.value);
2809
+ if (weight === undefined)
2810
+ return undefined;
2811
+ mods.push({ name: 'weight', args: [weight] });
2812
+ continue;
2813
+ }
2814
+ const mod = (0, style_1.textDeclaration)(key, property.value);
2815
+ if (!mod)
2816
+ return undefined;
2817
+ mods.push({ name: mod.name, args: [...mod.args] });
2818
+ }
2819
+ return mods;
2820
+ }
2821
+ /**
2822
+ * A static content container style (an object literal or a module
2823
+ * StyleSheet's style) of paddings and a gap, each a space token, as the
2824
+ * scroll view's content margins and spacing: the language's content
2825
+ * container style holds the same keys.
2826
+ */
2827
+ function contentStyleOf(expression) {
2828
+ // Content that grows while a condition holds (`empty ? { flexGrow: 1 } : undefined`):
2829
+ // `.contentGrows(condition)`, the style itself nothing but the grow.
2830
+ if (n.ConditionalExpression.check(expression) &&
2831
+ noStyle(expression.alternate) &&
2832
+ (isPlainRead(expression.test) || isBooleanForm(expression.test))) {
2833
+ const grown = contentStyleOf(expression.consequent);
2834
+ return grown?.length === 1 && grown[0]?.name === 'contentGrows'
2835
+ ? [{ name: 'contentGrows', args: [{ node: expression.test, hole: 'condition' }] }]
2836
+ : undefined;
2837
+ }
2838
+ const object = moduleStyleReads.has(expression)
2839
+ ? styleSheets.get(expression.object.name)?.get(expression.property.name)
2840
+ : (styleConstantReads.get(expression) ?? expression);
2841
+ if (!n.ObjectExpression.check(object))
2842
+ return undefined;
2843
+ const mods = [];
2844
+ for (const property of object.properties) {
2845
+ if (!(n.ObjectProperty.check(property) || n.Property.check(property)) ||
2846
+ property.computed ||
2847
+ !n.Identifier.check(property.key))
2848
+ return undefined;
2849
+ // A content container that grows to the scroll: `.contentGrows()`.
2850
+ if (property.key.name === 'flexGrow' && staticNumber(property.value) === 1) {
2851
+ mods.push({ name: 'contentGrows', args: [] });
2852
+ continue;
2853
+ }
2854
+ const token = components_1.SPACE[String(staticNumber(property.value))];
2855
+ const key = property.key.name;
2856
+ const edge = key === 'gap' ? undefined : CONTENT_EDGE[key];
2857
+ if (token === undefined || (key !== 'gap' && !edge))
2858
+ return undefined;
2859
+ mods.push(key === 'gap'
2860
+ ? { name: 'spacing', args: [token] }
2861
+ : { name: 'contentMargins', args: edge === 'all' ? [token] : [edge, token] });
2862
+ }
2863
+ if (object !== expression)
2864
+ styleLiterals.set(expression, recast.print(object).code);
2865
+ return mods;
2866
+ }
2867
+ /** A style that is a fill alone (`{ backgroundColor: '#000' }`) as its colour (`inkOf`). */
2868
+ function fillOf(node, expression) {
2869
+ const [property, ...rest] = n.ObjectExpression.check(expression) ? expression.properties : [];
2870
+ if (rest.length ||
2871
+ !(n.ObjectProperty.check(property) || n.Property.check(property)) ||
2872
+ property.computed ||
2873
+ !n.Identifier.check(property.key) ||
2874
+ property.key.name !== 'backgroundColor')
2875
+ return undefined;
2876
+ return inkOf(node, property.value);
2877
+ }
2878
+ /**
2879
+ * Bloom Screen's `reselect` (`{ refresh, isAtTop, scrollToTop }`, each as
2880
+ * written) as `.onReselect(refresh)` and `.reselectTop(isAtTop, scrollToTop)`:
2881
+ * where the top is comes with how to go there, both or neither.
2882
+ */
2883
+ function reselectOf(expression) {
2884
+ if (!n.ObjectExpression.check(expression))
2885
+ return undefined;
2886
+ const handlers = new Map();
2887
+ for (const property of expression.properties) {
2888
+ if (!(n.ObjectProperty.check(property) || n.Property.check(property)) ||
2889
+ property.computed ||
2890
+ !n.Identifier.check(property.key) ||
2891
+ !['refresh', 'isAtTop', 'scrollToTop'].includes(property.key.name) ||
2892
+ hasJsx(property.value))
2893
+ return undefined;
2894
+ handlers.set(property.key.name, { node: property.value, hole: 'handler' });
2895
+ }
2896
+ const [refresh, isAtTop, scrollToTop] = ['refresh', 'isAtTop', 'scrollToTop'].map((key) => handlers.get(key));
2897
+ if (Boolean(isAtTop) !== Boolean(scrollToTop))
2898
+ return undefined;
2899
+ const mods = [];
2900
+ if (refresh)
2901
+ mods.push({ name: 'onReselect', args: [refresh] });
2902
+ if (isAtTop && scrollToTop)
2903
+ mods.push({ name: 'reselectTop', args: [isAtTop, scrollToTop] });
2904
+ return mods.length ? mods : undefined;
2905
+ }
2906
+ /**
2907
+ * A scroll view's content class as its content view's build function: each
2908
+ * class through the className table, as a View's, and every modifier one the
2909
+ * content view takes (the spec's `contentView.modifiers`: the layout of one view).
2910
+ */
2911
+ function contentViewOf(className) {
2912
+ const resolution = (0, resolve_1.resolveClassName)(className, 'view', options.table, {
2913
+ overridden: options.overridden,
2914
+ });
2915
+ if (!resolution.ok)
2916
+ return { reasons: [...resolution.reasons] };
2917
+ for (const token of className.split(/\s+/).filter(Boolean))
2918
+ classes.add(token);
2919
+ const { axis, mods, variants } = resolution.value;
2920
+ const all = axis === 'row' ? [{ name: 'axis', args: ['horizontal'] }, ...mods] : [...mods];
2921
+ const subject = 'contentContainerClassName';
2922
+ if (variants.length)
2923
+ return {
2924
+ reasons: [
2925
+ {
2926
+ subject,
2927
+ code: 'contentView:variant',
2928
+ why: 'a content class with a variant (`md:`, `dark:`): the content view takes the layout of one view, without variants',
2929
+ },
2930
+ ],
2931
+ };
2932
+ const outside = all.find((mod) => !CONTENT_VIEW.has(mod.name));
2933
+ if (outside)
2934
+ return {
2935
+ reasons: [
2936
+ {
2937
+ subject,
2938
+ code: `contentView:${outside.name}`,
2939
+ why: `the content view takes the layout of one view (the spec's \`contentView.modifiers\`), not \`.${outside.name}()\``,
2940
+ },
2941
+ ],
2942
+ };
2943
+ return { $: 'build', mods: all };
2944
+ }
2945
+ /**
2946
+ * React Native's `RefreshControl` as a pull to refresh: its `refreshing` and
2947
+ * the binding a pull writes `true` to, which calls `onRefresh` with no
2948
+ * arguments as React Native does; its `tintColor` and `colors` as the tint
2949
+ * when both are one theme colour, since the tint paints both; each alone, or
2950
+ * two colours, the tint of its platform (`{ ios: 'primary' }`).
2951
+ */
2952
+ function refreshOf(expression) {
2953
+ const local = n.JSXElement.check(expression) ? jsxName(expression) : undefined;
2954
+ const source = local ? sources.get(local) : undefined;
2955
+ if (source?.module !== 'react-native' || source.imported !== 'RefreshControl')
2956
+ return undefined;
2957
+ if (expression.children.length)
2958
+ return undefined;
2959
+ const given = new Map();
2960
+ for (const attribute of expression.openingElement.attributes) {
2961
+ if (!n.JSXAttribute.check(attribute) || !n.JSXIdentifier.check(attribute.name))
2962
+ return undefined;
2963
+ if (!attribute.value)
2964
+ return undefined;
2965
+ given.set(attribute.name.name, attributeExpression(attribute.value));
2966
+ }
2967
+ const { refreshing, onRefresh, tintColor, colors, ...rest } = Object.fromEntries(given);
2968
+ if (Object.keys(rest).length || !refreshing || !onRefresh || hasJsx(refreshing))
2969
+ return undefined;
2970
+ // The refreshing value and the action a pull runs, as written: `{ refreshing, onRefresh }`.
2971
+ if (hasJsx(onRefresh))
2972
+ return undefined;
2973
+ const binding = {
2974
+ $: 'options',
2975
+ entries: [
2976
+ ['refreshing', { node: refreshing, hole: 'boolean' }],
2977
+ ['onRefresh', { node: onRefresh, hole: 'handler' }],
2978
+ ],
2979
+ };
2980
+ // iOS's `tintColor` and Android's `colors` (one theme colour), each the tint of its platform.
2981
+ const ios = tintColor ? themeRoles.get(tintColor) : undefined;
2982
+ const [only, ...others] = n.ArrayExpression.check(colors) ? colors.elements : [];
2983
+ const android = colors && only && !others.length ? themeRoles.get(only) : undefined;
2984
+ if ((tintColor && !ios) || (colors && !android))
2985
+ return undefined;
2986
+ // Its import goes with the element when nothing else draws one.
2987
+ convertedLocals.add(local);
2988
+ if (!ios && !android)
2989
+ return [binding];
2990
+ if (ios === android)
2991
+ return [binding, ios];
2992
+ const entries = [];
2993
+ if (ios)
2994
+ entries.push(['ios', ios]);
2995
+ if (android)
2996
+ entries.push(['android', android]);
2997
+ return [binding, { $: 'options', entries }];
2998
+ }
2999
+ /**
3000
+ * FlashList's `renderItem` as the node's row, which Bloom hands the same
3001
+ * `{ item, index }`: an arrow of one parameter returning an expression (its
3002
+ * parameter as written; an element as the row's view, anything else
3003
+ * embedded as it is), or a named function, carried as it is
3004
+ * (`VirtualList(posts, renderPost)`: the language draws its element as it
3005
+ * is, and the list's `renderItem` keeps its identity).
3006
+ */
3007
+ function rowOf(expression) {
3008
+ // A named renderItem is the row itself, as JSX handed it: its identity kept, so FlashList's memoised rows stay.
3009
+ if (n.Identifier.check(expression) || n.MemberExpression.check(expression))
3010
+ return { $: 'renderer', fn: { node: expression, hole: 'renderer' } };
3011
+ if (!n.ArrowFunctionExpression.check(expression) ||
3012
+ expression.params.length !== 1 ||
3013
+ n.BlockStatement.check(expression.body))
3014
+ return undefined;
3015
+ const [param] = expression.params;
3016
+ if (!n.Identifier.check(param) && !n.ObjectPattern.check(param))
3017
+ return undefined;
3018
+ const { body } = expression;
3019
+ // An element is converted where it can be; any other expression (`renderRow(item)`) is embedded as it is.
3020
+ const view = n.JSXElement.check(body)
3021
+ ? elementView(body)
3022
+ : { type: 'embed', content: { node: body, hole: 'element' } };
3023
+ return { $: 'row', param: recast.print(param).code, view };
3024
+ }
3025
+ /** An element as a view: converted when it can be, else embedded. */
3026
+ function elementView(element) {
3027
+ const inner = convert(element);
3028
+ return 'ir' in inner
3029
+ ? inner.ir
3030
+ : { type: 'embed', content: { node: element, hole: 'element' } };
3031
+ }
3032
+ /** A JSX comment's block comments as a code comment; undefined for a line comment. */
3033
+ function commentOf(container) {
3034
+ const text = source.slice(container.start + 1, container.end - 1).trim();
3035
+ // Block comments only: a line comment would swallow the arguments after it.
3036
+ return text.startsWith('/*') && text.endsWith('*/') && !text.includes('//')
3037
+ ? { type: 'comment', text }
3038
+ : undefined;
3039
+ }
3040
+ /**
3041
+ * A list of views as arguments: a comment sits before the view after it
3042
+ * (after the last one when it ends the list), never an argument of its own.
3043
+ */
3044
+ function printViews(views, carry) {
3045
+ const out = [];
3046
+ let pending = [];
3047
+ for (const view of views) {
3048
+ if (view.type === 'comment')
3049
+ pending.push(view.text);
3050
+ else {
3051
+ out.push([...pending, print(view, carry)].join(' '));
3052
+ pending = [];
3053
+ }
3054
+ }
3055
+ if (pending.length && out.length)
3056
+ out[out.length - 1] += ` ${pending.join(' ')}`;
3057
+ else if (pending.length)
3058
+ out.push(pending.join(' '));
3059
+ return out;
3060
+ }
3061
+ /** A child of a view-holding element as a view; null when it is no child, undefined when it is text. */
3062
+ function childView(child) {
3063
+ if (n.JSXText.check(child))
3064
+ return cleanJsxText(child.value) ? undefined : null;
3065
+ if (n.JSXExpressionContainer.check(child)) {
3066
+ if (n.JSXEmptyExpression.check(child.expression))
3067
+ return commentOf(child);
3068
+ if (n.StringLiteral.check(child.expression) || n.TemplateLiteral.check(child.expression))
3069
+ return undefined;
3070
+ return expressionChild(child.expression);
3071
+ }
3072
+ if (n.JSXElement.check(child))
3073
+ return elementView(child);
3074
+ if (n.JSXFragment.check(child))
3075
+ return { type: 'embed', content: { node: child, hole: 'element' } };
3076
+ return undefined;
3077
+ }
3078
+ /** An element's children as one string: one static text, or one expression (a hole). */
3079
+ function textOf(children) {
3080
+ const runs = children.filter((c) => !(n.JSXText.check(c) && cleanJsxText(c.value) === ''));
3081
+ if (runs.length !== 1)
3082
+ return undefined;
3083
+ const run = runs[0];
3084
+ if (n.JSXText.check(run))
3085
+ return cleanJsxText(run.value);
3086
+ if (!n.JSXExpressionContainer.check(run) || n.JSXEmptyExpression.check(run.expression))
3087
+ return undefined;
3088
+ const text = staticString(run);
3089
+ if (text !== undefined)
3090
+ return text;
3091
+ return hasJsx(run.expression) ? undefined : { node: run.expression, hole: 'string' };
3092
+ }
3093
+ /**
3094
+ * Bloom's `DropdownMenu` tree as `Menu(trigger, ...rows).menuStyle('dropdown')`,
3095
+ * which draws Bloom's DropdownMenu on every platform (parity/context-menu.cases.tsx):
3096
+ * a `DropdownMenuTrigger asChild` around one view the codemod converts, and a
3097
+ * `DropdownMenuContent` of `DropdownMenuItem`s and `DropdownMenuSeparator`s
3098
+ * (`Divider()`), with the trigger's label (`.label()`). The menu holds its
3099
+ * own open state, so a menu the app opens itself (`open`) stays JSX. An
3100
+ * item's `leading` is a language glyph, `toElement(Icon(icon).size(s).foreground(f))`:
3101
+ * the row's `.icon()`, `.iconSize()` and `.iconForeground()`.
3102
+ */
3103
+ function convertDropdownMenu(node) {
3104
+ const reasons = [];
3105
+ const fail = (subject, code, why) => {
3106
+ reasons.push({ subject, code: `DropdownMenu:${code}`, why });
3107
+ return { reasons };
3108
+ };
3109
+ const part = (element) => {
3110
+ const local = n.JSXElement.check(element) ? jsxName(element) : undefined;
3111
+ const source = local ? sources.get(local) : undefined;
3112
+ return source?.module === DROPDOWN ? source.imported : undefined;
3113
+ };
3114
+ const elements = (parent) => {
3115
+ const out = [];
3116
+ for (const child of parent.children) {
3117
+ if (n.JSXText.check(child) && cleanJsxText(child.value) === '')
3118
+ continue;
3119
+ if (!n.JSXElement.check(child))
3120
+ return undefined;
3121
+ out.push(child);
3122
+ }
3123
+ return out;
3124
+ };
3125
+ const attributes = (element) => {
3126
+ const out = new Map();
3127
+ for (const attribute of element.openingElement.attributes) {
3128
+ if (!n.JSXAttribute.check(attribute) || !n.JSXIdentifier.check(attribute.name))
3129
+ return undefined;
3130
+ out.set(attribute.name.name, attribute.value);
3131
+ }
3132
+ return out;
3133
+ };
3134
+ // A menu the app opens itself (`open` and `onOpenChange`) is `.presented([open, onOpenChange])`.
3135
+ const menuProps = attributes(node);
3136
+ const opened = menuProps?.get('open');
3137
+ const onOpenChange = menuProps?.get('onOpenChange');
3138
+ const presented = opened && onOpenChange && menuProps?.size === 2;
3139
+ if (menuProps?.size !== 0 && !presented)
3140
+ return fail('props', 'props', 'a menu with props besides `open` and `onOpenChange`, its `.presented()` binding');
3141
+ const [trigger, content, ...rest] = elements(node) ?? [];
3142
+ if (part(trigger) !== 'DropdownMenuTrigger' ||
3143
+ part(content) !== 'DropdownMenuContent' ||
3144
+ rest.length)
3145
+ return fail('children', 'children', 'children that are no trigger and content');
3146
+ const triggerProps = attributes(trigger);
3147
+ const contentProps = attributes(content);
3148
+ const label = triggerProps?.get('label');
3149
+ if (!triggerProps?.has('asChild') ||
3150
+ [...triggerProps.keys()].some((key) => key !== 'asChild' && key !== 'label'))
3151
+ return fail('trigger', 'trigger', 'a trigger that is not `asChild`, or with props besides its label');
3152
+ const labelText = (value) => value === undefined ? undefined : source.slice(value.start, value.end);
3153
+ if (!contentProps ||
3154
+ labelText(contentProps.get('label')) !== labelText(label) ||
3155
+ [...contentProps.keys()].some((key) => key !== 'label' && key !== 'testID'))
3156
+ return fail('content', 'content', 'a content whose label is not its trigger’s, or with other props');
3157
+ const [view, ...others] = elements(trigger) ?? [];
3158
+ const triggerView = view ? convert(view) : undefined;
3159
+ if (!triggerView || others.length || !('ir' in triggerView))
3160
+ return fail('trigger', 'trigger', 'a trigger that is no one view the codemod converts');
3161
+ /** One text child as a row's title: a literal, or the string it carries. */
3162
+ const titleOf = (element) => {
3163
+ const texts = element?.children?.filter((child) => !(n.JSXText.check(child) && cleanJsxText(child.value) === ''));
3164
+ const text = texts?.length === 1 ? texts[0] : undefined;
3165
+ return n.JSXText.check(text)
3166
+ ? cleanJsxText(text.value)
3167
+ : n.JSXExpressionContainer.check(text) && !n.JSXEmptyExpression.check(text.expression)
3168
+ ? (staticString(text) ?? { node: text.expression, hole: 'string' })
3169
+ : undefined;
3170
+ };
3171
+ const rowView = (node, args, props) => ({
3172
+ $: 'view',
3173
+ view: { type: 'component', node, within: undefined, args, props, key: null },
3174
+ });
3175
+ /**
3176
+ * An item, or a radio item (`radio`): its value is the row's tag, the
3177
+ * choice it is in its section of choices.
3178
+ */
3179
+ const itemRow = (row, radio) => {
3180
+ const props = row && part(row) === (radio ? 'DropdownMenuRadioItem' : 'DropdownMenuItem')
3181
+ ? attributes(row)
3182
+ : undefined;
3183
+ const title = titleOf(row);
3184
+ if (!props || title === undefined)
3185
+ return fail('row', 'row', 'a row that is no item with one text, or a separator');
3186
+ const mods = [];
3187
+ for (const [name, value] of props) {
3188
+ const expression = value ? attributeExpression(value) : undefined;
3189
+ if (name === 'onPress' && expression && !radio)
3190
+ mods.push({ name, args: [{ node: expression, hole: 'handler' }] });
3191
+ else if (name === 'value' && expression && radio)
3192
+ mods.push({
3193
+ name: 'tag',
3194
+ args: [staticString(value) ?? { node: expression, hole: 'string' }],
3195
+ });
3196
+ else if (name === 'variant' && staticString(value) === 'destructive' && !radio)
3197
+ mods.push({ name: 'destructive', args: [] });
3198
+ else if (name === 'variant' && staticString(value) === 'default' && !radio)
3199
+ continue;
3200
+ else if ((name === 'disabled' || name === 'keepOpen') && value === null)
3201
+ mods.push({ name, args: [] });
3202
+ else if (name === 'testID' && staticString(value) !== undefined)
3203
+ mods.push({ name, args: [staticString(value)] });
3204
+ else if (name === 'leading' && expression) {
3205
+ const glyph = menuGlyph(expression);
3206
+ if (!glyph)
3207
+ return fail(name, 'leading', 'a leading view that is no `toElement(Icon(icon).size(s).foreground(f))`');
3208
+ mods.unshift(...glyph);
3209
+ }
3210
+ else
3211
+ return fail(name, `item:${name}`, `an item's \`${name}\` (or its form here) has no mapping`);
3212
+ }
3213
+ // The tag first, as a choice is written: `Item(title).tag(value)`.
3214
+ mods.sort((a, b) => Number(b.name === 'tag') - Number(a.name === 'tag'));
3215
+ return rowView('Item', [title], mods);
3216
+ };
3217
+ const rows = [];
3218
+ /** Elements the menu holds below its content's rows (a radio group's items). */
3219
+ const nested = [];
3220
+ const contentRows = elements(content) ?? [undefined];
3221
+ for (let index = 0; index < contentRows.length; index++) {
3222
+ const row = contentRows[index];
3223
+ if (part(row) === 'DropdownMenuSeparator' &&
3224
+ attributes(row)?.size === 0 &&
3225
+ !elements(row)?.length) {
3226
+ rows.push(rowView('Divider', [], []));
3227
+ continue;
3228
+ }
3229
+ // A label over a radio group, or a radio group alone: a Section of choices,
3230
+ // `Section(...items).title(label).selection([value, onValueChange])`.
3231
+ const labelled = part(row) === 'DropdownMenuLabel' &&
3232
+ part(contentRows[index + 1]) === 'DropdownMenuRadioGroup' &&
3233
+ attributes(row)?.size === 0;
3234
+ const group = labelled ? contentRows[index + 1] : row;
3235
+ if (part(group) === 'DropdownMenuRadioGroup') {
3236
+ const title = labelled ? titleOf(row) : undefined;
3237
+ const groupProps = attributes(group);
3238
+ const value = groupProps?.get('value');
3239
+ const set = groupProps?.get('onValueChange');
3240
+ const items = elements(group);
3241
+ if ((labelled && title === undefined) ||
3242
+ !value ||
3243
+ !set ||
3244
+ groupProps?.size !== 2 ||
3245
+ !items?.length)
3246
+ return fail('radio-group', 'radio-group', 'a radio group that is no `value` and `onValueChange` over radio items, under one label');
3247
+ const choices = [];
3248
+ for (const item of items) {
3249
+ const choice = itemRow(item, true);
3250
+ if ('reasons' in choice)
3251
+ return choice;
3252
+ choices.push(choice);
3253
+ }
3254
+ nested.push(...items);
3255
+ const sectionProps = [];
3256
+ if (title !== undefined)
3257
+ sectionProps.push({ name: 'title', args: [title] });
3258
+ sectionProps.push({
3259
+ name: 'selection',
3260
+ args: [
3261
+ {
3262
+ $: 'binding',
3263
+ binding: [
3264
+ { node: attributeExpression(value), hole: 'string' },
3265
+ { node: attributeExpression(set), hole: 'handler' },
3266
+ ],
3267
+ },
3268
+ ],
3269
+ });
3270
+ rows.push(rowView('Section', choices, sectionProps));
3271
+ if (labelled)
3272
+ index++;
3273
+ continue;
3274
+ }
3275
+ const item = itemRow(row, false);
3276
+ if ('reasons' in item)
3277
+ return item;
3278
+ rows.push(item);
3279
+ }
3280
+ const props = [];
3281
+ if (label) {
3282
+ const expression = attributeExpression(label);
3283
+ props.push({
3284
+ name: 'label',
3285
+ args: [staticString(label) ?? { node: expression, hole: 'string' }],
3286
+ });
3287
+ }
3288
+ const testID = contentProps.get('testID');
3289
+ if (testID) {
3290
+ const text = staticString(testID);
3291
+ if (text === undefined)
3292
+ return fail('testID', 'testID', 'a testID set at runtime');
3293
+ props.push({ name: 'testID', args: [text] });
3294
+ }
3295
+ props.push({ name: 'menuStyle', args: ['dropdown'] });
3296
+ if (presented)
3297
+ props.push({
3298
+ name: 'presented',
3299
+ args: [
3300
+ {
3301
+ $: 'binding',
3302
+ binding: [
3303
+ { node: attributeExpression(opened), hole: 'boolean' },
3304
+ { node: attributeExpression(onOpenChange), hole: 'handler' },
3305
+ ],
3306
+ },
3307
+ ],
3308
+ });
3309
+ for (const element of [trigger, content, ...(elements(content) ?? []), ...nested])
3310
+ results.set(element, {
3311
+ ir: { type: 'component', node: 'Menu', within: undefined, args: [], props: [], key: null },
3312
+ });
3313
+ return {
3314
+ ir: {
3315
+ type: 'component',
3316
+ node: 'Menu',
3317
+ within: undefined,
3318
+ args: [{ $: 'view', view: triggerView.ir }, ...rows],
3319
+ props,
3320
+ key: null,
3321
+ },
3322
+ };
3323
+ }
3324
+ /**
3325
+ * Bloom's `Fab` as `FAB(Icon(icon), Text(label)).glass(identity)`
3326
+ * (parity/button.cases.tsx): the language's FAB is on glass, so an app's
3327
+ * solid Fab names no glass. Its `icon` is the glyph, its `label` the
3328
+ * extended label, `accessibilityLabel` its `.label()`, and `size`,
3329
+ * `appearance`, `tone`, `disabled`, `collapsed`, `onPress` and `testID` the
3330
+ * modifiers of the same meaning.
3331
+ */
3332
+ function convertFab(node) {
3333
+ const reasons = [];
3334
+ const fail = (subject, why) => {
3335
+ reasons.push({ subject, code: `Fab:${subject}`, why });
3336
+ return { reasons };
3337
+ };
3338
+ if (node.children.some((c) => !(n.JSXText.check(c) && cleanJsxText(c.value) === '')))
3339
+ return fail('children', 'children: a Fab draws its icon and label props');
3340
+ const views = [];
3341
+ const props = [];
3342
+ const TOKENS = {
3343
+ size: ['size', 'controlSize'],
3344
+ appearance: ['style', 'appearance'],
3345
+ tone: ['tint', 'tone'],
3346
+ };
3347
+ let icon;
3348
+ let label;
3349
+ for (const attribute of node.openingElement.attributes) {
3350
+ if (!n.JSXAttribute.check(attribute) || !n.JSXIdentifier.check(attribute.name))
3351
+ return fail('spread', 'spread props: the codemod cannot see what they set');
3352
+ const name = attribute.name.name;
3353
+ const { value } = attribute;
3354
+ const expression = value ? attributeExpression(value) : undefined;
3355
+ const text = staticString(value);
3356
+ if (name === 'icon' &&
3357
+ n.Identifier.check(expression) &&
3358
+ kindOf(sources.get(expression.name)) === 'icon')
3359
+ icon = {
3360
+ $: 'view',
3361
+ view: { type: 'icon', component: expression.name, mods: [], key: null },
3362
+ };
3363
+ else if (name === 'label' && expression && !hasJsx(expression))
3364
+ label = text ?? { node: expression, hole: 'string' };
3365
+ else if (name === 'accessibilityLabel' && expression && !hasJsx(expression))
3366
+ props.push({ name: 'label', args: [text ?? { node: expression, hole: 'string' }] });
3367
+ else if (TOKENS[name] && text !== undefined && spec.enums[TOKENS[name][1]]?.includes(text))
3368
+ props.push({ name: TOKENS[name][0], args: [text] });
3369
+ else if ((name === 'disabled' || name === 'collapsed') && (value === null || expression))
3370
+ props.push({
3371
+ name,
3372
+ args: [value === null ? true : { node: expression, hole: 'boolean' }],
3373
+ });
3374
+ else if (name === 'onPress' && expression)
3375
+ props.push({ name, args: [{ node: expression, hole: 'handler' }] });
3376
+ else if (name === 'testID' && text !== undefined)
3377
+ props.push({ name, args: [text] });
3378
+ else
3379
+ return fail(name, `a Fab's \`${name}\` (or its form here) has no mapping`);
3380
+ }
3381
+ if (icon === undefined)
3382
+ return fail('icon', 'a Fab with no icon the codemod reads');
3383
+ views.push(icon);
3384
+ if (label !== undefined)
3385
+ views.push({
3386
+ $: 'view',
3387
+ view: {
3388
+ type: 'text',
3389
+ raw: false,
3390
+ resolved: { axis: 'column', mods: [], variants: [] },
3391
+ choice: null,
3392
+ props: [],
3393
+ key: null,
3394
+ runs: [
3395
+ typeof label === 'string'
3396
+ ? { type: 'string', value: label }
3397
+ : { type: 'expr', value: label },
3398
+ ],
3399
+ },
3400
+ });
3401
+ props.push({ name: 'glass', args: [{ $: 'language', name: 'identity' }] });
3402
+ return {
3403
+ ir: { type: 'component', node: 'FAB', within: undefined, args: views, props, key: null },
3404
+ };
3405
+ }
3406
+ /** A row's glyph as the language writes it, `toElement(Icon(icon).size(s).foreground(f))`, as the row's modifiers. */
3407
+ function menuGlyph(expression) {
3408
+ if (!isToElement(expression) || expression.arguments.length !== 1)
3409
+ return undefined;
3410
+ const chain = [];
3411
+ let at = expression.arguments[0];
3412
+ while (n.CallExpression.check(at) && n.MemberExpression.check(at.callee)) {
3413
+ if (at.arguments.length !== 1 || !n.Identifier.check(at.callee.property))
3414
+ return undefined;
3415
+ chain.unshift([at.callee.property.name, at.arguments[0]]);
3416
+ at = at.callee.object;
3417
+ }
3418
+ const callee = n.CallExpression.check(at) ? at.callee : undefined;
3419
+ const base = n.Identifier.check(callee) ? sources.get(callee.name) : undefined;
3420
+ const icon = at?.arguments?.[0];
3421
+ if (base?.module !== LANGUAGE_MODULE ||
3422
+ base.imported !== 'Icon' ||
3423
+ at.arguments.length !== 1 ||
3424
+ !n.Identifier.check(icon) ||
3425
+ kindOf(sources.get(icon.name)) !== 'icon')
3426
+ return undefined;
3427
+ const size = chain.find(([name]) => name === 'size')?.[1];
3428
+ const ink = chain.find(([name]) => name === 'foreground')?.[1];
3429
+ // Both named: the menu's own glyph (`md`, quiet) is drawn otherwise.
3430
+ if (chain.length !== 2 || staticString(size) === undefined || staticString(ink) === undefined)
3431
+ return undefined;
3432
+ return [
3433
+ { name: 'icon', args: [{ $: 'icon', name: icon.name }] },
3434
+ { name: 'iconSize', args: [staticString(size)] },
3435
+ { name: 'iconForeground', args: [staticString(ink)] },
3436
+ ];
3437
+ }
3438
+ /** Bloom's `Button`, as the language's Button parity cases draw it (`packages/bloom-language/parity/button.cases.tsx`). */
3439
+ function convertButton(node) {
3440
+ const reasons = [];
3441
+ const fail = (subject, code, why) => reasons.push({ subject, code, why });
3442
+ const props = [];
3443
+ /** Its `style`, the button's box: chained after its own modifiers. */
3444
+ const styled = [];
3445
+ let key = null;
3446
+ let leading = null;
3447
+ let trailing = null;
3448
+ const flags = new Set();
3449
+ const ENUM = {
3450
+ appearance: 'style',
3451
+ tone: 'tint',
3452
+ size: 'size',
3453
+ density: 'density',
3454
+ linkTone: 'linkTone',
3455
+ };
3456
+ const BOOLEAN = {
3457
+ disabled: 'disabled',
3458
+ loading: 'loading',
3459
+ pressed: 'pressed',
3460
+ inverted: 'inverted',
3461
+ };
3462
+ const icon = (value) => {
3463
+ const expression = attributeExpression(value);
3464
+ return n.Identifier.check(expression) && kindOf(sources.get(expression.name)) === 'icon'
3465
+ ? expression.name
3466
+ : undefined;
3467
+ };
3468
+ for (const attribute of node.openingElement.attributes) {
3469
+ if (!n.JSXAttribute.check(attribute) || !n.JSXIdentifier.check(attribute.name)) {
3470
+ fail('{...spread}', 'spread', 'spread props: the codemod cannot see what they set');
3471
+ continue;
3472
+ }
3473
+ const name = attribute.name.name;
3474
+ const value = attribute.value;
3475
+ const expression = value ? attributeExpression(value) : null;
3476
+ if (name === 'key' && expression)
3477
+ key = { node: expression, hole: 'key', attribute };
3478
+ else if (ENUM[name] && staticString(value) !== undefined)
3479
+ props.push({ name: ENUM[name], args: [staticString(value)] });
3480
+ else if (BOOLEAN[name] && (value === null || value === undefined))
3481
+ props.push({ name: BOOLEAN[name], args: [] });
3482
+ else if (BOOLEAN[name] && expression)
3483
+ props.push({
3484
+ name: BOOLEAN[name],
3485
+ args: [{ node: expression, hole: 'boolean' }],
3486
+ });
3487
+ else if (['iconOnly', 'wide', 'grow'].includes(name) &&
3488
+ (value === null || value === undefined))
3489
+ flags.add(name);
3490
+ // An appearance or tone set at runtime is the modifier's own expression.
3491
+ else if (ENUM[name] && expression && !hasJsx(expression))
3492
+ props.push({ name: ENUM[name], args: [{ node: expression, hole: 'string' }] });
3493
+ else if (name === 'stopPropagation' && (value === null || value === undefined))
3494
+ props.push({ name: 'stopPropagation', args: [] });
3495
+ else if (name === 'iconSize' && ICON_SIZE_TOKEN.has(staticNumber(value)))
3496
+ props.push({
3497
+ name: 'iconSize',
3498
+ args: [ICON_SIZE_TOKEN.get(staticNumber(value))],
3499
+ });
3500
+ // No spinner while loading.
3501
+ else if (name === 'loadingIndicator' && n.NullLiteral.check(expression))
3502
+ props.push({ name: 'loadingIndicator', args: [{ node: expression, hole: 'handler' }] });
3503
+ // A menu trigger's open state: Bloom's aria-expanded is the language's accessibility state.
3504
+ else if (name === 'aria-expanded' && expression && !hasJsx(expression))
3505
+ props.push({
3506
+ name: 'accessibilityState',
3507
+ args: [
3508
+ {
3509
+ node: recast.types.builders.objectExpression([
3510
+ recast.types.builders.objectProperty(recast.types.builders.identifier('expanded'), expression),
3511
+ ]),
3512
+ hole: 'state',
3513
+ },
3514
+ ],
3515
+ });
3516
+ // Its inks, each a theme colour read as its role.
3517
+ else if ((name === 'color' || name === 'hoverColor') && expression && roleOf(expression))
3518
+ props.push({
3519
+ name: name === 'color' ? 'foreground' : 'hoverForeground',
3520
+ args: [roleOf(expression)],
3521
+ });
3522
+ else if (name === 'leadingIcon' && icon(value))
3523
+ leading = icon(value);
3524
+ else if (name === 'trailingIcon' && icon(value))
3525
+ trailing = icon(value);
3526
+ else if (name === 'accessibilityLabel' && value)
3527
+ props.push({
3528
+ name: 'label',
3529
+ args: [staticString(value) ?? { node: expression, hole: 'string' }],
3530
+ });
3531
+ else if ((name === 'onPress' || name === 'onLongPress') && expression)
3532
+ props.push({ name, args: [{ node: expression, hole: 'handler' }] });
3533
+ else if (name === 'testID' && value)
3534
+ props.push({
3535
+ name: 'testID',
3536
+ args: [staticString(value) ?? { node: expression, hole: 'string' }],
3537
+ });
3538
+ else if (name === 'style' && expression) {
3539
+ const box = componentStyle(expression, 'Button');
3540
+ if ('reasons' in box)
3541
+ reasons.push(...box.reasons);
3542
+ else
3543
+ styled.push(...box.mods);
3544
+ }
3545
+ else
3546
+ fail(name, `button:${name}`, `Button's \`${name}\` (or its form here) has no mapping`);
3547
+ }
3548
+ props.push(...styled);
3549
+ const shape = flags.has('iconOnly')
3550
+ ? flags.has('wide')
3551
+ ? 'pill'
3552
+ : 'circle'
3553
+ : flags.has('grow')
3554
+ ? 'fit'
3555
+ : null;
3556
+ if (flags.has('wide') && !flags.has('iconOnly'))
3557
+ fail('wide', 'button:wide', 'wide without iconOnly');
3558
+ if (flags.has('grow') && flags.has('iconOnly'))
3559
+ fail('grow', 'button:grow', 'grow with iconOnly');
3560
+ if (shape)
3561
+ props.unshift({ name: 'shape', args: [shape] });
3562
+ const runs = [];
3563
+ for (const child of node.children) {
3564
+ if (n.JSXText.check(child)) {
3565
+ const text = cleanJsxText(child.value);
3566
+ if (text)
3567
+ runs.push({ type: 'string', value: text });
3568
+ }
3569
+ else if (n.JSXExpressionContainer.check(child) &&
3570
+ !n.JSXEmptyExpression.check(child.expression)) {
3571
+ if (n.StringLiteral.check(child.expression))
3572
+ runs.push({ type: 'string', value: child.expression.value });
3573
+ else
3574
+ runs.push({ type: 'expr', value: { node: child.expression, hole: 'text' } });
3575
+ }
3576
+ else
3577
+ fail('child', 'button-child', 'a Button child that is no text');
3578
+ }
3579
+ if (reasons.length)
3580
+ return { reasons };
3581
+ return { ir: { type: 'button', leading, trailing, runs, props, key } };
3582
+ }
3583
+ /** A `{…}` child of a stack: a converted branch where its form is safe, else embedded. */
3584
+ function expressionChild(expression) {
3585
+ const branch = (node) => {
3586
+ if (n.NullLiteral.check(node))
3587
+ return null;
3588
+ if (n.JSXElement.check(node)) {
3589
+ const inner = convert(node);
3590
+ return 'ir' in inner ? inner.ir : undefined;
3591
+ }
3592
+ return undefined;
3593
+ };
3594
+ if (n.ConditionalExpression.check(expression)) {
3595
+ const then = branch(expression.consequent);
3596
+ const otherwise = branch(expression.alternate);
3597
+ if (then !== undefined && otherwise !== undefined && (then || otherwise))
3598
+ return {
3599
+ type: 'cond',
3600
+ test: { node: expression.test, hole: 'condition' },
3601
+ then,
3602
+ otherwise,
3603
+ };
3604
+ }
3605
+ if (n.LogicalExpression.check(expression) &&
3606
+ expression.operator === '&&' &&
3607
+ isBooleanForm(expression.left)) {
3608
+ const then = branch(expression.right);
3609
+ if (then)
3610
+ return {
3611
+ type: 'cond',
3612
+ test: { node: expression.left, hole: 'condition' },
3613
+ then,
3614
+ otherwise: null,
3615
+ };
3616
+ }
3617
+ return { type: 'embed', content: { node: expression, hole: 'element' } };
3618
+ }
3619
+ /**
3620
+ * React Native's `pointerEvents` as the language's hit testing: a static
3621
+ * value, or values (and none, `undefined`) chosen by a plain condition
3622
+ * (`split ? 'box-none' : undefined`). `auto` alone stays JSX, the default.
3623
+ */
3624
+ function hitTestingOf(expression) {
3625
+ if (n.ConditionalExpression.check(expression) &&
3626
+ (isPlainRead(expression.test) || isBooleanForm(expression.test))) {
3627
+ const branch = (node) => n.Identifier.check(node) && node.name === 'undefined'
3628
+ ? { $: 'absent' }
3629
+ : staticString(node) === 'auto'
3630
+ ? true
3631
+ : hitTestingOf(node);
3632
+ const then = branch(expression.consequent);
3633
+ const otherwise = branch(expression.alternate);
3634
+ return then === undefined || otherwise === undefined
3635
+ ? undefined
3636
+ : { $: 'choose', test: { node: expression.test, hole: 'condition' }, then, otherwise };
3637
+ }
3638
+ return HIT_TESTING[staticString(expression) ?? ''];
3639
+ }
3640
+ // ── styles left unread ───────────────────────────────────────────────
3641
+ /**
3642
+ * How often each module style is read: a StyleSheet's style by
3643
+ * `sheet.key`, a module style constant by its name (its declaration not counted).
3644
+ */
3645
+ function styleReadsIn(root) {
3646
+ const reads = new Map();
3647
+ const count = (name) => reads.set(name, (reads.get(name) ?? 0) + 1);
3648
+ recast.visit(root, {
3649
+ visitMemberExpression(path) {
3650
+ const { object, property } = path.node;
3651
+ if (!path.node.computed &&
3652
+ n.Identifier.check(object) &&
3653
+ n.Identifier.check(property) &&
3654
+ styleSheets.get(object.name)?.has(property.name))
3655
+ count(`${object.name}.${property.name}`);
3656
+ this.traverse(path);
3657
+ },
3658
+ visitIdentifier(path) {
3659
+ const parent = path.parent?.node;
3660
+ const declares = n.VariableDeclarator.check(parent) && parent.id === path.node;
3661
+ const member = (n.MemberExpression.check(parent) && parent.property === path.node && !parent.computed) ||
3662
+ (n.ObjectProperty.check(parent) && parent.key === path.node && !parent.computed);
3663
+ if (!declares && !member && styleConstants.has(path.node.name))
3664
+ count(path.node.name);
3665
+ this.traverse(path);
3666
+ },
3667
+ });
3668
+ return reads;
3669
+ }
3670
+ /**
3671
+ * The module styles the conversion leaves unread: a StyleSheet's style, or a
3672
+ * module style constant, that an element read before the walk and nothing
3673
+ * reads now is removed (a style never read before stays: not the
3674
+ * conversion's). A StyleSheet left empty goes with its declaration, its
3675
+ * `StyleSheet` import then pruned as a converted component's is. An
3676
+ * exported style is the module's API and stays.
3677
+ */
3678
+ function removeUnreadStyles(before) {
3679
+ const after = styleReadsIn(ast);
3680
+ const unread = (name) => (before.get(name) ?? 0) > 0 && !after.get(name);
3681
+ const body = ast.program.body;
3682
+ for (const statement of [...body]) {
3683
+ if (!n.VariableDeclaration.check(statement) || statement.kind !== 'const')
3684
+ continue;
3685
+ statement.declarations = statement.declarations.filter((declarator) => {
3686
+ if (!n.Identifier.check(declarator.id))
3687
+ return true;
3688
+ const name = declarator.id.name;
3689
+ if (styleConstants.has(name))
3690
+ return !unread(name);
3691
+ const sheet = styleSheets.get(name);
3692
+ const object = sheet ? declarator.init.arguments[0] : undefined;
3693
+ if (!object)
3694
+ return true;
3695
+ object.properties = object.properties.filter((property) => !(n.Identifier.check(property.key) && unread(`${name}.${property.key.name}`)));
3696
+ if (object.properties.length > 0)
3697
+ return true;
3698
+ if (styleSheetLocal)
3699
+ convertedLocals.add(styleSheetLocal);
3700
+ return false;
3701
+ });
3702
+ if (statement.declarations.length === 0)
3703
+ body.splice(body.indexOf(statement), 1);
3704
+ }
3705
+ }
3706
+ // ── printing ─────────────────────────────────────────────────────────
3707
+ /** Prints the chain; with `holes`, each carried value is its hole. */
3708
+ function print(ir, carry, root = false) {
3709
+ switch (ir.type) {
3710
+ case 'embed': {
3711
+ const text = carry(ir.content);
3712
+ const shown = ir.content.node.__carried ?? ir.content.node;
3713
+ // A language view the file placed with toElement() is that view: `Embed(toElement(v))` is
3714
+ // `v`. (A fixture's hole stands for the element, so there it stays embedded.)
3715
+ if (isToElement(shown) && shown.arguments.length === 1 && text === recast.print(shown).code)
3716
+ return recast.print(shown.arguments[0]).code;
3717
+ return `${lang('Embed')}(${text})`;
3718
+ }
3719
+ case 'comment':
3720
+ return ir.text;
3721
+ case 'screen':
3722
+ return `${print(ir.content, carry)}${ir.props.map((p) => printProp(p, carry)).join('')}`;
3723
+ case 'cond':
3724
+ return `${carry(ir.test)} ? ${ir.then ? print(ir.then, carry) : 'null'} : ${ir.otherwise ? print(ir.otherwise, carry) : 'null'}`;
3725
+ case 'map':
3726
+ return `${carry(ir.items)}.map((${ir.params.map((param) => recast.print(param).code).join(', ')}) => ${print(ir.body, carry)})`;
3727
+ case 'icon':
3728
+ return `${lang('Icon')}(${ir.component})${ir.mods.map((mod) => printMod(mod, carry)).join('')}${ir.color ? `.foreground(${appColorTable}.color.${ir.color.name})` : ''}${ir.key && !root ? `.id(${carry(ir.key)})` : ''}`;
3729
+ case 'component': {
3730
+ // Its children (the trailing views) with their comments; the arguments before them as values.
3731
+ const first = ir.args.findIndex((a) => isTagged(a) && a.$ === 'view');
3732
+ const leading = first === -1 ? ir.args : ir.args.slice(0, first);
3733
+ const views = first === -1 ? [] : ir.args.slice(first);
3734
+ const args = [
3735
+ ...leading.map((a) => printValue(a, carry)),
3736
+ ...(views.every((a) => isTagged(a) && a.$ === 'view')
3737
+ ? printViews(views.map((a) => a.view), carry)
3738
+ : views.map((a) => printValue(a, carry))),
3739
+ ].join(', ');
3740
+ const tail = ir.props.map((p) => printProp(p, carry)).join('');
3741
+ return `${lang(ir.node)}(${args})${tail}${ir.key && !root && !ir.part ? `.id(${carry(ir.key)})` : ''}`;
3742
+ }
3743
+ case 'button': {
3744
+ const parts = [];
3745
+ if (ir.leading)
3746
+ parts.push(`${lang('Icon')}(${ir.leading})`);
3747
+ if (ir.runs.length)
3748
+ parts.push(`${lang('Text')}(${ir.runs.map((run) => ('type' in run && run.type === 'string' ? quote(run.value) : carry(run.value))).join(', ')})`);
3749
+ if (ir.trailing)
3750
+ parts.push(`${lang('Icon')}(${ir.trailing})`);
3751
+ const tail = ir.props.map((p) => printProp(p, carry)).join('');
3752
+ return `${lang('Button')}(${parts.join(', ')})${tail}${ir.key && !root ? `.id(${carry(ir.key)})` : ''}`;
3753
+ }
3754
+ case 'text': {
3755
+ const runs = ir.runs.map((run) => 'type' in run && run.type === 'string'
3756
+ ? quote(run.value)
3757
+ : 'type' in run && run.type === 'expr'
3758
+ ? carry(run.value)
3759
+ : print(run, carry));
3760
+ return `${lang(ir.raw ? 'RawText' : 'Text')}(${runs.join(', ')})${chainTail(ir.resolved, ir.choice, ir.props, root ? null : ir.key, carry)}`;
3761
+ }
3762
+ case 'stack': {
3763
+ const ctor = lang(ir.resolved.axis === 'row' ? 'HStack' : 'VStack');
3764
+ const children = printViews(ir.children, carry);
3765
+ return `${ctor}(${children.join(', ')})${chainTail(ir.resolved, ir.choice, ir.props, root ? null : ir.key, carry)}`;
3766
+ }
3767
+ }
3768
+ }
3769
+ function chainTail(resolved, choice, props, key, carry) {
3770
+ // A value the other branch writes differently is chosen by its condition.
3771
+ let out = resolved.mods
3772
+ .map((mod, i) => {
3773
+ const other = choice && 'mods' in choice ? choice.mods[i] : undefined;
3774
+ if (!choice || !other)
3775
+ return printMod(mod, carry);
3776
+ const args = mod.args.map((arg, j) => {
3777
+ const alternative = other.args[j];
3778
+ return arg === alternative
3779
+ ? printArg(arg, carry)
3780
+ : `${carry(choice.test)} ? ${printArg(arg, carry)} : ${printArg(alternative, carry)}`;
3781
+ });
3782
+ return `.${mod.name}(${args.join(', ')})`;
3783
+ })
3784
+ .join('');
3785
+ // What one branch alone adds is a variant of its condition, before the live variants, which override it.
3786
+ if (choice && 'only' in choice) {
3787
+ const test = carry(choice.test);
3788
+ const plain = n.Identifier.check(choice.test.node) || n.MemberExpression.check(choice.test.node);
3789
+ const holds = isBooleanForm(choice.test.node) ? test : `Boolean(${test})`;
3790
+ const fails = plain ? `!${test}` : `!(${test})`;
3791
+ for (const [condition, mods] of [
3792
+ [holds, choice.only.whenTrue],
3793
+ [fails, choice.only.whenFalse],
3794
+ ])
3795
+ if (mods.length)
3796
+ out += `.when(${condition}, (v) => v${mods.map((mod) => printMod(mod, carry)).join('')})`;
3797
+ }
3798
+ for (const variant of resolved.variants) {
3799
+ let inner = `v${variant.mods.map((mod) => printMod(mod, carry)).join('')}`;
3800
+ for (const condition of [...variant.conditions].reverse().slice(0, -1))
3801
+ inner = `v.when(${quote(condition)}, (v) => ${inner})`;
3802
+ out += `.when(${quote(variant.conditions[0])}, (v) => ${inner})`;
3803
+ }
3804
+ for (const prop of props)
3805
+ out += printProp(prop, carry);
3806
+ if (key)
3807
+ out += `.id(${carry(key)})`;
3808
+ return out;
3809
+ }
3810
+ function printValue(value, carry) {
3811
+ if (isCarried(value))
3812
+ return value.hole === 'action' ? `() => ${carry(value)}()` : carry(value);
3813
+ if (isTagged(value)) {
3814
+ switch (value.$) {
3815
+ case 'view':
3816
+ return print(value.view, carry);
3817
+ case 'binding':
3818
+ return `[${printValue(value.binding[0], carry)}, ${printValue(value.binding[1], carry)}]`;
3819
+ case 'icon':
3820
+ return value.name;
3821
+ case 'options':
3822
+ return value.entries.length
3823
+ ? `{ ${value.entries.map(([key, v]) => `${key}: ${printValue(v, carry)}`).join(', ')} }`
3824
+ : '{}';
3825
+ case 'row':
3826
+ return `(${value.param}) => ${print(value.view, carry)}`;
3827
+ case 'build':
3828
+ return `(v) => v${value.mods.map((mod) => printMod(mod, carry)).join('')}`;
3829
+ case 'renderer':
3830
+ return carry(value.fn);
3831
+ case 'absent':
3832
+ return 'undefined';
3833
+ case 'component':
3834
+ return value.name;
3835
+ case 'language':
3836
+ return lang(value.name);
3837
+ case 'null':
3838
+ return 'null';
3839
+ case 'choose':
3840
+ return `${carry(value.test)} ? ${printValue(value.then, carry)} : ${printValue(value.otherwise, carry)}`;
3841
+ case 'appColor':
3842
+ return `${appColorTable}.color.${value.color.name}`;
3843
+ }
3844
+ }
3845
+ return printArg(value, carry);
3846
+ }
3847
+ const printProp = (prop, carry) => `.${prop.name}(${prop.args.map((a) => printValue(a, carry)).join(', ')})`;
3848
+ /** The carried values inside a value, in order. */
3849
+ function carriedOfValue(value, out) {
3850
+ if (isCarried(value))
3851
+ out.push(value);
3852
+ else if (!isTagged(value))
3853
+ out.push(...pointsOf(value));
3854
+ else if (isTagged(value)) {
3855
+ if (value.$ === 'view' || value.$ === 'row')
3856
+ carriedOf(value.view, out);
3857
+ else if (value.$ === 'binding')
3858
+ for (const v of value.binding)
3859
+ carriedOfValue(v, out);
3860
+ else if (value.$ === 'renderer')
3861
+ out.push(value.fn);
3862
+ else if (value.$ === 'options')
3863
+ for (const [, v] of value.entries)
3864
+ carriedOfValue(v, out);
3865
+ else if (value.$ === 'choose') {
3866
+ out.push(value.test);
3867
+ carriedOfValue(value.then, out);
3868
+ carriedOfValue(value.otherwise, out);
3869
+ }
3870
+ }
3871
+ }
3872
+ /** The views a value holds. */
3873
+ function viewsOfValue(value) {
3874
+ if (!isTagged(value))
3875
+ return [];
3876
+ if (value.$ === 'view' || value.$ === 'row')
3877
+ return [value.view];
3878
+ if (value.$ === 'options')
3879
+ return value.entries.flatMap(([, v]) => viewsOfValue(v));
3880
+ return [];
3881
+ }
3882
+ /** The views directly inside a view: its children, spans, branches and the views its values hold. */
3883
+ function childrenOf(ir) {
3884
+ const props = 'props' in ir ? ir.props.flatMap((prop) => prop.args.flatMap(viewsOfValue)) : [];
3885
+ switch (ir.type) {
3886
+ case 'cond':
3887
+ return [ir.then, ir.otherwise].filter((branch) => branch !== null);
3888
+ case 'map':
3889
+ return [ir.body];
3890
+ case 'component':
3891
+ return [...ir.args.flatMap(viewsOfValue), ...props];
3892
+ case 'text':
3893
+ return [
3894
+ ...ir.runs.filter((run) => !('type' in run && (run.type === 'string' || run.type === 'expr'))),
3895
+ ...props,
3896
+ ];
3897
+ case 'stack':
3898
+ return [...ir.children, ...props];
3899
+ case 'screen':
3900
+ return [ir.content, ...props];
3901
+ default:
3902
+ return props;
3903
+ }
3904
+ }
3905
+ /** The points a view's modifiers carry (a style's `width: itemSize`), each once. */
3906
+ function resolvedPoints(resolved, choice) {
3907
+ const mods = [
3908
+ ...resolved.mods,
3909
+ ...resolved.variants.flatMap((variant) => variant.mods),
3910
+ ...choiceMods(choice),
3911
+ ];
3912
+ return [...new Set(mods.flatMap((mod) => mod.args.flatMap(pointsOf)))];
3913
+ }
3914
+ /** Every carried value of a tree, in order. */
3915
+ function carriedOf(ir, out = []) {
3916
+ switch (ir.type) {
3917
+ case 'embed':
3918
+ out.push(ir.content);
3919
+ break;
3920
+ case 'screen':
3921
+ carriedOf(ir.content, out);
3922
+ for (const prop of ir.props)
3923
+ for (const a of prop.args)
3924
+ carriedOfValue(a, out);
3925
+ break;
3926
+ case 'cond':
3927
+ out.push(ir.test);
3928
+ if (ir.then)
3929
+ carriedOf(ir.then, out);
3930
+ if (ir.otherwise)
3931
+ carriedOf(ir.otherwise, out);
3932
+ break;
3933
+ case 'map':
3934
+ out.push(ir.items);
3935
+ carriedOf(ir.body, out);
3936
+ break;
3937
+ case 'icon':
3938
+ if (ir.key)
3939
+ out.push(ir.key);
3940
+ break;
3941
+ case 'component':
3942
+ for (const a of ir.args)
3943
+ carriedOfValue(a, out);
3944
+ for (const prop of ir.props)
3945
+ for (const a of prop.args)
3946
+ carriedOfValue(a, out);
3947
+ if (ir.key)
3948
+ out.push(ir.key);
3949
+ break;
3950
+ case 'button':
3951
+ for (const run of ir.runs)
3952
+ if ('type' in run && run.type === 'expr')
3953
+ out.push(run.value);
3954
+ for (const prop of ir.props)
3955
+ for (const a of prop.args)
3956
+ carriedOfValue(a, out);
3957
+ if (ir.key)
3958
+ out.push(ir.key);
3959
+ break;
3960
+ case 'text':
3961
+ for (const run of ir.runs)
3962
+ if ('type' in run && run.type === 'expr')
3963
+ out.push(run.value);
3964
+ else if (!('type' in run && run.type === 'string'))
3965
+ carriedOf(run, out);
3966
+ out.push(...resolvedPoints(ir.resolved, ir.choice));
3967
+ if (ir.choice)
3968
+ out.push(ir.choice.test);
3969
+ for (const prop of ir.props)
3970
+ for (const a of prop.args)
3971
+ carriedOfValue(a, out);
3972
+ if (ir.key)
3973
+ out.push(ir.key);
3974
+ break;
3975
+ case 'stack':
3976
+ for (const child of ir.children)
3977
+ carriedOf(child, out);
3978
+ out.push(...resolvedPoints(ir.resolved, ir.choice));
3979
+ if (ir.choice)
3980
+ out.push(ir.choice.test);
3981
+ for (const prop of ir.props)
3982
+ for (const a of prop.args)
3983
+ carriedOfValue(a, out);
3984
+ if (ir.key)
3985
+ out.push(ir.key);
3986
+ break;
3987
+ }
3988
+ return out;
3989
+ }
3990
+ // ── fixtures ─────────────────────────────────────────────────────────
3991
+ const fixtures = [];
3992
+ const HOLE = {
3993
+ text: (i) => `'⟨${i}⟩'`,
3994
+ string: (i) => `'⟨${i}⟩'`,
3995
+ key: (i) => `'k${i}'`,
3996
+ number: () => '2',
3997
+ // A length of its own for each, so a value carried to another key shows.
3998
+ points: (i) => String(37 + 6 * i),
3999
+ boolean: () => 'true',
4000
+ state: () => '{ selected: true, busy: false }',
4001
+ handler: () => '() => {}',
4002
+ action: () => '(() => {})',
4003
+ element: (i) => `<Hole n="${i}" />`,
4004
+ // The corpus's sample items (`corpus.ts`), the same array on both sides.
4005
+ items: () => 'ITEMS',
4006
+ // A row function drawing each item's index, so the argument it is handed is proven.
4007
+ renderer: (i) => `((${ROW_INFO}) => <Hole n={'${i}-' + ${ROW_INFO}.index} />)`,
4008
+ };
4009
+ /**
4010
+ * The region's fixture; a region with a condition has a second with every
4011
+ * condition false, so each branch it chooses between is drawn.
4012
+ */
4013
+ function fixture(node, ir, rootKey, conditions = true) {
4014
+ const carried = carriedOf(ir).filter((c) => c !== rootKey);
4015
+ if (conditions && carried.some((c) => c.hole === 'condition'))
4016
+ fixture(node, ir, rootKey, false);
4017
+ const index = new Map(carried.map((c, i) => [c, i]));
4018
+ // Points are one hole per expression: `width: size, height: size` stays a square.
4019
+ const pointsTexts = [];
4020
+ const pointsHole = (node) => {
4021
+ const text = recast.print(node).code;
4022
+ if (!pointsTexts.includes(text))
4023
+ pointsTexts.push(text);
4024
+ return HOLE.points(pointsTexts.indexOf(text));
4025
+ };
4026
+ const hole = (c) => c.hole === 'condition'
4027
+ ? String(conditions)
4028
+ : c.hole === 'points'
4029
+ ? pointsHole(c.node)
4030
+ : HOLE[c.hole](index.get(c) ?? 0);
4031
+ const removed = rootKey?.attribute;
4032
+ const after = ir.type === 'screen' ? print(ir, hole, true) : `toElement(${print(ir, hole, true)})`;
4033
+ // The source of the region, each carried value replaced by its hole.
4034
+ let before = '';
4035
+ let at = node.start;
4036
+ // A shorthand property's value is its key too (`{ width }`): the hole is written beside the key.
4037
+ const spans = carried.map((c) => ({
4038
+ start: c.node.start,
4039
+ end: c.node.end,
4040
+ text: shorthandValues.has(c.node) ? `${c.node.name}: ${hole(c)}` : hole(c),
4041
+ }));
4042
+ if (removed)
4043
+ spans.push({ start: removed.start, end: removed.end, text: '' });
4044
+ for (const side of heldPoints)
4045
+ if (side.start >= node.start && side.end <= node.end)
4046
+ spans.push({ start: side.start, end: side.end, text: pointsHole(side) });
4047
+ // An element's type arguments (`<SegmentedControl<Cadence>`) draw nothing, and name the app's types.
4048
+ recast.visit(node, {
4049
+ visitJSXOpeningElement(path) {
4050
+ const opening = path.node;
4051
+ const types = opening.typeParameters ?? opening.typeArguments;
4052
+ if (types)
4053
+ spans.push({ start: types.start, end: types.end, text: '' });
4054
+ this.traverse(path);
4055
+ },
4056
+ });
4057
+ // A StyleSheet's style is its object literal on the before side.
4058
+ for (const [read, literal] of styleLiterals)
4059
+ if (read.start >= node.start && read.end <= node.end)
4060
+ spans.push({ start: read.start, end: read.end, text: literal });
4061
+ // React Native's keyboard behavior reads its `Platform`, the corpus's own on the before side.
4062
+ for (const behavior of keyboardBehaviors)
4063
+ if (behavior.start >= node.start && behavior.end <= node.end)
4064
+ spans.push({
4065
+ start: behavior.test.left.object.start,
4066
+ end: behavior.test.left.object.end,
4067
+ text: 'RN.Platform',
4068
+ });
4069
+ // An inset the chain pads by is the corpus's on the before side, both sides drawn under it.
4070
+ let insets = false;
4071
+ for (const [read, side] of insetReads)
4072
+ if (read.start >= node.start &&
4073
+ read.end <= node.end &&
4074
+ // An inset inside points the chain carries (`top: insets.top + 8`) is that value's hole.
4075
+ !carried.some((c) => c.node.start <= read.start && read.end <= c.node.end)) {
4076
+ insets = true;
4077
+ spans.push({ start: read.start, end: read.end, text: `PARITY_INSETS.${side}` });
4078
+ }
4079
+ // A theme colour the chain names by its role is read from the theme the before side is drawn in.
4080
+ let themed = false;
4081
+ for (const [read] of themeRoles)
4082
+ if (read.start >= node.start && read.end <= node.end) {
4083
+ themed = true;
4084
+ spans.push({
4085
+ start: read.start,
4086
+ end: read.end,
4087
+ text: colorTokenReads.has(read)
4088
+ ? `parityTokens.${read.property.name}`
4089
+ : `parityTheme.colors.${read.property.name}`,
4090
+ });
4091
+ }
4092
+ // The surface fill is the before side's own read of it, where it is drawn.
4093
+ for (const read of surfaceReads)
4094
+ if (read.start >= node.start && read.end <= node.end) {
4095
+ themed = true;
4096
+ spans.push({ start: read.start, end: read.end, text: 'paritySurface' });
4097
+ }
4098
+ // A `const` holding the ink is its initialiser on the before side, its conditions the holes and its colours the theme's.
4099
+ for (const read of roleConstReads) {
4100
+ if (read.start < node.start || read.end > node.end)
4101
+ continue;
4102
+ const init = constInits.get(read);
4103
+ const inner = [];
4104
+ // A condition both inks read is one span.
4105
+ for (const c of carried)
4106
+ if (c.node.start >= init.start &&
4107
+ c.node.end <= init.end &&
4108
+ !inner.some((span) => span.start === c.node.start))
4109
+ inner.push({ start: c.node.start, end: c.node.end, text: hole(c) });
4110
+ for (const [themeRead] of themeRoles)
4111
+ if (themeRead.start >= init.start && themeRead.end <= init.end) {
4112
+ themed = true;
4113
+ inner.push({
4114
+ start: themeRead.start,
4115
+ end: themeRead.end,
4116
+ text: colorTokenReads.has(themeRead)
4117
+ ? `parityTokens.${themeRead.property.name}`
4118
+ : `parityTheme.colors.${themeRead.property.name}`,
4119
+ });
4120
+ }
4121
+ inner.sort((a, b) => a.start - b.start);
4122
+ let text = '';
4123
+ let from = init.start;
4124
+ for (const span of inner) {
4125
+ text += source.slice(from, span.start) + span.text;
4126
+ from = span.end;
4127
+ }
4128
+ text += source.slice(from, init.end);
4129
+ spans.push({ start: read.start, end: read.end, text: `(${text})` });
4130
+ }
4131
+ // A constant the chain names as an app colour is its colour on the before side, drawn without the module.
4132
+ const colors = colorsOf(ir);
4133
+ for (const color of colors)
4134
+ if (color.read)
4135
+ spans.push({ start: color.read.start, end: color.read.end, text: quote(color.value) });
4136
+ spans.sort((a, b) => a.start - b.start);
4137
+ for (const span of spans) {
4138
+ if (span.start < at)
4139
+ continue;
4140
+ before += source.slice(at, span.start) + span.text;
4141
+ at = span.end;
4142
+ }
4143
+ before += source.slice(at, node.end);
4144
+ const bindings = {};
4145
+ for (const local of new Set([...uncommented(before).matchAll(/<\/?([A-Z][\w]*)/g)].map((m) => m[1])))
4146
+ if (sources.has(local))
4147
+ bindings[local] = sources.get(local);
4148
+ // A Bloom or React Native value the before side reads or calls (`tokens.hitSlop.md`, `fontFamilyStyle('display')`).
4149
+ for (const match of uncommented(before).matchAll(/(?:^|[^\w.]|\.\.\.)([a-z]\w*)[.(]/g)) {
4150
+ const local = match[1];
4151
+ const module = sources.get(local)?.module ?? '';
4152
+ if (module.startsWith('@oxy.so/bloom/') || module === 'react-native')
4153
+ bindings[local] = sources.get(local);
4154
+ }
4155
+ // A language view the before side already writes (a menu row's `toElement(Icon(…))`).
4156
+ for (const match of uncommented(before).matchAll(/\b([A-Z][\w]*)\(/g)) {
4157
+ const local = match[1];
4158
+ if (sources.get(local)?.module === LANGUAGE_MODULE)
4159
+ bindings[local] = sources.get(local);
4160
+ }
4161
+ for (const match of uncommented(after).matchAll(/\b([A-Z][\w]*)\b/g)) {
4162
+ const local = match[1];
4163
+ if (sources.has(local))
4164
+ bindings[local] = sources.get(local);
4165
+ }
4166
+ const regionClasses = new Set();
4167
+ // A className, and a content class (`contentContainerClassName`).
4168
+ for (const m of before.matchAll(/(?:className|ClassName)=["'`{]+([^"'`}]*)/g))
4169
+ for (const token of m[1].split(/\s+/).filter(Boolean))
4170
+ regionClasses.add(token);
4171
+ for (const [read, both] of choiceClasses)
4172
+ if (read.start >= node.start && read.end <= node.end)
4173
+ for (const token of both.split(/\s+/).filter(Boolean))
4174
+ regionClasses.add(token);
4175
+ fixtures.push({
4176
+ name: `${options.name ?? 'file'}:${node.loc?.start.line ?? 0}${conditions ? '' : ' (false)'}`,
4177
+ before,
4178
+ after,
4179
+ bindings,
4180
+ language: [...usedLanguage.entries()].map(([name, local]) => name === local ? name : `${name}: ${local}`),
4181
+ classes: [...regionClasses],
4182
+ // A route's Screen is the Screen its nodes are drawn in.
4183
+ within: withinOf(ir).filter((key) => ir.type !== 'screen' || key !== SCREEN_KEY),
4184
+ themed,
4185
+ insets,
4186
+ screen: ir.type === 'screen',
4187
+ appColors: colors.length
4188
+ ? {
4189
+ table: appColorTable,
4190
+ color: Object.fromEntries(colors.map((c) => [c.name, c.value])),
4191
+ }
4192
+ : null,
4193
+ });
4194
+ }
4195
+ /** The app colours a region's icons paint with. */
4196
+ function colorsOf(ir) {
4197
+ const found = [];
4198
+ const inValue = (value) => {
4199
+ if (!isTagged(value))
4200
+ return;
4201
+ if (value.$ === 'appColor')
4202
+ found.push(value.color);
4203
+ else if (value.$ === 'choose') {
4204
+ inValue(value.then);
4205
+ inValue(value.otherwise);
4206
+ }
4207
+ };
4208
+ const visit = (at) => {
4209
+ if (at.type === 'icon' && at.color)
4210
+ found.push(at.color);
4211
+ if ('props' in at)
4212
+ for (const prop of at.props)
4213
+ for (const arg of prop.args)
4214
+ inValue(arg);
4215
+ for (const child of childrenOf(at))
4216
+ visit(child);
4217
+ };
4218
+ visit(ir);
4219
+ return found;
4220
+ }
4221
+ /** The Bloom components the region's nodes are drawn only inside. */
4222
+ function withinOf(ir) {
4223
+ const found = new Set();
4224
+ const visit = (at) => {
4225
+ if (at.type === 'component' && at.within)
4226
+ found.add(at.within);
4227
+ for (const child of childrenOf(at))
4228
+ visit(child);
4229
+ };
4230
+ visit(ir);
4231
+ return [...found];
4232
+ }
4233
+ // ── the walk ─────────────────────────────────────────────────────────
4234
+ let regions = 0;
4235
+ const markConverted = (node) => {
4236
+ recast.visit(node, {
4237
+ visitJSXElement(path) {
4238
+ const result = results.get(path.node);
4239
+ if (result && 'ir' in result) {
4240
+ convertedNodes.add(path.node);
4241
+ const local = jsxName(path.node);
4242
+ if (local)
4243
+ convertedLocals.add(local);
4244
+ this.traverse(path);
4245
+ }
4246
+ else
4247
+ return false;
4248
+ },
4249
+ });
4250
+ };
4251
+ const visitor = {
4252
+ visitJSXElement(path) {
4253
+ const node = path.node;
4254
+ const result = convert(node);
4255
+ if (!('ir' in result)) {
4256
+ if (elementOf(node))
4257
+ unconverted.push({
4258
+ line: node.loc?.start.line ?? 0,
4259
+ element: jsxName(node) ?? '',
4260
+ reasons: result.reasons,
4261
+ });
4262
+ this.traverse(path);
4263
+ return undefined;
4264
+ }
4265
+ regions++;
4266
+ markConverted(node);
4267
+ const ir = result.ir;
4268
+ const rootKey = 'key' in ir ? ir.key : null;
4269
+ // The file's table holds every app colour a region paints with.
4270
+ for (const color of colorsOf(ir)) {
4271
+ appColors.set(color.name, color);
4272
+ lang('defineTokens');
4273
+ }
4274
+ // A route's Screen inside what its screen modifiers draw is the return around it, whole.
4275
+ const outer = ir.type === 'screen' ? screenOuter.get(node)?.outer : undefined;
4276
+ if (options.fixtures)
4277
+ fixture(outer ?? node, ir, rootKey);
4278
+ // What wrapped the Screen is its modifiers now: its imports go where nothing else reads them.
4279
+ if (outer)
4280
+ for (let at = outer; at !== node; at = peelChild(at)) {
4281
+ convertedLocals.add(jsxName(at));
4282
+ for (const behavior of keyboardBehaviors)
4283
+ if (behavior.start >= at.start && behavior.end <= at.end)
4284
+ convertedLocals.add(behavior.test.left.object.name);
4285
+ }
4286
+ // Regions inside the values it carries (an embedded element's children, an array's elements).
4287
+ for (const c of carriedOf(ir)) {
4288
+ if (c.hole === 'element' || c.hole === 'items') {
4289
+ // An element can sit at the root of what is carried; visit inside it.
4290
+ const holder = { type: 'ExpressionStatement', expression: c.node };
4291
+ recast.visit(holder, visitor);
4292
+ c.node.__carried = holder.expression;
4293
+ }
4294
+ }
4295
+ const carry = (c) => recast.print(c.node.__carried ?? c.node).code;
4296
+ const chain = print(ir, carry, true);
4297
+ // A route's Screen is its body's root, the chain itself.
4298
+ if (ir.type === 'screen')
4299
+ routes.add(screenRoutes.get(node));
4300
+ const code = ir.type === 'screen'
4301
+ ? chain
4302
+ : `${lang('toElement')}(${chain}${rootKey ? `, ${carry(rootKey)}` : ''})`;
4303
+ // Parsed by recast, so the comments the chain carries are printed where they are.
4304
+ const expression = recast.parse(`${code};`, { parser: babelTs }).program.body[0].expression;
4305
+ let at = path;
4306
+ while (outer && at.node !== outer)
4307
+ at = at.parent;
4308
+ const parent = at.parent?.node;
4309
+ const inJsx = parent &&
4310
+ (n.JSXElement.check(parent) || n.JSXFragment.check(parent) || n.JSXAttribute.check(parent));
4311
+ at.replace(inJsx ? recast.types.builders.jsxExpressionContainer(expression) : expression);
4312
+ return false;
4313
+ },
4314
+ };
4315
+ // Bloom components the codemod does not map, counted before the walk rewrites anything.
4316
+ const bloomComponents = {};
4317
+ recast.visit(ast, {
4318
+ visitJSXOpeningElement(path) {
4319
+ const local = n.JSXIdentifier.check(path.node.name)
4320
+ ? path.node.name.name
4321
+ : undefined;
4322
+ const source = local ? sources.get(local) : undefined;
4323
+ if (source?.module.startsWith('@oxy.so/bloom') && !kindOf(source)) {
4324
+ const key = `${source.module}#${source.imported}`;
4325
+ bloomComponents[key] = (bloomComponents[key] ?? 0) + 1;
4326
+ }
4327
+ this.traverse(path);
4328
+ },
4329
+ });
4330
+ // A route converts whole: a Screen it returns that stays JSX keeps the others JSX.
4331
+ for (const fn of new Set(screenRoutes.values())) {
4332
+ const screens = [...screenRoutes].filter(([, of]) => of === fn).map(([node]) => node);
4333
+ if (screens.every((node) => 'ir' in convert(node)))
4334
+ continue;
4335
+ for (const node of screens)
4336
+ if ('ir' in convert(node))
4337
+ results.set(node, {
4338
+ reasons: [
4339
+ {
4340
+ subject: 'Screen',
4341
+ code: 'screen:route',
4342
+ why: 'another return of the route stays JSX, and a route converts whole',
4343
+ },
4344
+ ],
4345
+ });
4346
+ }
4347
+ /** The routes whose Screens converted: each becomes `screen(function …)`. */
4348
+ const routes = new Set();
4349
+ // The module styles elements read before the walk: what it leaves unread goes after it.
4350
+ const stylesReadBefore = styleReadsIn(ast);
4351
+ recast.visit(ast, visitor);
4352
+ for (const fn of routes) {
4353
+ const { statement, name } = screenDeclarations.get(fn);
4354
+ const b = recast.types.builders;
4355
+ const id = b.identifier(name);
4356
+ // An arrow's expression body is the one return of its function.
4357
+ const block = n.BlockStatement.check(fn.body)
4358
+ ? fn.body
4359
+ : b.blockStatement([b.returnStatement(fn.body)]);
4360
+ const body = b.functionExpression(id, fn.params, block);
4361
+ body.typeParameters = fn.typeParameters;
4362
+ const call = b.callExpression(b.identifier(lang('screen')), [body]);
4363
+ const program = ast.program.body;
4364
+ const at = program.indexOf(statement);
4365
+ let named = 0;
4366
+ recast.visit(ast, {
4367
+ visitIdentifier(path) {
4368
+ if (path.node.name === name)
4369
+ named++;
4370
+ this.traverse(path);
4371
+ },
4372
+ });
4373
+ if (n.ExportDefaultDeclaration.check(statement) && named === 1) {
4374
+ // A default export read nowhere else is the call itself.
4375
+ statement.declaration = call;
4376
+ continue;
4377
+ }
4378
+ const constant = b.variableDeclaration('const', [b.variableDeclarator(id, call)]);
4379
+ if (!n.ExportNamedDeclaration.check(statement))
4380
+ constant.comments = statement.comments;
4381
+ if (n.ExportDefaultDeclaration.check(statement))
4382
+ program.splice(at, 1, constant, b.exportDefaultDeclaration(b.identifier(name)));
4383
+ else if (n.ExportNamedDeclaration.check(statement))
4384
+ statement.declaration = constant;
4385
+ else
4386
+ program.splice(at, 1, constant);
4387
+ }
4388
+ const converted = [...counted].filter((node) => convertedNodes.has(node)).length;
4389
+ if (regions > 0) {
4390
+ removeUnreadStyles(stylesReadBefore);
4391
+ // Imports: the language's names in, and the converted components' out when nothing else uses them.
4392
+ const remaining = new Map();
4393
+ recast.visit(ast, {
4394
+ visitJSXIdentifier(path) {
4395
+ remaining.set(path.node.name, (remaining.get(path.node.name) ?? 0) + 1);
4396
+ this.traverse(path);
4397
+ },
4398
+ visitIdentifier(path) {
4399
+ const parent = path.parent?.node;
4400
+ if (!n.ImportSpecifier.check(parent) && !n.ImportDefaultSpecifier.check(parent))
4401
+ remaining.set(path.node.name, (remaining.get(path.node.name) ?? 0) + 1);
4402
+ this.traverse(path);
4403
+ },
4404
+ });
4405
+ const body = ast.program.body;
4406
+ for (const statement of [...body]) {
4407
+ if (!n.ImportDeclaration.check(statement))
4408
+ continue;
4409
+ const before = statement.specifiers?.length ?? 0;
4410
+ statement.specifiers = (statement.specifiers ?? []).filter((s) => {
4411
+ const local = s.local?.name;
4412
+ return !(convertedLocals.has(local) && !remaining.get(local));
4413
+ });
4414
+ if (before > 0 && statement.specifiers.length === 0)
4415
+ body.splice(body.indexOf(statement), 1);
4416
+ }
4417
+ // `screen` is the router's; every other name the language's own.
4418
+ const imports = (module, names) => {
4419
+ if (!names.length)
4420
+ return [];
4421
+ const specifiers = names
4422
+ .sort(([a], [b]) => (a < b ? -1 : 1))
4423
+ .map(([name, local]) => (name === local ? name : `${name} as ${local}`));
4424
+ return recast.parse(`import { ${specifiers.join(', ')} } from '${module}';\n`, {
4425
+ parser: babelTs,
4426
+ }).program.body;
4427
+ };
4428
+ const names = [...usedLanguage.entries()];
4429
+ const declarations = [
4430
+ ...imports(LANGUAGE_MODULE, names.filter(([name]) => name !== 'screen')),
4431
+ ...imports(`${LANGUAGE_MODULE}/router`, names.filter(([name]) => name === 'screen')),
4432
+ ];
4433
+ const lastImport = body.reduce((last, s, i) => (n.ImportDeclaration.check(s) ? i : last), -1);
4434
+ body.splice(lastImport + 1, 0, ...declarations);
4435
+ if (appColors.size > 0) {
4436
+ // The app colour table, after the imports and the constants it reads.
4437
+ const entries = [...appColors.values()].map((c) => c.constant ? c.constant : `${c.name}: ${quote(c.value)}`);
4438
+ const table = recast.parse(`const ${appColorTable} = ${lang('defineTokens')}({ color: { ${entries.join(', ')} } });\n`, { parser: babelTs }).program.body[0];
4439
+ const after = Math.max(lastImport + 1, ...[...appColors.values()].map((c) => c.constant ? body.indexOf(colorConstants.get(c.constant)?.statement) : -1));
4440
+ body.splice(after + 1, 0, table);
4441
+ }
4442
+ }
4443
+ return {
4444
+ code: regions > 0 ? recast.print(ast).code : source,
4445
+ changed: regions > 0,
4446
+ candidates,
4447
+ converted,
4448
+ regions,
4449
+ unconverted,
4450
+ fixtures,
4451
+ classes: [...classes],
4452
+ bloomComponents,
4453
+ };
4454
+ }