@oxy.so/bloom-language-codemod 0.2.1 → 0.4.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/CHANGELOG.md CHANGED
@@ -1,5 +1,34 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.0
4
+
5
+ ### Compatibility
6
+
7
+ - Its peer is `@oxy.so/bloom-language` 1.6.0 or newer, the language it writes.
8
+
9
+ ### Added
10
+
11
+ - Maps the React Native props the language 1.6.0 takes: `accessible`, `tabIndex` 0 / -1, `collapsable`, a static `delayLongPress` with an `onLongPress`, a text shadow written out, `insetInline` / `insetBlock`, `sticky` with `top-0` / `bottom-0` (bare or `web:`), a `TextFieldInput`'s `textContentType`, a field's `inputMode` and `inputRef`, Search's `ref` and `onSelectionChange`, Item's `role="option"` and a view's `role`, and `{...hoverGroupProps}` as `.hoverGroup()`.
12
+ - Maps Bloom component props: Dialog's `control`, `detached` and a `panelStyle` of static frame lengths; an Avatar style that is its radius alone; AvatarGroup's `ringColor`, `variant` and a one-parameter `renderItemAction`; Avatar's and AvatarGroup's `motion`; Search's `editable`; `stickyHeaderIndices`; `Loading`'s `color` and `PageHeader`'s `scrimColor`.
13
+ - A handler or none chosen by a plain condition is mapped as written where the modifier takes `undefined`: `onEndReached`, a list's `onRefresh`, an `Item`'s `onPress`, and PageHeader's `onBack` between a handler, `undefined` and `null`.
14
+ - A padding computed at render is points; an inset read from `useContentSafeAreaInsets()` is `.safeAreaPadding(side, 'content')`; `flexShrink: 20` is `.shrink('20')`; the className table maps `cursor-*`, `shrink-[n]`, `bg-primary/5`, `bg-foreground/5` and `bg-white/5`.
15
+ - A glyph-alone render function (`(color) => <X fill={color} />`, or with a busy spinner as its other branch) is `Group(Icon(X))`; an icon's `style` of margins, and `fill="currentColor"` with its `color` as `.foreground(c)`.
16
+ - A style a component's caller hands in (`style={[styles.row, style]}`, `props.containerStyle`) is the reason `caller-style`, with the documented form.
17
+
18
+ ### Fixed
19
+
20
+ - A `Pressable` whose children are a render function of its press state stays JSX (`render-children`): it wrote `Embed(({ pressed }) => …)`, but `Embed`'s function is handed the child, not the press state.
21
+
22
+ ## 0.3.0
23
+
24
+ ### Compatibility
25
+
26
+ - Its peer is `@oxy.so/bloom-language` 1.4.0 or newer, the language it writes.
27
+
28
+ ### Added
29
+
30
+ - A `VirtualList`'s `overrideItemLayout` is `.itemLayout(handler)`, as written, and a `ListHeaderComponentStyle` of exactly `{ flexGrow: 0, flexShrink: 0, alignSelf: 'stretch' }` (a literal or a module constant) is `.headerFitsContent()`. Any other header style stays a reason.
31
+
3
32
  ## 0.2.1
4
33
 
5
34
  ### Changed
@@ -42,8 +42,16 @@ import { type Arg } from './table';
42
42
  export type Form = 'string' | 'token' | 'flag' | 'boolean' | 'mark' | 'number' | 'handler' | 'view' | 'icon' | 'literal' | 'refresh' | 'contentStyle' | 'items' | 'element' | 'row' | 'placement' | 'empty' | 'className' | 'style' | 'textStyle' | 'content'
43
43
  /** A style that is its fill alone (`{ backgroundColor }`): a role or an app colour. */
44
44
  | 'fill'
45
+ /** A colour value (`theme.colors.background`): a role or an app colour. */
46
+ | 'ink'
47
+ /** A style that is its corner radius alone (`{ borderRadius: 12 }`): the radius token. */
48
+ | 'radius'
49
+ /** A style of frame lengths alone (`{ maxWidth: 540 }`): an object of their space tokens. */
50
+ | 'frame'
45
51
  /** Bloom Screen's `reselect` handler: `.onReselect(refresh)` and `.reselectTop(isAtTop, scrollToTop)`. */
46
- | 'reselect';
52
+ | 'reselect'
53
+ /** A list header container style that keeps the header to its content (`{ flexGrow: 0, flexShrink: 0, alignSelf: 'stretch' }`): the bare modifier. */
54
+ | 'headerStyle';
47
55
  /** A prop as a modifier: its name and form, and for a token, Bloom's value to the language's. */
48
56
  export interface PropRule {
49
57
  readonly modifier: string;
@@ -60,8 +68,9 @@ export interface PropRule {
60
68
  */
61
69
  readonly with?: readonly [prop: string, form: Form];
62
70
  /**
63
- * A token whose modifier takes `undefined` as no value of its own (a Chip's
64
- * `.tint()`): a token or none chosen by a plain condition is that choice.
71
+ * A token or a handler whose modifier takes `undefined` as no value of its own
72
+ * (a Chip's `.tint()`, a list's `.onEndReached()`): a value or none chosen by a
73
+ * plain condition is that choice.
65
74
  */
66
75
  readonly unset?: boolean;
67
76
  /** Fixed arguments after the value (`showsVerticalScrollIndicator` to `.scrollIndicators(value, 'vertical')`). */
@@ -82,6 +91,8 @@ export interface PropRule {
82
91
  * a modifier that ends the chain (`.presented()`). Either alone is a reason.
83
92
  */
84
93
  readonly closedBy?: string;
94
+ /** A modifier that ends the chain (`.control()`), drawn after every other. */
95
+ readonly last?: boolean;
85
96
  /**
86
97
  * Props that are the modifier's options object after its value
87
98
  * (`bottomBarPlacement` to `.footer(view, { placement })`), each by its key
package/lib/components.js CHANGED
@@ -82,6 +82,9 @@ const TEXT_INPUT = {
82
82
  onSubmitEditing: p('onSubmit', 'handler'),
83
83
  autoFocus: p('autoFocus', 'mark'),
84
84
  maxLength: p('maxLength', 'number'),
85
+ inputMode: p('inputMode', 'token', tokens('inputMode')),
86
+ // React Native's own event, handed on as it is.
87
+ onSelectionChange: p('onSelectionChange', 'handler'),
85
88
  };
86
89
  /** Bloom's accent tones as the Bloom tones they paint in (`appearance/colors.ts`, `PALETTE` read backwards). */
87
90
  const ACCENT_TONE = {
@@ -139,6 +142,10 @@ exports.COMPONENT_RULES = {
139
142
  maxHeightRatio: p('maxHeightRatio', 'number'),
140
143
  dismissOnBackdrop: p('dismissOnBackdrop', 'boolean'),
141
144
  scrollable: p('scrollable', 'flag'),
145
+ detached: p('detached', 'flag'),
146
+ panelStyle: p('panelFrame', 'frame'),
147
+ // Bloom's dialog control (`useDialogControl()`): presented by it, the chain's end as `.presented()` is.
148
+ control: { ...p('control', 'handler'), last: true },
142
149
  testID: p('testID', 'string'),
143
150
  },
144
151
  },
@@ -193,12 +200,17 @@ exports.COMPONENT_RULES = {
193
200
  within: '@oxy.so/bloom/screen#Screen',
194
201
  props: {
195
202
  keyboardShouldPersistTaps: p('keyboardTaps', 'token', tokens('keyboardTaps')),
196
- onEndReached: { ...p('onEndReached', 'handler'), with: ['onEndReachedThreshold', 'number'] },
203
+ onEndReached: {
204
+ ...p('onEndReached', 'handler'),
205
+ with: ['onEndReachedThreshold', 'number'],
206
+ unset: true,
207
+ },
197
208
  refreshControl: p('refreshable', 'refresh'),
198
209
  showsVerticalScrollIndicator: indicator('vertical'),
199
210
  showsHorizontalScrollIndicator: indicator('horizontal'),
200
211
  contentContainerStyle: p('contentMargins', 'contentStyle'),
201
212
  contentContainerClassName: p('contentView', 'className'),
213
+ stickyHeaderIndices: p('stickyIndices', 'items'),
202
214
  testID: p('testID', 'string'),
203
215
  },
204
216
  },
@@ -251,6 +263,8 @@ exports.COMPONENT_RULES = {
251
263
  multiline: p('multiline', 'flag'),
252
264
  editable: p('editable', 'boolean'),
253
265
  ...TEXT_INPUT,
266
+ inputRef: p('inputRef', 'handler'),
267
+ textContentType: p('textContentType', 'token', tokens('textContentType')),
254
268
  accessibilityHint: p('hint', 'string'),
255
269
  testID: p('testID', 'string'),
256
270
  },
@@ -318,7 +332,10 @@ exports.COMPONENT_RULES = {
318
332
  active: p('active', 'boolean'),
319
333
  highlighted: p('highlighted', 'flag'),
320
334
  contentDensity: p('density', 'token', densities('row')),
321
- onPress: p('onPress', 'handler'),
335
+ // A web role (Item's `role`): an option of a listbox is the language's `.role('option')`.
336
+ role: p('role', 'token', { option: 'option' }),
337
+ // A press or none chosen by a plain condition (`full ? undefined : add`): no press, no button.
338
+ onPress: { ...p('onPress', 'handler'), unset: true },
322
339
  onLongPress: p('onLongPress', 'handler'),
323
340
  ...NAMED,
324
341
  },
@@ -360,6 +377,8 @@ exports.COMPONENT_RULES = {
360
377
  resize: p('resize', 'token', tokens('textareaResize')),
361
378
  showCount: p('showCount', 'mark'),
362
379
  ...TEXT_INPUT,
380
+ // The ref of its TextInput, written as it is.
381
+ inputRef: p('inputRef', 'handler'),
363
382
  accessibilityLabel: p('label', 'string'),
364
383
  accessibilityHint: p('hint', 'string'),
365
384
  testID: p('testID', 'string'),
@@ -377,6 +396,9 @@ exports.COMPONENT_RULES = {
377
396
  disabled: p('disabled', 'flag'),
378
397
  onClearText: p('onClearText', 'handler'),
379
398
  ...TEXT_INPUT,
399
+ // Bloom's Search hands its `ref` to its TextInput: the language's `.inputRef()`.
400
+ ref: p('inputRef', 'handler'),
401
+ editable: p('editable', 'boolean'),
380
402
  testID: p('testID', 'string'),
381
403
  },
382
404
  },
@@ -413,6 +435,8 @@ exports.COMPONENT_RULES = {
413
435
  variant: p('style', 'token', tokens('loadingStyle')),
414
436
  size: p('size', 'token', tokens('controlSize')),
415
437
  tone: p('tint', 'token', tokens('tone')),
438
+ // An app's own colour (`#fff` over a photo): the tint, as written.
439
+ color: p('tint', 'ink'),
416
440
  ...NAMED,
417
441
  },
418
442
  },
@@ -446,9 +470,11 @@ exports.COMPONENT_RULES = {
446
470
  props: {
447
471
  size: p('size', 'token', AVATAR_SIZE),
448
472
  shape: p('shape', 'token', tokens('shapeName')),
473
+ motion: p('motion', 'token', tokens('avatarMotion')),
449
474
  verified: p('verified', 'flag'),
450
475
  live: p('live', 'flag'),
451
476
  alt: p('label', 'string'),
477
+ style: p('cornerRadius', 'radius'),
452
478
  testID: p('testID', 'string'),
453
479
  },
454
480
  },
@@ -540,7 +566,8 @@ exports.COMPONENT_RULES = {
540
566
  subtitle: p('subtitle', 'content'),
541
567
  actions: p('toolbar', 'view'),
542
568
  leading: p('toolbarLeading', 'view'),
543
- onBack: p('onBack', 'handler'),
569
+ // Bloom's own back (`undefined`) or none (`null`), chosen at render as written.
570
+ onBack: { ...p('onBack', 'handler'), unset: true },
544
571
  backLabel: p('backLabel', 'string'),
545
572
  headingLevel: p('headingLevel', 'number'),
546
573
  scrim: p('scrollEdge', 'token', tokens('scrollEdge')),
@@ -550,13 +577,20 @@ exports.COMPONENT_RULES = {
550
577
  accessory: p('accessory', 'view'),
551
578
  tone: p('tone', 'token', tokens('headerTone')),
552
579
  scrimFalloff: p('scrimFalloff', 'token', tokens('scrimFalloff')),
580
+ // A theme colour as its role, an app colour (`#000000`) as its own.
581
+ scrimColor: p('scrimColor', 'ink'),
553
582
  titleReveal: p('titleReveal', 'token', tokens('titleReveal')),
554
583
  testID: p('testID', 'string'),
555
584
  },
556
585
  },
557
586
  '@oxy.so/bloom/loading#SpinnerIcon': {
558
587
  node: 'SpinnerIcon',
559
- props: { size: p('size', 'token', ICON_SIZE), testID: p('testID', 'string') },
588
+ props: {
589
+ size: p('size', 'token', ICON_SIZE),
590
+ // A theme colour as its role, an app colour as its own (`ON_VIDEO_COLOR`).
591
+ color: p('tint', 'ink'),
592
+ testID: p('testID', 'string'),
593
+ },
560
594
  },
561
595
  // parity/slider.cases.tsx.
562
596
  '@oxy.so/bloom/slider#Slider': {
@@ -649,6 +683,7 @@ exports.COMPONENT_RULES = {
649
683
  layout: p('layout', 'token', tokens('avatarLayout')),
650
684
  size: p('size', 'token', AVATAR_SIZE),
651
685
  shape: p('shape', 'token', tokens('shapeName')),
686
+ motion: p('motion', 'token', tokens('avatarMotion')),
652
687
  max: p('max', 'number'),
653
688
  total: p('total', 'number'),
654
689
  spacing: p('spacing', 'token', exports.SPACE),
@@ -656,6 +691,9 @@ exports.COMPONENT_RULES = {
656
691
  showInitials: p('initials', 'mark'),
657
692
  onPressItem: p('onPressItem', 'handler'),
658
693
  hoverCard: p('hoverCard', 'flag'),
694
+ ringColor: p('ringColor', 'ink'),
695
+ renderItemAction: p('itemAction', 'row'),
696
+ variant: p('variant', 'string'),
659
697
  accessibilityLabel: p('label', 'string'),
660
698
  testID: p('testID', 'string'),
661
699
  },
@@ -690,15 +728,21 @@ exports.COMPONENT_RULES = {
690
728
  estimatedItemSize: p('estimatedItemSize', 'number'),
691
729
  contentContainerStyle: p('contentMargins', 'contentStyle'),
692
730
  numColumns: p('columns', 'number'),
693
- onEndReached: { ...p('onEndReached', 'handler'), with: ['onEndReachedThreshold', 'number'] },
731
+ overrideItemLayout: p('itemLayout', 'handler'),
732
+ onEndReached: {
733
+ ...p('onEndReached', 'handler'),
734
+ with: ['onEndReachedThreshold', 'number'],
735
+ unset: true,
736
+ },
694
737
  restorationKey: p('restorationKey', 'string'),
695
738
  stickyHeaderIndices: p('stickyIndices', 'items'),
696
739
  ListHeaderComponent: p('headerContent', 'element'),
740
+ ListHeaderComponentStyle: p('headerFitsContent', 'headerStyle'),
697
741
  ListFooterComponent: p('footerContent', 'element'),
698
742
  ListEmptyComponent: p('emptyState', 'element'),
699
743
  // A query-driven pull to refresh: `.refreshable({ refreshing, onRefresh })`, as written.
700
744
  refreshing: { ...p('refreshable', 'boolean'), key: 'refreshing' },
701
- onRefresh: { ...p('refreshable', 'handler'), key: 'onRefresh' },
745
+ onRefresh: { ...p('refreshable', 'handler'), key: 'onRefresh', unset: true },
702
746
  screen: { ...p('screen', 'empty'), within: '@oxy.so/bloom/screen#Screen' },
703
747
  scrollbar: p('scrollbar', 'token', tokens('scrollbarVisibility')),
704
748
  keyboardShouldPersistTaps: p('keyboardTaps', 'token', tokens('keyboardTaps')),
package/lib/resolve.js CHANGED
@@ -220,7 +220,21 @@ function resolveClassName(className, kind, table, options = {}) {
220
220
  groups.set(key, found);
221
221
  return found;
222
222
  };
223
- for (const token of className.split(/\s+/).filter(Boolean)) {
223
+ const tokens = className.split(/\s+/).filter(Boolean);
224
+ const sticky = stickyOf(tokens);
225
+ if (sticky !== undefined) {
226
+ const into = group([]);
227
+ const mod = { name: 'sticky', args: [sticky.edge] };
228
+ into.mods.push(mod);
229
+ into.subjects.set(mod, sticky.tokens.join(' '));
230
+ }
231
+ for (const token of tokens) {
232
+ if (sticky?.tokens.includes(token))
233
+ continue;
234
+ if (splitVariants(token).utility === 'sticky') {
235
+ fail(token, 'sticky', 'a sticky position held at no edge but `top-0` or `bottom-0` of the same variant (web only)');
236
+ continue;
237
+ }
224
238
  const { variants, utility: rawUtility } = splitVariants(token);
225
239
  if (rawUtility.startsWith('!') || rawUtility.endsWith('!')) {
226
240
  fail(token, 'important', 'an !important utility outranks every other rule');
@@ -358,6 +372,24 @@ function resolveClassName(className, kind, table, options = {}) {
358
372
  .sort((a, b) => rank(a.conditions) - rank(b.conditions));
359
373
  return { ok: true, value: { axis, mods: base, variants } };
360
374
  }
375
+ /**
376
+ * `sticky` with `top-0` or `bottom-0`, both bare or both `web:`: the
377
+ * language's `.sticky(edge)`, which is the web's alone (NativeWind draws no
378
+ * sticky position natively, and a relative view's zero inset moves nothing),
379
+ * so the `web:` its classes are written under is the modifier's own.
380
+ */
381
+ function stickyOf(tokens) {
382
+ for (const prefix of ['', 'web:']) {
383
+ if (!tokens.includes(`${prefix}sticky`))
384
+ continue;
385
+ const edges = ['top', 'bottom'].filter((edge) => tokens.includes(`${prefix}${edge}-0`));
386
+ if (edges.length !== 1)
387
+ return undefined;
388
+ const edge = edges[0];
389
+ return { edge, tokens: [`${prefix}sticky`, `${prefix}${edge}-0`] };
390
+ }
391
+ return undefined;
392
+ }
361
393
  function rank(conditions) {
362
394
  const first = conditions[0] ?? '';
363
395
  const breakpoint = BREAKPOINTS.indexOf(first);
package/lib/style.js CHANGED
@@ -68,9 +68,41 @@ function byValue(scale) {
68
68
  return out;
69
69
  }
70
70
  const CORNER = byValue(scales.corner);
71
+ const SHRINK = byValue(scales.shrink);
71
72
  const Z_INDEX = byValue(scales.zIndex);
72
73
  const FONT_SIZE = byValue(scales.fontSize);
73
74
  const LEADING_PX = byValue(scales.leadingPx);
75
+ const SPACE = byValue(scales.space);
76
+ /** React Native's inline and block insets, as the edge of `.position()` that sets both sides. */
77
+ const INSET_AXIS = {
78
+ insetInline: 'horizontal',
79
+ insetBlock: 'vertical',
80
+ };
81
+ const TEXT_SHADOW_KEYS = ['textShadowColor', 'textShadowOffset', 'textShadowRadius'];
82
+ /**
83
+ * A text shadow written out (`textShadowColor: 'rgba(0, 0, 0, 0.8)'`,
84
+ * `textShadowOffset: { width: 0, height: 1 }`, `textShadowRadius: 3`) as the
85
+ * text shadow token of exactly those three values, or undefined.
86
+ */
87
+ function textShadowToken(object) {
88
+ const [color, offset, radius] = TEXT_SHADOW_KEYS.map((key) => declared(object, key));
89
+ if (!n.StringLiteral.check(color) || !n.ObjectExpression.check(offset))
90
+ return undefined;
91
+ if (!n.NumericLiteral.check(radius))
92
+ return undefined;
93
+ const width = declared(offset, 'width');
94
+ const height = declared(offset, 'height');
95
+ if (!n.NumericLiteral.check(width) || !n.NumericLiteral.check(height))
96
+ return undefined;
97
+ if (offset.properties.length !== 2)
98
+ return undefined;
99
+ const shadows = scales.textShadow;
100
+ return Object.entries(shadows).find(([name, shadow]) => name !== '$comment' &&
101
+ shadow.color === color.value &&
102
+ shadow.offset[0] === width.value &&
103
+ shadow.offset[1] === height.value &&
104
+ shadow.radius === radius.value)?.[0];
105
+ }
74
106
  /**
75
107
  * A text's own `fontSize` and `lineHeight` written out, as the language's
76
108
  * size and line: `fontSize: 15` is `.font('md')` (a named rung over a numeric
@@ -199,6 +231,9 @@ const CORNER_SIDE = {
199
231
  * both round any box under 1998pt fully, so they draw alike.
200
232
  */
201
233
  function direct(key, value) {
234
+ // The platform's own monospaced face, by its generic name.
235
+ if (key === 'fontFamily' && n.StringLiteral.check(value) && value.value === 'monospace')
236
+ return { name: 'font', args: ['system-mono'] };
202
237
  const number = n.NumericLiteral.check(value)
203
238
  ? value.value
204
239
  : n.UnaryExpression.check(value) &&
@@ -223,6 +258,18 @@ function direct(key, value) {
223
258
  }
224
259
  if (key === 'aspectRatio' && number > 0)
225
260
  return { name: 'aspectRatio', args: [number] };
261
+ // A shrink rank Tailwind has no utility for (`flexShrink: 20`): the spec's rank of that value.
262
+ if (key === 'flexShrink' && number > 1) {
263
+ const rank = SHRINK.get(number);
264
+ return rank === undefined ? undefined : { name: 'shrink', args: [rank] };
265
+ }
266
+ const axis = INSET_AXIS[key];
267
+ if (axis !== undefined) {
268
+ const token = SPACE.get(Math.abs(number));
269
+ return token === undefined
270
+ ? undefined
271
+ : { name: 'position', args: [{ [axis]: number < 0 ? `-${token}` : token }] };
272
+ }
226
273
  return undefined;
227
274
  }
228
275
  /** One declaration as its utility, or undefined. */
@@ -329,11 +376,24 @@ function sidesResolved(properties) {
329
376
  const FRAME_KEYS = new Set(['width', 'height', 'minWidth', 'minHeight', 'maxWidth', 'maxHeight']);
330
377
  /** A pinned view's physical edges, as React Native's keys (spec `objects.edges`). */
331
378
  const PINNED_EDGES = new Set(['top', 'bottom', 'left', 'right']);
379
+ /** React Native's padding keys as the language's edges. */
380
+ const PADDING_EDGES = {
381
+ padding: 'all',
382
+ paddingTop: 'top',
383
+ paddingBottom: 'bottom',
384
+ paddingLeft: 'left',
385
+ paddingRight: 'right',
386
+ paddingStart: 'leading',
387
+ paddingEnd: 'trailing',
388
+ paddingHorizontal: 'horizontal',
389
+ paddingVertical: 'vertical',
390
+ };
332
391
  /**
333
392
  * Geometry computed at render as the language's points (spec `points`):
334
393
  * `width: itemSize` is `.frame({ width: itemSize })`, `top: insets.top + 8`
335
394
  * `.position({ top: insets.top + 8 })` (which joins the view's `absolute`),
336
- * `zIndex: count - index` `.zIndex(count - index)`. Only a value `computed`
395
+ * `zIndex: count - index` `.zIndex(count - index)`, and a padding the view
396
+ * computes, `paddingLeft: depth * 12` `.padding('left', depth * 12)`. Only a value `computed`
337
397
  * says the view works out as it renders; a number written out is a token.
338
398
  */
339
399
  function pointsDeclaration(key, value) {
@@ -344,6 +404,11 @@ function pointsDeclaration(key, value) {
344
404
  return { name: 'position', args: [{ [key]: points }] };
345
405
  if (key === 'zIndex')
346
406
  return { name: 'zIndex', args: [points] };
407
+ const edge = PADDING_EDGES[key];
408
+ if (edge === 'all')
409
+ return { name: 'padding', args: [points] };
410
+ if (edge !== undefined)
411
+ return { name: 'padding', args: [edge, points] };
347
412
  return undefined;
348
413
  }
349
414
  /** A style's own declaration by its key, or undefined. */
@@ -428,6 +493,18 @@ function styleUtilities(object, { read, spreadOf, numberOf, computed } = {}) {
428
493
  !n.Identifier.check(property.key))
429
494
  return { ok: false, subject: 'style', why: 'a style built at runtime' };
430
495
  const key = property.key.name;
496
+ if (TEXT_SHADOW_KEYS.includes(key)) {
497
+ const token = textShadowToken(object);
498
+ if (token === undefined)
499
+ return {
500
+ ok: false,
501
+ subject: key,
502
+ why: 'a text shadow that is no text shadow token (its colour, offset and radius written out)',
503
+ };
504
+ if (key === 'textShadowColor')
505
+ mods.push({ subject: key, mod: { name: 'textShadow', args: [token] } });
506
+ continue;
507
+ }
431
508
  const known = numberOf?.(property.value);
432
509
  const value = known === undefined
433
510
  ? property.value
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);
@@ -353,6 +377,18 @@ function staticNumber(value) {
353
377
  return value.value;
354
378
  if (n.Literal.check(value) && typeof value.value === 'number')
355
379
  return value.value;
380
+ if (n.UnaryExpression.check(value) && value.operator === '-') {
381
+ const number = staticNumber(value.argument);
382
+ return number === undefined ? undefined : -number;
383
+ }
384
+ return undefined;
385
+ }
386
+ /** A boolean written out (`false`), or undefined. */
387
+ function staticBoolean(value) {
388
+ if (n.JSXExpressionContainer.check(value))
389
+ return staticBoolean(value.expression);
390
+ if (n.BooleanLiteral.check(value) || (n.Literal.check(value) && typeof value.value === 'boolean'))
391
+ return value.value;
356
392
  return undefined;
357
393
  }
358
394
  /** The expression of an attribute value, or a string literal's node. */
@@ -382,6 +418,24 @@ const pointsOf = (arg) => (0, table_1.isPoints)(arg)
382
418
  : typeof arg === 'object' && arg !== null && !('$' in arg) && !('hole' in arg)
383
419
  ? Object.values(arg).filter(table_1.isPoints)
384
420
  : [];
421
+ /** Whether a JSX element writes the attribute `name`. */
422
+ function hasAttribute(node, name) {
423
+ return node.openingElement.attributes.some((attribute) => n.JSXAttribute.check(attribute) &&
424
+ n.JSXIdentifier.check(attribute.name) &&
425
+ attribute.name.name === name);
426
+ }
427
+ /** React Native's margin keys as the language's edges. */
428
+ const MARGIN_EDGES = {
429
+ margin: 'all',
430
+ marginTop: 'top',
431
+ marginBottom: 'bottom',
432
+ marginLeft: 'left',
433
+ marginRight: 'right',
434
+ marginStart: 'leading',
435
+ marginEnd: 'trailing',
436
+ marginHorizontal: 'horizontal',
437
+ marginVertical: 'vertical',
438
+ };
385
439
  /** Transforms one file's source. */
386
440
  function transformSource(source, options) {
387
441
  const ast = recast.parse(source, { parser: babelTs });
@@ -547,7 +601,8 @@ function transformSource(source, options) {
547
601
  /**
548
602
  * Each `insets.top` (`bottom`, `left`, `right`) where `insets` is a `const`
549
603
  * holding `useSafeAreaInsets()` (react-native-safe-area-context): the device's
550
- * inset on that side, which `.safeAreaPadding(side)` pads by.
604
+ * inset on that side, which `.safeAreaPadding(side)` pads by; or Bloom's
605
+ * `useContentSafeAreaInsets()`, the content's, `.safeAreaPadding(side, 'content')`.
551
606
  */
552
607
  const insetReads = new Map();
553
608
  recast.visit(ast, {
@@ -562,12 +617,21 @@ function transformSource(source, options) {
562
617
  const init = at?.node.init;
563
618
  const callee = n.CallExpression.check(init) ? init.callee : undefined;
564
619
  const source = n.Identifier.check(callee) ? sources.get(callee.name) : undefined;
620
+ const from = source?.module === 'react-native-safe-area-context' &&
621
+ source.imported === 'useSafeAreaInsets'
622
+ ? 'device'
623
+ : source?.module === '@oxy.so/bloom/layout' &&
624
+ source.imported === 'useContentSafeAreaInsets'
625
+ ? 'content'
626
+ : undefined;
565
627
  if (at?.parent?.node.kind === 'const' &&
566
628
  n.Identifier.check(at.node.id) &&
567
629
  init.arguments.length === 0 &&
568
- source?.module === 'react-native-safe-area-context' &&
569
- source.imported === 'useSafeAreaInsets')
570
- insetReads.set(path.node, side);
630
+ from !== undefined)
631
+ insetReads.set(path.node, {
632
+ side: side,
633
+ source: from,
634
+ });
571
635
  }
572
636
  this.traverse(path);
573
637
  },
@@ -652,17 +716,19 @@ function transformSource(source, options) {
652
716
  return undefined;
653
717
  const sum = n.BinaryExpression.check(value) && value.operator === '+' ? value : undefined;
654
718
  const inset = sum ? sum.left : value;
655
- if (insetReads.get(inset) !== side)
719
+ const read = insetReads.get(inset);
720
+ if (read?.side !== side)
656
721
  return undefined;
722
+ const padded = {
723
+ name: 'safeAreaPadding',
724
+ args: read.source === 'content' ? [side, 'content'] : [side],
725
+ };
657
726
  if (!sum)
658
- return [{ name: 'safeAreaPadding', args: [side] }];
727
+ return [padded];
659
728
  const beyond = n.NumericLiteral.check(sum.right) ? components_1.SPACE[String(sum.right.value)] : undefined;
660
729
  if (beyond === undefined || (side !== 'top' && side !== 'bottom'))
661
730
  return undefined;
662
- return [
663
- { name: 'safeAreaPadding', args: [side] },
664
- { name: 'padding', args: [side, beyond] },
665
- ];
731
+ return [padded, { name: 'padding', args: [side, beyond] }];
666
732
  };
667
733
  /**
668
734
  * Each read of a `const` holding Bloom's `useSurfaceFill()`: the fill of the
@@ -800,6 +866,59 @@ function transformSource(source, options) {
800
866
  this.traverse(path);
801
867
  },
802
868
  });
869
+ /**
870
+ * The style props a component's caller hands in, as read in a `style` (or
871
+ * any `*Style`) attribute: a parameter, a name destructured from one, or a
872
+ * property of either (`style`, `style?.container`, `props.rowStyle`). The
873
+ * language takes no style object from a caller: the caller chains modifiers
874
+ * on the view it places, and a part inside takes a `ViewModifier`.
875
+ */
876
+ const callerStyles = new Set();
877
+ const isParameter = (path, name) => {
878
+ const bindings = scopeOf(path, name)?.getBindings()[name];
879
+ if (bindings?.length !== 1)
880
+ return false;
881
+ for (let at = bindings[0]; at; at = at.parent) {
882
+ const parent = at.parent?.node;
883
+ if (parent &&
884
+ (n.ArrowFunctionExpression.check(parent) ||
885
+ n.FunctionExpression.check(parent) ||
886
+ n.FunctionDeclaration.check(parent)))
887
+ return parent.params.includes(at.node);
888
+ if (n.VariableDeclarator.check(at.node)) {
889
+ // `const { style } = props`: a name destructured from a parameter.
890
+ const init = at.node.init;
891
+ return n.Identifier.check(init) && isParameter(at, init.name);
892
+ }
893
+ }
894
+ return false;
895
+ };
896
+ recast.visit(ast, {
897
+ visitJSXAttribute(path) {
898
+ const { name, value } = path.node;
899
+ if (!n.JSXIdentifier.check(name) || !/(^s|S)tyle$/.test(name.name) || !value)
900
+ return false;
901
+ // A parameter read as a whole style: by name, or a property of one (`style?.container`).
902
+ const read = (node) => {
903
+ let root = node;
904
+ while (n.MemberExpression.check(root) || n.OptionalMemberExpression.check(root))
905
+ root = root.object;
906
+ return n.Identifier.check(root) && isParameter(path, root.name);
907
+ };
908
+ // The style itself, an entry of a style list, a branch of a choice, or a spread into an object.
909
+ const handsIn = (node) => read(node) ||
910
+ (n.ArrayExpression.check(node) && node.elements.some((e) => e && handsIn(e))) ||
911
+ (n.LogicalExpression.check(node) && handsIn(node.right)) ||
912
+ (n.ConditionalExpression.check(node) &&
913
+ (handsIn(node.consequent) || handsIn(node.alternate))) ||
914
+ (n.ObjectExpression.check(node) &&
915
+ node.properties.some((p) => n.SpreadElement.check(p) && read(p.argument)));
916
+ const expression = attributeExpression(value);
917
+ if (handsIn(expression))
918
+ callerStyles.add(expression);
919
+ return false;
920
+ },
921
+ });
803
922
  /**
804
923
  * Module-level `const NAME = 'text'` (no type annotation, so a colour's type is
805
924
  * the literal `defineTokens` takes), by name: a colour the codemod reads in the file.
@@ -1526,7 +1645,18 @@ function transformSource(source, options) {
1526
1645
  const fades = kind === 'pressable' &&
1527
1646
  sources.get(local)?.imported === 'TouchableOpacity';
1528
1647
  let fade;
1648
+ /** A pressable's `delayLongPress`: its long press's duration token. */
1649
+ let longPressDelay;
1529
1650
  for (const attribute of node.openingElement.attributes) {
1651
+ // Bloom's hover group marker (`{...hoverGroupProps}`) on a view: `.hoverGroup()`, with no press of its own.
1652
+ if (n.JSXSpreadAttribute.check(attribute) &&
1653
+ (kind === 'view' || kind === 'pressable') &&
1654
+ n.Identifier.check(attribute.argument) &&
1655
+ sources.get(attribute.argument.name)?.module === '@oxy.so/bloom/subtle-hover' &&
1656
+ sources.get(attribute.argument.name)?.imported === 'hoverGroupProps') {
1657
+ props.push({ name: 'hoverGroup', args: [] });
1658
+ continue;
1659
+ }
1530
1660
  if (!n.JSXAttribute.check(attribute) || !n.JSXIdentifier.check(attribute.name)) {
1531
1661
  fail('{...spread}', 'spread', 'spread props: the codemod cannot see what they set');
1532
1662
  continue;
@@ -1604,6 +1734,36 @@ function transformSource(source, options) {
1604
1734
  fail(name, 'prop:accessibilityLiveRegion', 'a live region set at runtime');
1605
1735
  continue;
1606
1736
  }
1737
+ if (kind !== 'icon' && name === 'accessible') {
1738
+ props.push({
1739
+ name: 'accessibilityElement',
1740
+ args: [staticBoolean(expression) ?? { node: expression, hole: 'boolean' }],
1741
+ });
1742
+ continue;
1743
+ }
1744
+ if (kind !== 'icon' && name === 'tabIndex') {
1745
+ const index = staticNumber(value);
1746
+ if (index === 0 || index === -1)
1747
+ props.push({ name: 'focusable', args: [index === 0] });
1748
+ else
1749
+ fail(name, 'prop:tabIndex', 'a tabIndex other than 0 or -1, or set at runtime');
1750
+ continue;
1751
+ }
1752
+ if ((kind === 'view' || kind === 'pressable') && name === 'collapsable') {
1753
+ props.push({
1754
+ name: 'collapsable',
1755
+ args: [staticBoolean(expression) ?? { node: expression, hole: 'boolean' }],
1756
+ });
1757
+ continue;
1758
+ }
1759
+ if (kind === 'pressable' && name === 'delayLongPress') {
1760
+ const token = DURATION_TOKEN.get(staticNumber(value));
1761
+ if (token === undefined)
1762
+ fail(name, 'prop:delayLongPress', 'a long press delay that is no duration token, or set at runtime');
1763
+ else
1764
+ longPressDelay = token;
1765
+ continue;
1766
+ }
1607
1767
  if (kind !== 'icon' && name === 'accessibilityState') {
1608
1768
  props.push({ name: 'accessibilityState', args: [{ node: expression, hole: 'state' }] });
1609
1769
  continue;
@@ -1687,6 +1847,8 @@ function transformSource(source, options) {
1687
1847
  styleMods.push(...style.mods);
1688
1848
  styleChoice = style.choice;
1689
1849
  }
1850
+ else if (callerStyles.has(expression))
1851
+ 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
1852
  else
1691
1853
  fail(style.subject, 'style', style.why);
1692
1854
  continue;
@@ -1700,8 +1862,24 @@ function transformSource(source, options) {
1700
1862
  fail(name, 'prop:pointerEvents', 'a pointerEvents set at runtime');
1701
1863
  continue;
1702
1864
  }
1865
+ // React Native's web roles (`role="listbox"`), which it names as no `accessibilityRole`.
1866
+ if (name === 'role' && (kind === 'view' || kind === 'pressable')) {
1867
+ const role = staticString(value);
1868
+ // React Native's web takes `role` over `accessibilityRole`, native the other: one modifier holds neither.
1869
+ if (hasAttribute(node, 'accessibilityRole')) {
1870
+ fail(name, 'role', 'a `role` beside an `accessibilityRole`, which each platform reads alone');
1871
+ continue;
1872
+ }
1873
+ if (role !== undefined && WEB_ROLES.has(role))
1874
+ props.push({ name: 'role', args: [role] });
1875
+ else
1876
+ fail(name, 'role', 'a role the language does not take, or set at runtime');
1877
+ continue;
1878
+ }
1703
1879
  if (name === 'accessibilityRole' && kind !== 'icon') {
1704
1880
  const role = staticString(value);
1881
+ if ((kind === 'view' || kind === 'pressable') && hasAttribute(node, 'role'))
1882
+ continue;
1705
1883
  if (role !== undefined && ROLES.has(role))
1706
1884
  props.push({ name: 'role', args: [role] });
1707
1885
  else
@@ -1712,12 +1890,25 @@ function transformSource(source, options) {
1712
1890
  size = value;
1713
1891
  continue;
1714
1892
  }
1715
- if (kind === 'icon' && (name === 'width' || name === 'height' || name === 'fill')) {
1893
+ if (kind === 'icon' &&
1894
+ (name === 'width' ||
1895
+ name === 'height' ||
1896
+ name === 'fill' ||
1897
+ name === 'color' ||
1898
+ name === 'style')) {
1716
1899
  iconProps.set(name, value);
1717
1900
  continue;
1718
1901
  }
1719
1902
  fail(name, `prop:${name}`, `the prop \`${name}\` has no mapping`);
1720
1903
  }
1904
+ // The long press's hold is its modifier's second argument.
1905
+ if (longPressDelay !== undefined) {
1906
+ const longPress = props.find((prop) => prop.name === 'onLongPress');
1907
+ if (longPress === undefined)
1908
+ fail('delayLongPress', 'prop:delayLongPress', 'a long press delay with no onLongPress');
1909
+ else
1910
+ longPress.args.push(longPressDelay);
1911
+ }
1721
1912
  // A style chosen by a condition is the className choice it writes: what each branch adds.
1722
1913
  if (styleChoice) {
1723
1914
  if (other)
@@ -1763,7 +1954,24 @@ function transformSource(source, options) {
1763
1954
  }
1764
1955
  if (node.children.some((c) => !(n.JSXText.check(c) && cleanJsxText(c.value) === '')))
1765
1956
  fail('children', 'icon-children', 'an icon with children');
1766
- const fill = iconProps.get('fill');
1957
+ // `currentColor` is the glyph's `color` on every platform (react-native-svg's, Bloom's
1958
+ // native glyph's and CSS's): that colour is its fill.
1959
+ const written = iconProps.get('fill');
1960
+ const current = written !== undefined && staticString(written) === 'currentColor'
1961
+ ? iconProps.get('color')
1962
+ : undefined;
1963
+ const fill = current ?? written;
1964
+ // A margin on the Svg itself (`style={{ marginLeft: 2 }}`): the glyph's own, with no view around it.
1965
+ const style = iconProps.get('style');
1966
+ if (style !== undefined) {
1967
+ const margins = iconMargins(attributeExpression(style));
1968
+ if (margins === undefined)
1969
+ fail('style', 'prop:style', 'an icon style other than its margin, by space tokens');
1970
+ else
1971
+ mods.push(...margins);
1972
+ }
1973
+ if (iconProps.has('color') && current === undefined)
1974
+ fail('color', 'prop:color', 'an icon `color` with no `fill="currentColor"` to paint it');
1767
1975
  let color;
1768
1976
  if (fill !== undefined) {
1769
1977
  const ink = iconFill(node, fill);
@@ -1898,6 +2106,11 @@ function transformSource(source, options) {
1898
2106
  fail('{/* */}', 'comment', 'a line comment in JSX (only a block comment moves)');
1899
2107
  continue;
1900
2108
  }
2109
+ if (n.ArrowFunctionExpression.check(child.expression) ||
2110
+ n.FunctionExpression.check(child.expression)) {
2111
+ 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");
2112
+ continue;
2113
+ }
1901
2114
  children.push(expressionChild(child.expression));
1902
2115
  }
1903
2116
  else if (n.JSXElement.check(child)) {
@@ -2330,6 +2543,37 @@ function transformSource(source, options) {
2330
2543
  props.push({ name: prop.modifier, args: [ink] });
2331
2544
  continue;
2332
2545
  }
2546
+ if (prop?.form === 'ink') {
2547
+ const ink = value ? inkOf(node, attributeExpression(value)) : undefined;
2548
+ if (ink === undefined)
2549
+ unmapped(name);
2550
+ else
2551
+ props.push({ name: prop.modifier, args: [ink] });
2552
+ continue;
2553
+ }
2554
+ if (prop?.form === 'radius' || prop?.form === 'frame') {
2555
+ const lengths = value ? lengthsOf(attributeExpression(value)) : undefined;
2556
+ const radius = lengths?.size === 1 ? lengths.get('borderRadius') : undefined;
2557
+ const token = radius === undefined ? undefined : CORNER_TOKEN.get(radius);
2558
+ if (prop.form === 'radius') {
2559
+ if (token === undefined)
2560
+ unmapped(name);
2561
+ else
2562
+ props.push({ name: prop.modifier, args: [token] });
2563
+ continue;
2564
+ }
2565
+ const entries = [];
2566
+ for (const [key, points] of lengths ?? []) {
2567
+ const space = FRAME_KEYS.has(key) ? SPACE_TOKEN.get(points) : undefined;
2568
+ if (space !== undefined)
2569
+ entries.push([key, space]);
2570
+ }
2571
+ if (lengths === undefined || entries.length !== lengths.size || entries.length === 0)
2572
+ unmapped(name);
2573
+ else
2574
+ props.push({ name: prop.modifier, args: [{ $: 'options', entries }] });
2575
+ continue;
2576
+ }
2333
2577
  if (prop?.form === 'reselect') {
2334
2578
  const handlers = value ? reselectOf(attributeExpression(value)) : undefined;
2335
2579
  if (!handlers)
@@ -2354,6 +2598,13 @@ function transformSource(source, options) {
2354
2598
  unmapped(name);
2355
2599
  continue;
2356
2600
  }
2601
+ if (prop?.form === 'headerStyle') {
2602
+ if (value && fitsContent(attributeExpression(value)))
2603
+ props.push({ name: prop.modifier, args: [] });
2604
+ else
2605
+ unmapped(name);
2606
+ continue;
2607
+ }
2357
2608
  if (prop?.marks) {
2358
2609
  // A static string naming the bare modifier, or none.
2359
2610
  const text = staticString(value);
@@ -2376,12 +2627,19 @@ function transformSource(source, options) {
2376
2627
  else
2377
2628
  values.push(next[0]);
2378
2629
  }
2630
+ if (prop.last) {
2631
+ if (last !== undefined || values.length !== 1)
2632
+ unmapped(name);
2633
+ else
2634
+ last = { name: prop.modifier, args: values };
2635
+ continue;
2636
+ }
2379
2637
  if (prop.closedBy) {
2380
2638
  // The value and the close handler, one binding: setting it false calls the handler.
2381
2639
  const close = given.has(prop.closedBy)
2382
2640
  ? actionOf(attributeExpression(given.get(prop.closedBy)))
2383
2641
  : undefined;
2384
- if (values.length !== 1 || !close)
2642
+ if (values.length !== 1 || !close || last !== undefined)
2385
2643
  unmapped(name);
2386
2644
  else
2387
2645
  last = {
@@ -2646,6 +2904,14 @@ function transformSource(source, options) {
2646
2904
  // `null` is a handler's own value (a header's `onBack={null}` shows no back button).
2647
2905
  if (n.NullLiteral.check(expression))
2648
2906
  return [{ $: 'null' }];
2907
+ // A handler or none chosen by a plain condition (`hasMore ? loadMore : undefined`), as
2908
+ // written, where the modifier takes `undefined` (`unset`): it calls nothing then.
2909
+ if (unset &&
2910
+ n.ConditionalExpression.check(expression) &&
2911
+ (isPlainRead(expression.test) || isBooleanForm(expression.test)) &&
2912
+ [expression.consequent, expression.alternate].every((branch) => (n.Identifier.check(branch) && branch.name === 'undefined') ||
2913
+ valuesOf('handler', branch, map) !== undefined))
2914
+ return [{ node: expression, hole: 'handler' }];
2649
2915
  return n.ArrowFunctionExpression.check(expression) ||
2650
2916
  n.FunctionExpression.check(expression) ||
2651
2917
  n.Identifier.check(expression) ||
@@ -2864,7 +3130,52 @@ function transformSource(source, options) {
2864
3130
  styleLiterals.set(expression, recast.print(object).code);
2865
3131
  return mods;
2866
3132
  }
3133
+ /**
3134
+ * A list header container style (an object literal or a module constant)
3135
+ * that is exactly `{ flexGrow: 0, flexShrink: 0, alignSelf: 'stretch' }`,
3136
+ * in any order: the header kept to its content, `.headerFitsContent()`.
3137
+ */
3138
+ function fitsContent(expression) {
3139
+ const object = moduleStyleReads.has(expression)
3140
+ ? styleSheets.get(expression.object.name)?.get(expression.property.name)
3141
+ : (styleConstantReads.get(expression) ?? expression);
3142
+ if (!n.ObjectExpression.check(object))
3143
+ return false;
3144
+ const seen = new Map();
3145
+ for (const property of object.properties) {
3146
+ if (!(n.ObjectProperty.check(property) || n.Property.check(property)) ||
3147
+ property.computed ||
3148
+ !n.Identifier.check(property.key))
3149
+ return false;
3150
+ const key = property.key.name;
3151
+ seen.set(key, key === 'alignSelf' ? staticString(property.value) : staticNumber(property.value));
3152
+ }
3153
+ const fits = seen.size === 3 &&
3154
+ seen.get('flexGrow') === 0 &&
3155
+ seen.get('flexShrink') === 0 &&
3156
+ seen.get('alignSelf') === 'stretch';
3157
+ if (fits && object !== expression)
3158
+ styleLiterals.set(expression, recast.print(object).code);
3159
+ return fits;
3160
+ }
2867
3161
  /** A style that is a fill alone (`{ backgroundColor: '#000' }`) as its colour (`inkOf`). */
3162
+ /** A style object of static numbers alone (`{ maxWidth: 540 }`), by key; undefined for any other. */
3163
+ function lengthsOf(expression) {
3164
+ if (!n.ObjectExpression.check(expression))
3165
+ return undefined;
3166
+ const out = new Map();
3167
+ for (const property of expression.properties) {
3168
+ if (!(n.ObjectProperty.check(property) || n.Property.check(property)) ||
3169
+ property.computed ||
3170
+ !n.Identifier.check(property.key))
3171
+ return undefined;
3172
+ const number = staticNumber(property.value);
3173
+ if (number === undefined)
3174
+ return undefined;
3175
+ out.set(property.key.name, number);
3176
+ }
3177
+ return out;
3178
+ }
2868
3179
  function fillOf(node, expression) {
2869
3180
  const [property, ...rest] = n.ObjectExpression.check(expression) ? expression.properties : [];
2870
3181
  if (rest.length ||
@@ -3560,12 +3871,22 @@ function transformSource(source, options) {
3560
3871
  if (shape)
3561
3872
  props.unshift({ name: 'shape', args: [shape] });
3562
3873
  const runs = [];
3874
+ let handed;
3563
3875
  for (const child of node.children) {
3564
3876
  if (n.JSXText.check(child)) {
3565
3877
  const text = cleanJsxText(child.value);
3566
3878
  if (text)
3567
3879
  runs.push({ type: 'string', value: text });
3568
3880
  }
3881
+ else if (n.JSXExpressionContainer.check(child) &&
3882
+ (n.ArrowFunctionExpression.check(child.expression) ||
3883
+ n.FunctionExpression.check(child.expression))) {
3884
+ const glyph = handedGlyphOf(child.expression);
3885
+ if (glyph === undefined || handed !== undefined)
3886
+ 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)');
3887
+ else
3888
+ handed = glyph;
3889
+ }
3569
3890
  else if (n.JSXExpressionContainer.check(child) &&
3570
3891
  !n.JSXEmptyExpression.check(child.expression)) {
3571
3892
  if (n.StringLiteral.check(child.expression))
@@ -3576,9 +3897,80 @@ function transformSource(source, options) {
3576
3897
  else
3577
3898
  fail('child', 'button-child', 'a Button child that is no text');
3578
3899
  }
3900
+ if (handed !== undefined && (leading || trailing || runs.length))
3901
+ fail('children', 'render-children', 'a render function beside a glyph or a label');
3579
3902
  if (reasons.length)
3580
3903
  return { reasons };
3581
- return { ir: { type: 'button', leading, trailing, runs, props, key } };
3904
+ return { ir: { type: 'button', leading, trailing, handed, runs, props, key } };
3905
+ }
3906
+ /** A glyph's `style` of margins alone, each a space token (`{ marginLeft: 2 }`), as its margins. */
3907
+ function iconMargins(expression) {
3908
+ if (!n.ObjectExpression.check(expression))
3909
+ return undefined;
3910
+ const out = [];
3911
+ for (const property of expression.properties) {
3912
+ if (!(n.ObjectProperty.check(property) || n.Property.check(property)) || property.computed)
3913
+ return undefined;
3914
+ const key = n.Identifier.check(property.key) ? property.key.name : '';
3915
+ const edge = MARGIN_EDGES[key];
3916
+ const token = n.NumericLiteral.check(property.value)
3917
+ ? components_1.SPACE[String(property.value.value)]
3918
+ : undefined;
3919
+ if (edge === undefined || token === undefined)
3920
+ return undefined;
3921
+ out.push({ name: 'margin', args: edge === 'all' ? [token] : [edge, token] });
3922
+ }
3923
+ return out.length > 0 ? out : undefined;
3924
+ }
3925
+ /**
3926
+ * Bloom's render-function children of a glyph alone, `(color) => <X fill={color}
3927
+ * size="md" />` (or a `width` and `height` of one rung's points), as its icon
3928
+ * and rung; undefined for any other function.
3929
+ */
3930
+ function handedGlyphOf(fn) {
3931
+ const [param, ...more] = fn.params;
3932
+ if (!n.Identifier.check(param) || more.length > 0)
3933
+ return undefined;
3934
+ // A view in the glyph's place while a plain condition holds (the location control's spinner while it locates).
3935
+ if (n.ConditionalExpression.check(fn.body) &&
3936
+ (isPlainRead(fn.body.test) || isBooleanForm(fn.body.test)) &&
3937
+ n.JSXElement.check(fn.body.consequent)) {
3938
+ const glyph = handedGlyphOf({ ...fn, body: fn.body.alternate });
3939
+ const view = convert(fn.body.consequent);
3940
+ return glyph === undefined || glyph.busy !== undefined || !('ir' in view)
3941
+ ? undefined
3942
+ : { ...glyph, busy: { test: { node: fn.body.test, hole: 'condition' }, view: view.ir } };
3943
+ }
3944
+ if (!n.JSXElement.check(fn.body))
3945
+ return undefined;
3946
+ const name = fn.body.openingElement.name;
3947
+ if (!n.JSXIdentifier.check(name) || kindOf(sources.get(name.name)) !== 'icon')
3948
+ return undefined;
3949
+ if (fn.body.children.some((c) => !(n.JSXText.check(c) && cleanJsxText(c.value) === '')))
3950
+ return undefined;
3951
+ const given = new Map();
3952
+ for (const attribute of fn.body.openingElement.attributes) {
3953
+ if (!n.JSXAttribute.check(attribute) || !n.JSXIdentifier.check(attribute.name))
3954
+ return undefined;
3955
+ given.set(attribute.name.name, attribute.value);
3956
+ }
3957
+ const fill = given.get('fill');
3958
+ if (!fill ||
3959
+ !n.Identifier.check(attributeExpression(fill)) ||
3960
+ attributeExpression(fill).name !== param.name)
3961
+ return undefined;
3962
+ const keys = [...given.keys()]
3963
+ .filter((key) => key !== 'fill')
3964
+ .sort()
3965
+ .join(',');
3966
+ const named = staticString(given.get('size'));
3967
+ const side = staticNumber(given.get('width'));
3968
+ const rung = keys === 'size'
3969
+ ? ICON_SIZES.find(([k]) => k === named)
3970
+ : keys === 'height,width' && staticNumber(given.get('height')) === side
3971
+ ? ICON_SIZES.find(([, v]) => v === side)
3972
+ : undefined;
3973
+ return rung === undefined ? undefined : { icon: name.name, size: rung[0] };
3582
3974
  }
3583
3975
  /** A `{…}` child of a stack: a converted branch where its form is safe, else embedded. */
3584
3976
  function expressionChild(expression) {
@@ -3742,6 +4134,11 @@ function transformSource(source, options) {
3742
4134
  }
3743
4135
  case 'button': {
3744
4136
  const parts = [];
4137
+ if (ir.handed) {
4138
+ const glyph = `${lang('Icon')}(${ir.handed.icon})${ir.handed.size === 'md' ? '' : `.size(${quote(ir.handed.size)})`}`;
4139
+ const { busy } = ir.handed;
4140
+ parts.push(`${lang('Group')}(${busy ? `${carry(busy.test)} ? ${print(busy.view, carry)} : ${glyph}` : glyph})`);
4141
+ }
3745
4142
  if (ir.leading)
3746
4143
  parts.push(`${lang('Icon')}(${ir.leading})`);
3747
4144
  if (ir.runs.length)
@@ -3898,6 +4295,8 @@ function transformSource(source, options) {
3898
4295
  return [...ir.children, ...props];
3899
4296
  case 'screen':
3900
4297
  return [ir.content, ...props];
4298
+ case 'button':
4299
+ return ir.handed?.busy ? [ir.handed.busy.view, ...props] : props;
3901
4300
  default:
3902
4301
  return props;
3903
4302
  }
@@ -3956,6 +4355,10 @@ function transformSource(source, options) {
3956
4355
  carriedOfValue(a, out);
3957
4356
  if (ir.key)
3958
4357
  out.push(ir.key);
4358
+ if (ir.handed?.busy) {
4359
+ out.push(ir.handed.busy.test);
4360
+ carriedOf(ir.handed.busy.view, out);
4361
+ }
3959
4362
  break;
3960
4363
  case 'text':
3961
4364
  for (const run of ir.runs)
@@ -4066,9 +4469,10 @@ function transformSource(source, options) {
4066
4469
  end: behavior.test.left.object.end,
4067
4470
  text: 'RN.Platform',
4068
4471
  });
4069
- // An inset the chain pads by is the corpus's on the before side, both sides drawn under it.
4472
+ // An inset the chain pads by is the corpus's on the before side, both sides drawn under it
4473
+ // (with no frame around the view, the content's insets are the device's).
4070
4474
  let insets = false;
4071
- for (const [read, side] of insetReads)
4475
+ for (const [read, { side }] of insetReads)
4072
4476
  if (read.start >= node.start &&
4073
4477
  read.end <= node.end &&
4074
4478
  // An inset inside points the chain carries (`top: insets.top + 8`) is that value's hole.
@@ -4145,8 +4549,9 @@ function transformSource(source, options) {
4145
4549
  for (const local of new Set([...uncommented(before).matchAll(/<\/?([A-Z][\w]*)/g)].map((m) => m[1])))
4146
4550
  if (sources.has(local))
4147
4551
  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)) {
4552
+ // A Bloom or React Native value the before side reads, calls or spreads (`tokens.hitSlop.md`,
4553
+ // `fontFamilyStyle('display')`, `{...hoverGroupProps}`).
4554
+ for (const match of uncommented(before).matchAll(/(?:^|[^\w.]|\.\.\.)([a-z]\w*)(?:[.(]|(?<=\.\.\.\w+)\})/g)) {
4150
4555
  const local = match[1];
4151
4556
  const module = sources.get(local)?.module ?? '';
4152
4557
  if (module.startsWith('@oxy.so/bloom/') || module === 'react-native')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oxy.so/bloom-language-codemod",
3
- "version": "0.2.1",
3
+ "version": "0.4.0",
4
4
  "description": "Moves an app's NativeWind className JSX and Bloom JSX to Bloom's UI language, only where the rendered result stays identical, and proves it with the language's parity harness.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "repository": {
@@ -51,10 +51,10 @@
51
51
  "recast": "0.23.11"
52
52
  },
53
53
  "peerDependencies": {
54
- "@oxy.so/bloom-language": ">=1.1.0"
54
+ "@oxy.so/bloom-language": ">=1.6.0"
55
55
  },
56
56
  "devDependencies": {
57
- "@oxy.so/bloom-language": "1.2.0",
57
+ "@oxy.so/bloom-language": "1.6.0",
58
58
  "bloom-22": "https://registry.npmjs.org/@oxy.so/bloom/-/bloom-22.1.11.tgz",
59
59
  "lightningcss": "1.30.1",
60
60
  "nativewind": "5.0.0-rc.0",