embedded-react 0.21.0 → 0.22.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.
Files changed (99) hide show
  1. package/README.md +2 -2
  2. package/aot/compile.mjs +1 -1
  3. package/aot/compiler/alerts.mjs +604 -0
  4. package/aot/compiler/check.mjs +1 -1
  5. package/aot/compiler/collect.mjs +1 -1
  6. package/aot/compiler/elements/button.mjs +3 -3
  7. package/aot/compiler/elements/image-background.mjs +1 -1
  8. package/aot/compiler/elements/props.mjs +10 -6
  9. package/aot/compiler/elements/section-list.mjs +1 -1
  10. package/aot/compiler/expressions.mjs +29 -2
  11. package/aot/compiler/handlers.mjs +73 -16
  12. package/aot/compiler/keyboard-dismiss.mjs +99 -0
  13. package/aot/compiler/keyboard.mjs +1 -1
  14. package/aot/compiler/lower.mjs +12 -0
  15. package/aot/compiler/nodes.mjs +17 -9
  16. package/aot/compiler/out.mjs +4 -0
  17. package/aot/compiler/package/codegen.mjs +36 -2
  18. package/aot/compiler/package/format.mjs +5 -3
  19. package/aot/compiler/package/lower.mjs +53 -19
  20. package/aot/compiler/scroll-to.mjs +112 -0
  21. package/aot/compiler/style-text.mjs +2 -2
  22. package/aot/compiler/svg.mjs +6 -3
  23. package/aot/compiler/updaters.mjs +1 -0
  24. package/aot/style-map.mjs +44 -1
  25. package/assets/bake-font.mjs +187 -244
  26. package/assets/bake-image.mjs +47 -71
  27. package/assets/bake-svg.mjs +465 -533
  28. package/assets/build-builtin-font.mjs +14 -27
  29. package/assets/emit-c.mjs +124 -204
  30. package/assets/emit-container.mjs +129 -197
  31. package/assets/emit-pack.mjs +92 -136
  32. package/assets/font-config.mjs +19 -27
  33. package/assets/font-sizes.mjs +432 -507
  34. package/assets/glyph-coverage.mjs +170 -214
  35. package/assets/index.mjs +52 -97
  36. package/assets/rasterize.mjs +173 -194
  37. package/assets/svg-loader.mjs +42 -48
  38. package/build.mjs +84 -101
  39. package/cli.mjs +482 -621
  40. package/compile-bin.mjs +24 -36
  41. package/flash.mjs +297 -401
  42. package/hotreload/dev-device.mjs +229 -270
  43. package/hotreload/pack-app.mjs +118 -159
  44. package/hotreload/pack-split.mjs +144 -200
  45. package/hotreload/package-transfer.mjs +128 -131
  46. package/hotreload/protocol.mjs +118 -118
  47. package/hotreload/uploader.mjs +132 -159
  48. package/hotreload/watch-tree.mjs +56 -65
  49. package/pack-container.mjs +93 -123
  50. package/package.json +19 -16
  51. package/persist-transform.mjs +89 -105
  52. package/qjsc-wasm.mjs +47 -72
  53. package/sim/embedded-react.wasm +0 -0
  54. package/sim/index.html +1 -1
  55. package/sim-server.mjs +260 -354
  56. package/src/embedded-react/Alert.mjs +112 -0
  57. package/src/embedded-react/Animated.mjs +412 -0
  58. package/src/embedded-react/{AppRegistry.js → AppRegistry.mjs} +26 -25
  59. package/src/embedded-react/{Button.js → Button.mjs} +29 -53
  60. package/src/embedded-react/{Dimensions.js → Dimensions.mjs} +12 -17
  61. package/src/embedded-react/Easing.mjs +34 -0
  62. package/src/embedded-react/{FlatList.js → FlatList.mjs} +25 -42
  63. package/src/embedded-react/{ImageBackground.js → ImageBackground.mjs} +11 -22
  64. package/src/embedded-react/Keyboard.mjs +82 -0
  65. package/src/embedded-react/{LayoutAnimation.js → LayoutAnimation.mjs} +17 -28
  66. package/src/embedded-react/PanResponder.mjs +256 -0
  67. package/src/embedded-react/{Platform.js → Platform.mjs} +8 -9
  68. package/src/embedded-react/{Pressable.js → Pressable.mjs} +12 -25
  69. package/src/embedded-react/SectionList.mjs +103 -0
  70. package/src/embedded-react/{StyleSheet.js → StyleSheet.mjs} +16 -20
  71. package/src/embedded-react/{TouchableOpacity.js → TouchableOpacity.mjs} +47 -83
  72. package/src/embedded-react/background-image.mjs +321 -0
  73. package/src/embedded-react/{components.js → components.mjs} +1 -3
  74. package/src/embedded-react/{imperative.js → imperative.mjs} +27 -38
  75. package/src/embedded-react/index.d.ts +155 -2
  76. package/src/embedded-react/index.js +26 -19
  77. package/src/embedded-react/layout-anim-config.mjs +85 -0
  78. package/src/embedded-react/{list-child.js → list-child.mjs} +11 -20
  79. package/src/embedded-react/{named-colors.js → named-colors.mjs} +2 -6
  80. package/src/embedded-react/nativeModule.mjs +371 -0
  81. package/src/embedded-react/split-style.mjs +57 -0
  82. package/src/embedded-react/svg-ops.mjs +1075 -0
  83. package/src/embedded-react/{useHostValue.js → useHostValue.mjs} +2 -4
  84. package/src/embedded-react/{usePersistentState.js → usePersistentState.mjs} +34 -38
  85. package/src/embedded-react/{warn-props.js → warn-props.mjs} +32 -39
  86. package/src/host-config.mjs +512 -0
  87. package/src/{native-ui.js → native-ui.mjs} +1 -8
  88. package/src/props.mjs +341 -0
  89. package/src/{renderer.js → renderer.mjs} +30 -44
  90. package/src/embedded-react/Animated.js +0 -440
  91. package/src/embedded-react/Easing.js +0 -39
  92. package/src/embedded-react/PanResponder.js +0 -330
  93. package/src/embedded-react/SectionList.js +0 -146
  94. package/src/embedded-react/layout-anim-config.js +0 -101
  95. package/src/embedded-react/nativeModule.js +0 -462
  96. package/src/embedded-react/split-style.js +0 -58
  97. package/src/embedded-react/svg-ops.js +0 -1295
  98. package/src/host-config.js +0 -548
  99. package/src/props.js +0 -306
@@ -16,7 +16,7 @@
16
16
  /*----------------------------------------------------------------------------------------------------------------------
17
17
  - Imports
18
18
  ---------------------------------------------------------------------------------------------------------------------*/
19
- import { RN_PLATFORM_NO_OPS } from '../../../src/embedded-react/warn-props.js';
19
+ import { RN_PLATFORM_NO_OPS } from '../../../src/embedded-react/warn-props.mjs';
20
20
  import { isStyleKey } from '../../style-map.mjs';
21
21
  import { aotError } from '../diagnostics.mjs';
22
22
  /*----------------------------------------------------------------------------------------------------------------------
@@ -32,6 +32,7 @@ export const EVENT_TYPES = {
32
32
  onTouchMove: 'ER_EVENT_TOUCH_MOVE',
33
33
  onTouchEnd: 'ER_EVENT_TOUCH_END',
34
34
  onLayout: 'ER_EVENT_LAYOUT',
35
+ onScroll: 'ER_EVENT_SCROLL',
35
36
  };
36
37
  /** Style keys every node lays out by, and `transform`, which every node draws through. */
37
38
  const LAYOUT_STYLE = [
@@ -63,6 +64,7 @@ const LAYOUT_STYLE = [
63
64
  'flexGrow',
64
65
  'flexShrink',
65
66
  'flexDirection',
67
+ 'flexWrap',
66
68
  'alignItems',
67
69
  'alignSelf',
68
70
  'justifyContent',
@@ -87,6 +89,7 @@ const SHADOW_STYLE = [
87
89
  const VIEW_STYLE = [
88
90
  ...SHADOW_STYLE,
89
91
  'backgroundColor',
92
+ 'backgroundImage',
90
93
  'borderRadius',
91
94
  'borderTopLeftRadius',
92
95
  'borderTopRightRadius',
@@ -123,7 +126,7 @@ const BOX_STYLE = [
123
126
  'opacity',
124
127
  ];
125
128
  /** What the engine draws a Modal's own box with. */
126
- const MODAL_STYLE = [...BOX_STYLE, ...SHADOW_STYLE];
129
+ const MODAL_STYLE = [...BOX_STYLE, ...SHADOW_STYLE, 'backgroundImage'];
127
130
  /** What the engine draws a TextInput with. */
128
131
  const TEXT_INPUT_STYLE = [...BOX_STYLE, 'color', 'fontSize'];
129
132
  /** The style keys the engine animates on a View, ScrollView, Pressable or Modal; `transform` animates anywhere. */
@@ -146,13 +149,15 @@ const SVG_PAINT = [
146
149
  'fillGradient',
147
150
  'strokeGradient',
148
151
  ];
152
+ /** The events every host node takes; only a ScrollView scrolls. */
153
+ const HOST_EVENTS = Object.keys(EVENT_TYPES).filter(name => name !== 'onScroll');
149
154
  /** The attributes every host node lowers: style, visibility, a node ref, and its events. */
150
155
  const HOST_PROPS = [
151
156
  'style',
152
157
  'visible',
153
158
  'ref',
154
159
  'delayLongPress',
155
- ...Object.keys(EVENT_TYPES),
160
+ ...HOST_EVENTS,
156
161
  ];
157
162
  /** Why the engine's TextInput refuses a React Native prop it has no field for. */
158
163
  const NO_TEXT_INPUT_FIELD = "the engine's TextInput has no such setting, so the device would ignore it. Remove it.";
@@ -161,8 +166,7 @@ const SVG_EVENT = 'wrap it in a <Pressable> (or a <View>) that takes the event:
161
166
  /** The built-in elements, by tag. `Animated.X` resolves to X. */
162
167
  const ELEMENTS = {
163
168
  View: element('View', HOST_PROPS, [...LAYOUT_STYLE, ...VIEW_STYLE], 'nodes', {}, VIEW_ANIMATED),
164
- ScrollView: element('ScrollView', HOST_PROPS, [...LAYOUT_STYLE, ...VIEW_STYLE], 'nodes', {
165
- onScroll: 'scroll events are not lowered yet. Read the position another way, or keep this screen Flow A only.',
169
+ ScrollView: element('ScrollView', [...HOST_PROPS, 'onScroll'], [...LAYOUT_STYLE, ...VIEW_STYLE], 'nodes', {
166
170
  horizontal: "the engine's ScrollView scrolls vertically; lay a horizontal strip out with flexDirection: 'row'.",
167
171
  }, VIEW_ANIMATED),
168
172
  Pressable: element('Pressable', [...HOST_PROPS, 'disabled'], [...LAYOUT_STYLE, ...VIEW_STYLE], 'nodes', {}, VIEW_ANIMATED),
@@ -276,7 +280,7 @@ const ELEMENTS = {
276
280
  ], [...LAYOUT_STYLE, ...VIEW_STYLE], 'nodes', {}, VIEW_ANIMATED),
277
281
  Svg: element('Svg', ['style', 'ref', 'width', 'height', 'viewBox', 'source', ...SVG_PAINT], LAYOUT_STYLE, 'shapes', {
278
282
  visible: 'wrap it: <View visible={…}><Svg …/></View> — the View carries the hide and the whole subtree goes with it.',
279
- ...Object.fromEntries(Object.keys(EVENT_TYPES).map(name => [name, SVG_EVENT])),
283
+ ...Object.fromEntries(HOST_EVENTS.map(name => [name, SVG_EVENT])),
280
284
  }),
281
285
  };
282
286
  /** The shapes inside an <Svg>, by tag; they are drawing data, so they take no ref, style or events. */
@@ -38,7 +38,7 @@ const SECTIONS_HINT = 'write sections={[{title: …, data: …}, …]} in place,
38
38
  ---------------------------------------------------------------------------------------------------------------------*/
39
39
  /**
40
40
  * <SectionList sections renderItem renderSectionHeader renderSectionFooter style /> → a <ScrollView> holding each
41
- * section's header, rows and footer as flat siblings, as SectionList.js renders it. The sections are unrolled at
41
+ * section's header, rows and footer as flat siblings, as SectionList.mts renders it. The sections are unrolled at
42
42
  * build time; each section's rows are a `.map` over its data, so a data that is list state is a pool of rows.
43
43
  * keyExtractor is ignored (no reconciler).
44
44
  *
@@ -31,6 +31,7 @@ import { helperValueOf, returnedExpression } from './helper-values.mjs';
31
31
  import { isObjectTree, propertyKey } from './records.mjs';
32
32
  import { lowerNativeCall, nativeAvailableOf, unkeptRecordError, nativeCalleeOf, readsNativeModule, } from './native-modules.mjs';
33
33
  import { lowerTagTest, narrowOn, narrowed, tagTestOf, } from './tagged-records.mjs';
34
+ import { unkeptScrollError } from './scroll-to.mjs';
34
35
  import { TEXT_END } from './ir/text.mjs';
35
36
  import { BOOL, FLOAT, INT, INT64_NUMBER, INT64_MATH, STRING, TIME, isBoolean, isConvertible64, isIntSlot, isTime, int64Join, int64Of, stateType, refType, slotOf, typeOfSlot, typeOfSlotValue, wideSlotOf, } from './ir/types.mjs';
36
37
  /*----------------------------------------------------------------------------------------------------------------------
@@ -1267,6 +1268,16 @@ export const binarySource = (node, left, right, environment) => ({
1267
1268
  rightIsNumber: isWrittenAsNumber(node.right, environment),
1268
1269
  location: node.loc?.start,
1269
1270
  });
1271
+ /**
1272
+ * An onScroll handler read a touch field, which a scroll event doesn't carry.
1273
+ *
1274
+ * @param field The field read.
1275
+ *
1276
+ * @returns The error to throw.
1277
+ */
1278
+ function scrollTouchError(field) {
1279
+ return aotError(`AOT: an onScroll event carries no touch, so it has no "${field}"`, 'read e.scrollX / e.scrollY — the offset is all a scroll event has.');
1280
+ }
1270
1281
  /**
1271
1282
  * Whether `node` is the handler's event, or its `nativeEvent` as React Native code reads it.
1272
1283
  *
@@ -1964,12 +1975,25 @@ function sourceOf(node, environment) {
1964
1975
  if (object.type === 'Identifier' &&
1965
1976
  environment.event === object.name &&
1966
1977
  (prop === 'x' || prop === 'y' || prop === 'dx' || prop === 'dy')) {
1978
+ if (environment.scroll)
1979
+ throw scrollTouchError(prop);
1967
1980
  return fixed({ kind: 'event', field: prop, type: INT });
1968
1981
  }
1969
1982
  // `<event>.vx / .vy` — finger velocity (px/ms) at the last move; the engine measures it, a handler cannot.
1970
1983
  if (object.type === 'Identifier' &&
1971
1984
  environment.event === object.name &&
1972
1985
  (prop === 'vx' || prop === 'vy')) {
1986
+ if (environment.scroll)
1987
+ throw scrollTouchError(prop);
1988
+ return fixed({ kind: 'event', field: prop, type: FLOAT });
1989
+ }
1990
+ // `<event>.scrollX / .scrollY` — where an onScroll handler's ScrollView is now.
1991
+ if (object.type === 'Identifier' &&
1992
+ environment.event === object.name &&
1993
+ (prop === 'scrollX' || prop === 'scrollY')) {
1994
+ if (!environment.scroll) {
1995
+ throw aotError('AOT: only an onScroll event carries a scroll offset', 'read e.scrollX / e.scrollY inside an onScroll handler, or ask with scrollTo(ref.current).');
1996
+ }
1973
1997
  return fixed({ kind: 'event', field: prop, type: FLOAT });
1974
1998
  }
1975
1999
  // `<gestureState>.…` — the second argument of a PanResponder callback (see emitPanResponder).
@@ -2002,11 +2026,11 @@ function sourceOf(node, environment) {
2002
2026
  let root = node;
2003
2027
  while (root.type === 'MemberExpression')
2004
2028
  root = root.object;
2005
- const unkept = unkeptRecordError(root, environment);
2029
+ const unkept = unkeptRecordError(root, environment) ?? unkeptScrollError(root);
2006
2030
  if (unkept)
2007
2031
  throw unkept;
2008
2032
  throw aotError('AOT: unsupported member expression in a dynamic context', "in a handler or dynamic expression you can read state, `ref.current`, a list item's " +
2009
- 'field (`item.title`, `items[i].title`), event fields (e.x / e.y / e.dx / e.dy / e.vx / e.vy / e.layout.*), and ' +
2033
+ 'field (`item.title`, `items[i].title`), event fields (e.x / e.y / e.dx / e.dy / e.vx / e.vy / e.scrollX / e.scrollY / e.layout.*), and ' +
2010
2034
  'Math.PI — other member access must be a compile-time constant.');
2011
2035
  }
2012
2036
  case 'OptionalMemberExpression': {
@@ -2019,6 +2043,9 @@ function sourceOf(node, environment) {
2019
2043
  }
2020
2044
  case 'CallExpression': {
2021
2045
  const callee = node.callee;
2046
+ const unkeptScroll = unkeptScrollError(node);
2047
+ if (unkeptScroll)
2048
+ throw unkeptScroll;
2022
2049
  // `Sensors.read(channel)`: a native method's result.
2023
2050
  const nativeCallee = nativeCalleeOf(node, environment);
2024
2051
  if (nativeCallee) {
@@ -16,9 +16,11 @@
16
16
  /*----------------------------------------------------------------------------------------------------------------------
17
17
  - Imports
18
18
  ---------------------------------------------------------------------------------------------------------------------*/
19
- import { parseColor, parsePath } from '../../src/embedded-react/svg-ops.js';
19
+ import { parseColor, parsePath } from '../../src/embedded-react/svg-ops.mjs';
20
20
  import { aotError, constantText, ENGINE_STRING_MAX, withLoc, } from './diagnostics.mjs';
21
21
  import { evalStatic, foldScope, RuntimeLeaf } from './static-eval.mjs';
22
+ import { ALERT_CALL, raiseAlert, withAlertBase } from './alerts.mjs';
23
+ import { KEYBOARD_DISMISS_CALL } from './keyboard-dismiss.mjs';
22
24
  import { fieldsUnder } from './list-items.mjs';
23
25
  import { lowerNativeCall, nativeCalleeOf, nativeEventOf, nativeRecordCallOf, recordTreeOf, valueCount, } from './native-modules.mjs';
24
26
  import { itemCallback, listChainOf, orderStatements } from './list-order.mjs';
@@ -37,6 +39,7 @@ import { isFn } from './collect.mjs';
37
39
  import { keepingStates, readingLatest } from './kept-states.mjs';
38
40
  import { isAnimatedCall, resolveAnim, animValues, lowerAnimateStart, stopWaitOwner, } from './animations.mjs';
39
41
  import { svgNum, CAP_MAP, JOIN_MAP, arcTape, circleTape, rectTape, lineTape, checkedTapeNumber, checkVectorPaints, vectorPaintOf, DEFAULT_MITER_LIMIT, } from './svg.mjs';
42
+ import { isScrollToCall, lowerScrollTo, SCROLL_POSITION_FIELDS, } from './scroll-to.mjs';
40
43
  import { armedFlag } from './ir/functions.mjs';
41
44
  import { INT, isConvertible64, isIntSlot, isTime, refType, STRING, } from './ir/types.mjs';
42
45
  /*----------------------------------------------------------------------------------------------------------------------
@@ -1591,12 +1594,29 @@ function lowerHandlerExprImpl(expression, handlerEnvironment, state, context) {
1591
1594
  const text = lowerLogText(expression.arguments, environment);
1592
1595
  return context.output.release ? [] : [{ kind: 'log', text }];
1593
1596
  }
1597
+ // Alert.alert(…) → its dialog is built under the root, and the call sets the state that shows it.
1598
+ if (expression.type === 'CallExpression' &&
1599
+ expression.callee.type === 'Identifier' &&
1600
+ expression.callee.name === ALERT_CALL) {
1601
+ const raised = raiseAlert(expression, environment, state, context.output);
1602
+ return lowerHandlerExprImpl(raised.setter, raised.environment, raised.state, context);
1603
+ }
1594
1604
  // updateVector(ref, shapes, dirtyRect?) — imperative vector redraw (no update).
1595
1605
  if (expression.type === 'CallExpression' &&
1596
1606
  expression.callee.type === 'Identifier' &&
1597
1607
  expression.callee.name === 'updateVector') {
1598
1608
  return [lowerUpdateVector(expression, environment, context)];
1599
1609
  }
1610
+ // scrollTo(ref.current, {x, y}) — scrolls a ScrollView, its position dropped.
1611
+ if (isScrollToCall(expression)) {
1612
+ return [lowerScrollTo(expression, environment)];
1613
+ }
1614
+ // Keyboard.dismiss() — blurs the focused TextInput.
1615
+ if (expression.type === 'CallExpression' &&
1616
+ expression.callee.type === 'Identifier' &&
1617
+ expression.callee.name === KEYBOARD_DISMISS_CALL) {
1618
+ return [{ kind: 'dismissKeyboard' }];
1619
+ }
1600
1620
  // setInterval / setTimeout(cb, ms) → register a host-tick timer (the returned id is discarded here).
1601
1621
  if (expression.type === 'CallExpression' &&
1602
1622
  expression.callee.type === 'Identifier' &&
@@ -1859,10 +1879,11 @@ export function lowerStmts(statements, bodyEnvironment, state, context) {
1859
1879
  continue;
1860
1880
  }
1861
1881
  const declarator = entry;
1862
- // A native method's record: its values kept in locals, then declared as an object of them, or a field.
1863
- const recordRoot = nativeRecordRootOf(declarator.init, environment);
1882
+ // A native method's record, or scrollTo's: its values kept in locals, then declared as an object of them,
1883
+ // or a field.
1884
+ const recordRoot = recordRootOf(declarator.init, environment);
1864
1885
  if (recordRoot) {
1865
- const kept = keepNativeRecord(recordRoot.call, recordRoot.callee, environment);
1886
+ const kept = recordRoot.keep(environment);
1866
1887
  lowered.push(kept.statement);
1867
1888
  environment = kept.environment;
1868
1889
  queue.unshift({
@@ -2169,7 +2190,7 @@ export function lowerStmts(statements, bodyEnvironment, state, context) {
2169
2190
  // setLat(Gps.fix().lat): kept first, then passed by its name.
2170
2191
  let expression = statement.expression;
2171
2192
  const keptRoot = (argument, index) => {
2172
- const recordRoot = nativeRecordRootOf(argument, environment);
2193
+ const recordRoot = recordRootOf(argument, environment);
2173
2194
  return recordRoot &&
2174
2195
  (recordRoot.call !== argument ||
2175
2196
  takesRecord(expression, index, environment, state))
@@ -2182,7 +2203,7 @@ export function lowerStmts(statements, bodyEnvironment, state, context) {
2182
2203
  const recordRoot = keptRoot(argument, index);
2183
2204
  if (!recordRoot)
2184
2205
  return argument;
2185
- const kept = keepNativeRecord(recordRoot.call, recordRoot.callee, environment);
2206
+ const kept = recordRoot.keep(environment);
2186
2207
  lowered.push(kept.statement);
2187
2208
  environment = kept.environment;
2188
2209
  return recordRoot.replaced({
@@ -2266,7 +2287,8 @@ function markLoc(lowered, from, location) {
2266
2287
  * @param state The component's state table.
2267
2288
  * @param output Everything emitted so far; the effect is added to it.
2268
2289
  */
2269
- export function lowerEffect(effect, environment, state, output) {
2290
+ export function lowerEffect(effect, componentEnvironment, state, output) {
2291
+ const environment = withAlertBase(componentEnvironment);
2270
2292
  // An expression body is a single statement.
2271
2293
  const body = effect.functionNode.body;
2272
2294
  const statements = body.type === 'BlockStatement'
@@ -2369,26 +2391,34 @@ export function lowerEffect(effect, environment, state, output) {
2369
2391
  output.dependencyEffects.push(dependencyEffect);
2370
2392
  }
2371
2393
  /**
2372
- * The native call that returns a record at the root of an expression: the call itself, or the record a field read
2373
- * starts from, `Gps.fix().place.lat`.
2394
+ * The call that returns a record at the root of an expression, a native method's or scrollTo's: the call itself,
2395
+ * or the record a field read starts from, `Gps.fix().place.lat`.
2374
2396
  *
2375
2397
  * @param node The expression.
2376
2398
  * @param environment The expression environment.
2377
2399
  *
2378
- * @returns The call and its callee, and the expression with the call replaced by another; or null.
2400
+ * @returns The call, or null.
2379
2401
  */
2380
- function nativeRecordRootOf(node, environment) {
2402
+ function recordRootOf(node, environment) {
2381
2403
  if (node?.type === 'MemberExpression') {
2382
- const root = nativeRecordRootOf(node.object, environment);
2404
+ const root = recordRootOf(node.object, environment);
2383
2405
  return (root && {
2384
2406
  ...root,
2385
2407
  replaced: by => ({ ...node, object: root.replaced(by) }),
2386
2408
  });
2387
2409
  }
2410
+ if (isScrollToCall(node)) {
2411
+ const call = node;
2412
+ return {
2413
+ call,
2414
+ keep: inEnvironment => keepScrollPosition(call, inEnvironment),
2415
+ replaced: by => by,
2416
+ };
2417
+ }
2388
2418
  const callee = nativeRecordCallOf(node, environment);
2389
2419
  return (callee && {
2390
2420
  call: node,
2391
- callee,
2421
+ keep: inEnvironment => keepNativeRecord(node, callee, inEnvironment),
2392
2422
  replaced: by => by,
2393
2423
  });
2394
2424
  }
@@ -2436,6 +2466,31 @@ function keepNativeRecord(node, callee, environment) {
2436
2466
  },
2437
2467
  };
2438
2468
  }
2469
+ /**
2470
+ * Scrolls with scrollTo, keeping the position it returns in locals, and binds the position to a name no JS binding
2471
+ * has, as an object of them.
2472
+ *
2473
+ * @param node The call.
2474
+ * @param environment The expression environment.
2475
+ *
2476
+ * @returns The call, the name, and the environment that binds it.
2477
+ */
2478
+ function keepScrollPosition(node, environment) {
2479
+ const name = `#record${keptRecords++}`;
2480
+ const results = SCROLL_POSITION_FIELDS.map(field => `${name}_${field}`);
2481
+ const position = Object.fromEntries(SCROLL_POSITION_FIELDS.map((field, index) => [
2482
+ field,
2483
+ new RuntimeLeaf({ name: results[index], slotKind: 'float' }),
2484
+ ]));
2485
+ return {
2486
+ statement: lowerScrollTo(node, environment, results),
2487
+ name,
2488
+ environment: {
2489
+ ...environment,
2490
+ constants: { ...environment.constants, [name]: position },
2491
+ },
2492
+ };
2493
+ }
2439
2494
  /**
2440
2495
  * Lowers a `useNativeEvent(Module, 'event', handler)` to a handler the runtime runs with the event's values. The
2441
2496
  * handler does nothing while its component isn't mounted: the conditions it is built under, read as it runs.
@@ -2445,7 +2500,8 @@ function keepNativeRecord(node, callee, environment) {
2445
2500
  * @param state The component's state table.
2446
2501
  * @param output Everything emitted so far; the handler is added to it.
2447
2502
  */
2448
- export function lowerNativeEvent(call, environment, state, output) {
2503
+ export function lowerNativeEvent(call, componentEnvironment, state, output) {
2504
+ const environment = withAlertBase(componentEnvironment);
2449
2505
  const { event, values: declared, handler } = nativeEventOf(call, environment);
2450
2506
  const index = output.nativeEventHandlers.length;
2451
2507
  // Each value is a register the handler is entered with, read by a name no JS binding can have. A record's fields
@@ -2527,7 +2583,7 @@ export function lowerHandler(functionNode, environment, state, output, pan = nul
2527
2583
  const gestureParameter = pan && functionNode.params[1]?.type === 'Identifier'
2528
2584
  ? functionNode.params[1].name
2529
2585
  : null;
2530
- let handlerEnvironment = environment;
2586
+ let handlerEnvironment = withAlertBase(environment);
2531
2587
  if (eventParameter) {
2532
2588
  handlerEnvironment = { ...handlerEnvironment, event: eventParameter };
2533
2589
  }
@@ -2559,7 +2615,8 @@ export function lowerHandler(functionNode, environment, state, output, pan = nul
2559
2615
  *
2560
2616
  * @returns The callback.
2561
2617
  */
2562
- export function lowerValueHandler(functionNode, environment, state, output, slotKind, isBoolean, valueExpression, secondValueExpression) {
2618
+ export function lowerValueHandler(functionNode, componentEnvironment, state, output, slotKind, isBoolean, valueExpression, secondValueExpression) {
2619
+ const environment = withAlertBase(componentEnvironment);
2563
2620
  // A <Switch> hands its callback a boolean; carry that so `'on=' + v` prints true/false, not 1/0.
2564
2621
  const valueParameter = functionNode.params[0]?.type === 'Identifier'
2565
2622
  ? functionNode.params[0].name
@@ -0,0 +1,99 @@
1
+ /*
2
+ * Copyright 2026 Cory Lamming
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ /**
17
+ * @file compiler/keyboard-dismiss.mts
18
+ * @brief Finds each `Keyboard.dismiss()`, by the package's own export, and refuses any other use of Keyboard.
19
+ */
20
+ import { traverse } from '@babel/core';
21
+ import { aotError } from './diagnostics.mjs';
22
+ /*----------------------------------------------------------------------------------------------------------------------
23
+ - Constants
24
+ ---------------------------------------------------------------------------------------------------------------------*/
25
+ /** The package Keyboard is imported from. */
26
+ const PACKAGE = 'embedded-react';
27
+ /** What a `Keyboard.dismiss()` is rewritten to call. Not a name JS allows, so no binding of the app's is one. */
28
+ export const KEYBOARD_DISMISS_CALL = '#Keyboard.dismiss';
29
+ const HINT = 'Keyboard.dismiss() is the one Keyboard call a package has; to follow the keyboard, set state in the ' +
30
+ "<TextInput>'s onFocus and onBlur.";
31
+ /*----------------------------------------------------------------------------------------------------------------------
32
+ - Implementation
33
+ ---------------------------------------------------------------------------------------------------------------------*/
34
+ /**
35
+ * Whether a name stands for the package's Keyboard where it is read. A local, a prop or a state of that name hides
36
+ * the import.
37
+ *
38
+ * @param path Where the name is read.
39
+ *
40
+ * @returns Whether it does.
41
+ */
42
+ function isKeyboard(path) {
43
+ const binding = path.scope.getBinding(path.node.name);
44
+ const specifier = binding?.path.node;
45
+ const declaration = binding?.path.parent;
46
+ if (specifier?.type !== 'ImportSpecifier' ||
47
+ declaration?.type !== 'ImportDeclaration' ||
48
+ declaration.source.value !== PACKAGE) {
49
+ return false;
50
+ }
51
+ const { imported } = specifier;
52
+ return ((imported.type === 'Identifier' ? imported.name : imported.value) ===
53
+ 'Keyboard');
54
+ }
55
+ /**
56
+ * Rewrites every `Keyboard.dismiss()` to a call of KEYBOARD_DISMISS_CALL, by whatever name Keyboard is imported.
57
+ *
58
+ * @param ast The parsed file, rewritten in place.
59
+ *
60
+ * @throws An AotError for any other use of Keyboard.
61
+ */
62
+ export function rewriteKeyboardDismiss(ast) {
63
+ traverse.cache.clear();
64
+ traverse(ast, {
65
+ Identifier(path) {
66
+ if (!path.isReferencedIdentifier() || !isKeyboard(path))
67
+ return;
68
+ const member = path.parent;
69
+ const call = path.parentPath?.parent;
70
+ const method = member.type === 'MemberExpression' &&
71
+ member.object === path.node &&
72
+ !member.computed &&
73
+ member.property.type === 'Identifier' &&
74
+ call?.type === 'CallExpression' &&
75
+ call.callee === member
76
+ ? member.property.name
77
+ : null;
78
+ if (method === 'dismiss' &&
79
+ call.arguments.length === 0) {
80
+ call.callee = {
81
+ type: 'Identifier',
82
+ name: KEYBOARD_DISMISS_CALL,
83
+ loc: member.loc,
84
+ };
85
+ path.skip();
86
+ return;
87
+ }
88
+ const error = aotError(method === 'dismiss'
89
+ ? 'AOT: Keyboard.dismiss() takes no arguments'
90
+ : method
91
+ ? `AOT: Keyboard.${method}() is not in the subset`
92
+ : 'AOT: Keyboard has only Keyboard.dismiss()', HINT);
93
+ if (path.node.loc)
94
+ error.aotLoc = path.node.loc.start;
95
+ throw error;
96
+ },
97
+ });
98
+ traverse.cache.clear();
99
+ }
@@ -16,7 +16,7 @@
16
16
  /*----------------------------------------------------------------------------------------------------------------------
17
17
  - Imports
18
18
  ---------------------------------------------------------------------------------------------------------------------*/
19
- import { parseColor } from '../../src/embedded-react/svg-ops.js';
19
+ import { parseColor } from '../../src/embedded-react/svg-ops.mjs';
20
20
  import { aotError, withLoc } from './diagnostics.mjs';
21
21
  import { evalStatic } from './static-eval.mjs';
22
22
  /*----------------------------------------------------------------------------------------------------------------------
@@ -31,6 +31,8 @@ import { normalizeUndefined, parseApp } from './parse.mjs';
31
31
  import { collectNativeModules, optionalModulesOf } from './native-modules.mjs';
32
32
  import { inlineCustomHooks } from './custom-hooks.mjs';
33
33
  import { rewriteWindowDimensions } from './window-dimensions.mjs';
34
+ import { alertState, emitAlertDialogs, rewriteAlerts } from './alerts.mjs';
35
+ import { rewriteKeyboardDismiss } from './keyboard-dismiss.mjs';
34
36
  import { Out } from './out.mjs';
35
37
  import { conditionalsOf, isStateDriven, nodesOf, updatedVectorOf, } from './ir/nodes.mjs';
36
38
  import { expressionReads, listStates, nodeReads, vectorReads, workedStates, } from './ir/reads.mjs';
@@ -227,6 +229,8 @@ function lowerProgram(source, options, wide, stores) {
227
229
  });
228
230
  normalizeUndefined(ast);
229
231
  rewriteWindowDimensions(ast);
232
+ const raisesAlerts = rewriteAlerts(ast);
233
+ rewriteKeyboardDismiss(ast);
230
234
  inlineCustomHooks(ast);
231
235
  refuseHiddenContexts(ast);
232
236
  const shadowedClock = findShadowedClockCalls(ast);
@@ -320,6 +324,11 @@ function lowerProgram(source, options, wide, stores) {
320
324
  for (const name of state.byName.keys()) {
321
325
  delete scope[name];
322
326
  }
327
+ const activeAlert = raisesAlerts ? alertState() : null;
328
+ if (activeAlert) {
329
+ state.byName.set(activeAlert.name, activeAlert);
330
+ state.bySetter.set(activeAlert.setter, activeAlert);
331
+ }
323
332
  // Collect the component's other hooks, plus the file's helpers and child components.
324
333
  const rootJSX = findReturnJSX(component.body, scope);
325
334
  const animations = collectAnims(component.body, scope);
@@ -389,6 +398,7 @@ function lowerProgram(source, options, wide, stores) {
389
398
  const output = new Out(components, ast.program);
390
399
  output.release = Boolean(options.release);
391
400
  output.optionalModules = optionalModulesOf(nativeModules);
401
+ output.alertState = activeAlert;
392
402
  const keyboard = lowerKeyboardConfig(ast.program); // a module-level setKeyboardConfig({...})
393
403
  const root = emitNode(rootJSX, scope, output, environment, state);
394
404
  // Emit registered only the images it reached; a dynamic source can't be enumerated, so bake every import.
@@ -404,6 +414,8 @@ function lowerProgram(source, options, wide, stores) {
404
414
  for (const call of collectNativeEvents(component.body)) {
405
415
  lowerNativeEvent(call, environment, state, output);
406
416
  }
417
+ // Every alert raised is known by now, so their dialogs go under the root, after everything else.
418
+ emitAlertDialogs(root, output);
407
419
  // An update exists only when something has to be re-applied after a state change, or a list filtered or sorted
408
420
  // in render rebuilt.
409
421
  const derivedLists = [...environment.derivedLists.values()].flatMap(lists => [...lists.values()]);
@@ -228,7 +228,7 @@ function opacityLiteralOrThrow(value, attribute) {
228
228
  /**
229
229
  * Lowers <TouchableOpacity>'s press feedback: a Pressable node plus one synthetic animated value bound to its
230
230
  * opacity. Press-in snaps it to activeOpacity, press-out fades it back to whatever the style asks for. Flow A
231
- * builds the same thing out of hooks (TouchableOpacity.js); here the feedback runs on the engine's native
231
+ * builds the same thing out of hooks (TouchableOpacity.mts); here the feedback runs on the engine's native
232
232
  * driver with no JS on the device at all. Returns the value's bind, and the two fades for the event loop to
233
233
  * fold into its press handlers.
234
234
  *
@@ -322,22 +322,30 @@ function applyShow(node, show) {
322
322
  */
323
323
  export function lowerEventHandler(attribute, output, environment, state) {
324
324
  const handlerExpression = attrExpr(attribute);
325
- const layout = attribute.name.name === 'onLayout';
325
+ const eventName = attribute.name.name;
326
+ // The events whose data only their own handler reads.
327
+ const carries = eventName === 'onLayout'
328
+ ? 'layout'
329
+ : eventName === 'onScroll'
330
+ ? 'scroll'
331
+ : null;
332
+ const carried = { layout: carries === 'layout', scroll: carries === 'scroll' };
326
333
  if (handlerExpression.type === 'Identifier' &&
327
334
  environment.callbacks?.has(handlerExpression.name)) {
328
335
  // A useCallback compiles to one shared handler, namespaced by cbPrefix so each child instance gets its own.
329
- // Its onLayout use gets a handler of its own, since only that event carries the layout rect. The key's
330
- // `layout:` and the name's `layout_callback_` can't come from an identifier, so they never meet another callback.
336
+ // Its onLayout or onScroll use gets a handler of its own, since only that event carries the layout rect or the
337
+ // offset. The key's `layout:` and the name's `layout_callback_` can't come from an identifier, so they never
338
+ // meet another callback.
331
339
  const callbackKey = `${environment.callbackPrefix ?? ''}${handlerExpression.name}`;
332
- const emittedKey = layout ? `layout:${callbackKey}` : callbackKey;
340
+ const emittedKey = carries ? `${carries}:${callbackKey}` : callbackKey;
333
341
  let handlerName = output.emittedCallbacks.get(emittedKey);
334
342
  if (!handlerName) {
335
- handlerName = `${layout ? 'layout_callback_' : 'callback_'}${callbackKey}`;
343
+ handlerName = `${carries ? `${carries}_callback_` : 'callback_'}${callbackKey}`;
336
344
  output.emittedCallbacks.set(emittedKey, handlerName);
337
345
  output.handlers.push({
338
346
  kind: 'callback',
339
347
  name: handlerName,
340
- callback: lowerHandler(environment.callbacks.get(handlerExpression.name), { ...environment, layout }, state, output),
348
+ callback: lowerHandler(environment.callbacks.get(handlerExpression.name), { ...environment, ...carried }, state, output),
341
349
  });
342
350
  }
343
351
  return handlerName;
@@ -350,14 +358,14 @@ export function lowerEventHandler(attribute, output, environment, state) {
350
358
  output.handlers.push({
351
359
  kind: 'callback',
352
360
  name: handlerName,
353
- callback: lowerHandler(callbackProp.node, { ...callbackProp.environment, layout }, callbackProp.state, output),
361
+ callback: lowerHandler(callbackProp.node, { ...callbackProp.environment, ...carried }, callbackProp.state, output),
354
362
  });
355
363
  }
356
364
  else if (isFn(handlerExpression)) {
357
365
  output.handlers.push({
358
366
  kind: 'callback',
359
367
  name: handlerName,
360
- callback: lowerHandler(handlerExpression, { ...environment, layout }, state, output),
368
+ callback: lowerHandler(handlerExpression, { ...environment, ...carried }, state, output),
361
369
  });
362
370
  }
363
371
  else {
@@ -76,6 +76,10 @@ export class Out {
76
76
  panCount = 0;
77
77
  /** Every PanResponder a node spreads, lowered once each. */
78
78
  panResponders = [];
79
+ /** The hidden state naming the alert that is up, in an app that raises one. */
80
+ alertState = null;
81
+ /** Every Alert.alert lowered so far, whose dialogs are built under the root last. */
82
+ alertSites = [];
79
83
  /** The module's function components, by name, for inlining. */
80
84
  components;
81
85
  /** The parsed module, for the passes that scan it again. */
@@ -79,7 +79,7 @@ const CONVERSIONS = {
79
79
  'int64>float': 'LTOF',
80
80
  'int64>double': 'LTOD',
81
81
  };
82
- /** The event field each touch field, and what a <Dial> passes, reads. */
82
+ /** The event field each touch or scroll field, and what a <Dial> passes, reads. */
83
83
  const EVENT_FIELDS = {
84
84
  x: EventField.x,
85
85
  y: EventField.y,
@@ -87,6 +87,8 @@ const EVENT_FIELDS = {
87
87
  dy: EventField.dy,
88
88
  vx: EventField.vx,
89
89
  vy: EventField.vy,
90
+ scrollX: EventField.scrollX,
91
+ scrollY: EventField.scrollY,
90
92
  value: EventField.value,
91
93
  value_start: EventField.valueStart,
92
94
  };
@@ -210,7 +212,7 @@ export class Codegen {
210
212
  case 'event':
211
213
  return expression.field === 'changed_text'
212
214
  ? 'string'
213
- : ['vx', 'vy', 'value', 'value_start'].includes(expression.field)
215
+ : expression.type.kind === 'float'
214
216
  ? 'float'
215
217
  : 'int';
216
218
  case 'gesture':
@@ -1302,8 +1304,40 @@ export class Codegen {
1302
1304
  return;
1303
1305
  case 'updateVector':
1304
1306
  updateVector(this, statement, this.program.vectors);
1307
+ return;
1308
+ case 'scrollTo':
1309
+ this.scrollTo(statement);
1310
+ return;
1311
+ case 'dismissKeyboard':
1312
+ builder.abc('BLUR', 0);
1305
1313
  }
1306
1314
  }
1315
+ /**
1316
+ * Scrolls the ScrollView a ref is on, then keeps where it landed for the locals that read it.
1317
+ *
1318
+ * @param statement The call.
1319
+ */
1320
+ scrollTo(statement) {
1321
+ const { builder } = this;
1322
+ const handle = required(this.program.vectors.refNodes.get(statement.node), 'the node a scrollTo scrolls');
1323
+ const kept = statement.results?.map(() => builder.register('float'));
1324
+ this.scoped(() => {
1325
+ const node = builder.register('node');
1326
+ builder.abx('GET64', node.index, handle.index);
1327
+ if (statement.x || statement.y) {
1328
+ // An axis left out is NaN, which the engine keeps where it is.
1329
+ const axis = (value) => value ? this.valueAs(value, 'float') : this.load('float', NaN);
1330
+ const x = axis(statement.x);
1331
+ builder.abc('SCROLL', node.index, x.index, axis(statement.y).index);
1332
+ }
1333
+ if (kept) {
1334
+ const position = builder.consecutive(kept.map(() => 'float'));
1335
+ builder.abc('SCROLLAT', node.index, position[0].index);
1336
+ position.forEach((value, index) => builder.abc('MOVE', kept[index].index, value.index));
1337
+ }
1338
+ });
1339
+ statement.results?.forEach((name, index) => this.locals.set(name, { register: kept[index] }));
1340
+ }
1307
1341
  /**
1308
1342
  * A counted loop, its counter the one for its depth, so a loop inside it counts with another.
1309
1343
  *