@oxy.so/bloom-language-codemod 0.3.0 → 0.5.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.
package/lib/transform.js CHANGED
@@ -61,6 +61,8 @@ const n = recast.types.namedTypes;
61
61
  const spec = JSON.parse((0, node_fs_1.readFileSync)((0, node_path_1.join)(table_1.LANGUAGE_PACKAGE, 'spec/language.json'), 'utf8'));
62
62
  /** The roles the universal `.role()` takes, each React Native's `accessibilityRole` of its name. */
63
63
  const ROLES = new Set(spec.enums.role);
64
+ /** The roles React Native names only as a web `role`, which the language's `.role()` writes as that prop. */
65
+ const WEB_ROLES = new Set(['option', 'listbox']);
64
66
  /** A React Native `fontWeight` as the spec's weight of that value (`'700'` is `bold`). */
65
67
  const WEIGHT_BY_VALUE = {
66
68
  ...Object.fromEntries(Object.entries(spec.scales.weight).map(([name, value]) => [value, name])),
@@ -90,6 +92,28 @@ const OPACITY_TOKEN = new Map(Object.entries(spec.scales.opacity)
90
92
  /** 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
93
  const HIT_SLOP = Object.fromEntries(Object.entries(spec.scales.hitSlop).filter(([name]) => name !== '$comment'));
92
94
  const HIT_SLOP_TOKEN = new Map(Object.entries(HIT_SLOP).map(([name, value]) => [value, name]));
95
+ /** A press's hold in milliseconds (`500`) as the duration token of its value (`'500'`): `delayLongPress`. */
96
+ const DURATION_TOKEN = new Map();
97
+ for (const [name, value] of Object.entries(spec.scales.duration))
98
+ if (name !== '$comment' && !DURATION_TOKEN.has(value))
99
+ DURATION_TOKEN.set(value, name);
100
+ /** A scale's tokens by value, a named rung over a numeric token of the same value. */
101
+ function tokensByValue(scale) {
102
+ const out = new Map();
103
+ for (const [name, value] of Object.entries(scale)) {
104
+ if (typeof value !== 'number')
105
+ continue;
106
+ if (!/^-?\d/.test(name) || !out.has(value))
107
+ out.set(value, name);
108
+ }
109
+ return out;
110
+ }
111
+ /** A radius in points (`12`) as its corner token (`'md'`): an avatar's own corners. */
112
+ const CORNER_TOKEN = tokensByValue(spec.scales.corner);
113
+ /** A length in points (`540`) as its space token (`'540'`): a dialog panel's frame. */
114
+ const SPACE_TOKEN = tokensByValue(spec.scales.space);
115
+ /** A frame's own length keys (spec `objects.frame`). */
116
+ const FRAME_KEYS = new Set(['width', 'height', 'minWidth', 'minHeight', 'maxWidth', 'maxHeight']);
93
117
  /** One side's slop: a static number, or Bloom's `tokens.hitSlop.<name>`, as its token. */
94
118
  function hitSlopToken(value) {
95
119
  const number = staticNumber(value);
@@ -335,6 +359,21 @@ function jsxName(node) {
335
359
  const name = node.openingElement.name;
336
360
  return n.JSXIdentifier.check(name) ? name.name : undefined;
337
361
  }
362
+ /** An element with `asChild` set (bare or `{true}`): it hands its props to the one element inside it. */
363
+ function isAsChild(element) {
364
+ return element.openingElement.attributes.some((attribute) => n.JSXAttribute.check(attribute) &&
365
+ n.JSXIdentifier.check(attribute.name) &&
366
+ attribute.name.name === 'asChild' &&
367
+ (attribute.value === null ||
368
+ (n.JSXExpressionContainer.check(attribute.value) &&
369
+ n.BooleanLiteral.check(attribute.value.expression) &&
370
+ attribute.value.expression.value === true)));
371
+ }
372
+ /** The one element among an element's children (blank text aside), if it holds nothing else. */
373
+ function onlyElementChild(element) {
374
+ const children = element.children.filter((child) => !(n.JSXText.check(child) && cleanJsxText(child.value) === ''));
375
+ return children.length === 1 && n.JSXElement.check(children[0]) ? children[0] : undefined;
376
+ }
338
377
  function staticString(value) {
339
378
  if (!value)
340
379
  return undefined;
@@ -353,6 +392,18 @@ function staticNumber(value) {
353
392
  return value.value;
354
393
  if (n.Literal.check(value) && typeof value.value === 'number')
355
394
  return value.value;
395
+ if (n.UnaryExpression.check(value) && value.operator === '-') {
396
+ const number = staticNumber(value.argument);
397
+ return number === undefined ? undefined : -number;
398
+ }
399
+ return undefined;
400
+ }
401
+ /** A boolean written out (`false`), or undefined. */
402
+ function staticBoolean(value) {
403
+ if (n.JSXExpressionContainer.check(value))
404
+ return staticBoolean(value.expression);
405
+ if (n.BooleanLiteral.check(value) || (n.Literal.check(value) && typeof value.value === 'boolean'))
406
+ return value.value;
356
407
  return undefined;
357
408
  }
358
409
  /** The expression of an attribute value, or a string literal's node. */
@@ -366,6 +417,8 @@ const uncommented = (code) => code.replace(/\/\*[\s\S]*?\*\//g, '');
366
417
  const quote = (text) => `'${text.replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/\n/g, '\\n')}'`;
367
418
  /** An argument as code; points computed at render are their carried value (`carry`). */
368
419
  function printArg(arg, carry) {
420
+ if (arg === undefined)
421
+ return 'undefined';
369
422
  if (typeof arg === 'string')
370
423
  return quote(arg);
371
424
  if (typeof arg === 'number' || typeof arg === 'boolean')
@@ -373,7 +426,7 @@ function printArg(arg, carry) {
373
426
  if ((0, table_1.isPoints)(arg))
374
427
  return carry(arg);
375
428
  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(', ')} }`;
429
+ return entries.length === 0 ? '{}' : `{ ${entries.join(', ')} }`;
377
430
  }
378
431
  const printMod = (mod, carry) => `.${mod.name}(${mod.args.map((arg) => printArg(arg, carry)).join(', ')})`;
379
432
  /** The points an argument carries: itself, or an object's values (`{ width: itemSize }`). */
@@ -382,6 +435,24 @@ const pointsOf = (arg) => (0, table_1.isPoints)(arg)
382
435
  : typeof arg === 'object' && arg !== null && !('$' in arg) && !('hole' in arg)
383
436
  ? Object.values(arg).filter(table_1.isPoints)
384
437
  : [];
438
+ /** Whether a JSX element writes the attribute `name`. */
439
+ function hasAttribute(node, name) {
440
+ return node.openingElement.attributes.some((attribute) => n.JSXAttribute.check(attribute) &&
441
+ n.JSXIdentifier.check(attribute.name) &&
442
+ attribute.name.name === name);
443
+ }
444
+ /** React Native's margin keys as the language's edges. */
445
+ const MARGIN_EDGES = {
446
+ margin: 'all',
447
+ marginTop: 'top',
448
+ marginBottom: 'bottom',
449
+ marginLeft: 'left',
450
+ marginRight: 'right',
451
+ marginStart: 'leading',
452
+ marginEnd: 'trailing',
453
+ marginHorizontal: 'horizontal',
454
+ marginVertical: 'vertical',
455
+ };
385
456
  /** Transforms one file's source. */
386
457
  function transformSource(source, options) {
387
458
  const ast = recast.parse(source, { parser: babelTs });
@@ -547,7 +618,8 @@ function transformSource(source, options) {
547
618
  /**
548
619
  * Each `insets.top` (`bottom`, `left`, `right`) where `insets` is a `const`
549
620
  * holding `useSafeAreaInsets()` (react-native-safe-area-context): the device's
550
- * inset on that side, which `.safeAreaPadding(side)` pads by.
621
+ * inset on that side, which `.safeAreaPadding(side)` pads by; or Bloom's
622
+ * `useContentSafeAreaInsets()`, the content's, `.safeAreaPadding(side, 'content')`.
551
623
  */
552
624
  const insetReads = new Map();
553
625
  recast.visit(ast, {
@@ -562,12 +634,21 @@ function transformSource(source, options) {
562
634
  const init = at?.node.init;
563
635
  const callee = n.CallExpression.check(init) ? init.callee : undefined;
564
636
  const source = n.Identifier.check(callee) ? sources.get(callee.name) : undefined;
637
+ const from = source?.module === 'react-native-safe-area-context' &&
638
+ source.imported === 'useSafeAreaInsets'
639
+ ? 'device'
640
+ : source?.module === '@oxy.so/bloom/layout' &&
641
+ source.imported === 'useContentSafeAreaInsets'
642
+ ? 'content'
643
+ : undefined;
565
644
  if (at?.parent?.node.kind === 'const' &&
566
645
  n.Identifier.check(at.node.id) &&
567
646
  init.arguments.length === 0 &&
568
- source?.module === 'react-native-safe-area-context' &&
569
- source.imported === 'useSafeAreaInsets')
570
- insetReads.set(path.node, side);
647
+ from !== undefined)
648
+ insetReads.set(path.node, {
649
+ side: side,
650
+ source: from,
651
+ });
571
652
  }
572
653
  this.traverse(path);
573
654
  },
@@ -652,17 +733,19 @@ function transformSource(source, options) {
652
733
  return undefined;
653
734
  const sum = n.BinaryExpression.check(value) && value.operator === '+' ? value : undefined;
654
735
  const inset = sum ? sum.left : value;
655
- if (insetReads.get(inset) !== side)
736
+ const read = insetReads.get(inset);
737
+ if (read?.side !== side)
656
738
  return undefined;
739
+ const padded = {
740
+ name: 'safeAreaPadding',
741
+ args: read.source === 'content' ? [side, 'content'] : [side],
742
+ };
657
743
  if (!sum)
658
- return [{ name: 'safeAreaPadding', args: [side] }];
744
+ return [padded];
659
745
  const beyond = n.NumericLiteral.check(sum.right) ? components_1.SPACE[String(sum.right.value)] : undefined;
660
746
  if (beyond === undefined || (side !== 'top' && side !== 'bottom'))
661
747
  return undefined;
662
- return [
663
- { name: 'safeAreaPadding', args: [side] },
664
- { name: 'padding', args: [side, beyond] },
665
- ];
748
+ return [padded, { name: 'padding', args: [side, beyond] }];
666
749
  };
667
750
  /**
668
751
  * Each read of a `const` holding Bloom's `useSurfaceFill()`: the fill of the
@@ -800,6 +883,59 @@ function transformSource(source, options) {
800
883
  this.traverse(path);
801
884
  },
802
885
  });
886
+ /**
887
+ * The style props a component's caller hands in, as read in a `style` (or
888
+ * any `*Style`) attribute: a parameter, a name destructured from one, or a
889
+ * property of either (`style`, `style?.container`, `props.rowStyle`). The
890
+ * language takes no style object from a caller: the caller chains modifiers
891
+ * on the view it places, and a part inside takes a `ViewModifier`.
892
+ */
893
+ const callerStyles = new Set();
894
+ const isParameter = (path, name) => {
895
+ const bindings = scopeOf(path, name)?.getBindings()[name];
896
+ if (bindings?.length !== 1)
897
+ return false;
898
+ for (let at = bindings[0]; at; at = at.parent) {
899
+ const parent = at.parent?.node;
900
+ if (parent &&
901
+ (n.ArrowFunctionExpression.check(parent) ||
902
+ n.FunctionExpression.check(parent) ||
903
+ n.FunctionDeclaration.check(parent)))
904
+ return parent.params.includes(at.node);
905
+ if (n.VariableDeclarator.check(at.node)) {
906
+ // `const { style } = props`: a name destructured from a parameter.
907
+ const init = at.node.init;
908
+ return n.Identifier.check(init) && isParameter(at, init.name);
909
+ }
910
+ }
911
+ return false;
912
+ };
913
+ recast.visit(ast, {
914
+ visitJSXAttribute(path) {
915
+ const { name, value } = path.node;
916
+ if (!n.JSXIdentifier.check(name) || !/(^s|S)tyle$/.test(name.name) || !value)
917
+ return false;
918
+ // A parameter read as a whole style: by name, or a property of one (`style?.container`).
919
+ const read = (node) => {
920
+ let root = node;
921
+ while (n.MemberExpression.check(root) || n.OptionalMemberExpression.check(root))
922
+ root = root.object;
923
+ return n.Identifier.check(root) && isParameter(path, root.name);
924
+ };
925
+ // The style itself, an entry of a style list, a branch of a choice, or a spread into an object.
926
+ const handsIn = (node) => read(node) ||
927
+ (n.ArrayExpression.check(node) && node.elements.some((e) => e && handsIn(e))) ||
928
+ (n.LogicalExpression.check(node) && handsIn(node.right)) ||
929
+ (n.ConditionalExpression.check(node) &&
930
+ (handsIn(node.consequent) || handsIn(node.alternate))) ||
931
+ (n.ObjectExpression.check(node) &&
932
+ node.properties.some((p) => n.SpreadElement.check(p) && read(p.argument)));
933
+ const expression = attributeExpression(value);
934
+ if (handsIn(expression))
935
+ callerStyles.add(expression);
936
+ return false;
937
+ },
938
+ });
803
939
  /**
804
940
  * Module-level `const NAME = 'text'` (no type annotation, so a colour's type is
805
941
  * the literal `defineTokens` takes), by name: a colour the codemod reads in the file.
@@ -1045,6 +1181,7 @@ function transformSource(source, options) {
1045
1181
  spreadOf,
1046
1182
  numberOf: bloomTokenNumber,
1047
1183
  computed: computedAtRender,
1184
+ compiled: referenced,
1048
1185
  })
1049
1186
  : undefined;
1050
1187
  if (!style)
@@ -1055,8 +1192,13 @@ function transformSource(source, options) {
1055
1192
  mods.push(...style.mods);
1056
1193
  for (const side of style.held)
1057
1194
  heldPoints.add(side);
1195
+ // react-native-web compiles a StyleSheet's `pointerEvents` into its prop's classes, where an
1196
+ // inline object's is written as it is: on the before side that style is compiled again,
1197
+ // through the corpus's own React Native.
1058
1198
  if (referenced)
1059
- literals.set(part, style.literal);
1199
+ literals.set(part, style.mods.some((mod) => mod.subject === 'pointerEvents')
1200
+ ? `RN.StyleSheet.create({ style: ${style.literal} }).style`
1201
+ : style.literal);
1060
1202
  }
1061
1203
  for (const [part, literal] of literals)
1062
1204
  styleLiterals.set(part, literal);
@@ -1077,6 +1219,9 @@ function transformSource(source, options) {
1077
1219
  const style = staticStyle(expression, () => undefined);
1078
1220
  if (!style.ok)
1079
1221
  return reason(style.subject, style.why);
1222
+ const held = style.mods.find((mod) => mod.conditions !== undefined);
1223
+ if (held)
1224
+ return reason(held.subject, 'a style that holds on one platform only');
1080
1225
  const resolution = (0, resolve_1.resolveClassName)(style.classes.join(' '), 'view', options.table, {
1081
1226
  overridden: options.overridden,
1082
1227
  });
@@ -1526,7 +1671,18 @@ function transformSource(source, options) {
1526
1671
  const fades = kind === 'pressable' &&
1527
1672
  sources.get(local)?.imported === 'TouchableOpacity';
1528
1673
  let fade;
1674
+ /** A pressable's `delayLongPress`: its long press's duration token. */
1675
+ let longPressDelay;
1529
1676
  for (const attribute of node.openingElement.attributes) {
1677
+ // Bloom's hover group marker (`{...hoverGroupProps}`) on a view: `.hoverGroup()`, with no press of its own.
1678
+ if (n.JSXSpreadAttribute.check(attribute) &&
1679
+ (kind === 'view' || kind === 'pressable') &&
1680
+ n.Identifier.check(attribute.argument) &&
1681
+ sources.get(attribute.argument.name)?.module === '@oxy.so/bloom/subtle-hover' &&
1682
+ sources.get(attribute.argument.name)?.imported === 'hoverGroupProps') {
1683
+ props.push({ name: 'hoverGroup', args: [] });
1684
+ continue;
1685
+ }
1530
1686
  if (!n.JSXAttribute.check(attribute) || !n.JSXIdentifier.check(attribute.name)) {
1531
1687
  fail('{...spread}', 'spread', 'spread props: the codemod cannot see what they set');
1532
1688
  continue;
@@ -1580,7 +1736,9 @@ function transformSource(source, options) {
1580
1736
  });
1581
1737
  continue;
1582
1738
  }
1583
- if (kind === 'pressable' && (name === 'onPress' || name === 'onLongPress')) {
1739
+ // A Text takes a press as a Pressable does: React Native's Text with its `onPress`, a span's too.
1740
+ if ((kind === 'pressable' || kind === 'bloomText' || kind === 'rnText') &&
1741
+ (name === 'onPress' || name === 'onLongPress')) {
1584
1742
  props.push({ name, args: [{ node: expression, hole: 'handler' }] });
1585
1743
  continue;
1586
1744
  }
@@ -1604,6 +1762,36 @@ function transformSource(source, options) {
1604
1762
  fail(name, 'prop:accessibilityLiveRegion', 'a live region set at runtime');
1605
1763
  continue;
1606
1764
  }
1765
+ if (kind !== 'icon' && name === 'accessible') {
1766
+ props.push({
1767
+ name: 'accessibilityElement',
1768
+ args: [staticBoolean(expression) ?? { node: expression, hole: 'boolean' }],
1769
+ });
1770
+ continue;
1771
+ }
1772
+ if (kind !== 'icon' && name === 'tabIndex') {
1773
+ const index = staticNumber(value);
1774
+ if (index === 0 || index === -1)
1775
+ props.push({ name: 'focusable', args: [index === 0] });
1776
+ else
1777
+ fail(name, 'prop:tabIndex', 'a tabIndex other than 0 or -1, or set at runtime');
1778
+ continue;
1779
+ }
1780
+ if ((kind === 'view' || kind === 'pressable') && name === 'collapsable') {
1781
+ props.push({
1782
+ name: 'collapsable',
1783
+ args: [staticBoolean(expression) ?? { node: expression, hole: 'boolean' }],
1784
+ });
1785
+ continue;
1786
+ }
1787
+ if (kind === 'pressable' && name === 'delayLongPress') {
1788
+ const token = DURATION_TOKEN.get(staticNumber(value));
1789
+ if (token === undefined)
1790
+ fail(name, 'prop:delayLongPress', 'a long press delay that is no duration token, or set at runtime');
1791
+ else
1792
+ longPressDelay = token;
1793
+ continue;
1794
+ }
1607
1795
  if (kind !== 'icon' && name === 'accessibilityState') {
1608
1796
  props.push({ name: 'accessibilityState', args: [{ node: expression, hole: 'state' }] });
1609
1797
  continue;
@@ -1687,6 +1875,8 @@ function transformSource(source, options) {
1687
1875
  styleMods.push(...style.mods);
1688
1876
  styleChoice = style.choice;
1689
1877
  }
1878
+ else if (callerStyles.has(expression))
1879
+ fail('style', 'caller-style', 'a style the caller hands in: the caller chains modifiers on the view it places, and a part inside takes a `ViewModifier` (`look?: ViewModifier`, `.modifier(look)`)');
1690
1880
  else
1691
1881
  fail(style.subject, 'style', style.why);
1692
1882
  continue;
@@ -1700,8 +1890,24 @@ function transformSource(source, options) {
1700
1890
  fail(name, 'prop:pointerEvents', 'a pointerEvents set at runtime');
1701
1891
  continue;
1702
1892
  }
1893
+ // React Native's web roles (`role="listbox"`), which it names as no `accessibilityRole`.
1894
+ if (name === 'role' && (kind === 'view' || kind === 'pressable')) {
1895
+ const role = staticString(value);
1896
+ // React Native's web takes `role` over `accessibilityRole`, native the other: one modifier holds neither.
1897
+ if (hasAttribute(node, 'accessibilityRole')) {
1898
+ fail(name, 'role', 'a `role` beside an `accessibilityRole`, which each platform reads alone');
1899
+ continue;
1900
+ }
1901
+ if (role !== undefined && WEB_ROLES.has(role))
1902
+ props.push({ name: 'role', args: [role] });
1903
+ else
1904
+ fail(name, 'role', 'a role the language does not take, or set at runtime');
1905
+ continue;
1906
+ }
1703
1907
  if (name === 'accessibilityRole' && kind !== 'icon') {
1704
1908
  const role = staticString(value);
1909
+ if ((kind === 'view' || kind === 'pressable') && hasAttribute(node, 'role'))
1910
+ continue;
1705
1911
  if (role !== undefined && ROLES.has(role))
1706
1912
  props.push({ name: 'role', args: [role] });
1707
1913
  else
@@ -1712,12 +1918,25 @@ function transformSource(source, options) {
1712
1918
  size = value;
1713
1919
  continue;
1714
1920
  }
1715
- if (kind === 'icon' && (name === 'width' || name === 'height' || name === 'fill')) {
1921
+ if (kind === 'icon' &&
1922
+ (name === 'width' ||
1923
+ name === 'height' ||
1924
+ name === 'fill' ||
1925
+ name === 'color' ||
1926
+ name === 'style')) {
1716
1927
  iconProps.set(name, value);
1717
1928
  continue;
1718
1929
  }
1719
1930
  fail(name, `prop:${name}`, `the prop \`${name}\` has no mapping`);
1720
1931
  }
1932
+ // The long press's hold is its modifier's second argument.
1933
+ if (longPressDelay !== undefined) {
1934
+ const longPress = props.find((prop) => prop.name === 'onLongPress');
1935
+ if (longPress === undefined)
1936
+ fail('delayLongPress', 'prop:delayLongPress', 'a long press delay with no onLongPress');
1937
+ else
1938
+ longPress.args.push(longPressDelay);
1939
+ }
1721
1940
  // A style chosen by a condition is the className choice it writes: what each branch adds.
1722
1941
  if (styleChoice) {
1723
1942
  if (other)
@@ -1763,7 +1982,24 @@ function transformSource(source, options) {
1763
1982
  }
1764
1983
  if (node.children.some((c) => !(n.JSXText.check(c) && cleanJsxText(c.value) === '')))
1765
1984
  fail('children', 'icon-children', 'an icon with children');
1766
- const fill = iconProps.get('fill');
1985
+ // `currentColor` is the glyph's `color` on every platform (react-native-svg's, Bloom's
1986
+ // native glyph's and CSS's): that colour is its fill.
1987
+ const written = iconProps.get('fill');
1988
+ const current = written !== undefined && staticString(written) === 'currentColor'
1989
+ ? iconProps.get('color')
1990
+ : undefined;
1991
+ const fill = current ?? written;
1992
+ // A margin on the Svg itself (`style={{ marginLeft: 2 }}`): the glyph's own, with no view around it.
1993
+ const style = iconProps.get('style');
1994
+ if (style !== undefined) {
1995
+ const margins = iconMargins(attributeExpression(style));
1996
+ if (margins === undefined)
1997
+ fail('style', 'prop:style', 'an icon style other than its margin, by space tokens');
1998
+ else
1999
+ mods.push(...margins);
2000
+ }
2001
+ if (iconProps.has('color') && current === undefined)
2002
+ fail('color', 'prop:color', 'an icon `color` with no `fill="currentColor"` to paint it');
1767
2003
  let color;
1768
2004
  if (fill !== undefined) {
1769
2005
  const ink = iconFill(node, fill);
@@ -1838,6 +2074,10 @@ function transformSource(source, options) {
1838
2074
  const span = jsxName(child);
1839
2075
  if ('ir' in inner && innerKind === kind && !(span && textStyleOf(span)))
1840
2076
  runs.push(inner.ir);
2077
+ // An element the codemod does not convert (a router's Link, an app's own component) is
2078
+ // an element run, drawn as it is inside the text.
2079
+ else if (!('ir' in inner))
2080
+ runs.push({ type: 'embed', content: { node: child, hole: 'element' } });
1841
2081
  else
1842
2082
  fail(jsxName(child) ?? 'element', 'text-child', 'an element inside a Text that is no convertible Text');
1843
2083
  }
@@ -1898,6 +2138,11 @@ function transformSource(source, options) {
1898
2138
  fail('{/* */}', 'comment', 'a line comment in JSX (only a block comment moves)');
1899
2139
  continue;
1900
2140
  }
2141
+ if (n.ArrowFunctionExpression.check(child.expression) ||
2142
+ n.FunctionExpression.check(child.expression)) {
2143
+ fail('children', 'render-children', "children as a render function (a Pressable's `({ pressed }) => …`): a view takes no function child, and `Embed`'s function is handed the child, not the press state");
2144
+ continue;
2145
+ }
1901
2146
  children.push(expressionChild(child.expression));
1902
2147
  }
1903
2148
  else if (n.JSXElement.check(child)) {
@@ -2330,6 +2575,37 @@ function transformSource(source, options) {
2330
2575
  props.push({ name: prop.modifier, args: [ink] });
2331
2576
  continue;
2332
2577
  }
2578
+ if (prop?.form === 'ink') {
2579
+ const ink = value ? inkOf(node, attributeExpression(value)) : undefined;
2580
+ if (ink === undefined)
2581
+ unmapped(name);
2582
+ else
2583
+ props.push({ name: prop.modifier, args: [ink] });
2584
+ continue;
2585
+ }
2586
+ if (prop?.form === 'radius' || prop?.form === 'frame') {
2587
+ const lengths = value ? lengthsOf(attributeExpression(value)) : undefined;
2588
+ const radius = lengths?.size === 1 ? lengths.get('borderRadius') : undefined;
2589
+ const token = radius === undefined ? undefined : CORNER_TOKEN.get(radius);
2590
+ if (prop.form === 'radius') {
2591
+ if (token === undefined)
2592
+ unmapped(name);
2593
+ else
2594
+ props.push({ name: prop.modifier, args: [token] });
2595
+ continue;
2596
+ }
2597
+ const entries = [];
2598
+ for (const [key, points] of lengths ?? []) {
2599
+ const space = FRAME_KEYS.has(key) ? SPACE_TOKEN.get(points) : undefined;
2600
+ if (space !== undefined)
2601
+ entries.push([key, space]);
2602
+ }
2603
+ if (lengths === undefined || entries.length !== lengths.size || entries.length === 0)
2604
+ unmapped(name);
2605
+ else
2606
+ props.push({ name: prop.modifier, args: [{ $: 'options', entries }] });
2607
+ continue;
2608
+ }
2333
2609
  if (prop?.form === 'reselect') {
2334
2610
  const handlers = value ? reselectOf(attributeExpression(value)) : undefined;
2335
2611
  if (!handlers)
@@ -2383,12 +2659,19 @@ function transformSource(source, options) {
2383
2659
  else
2384
2660
  values.push(next[0]);
2385
2661
  }
2662
+ if (prop.last) {
2663
+ if (last !== undefined || values.length !== 1)
2664
+ unmapped(name);
2665
+ else
2666
+ last = { name: prop.modifier, args: values };
2667
+ continue;
2668
+ }
2386
2669
  if (prop.closedBy) {
2387
2670
  // The value and the close handler, one binding: setting it false calls the handler.
2388
2671
  const close = given.has(prop.closedBy)
2389
2672
  ? actionOf(attributeExpression(given.get(prop.closedBy)))
2390
2673
  : undefined;
2391
- if (values.length !== 1 || !close)
2674
+ if (values.length !== 1 || !close || last !== undefined)
2392
2675
  unmapped(name);
2393
2676
  else
2394
2677
  last = {
@@ -2653,6 +2936,14 @@ function transformSource(source, options) {
2653
2936
  // `null` is a handler's own value (a header's `onBack={null}` shows no back button).
2654
2937
  if (n.NullLiteral.check(expression))
2655
2938
  return [{ $: 'null' }];
2939
+ // A handler or none chosen by a plain condition (`hasMore ? loadMore : undefined`), as
2940
+ // written, where the modifier takes `undefined` (`unset`): it calls nothing then.
2941
+ if (unset &&
2942
+ n.ConditionalExpression.check(expression) &&
2943
+ (isPlainRead(expression.test) || isBooleanForm(expression.test)) &&
2944
+ [expression.consequent, expression.alternate].every((branch) => (n.Identifier.check(branch) && branch.name === 'undefined') ||
2945
+ valuesOf('handler', branch, map) !== undefined))
2946
+ return [{ node: expression, hole: 'handler' }];
2656
2947
  return n.ArrowFunctionExpression.check(expression) ||
2657
2948
  n.FunctionExpression.check(expression) ||
2658
2949
  n.Identifier.check(expression) ||
@@ -2900,6 +3191,23 @@ function transformSource(source, options) {
2900
3191
  return fits;
2901
3192
  }
2902
3193
  /** A style that is a fill alone (`{ backgroundColor: '#000' }`) as its colour (`inkOf`). */
3194
+ /** A style object of static numbers alone (`{ maxWidth: 540 }`), by key; undefined for any other. */
3195
+ function lengthsOf(expression) {
3196
+ if (!n.ObjectExpression.check(expression))
3197
+ return undefined;
3198
+ const out = new Map();
3199
+ for (const property of expression.properties) {
3200
+ if (!(n.ObjectProperty.check(property) || n.Property.check(property)) ||
3201
+ property.computed ||
3202
+ !n.Identifier.check(property.key))
3203
+ return undefined;
3204
+ const number = staticNumber(property.value);
3205
+ if (number === undefined)
3206
+ return undefined;
3207
+ out.set(property.key.name, number);
3208
+ }
3209
+ return out;
3210
+ }
2903
3211
  function fillOf(node, expression) {
2904
3212
  const [property, ...rest] = n.ObjectExpression.check(expression) ? expression.properties : [];
2905
3213
  if (rest.length ||
@@ -3595,12 +3903,22 @@ function transformSource(source, options) {
3595
3903
  if (shape)
3596
3904
  props.unshift({ name: 'shape', args: [shape] });
3597
3905
  const runs = [];
3906
+ let handed;
3598
3907
  for (const child of node.children) {
3599
3908
  if (n.JSXText.check(child)) {
3600
3909
  const text = cleanJsxText(child.value);
3601
3910
  if (text)
3602
3911
  runs.push({ type: 'string', value: text });
3603
3912
  }
3913
+ else if (n.JSXExpressionContainer.check(child) &&
3914
+ (n.ArrowFunctionExpression.check(child.expression) ||
3915
+ n.FunctionExpression.check(child.expression))) {
3916
+ const glyph = handedGlyphOf(child.expression);
3917
+ if (glyph === undefined || handed !== undefined)
3918
+ fail('children', 'render-children', 'children as a render function other than `(color) => <Glyph fill={color} />` at one icon rung (or a view in its place under a plain condition)');
3919
+ else
3920
+ handed = glyph;
3921
+ }
3604
3922
  else if (n.JSXExpressionContainer.check(child) &&
3605
3923
  !n.JSXEmptyExpression.check(child.expression)) {
3606
3924
  if (n.StringLiteral.check(child.expression))
@@ -3611,9 +3929,80 @@ function transformSource(source, options) {
3611
3929
  else
3612
3930
  fail('child', 'button-child', 'a Button child that is no text');
3613
3931
  }
3932
+ if (handed !== undefined && (leading || trailing || runs.length))
3933
+ fail('children', 'render-children', 'a render function beside a glyph or a label');
3614
3934
  if (reasons.length)
3615
3935
  return { reasons };
3616
- return { ir: { type: 'button', leading, trailing, runs, props, key } };
3936
+ return { ir: { type: 'button', leading, trailing, handed, runs, props, key } };
3937
+ }
3938
+ /** A glyph's `style` of margins alone, each a space token (`{ marginLeft: 2 }`), as its margins. */
3939
+ function iconMargins(expression) {
3940
+ if (!n.ObjectExpression.check(expression))
3941
+ return undefined;
3942
+ const out = [];
3943
+ for (const property of expression.properties) {
3944
+ if (!(n.ObjectProperty.check(property) || n.Property.check(property)) || property.computed)
3945
+ return undefined;
3946
+ const key = n.Identifier.check(property.key) ? property.key.name : '';
3947
+ const edge = MARGIN_EDGES[key];
3948
+ const token = n.NumericLiteral.check(property.value)
3949
+ ? components_1.SPACE[String(property.value.value)]
3950
+ : undefined;
3951
+ if (edge === undefined || token === undefined)
3952
+ return undefined;
3953
+ out.push({ name: 'margin', args: edge === 'all' ? [token] : [edge, token] });
3954
+ }
3955
+ return out.length > 0 ? out : undefined;
3956
+ }
3957
+ /**
3958
+ * Bloom's render-function children of a glyph alone, `(color) => <X fill={color}
3959
+ * size="md" />` (or a `width` and `height` of one rung's points), as its icon
3960
+ * and rung; undefined for any other function.
3961
+ */
3962
+ function handedGlyphOf(fn) {
3963
+ const [param, ...more] = fn.params;
3964
+ if (!n.Identifier.check(param) || more.length > 0)
3965
+ return undefined;
3966
+ // A view in the glyph's place while a plain condition holds (the location control's spinner while it locates).
3967
+ if (n.ConditionalExpression.check(fn.body) &&
3968
+ (isPlainRead(fn.body.test) || isBooleanForm(fn.body.test)) &&
3969
+ n.JSXElement.check(fn.body.consequent)) {
3970
+ const glyph = handedGlyphOf({ ...fn, body: fn.body.alternate });
3971
+ const view = convert(fn.body.consequent);
3972
+ return glyph === undefined || glyph.busy !== undefined || !('ir' in view)
3973
+ ? undefined
3974
+ : { ...glyph, busy: { test: { node: fn.body.test, hole: 'condition' }, view: view.ir } };
3975
+ }
3976
+ if (!n.JSXElement.check(fn.body))
3977
+ return undefined;
3978
+ const name = fn.body.openingElement.name;
3979
+ if (!n.JSXIdentifier.check(name) || kindOf(sources.get(name.name)) !== 'icon')
3980
+ return undefined;
3981
+ if (fn.body.children.some((c) => !(n.JSXText.check(c) && cleanJsxText(c.value) === '')))
3982
+ return undefined;
3983
+ const given = new Map();
3984
+ for (const attribute of fn.body.openingElement.attributes) {
3985
+ if (!n.JSXAttribute.check(attribute) || !n.JSXIdentifier.check(attribute.name))
3986
+ return undefined;
3987
+ given.set(attribute.name.name, attribute.value);
3988
+ }
3989
+ const fill = given.get('fill');
3990
+ if (!fill ||
3991
+ !n.Identifier.check(attributeExpression(fill)) ||
3992
+ attributeExpression(fill).name !== param.name)
3993
+ return undefined;
3994
+ const keys = [...given.keys()]
3995
+ .filter((key) => key !== 'fill')
3996
+ .sort()
3997
+ .join(',');
3998
+ const named = staticString(given.get('size'));
3999
+ const side = staticNumber(given.get('width'));
4000
+ const rung = keys === 'size'
4001
+ ? ICON_SIZES.find(([k]) => k === named)
4002
+ : keys === 'height,width' && staticNumber(given.get('height')) === side
4003
+ ? ICON_SIZES.find(([, v]) => v === side)
4004
+ : undefined;
4005
+ return rung === undefined ? undefined : { icon: name.name, size: rung[0] };
3617
4006
  }
3618
4007
  /** A `{…}` child of a stack: a converted branch where its form is safe, else embedded. */
3619
4008
  function expressionChild(expression) {
@@ -3749,6 +4138,9 @@ function transformSource(source, options) {
3749
4138
  // `v`. (A fixture's hole stands for the element, so there it stays embedded.)
3750
4139
  if (isToElement(shown) && shown.arguments.length === 1 && text === recast.print(shown).code)
3751
4140
  return recast.print(shown.arguments[0]).code;
4141
+ // An `asChild` element whose child is a text the codemod converted: it hands the text's host its props.
4142
+ if (renderedAsChild.has(ir.content.node))
4143
+ return `${lang('Embed')}((render) => ${text})`;
3752
4144
  return `${lang('Embed')}(${text})`;
3753
4145
  }
3754
4146
  case 'comment':
@@ -3777,6 +4169,11 @@ function transformSource(source, options) {
3777
4169
  }
3778
4170
  case 'button': {
3779
4171
  const parts = [];
4172
+ if (ir.handed) {
4173
+ const glyph = `${lang('Icon')}(${ir.handed.icon})${ir.handed.size === 'md' ? '' : `.size(${quote(ir.handed.size)})`}`;
4174
+ const { busy } = ir.handed;
4175
+ parts.push(`${lang('Group')}(${busy ? `${carry(busy.test)} ? ${print(busy.view, carry)} : ${glyph}` : glyph})`);
4176
+ }
3780
4177
  if (ir.leading)
3781
4178
  parts.push(`${lang('Icon')}(${ir.leading})`);
3782
4179
  if (ir.runs.length)
@@ -3933,6 +4330,8 @@ function transformSource(source, options) {
3933
4330
  return [...ir.children, ...props];
3934
4331
  case 'screen':
3935
4332
  return [ir.content, ...props];
4333
+ case 'button':
4334
+ return ir.handed?.busy ? [ir.handed.busy.view, ...props] : props;
3936
4335
  default:
3937
4336
  return props;
3938
4337
  }
@@ -3991,6 +4390,10 @@ function transformSource(source, options) {
3991
4390
  carriedOfValue(a, out);
3992
4391
  if (ir.key)
3993
4392
  out.push(ir.key);
4393
+ if (ir.handed?.busy) {
4394
+ out.push(ir.handed.busy.test);
4395
+ carriedOf(ir.handed.busy.view, out);
4396
+ }
3994
4397
  break;
3995
4398
  case 'text':
3996
4399
  for (const run of ir.runs)
@@ -4101,9 +4504,10 @@ function transformSource(source, options) {
4101
4504
  end: behavior.test.left.object.end,
4102
4505
  text: 'RN.Platform',
4103
4506
  });
4104
- // An inset the chain pads by is the corpus's on the before side, both sides drawn under it.
4507
+ // An inset the chain pads by is the corpus's on the before side, both sides drawn under it
4508
+ // (with no frame around the view, the content's insets are the device's).
4105
4509
  let insets = false;
4106
- for (const [read, side] of insetReads)
4510
+ for (const [read, { side }] of insetReads)
4107
4511
  if (read.start >= node.start &&
4108
4512
  read.end <= node.end &&
4109
4513
  // An inset inside points the chain carries (`top: insets.top + 8`) is that value's hole.
@@ -4180,8 +4584,9 @@ function transformSource(source, options) {
4180
4584
  for (const local of new Set([...uncommented(before).matchAll(/<\/?([A-Z][\w]*)/g)].map((m) => m[1])))
4181
4585
  if (sources.has(local))
4182
4586
  bindings[local] = sources.get(local);
4183
- // A Bloom or React Native value the before side reads or calls (`tokens.hitSlop.md`, `fontFamilyStyle('display')`).
4184
- for (const match of uncommented(before).matchAll(/(?:^|[^\w.]|\.\.\.)([a-z]\w*)[.(]/g)) {
4587
+ // A Bloom or React Native value the before side reads, calls or spreads (`tokens.hitSlop.md`,
4588
+ // `fontFamilyStyle('display')`, `{...hoverGroupProps}`).
4589
+ for (const match of uncommented(before).matchAll(/(?:^|[^\w.]|\.\.\.)([a-z]\w*)(?:[.(]|(?<=\.\.\.\w+)\})/g)) {
4185
4590
  const local = match[1];
4186
4591
  const module = sources.get(local)?.module ?? '';
4187
4592
  if (module.startsWith('@oxy.so/bloom/') || module === 'react-native')
@@ -4267,6 +4672,38 @@ function transformSource(source, options) {
4267
4672
  }
4268
4673
  // ── the walk ─────────────────────────────────────────────────────────
4269
4674
  let regions = 0;
4675
+ /** Element runs whose `asChild` element is handed its text by `Embed`'s render function. */
4676
+ const renderedAsChild = new WeakSet();
4677
+ /**
4678
+ * An embedded `asChild` element (expo-router's `Link asChild`) around one
4679
+ * text the codemod converts: the text becomes `render(text)`, which draws
4680
+ * the text's host for the element to hand its props to, as its JSX child
4681
+ * was (`Embed((render) => <Link asChild>{render(Text(…))}</Link>)`). Inside
4682
+ * a text it is a span. A file that names `render` itself keeps the JSX.
4683
+ */
4684
+ function renderAsChild(element) {
4685
+ if (!n.JSXElement.check(element) || !isAsChild(element))
4686
+ return;
4687
+ const child = onlyElementChild(element);
4688
+ const kind = child ? elementOf(child)?.kind : undefined;
4689
+ if (!child || (kind !== 'bloomText' && kind !== 'rnText'))
4690
+ return;
4691
+ const { start, end } = element;
4692
+ if (/\brender\b/.test(source.slice(start, end)))
4693
+ return;
4694
+ const result = convert(child);
4695
+ if (!('ir' in result))
4696
+ return;
4697
+ markConverted(child);
4698
+ for (const color of colorsOf(result.ir)) {
4699
+ appColors.set(color.name, color);
4700
+ lang('defineTokens');
4701
+ }
4702
+ const code = `render(${print(result.ir, (c) => recast.print(c.node).code, true)})`;
4703
+ const call = recast.parse(`${code};`, { parser: babelTs }).program.body[0].expression;
4704
+ element.children = element.children.map((at) => at === child ? recast.types.builders.jsxExpressionContainer(call) : at);
4705
+ renderedAsChild.add(element);
4706
+ }
4270
4707
  const markConverted = (node) => {
4271
4708
  recast.visit(node, {
4272
4709
  visitJSXElement(path) {
@@ -4297,6 +4734,29 @@ function transformSource(source, options) {
4297
4734
  this.traverse(path);
4298
4735
  return undefined;
4299
4736
  }
4737
+ // An `asChild` element hands the one element inside it its own props (an href, a press):
4738
+ // a root there would take them in place of the element's host, and drop them. (A Screen
4739
+ // whose route draws its wrappers as screen modifiers, a colour scope among them, takes them.)
4740
+ const holder = path.parent?.node;
4741
+ if (n.JSXElement.check(holder) &&
4742
+ isAsChild(holder) &&
4743
+ onlyElementChild(holder) === node &&
4744
+ !screenOuter.has(node)) {
4745
+ if (elementOf(node))
4746
+ unconverted.push({
4747
+ line: node.loc?.start.line ?? 0,
4748
+ element: jsxName(node) ?? '',
4749
+ reasons: [
4750
+ {
4751
+ subject: jsxName(node) ?? 'element',
4752
+ code: 'as-child',
4753
+ why: 'the child of an `asChild` element, which hands it its own props: a root would drop them (a text inside a language view is `Embed((render) => …)`)',
4754
+ },
4755
+ ],
4756
+ });
4757
+ this.traverse(path);
4758
+ return undefined;
4759
+ }
4300
4760
  regions++;
4301
4761
  markConverted(node);
4302
4762
  const ir = result.ir;
@@ -4320,6 +4780,8 @@ function transformSource(source, options) {
4320
4780
  }
4321
4781
  // Regions inside the values it carries (an embedded element's children, an array's elements).
4322
4782
  for (const c of carriedOf(ir)) {
4783
+ if (c.hole === 'element')
4784
+ renderAsChild(c.node);
4323
4785
  if (c.hole === 'element' || c.hole === 'items') {
4324
4786
  // An element can sit at the root of what is carried; visit inside it.
4325
4787
  const holder = { type: 'ExpressionStatement', expression: c.node };