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
@@ -39,22 +39,29 @@ export {
39
39
  Line,
40
40
  G,
41
41
  Arc,
42
- } from './components.js';
43
- export {Pressable} from './Pressable.js';
44
- export {Button} from './Button.js';
45
- export {TouchableOpacity} from './TouchableOpacity.js';
46
- export {FlatList} from './FlatList.js';
47
- export {ImageBackground} from './ImageBackground.js';
48
- export {SectionList} from './SectionList.js';
49
- export {updateVector, updateText, setKeyboardConfig} from './imperative.js';
50
- export {StyleSheet} from './StyleSheet.js';
51
- export {Platform} from './Platform.js';
52
- export {Dimensions, useWindowDimensions} from './Dimensions.js';
53
- export {AppRegistry} from './AppRegistry.js';
54
- export {Animated, useAnimatedValue} from './Animated.js';
55
- export {PanResponder} from './PanResponder.js';
56
- export {usePersistentState} from './usePersistentState.js';
57
- export {useHostValue} from './useHostValue.js';
58
- export {nativeModule, useNativeEvent} from './nativeModule.js';
59
- export {Easing} from './Easing.js';
60
- export {LayoutAnimation} from './LayoutAnimation.js';
42
+ } from './components.mjs';
43
+ export {Pressable} from './Pressable.mjs';
44
+ export {Button} from './Button.mjs';
45
+ export {TouchableOpacity} from './TouchableOpacity.mjs';
46
+ export {FlatList} from './FlatList.mjs';
47
+ export {ImageBackground} from './ImageBackground.mjs';
48
+ export {SectionList} from './SectionList.mjs';
49
+ export {
50
+ updateVector,
51
+ updateText,
52
+ scrollTo,
53
+ setKeyboardConfig,
54
+ } from './imperative.mjs';
55
+ export {StyleSheet} from './StyleSheet.mjs';
56
+ export {Platform} from './Platform.mjs';
57
+ export {Dimensions, useWindowDimensions} from './Dimensions.mjs';
58
+ export {AppRegistry} from './AppRegistry.mjs';
59
+ export {Alert} from './Alert.mjs';
60
+ export {Keyboard} from './Keyboard.mjs';
61
+ export {Animated, useAnimatedValue} from './Animated.mjs';
62
+ export {PanResponder} from './PanResponder.mjs';
63
+ export {usePersistentState} from './usePersistentState.mjs';
64
+ export {useHostValue} from './useHostValue.mjs';
65
+ export {nativeModule, useNativeEvent} from './nativeModule.mjs';
66
+ export {Easing} from './Easing.mjs';
67
+ export {LayoutAnimation} from './LayoutAnimation.mjs';
@@ -0,0 +1,85 @@
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
+ /** Duration when a config gives none, as in RN. */
17
+ export const DEFAULT_DURATION_MS = 300;
18
+ /** RN-compatible animation type tokens. */
19
+ export const Types = {
20
+ spring: 'spring',
21
+ linear: 'linear',
22
+ easeInEaseOut: 'easeInEaseOut',
23
+ easeIn: 'easeIn',
24
+ easeOut: 'easeOut',
25
+ keyboard: 'keyboard',
26
+ };
27
+ /** RN-compatible animated-property tokens (accepted for API parity; the engine tweens position). */
28
+ export const Properties = {
29
+ opacity: 'opacity',
30
+ scaleX: 'scaleX',
31
+ scaleY: 'scaleY',
32
+ scaleXY: 'scaleXY',
33
+ };
34
+ /** Maps an RN animation-type token to an engine easing token. */
35
+ function easingForType(type) {
36
+ switch (type) {
37
+ case Types.linear:
38
+ return 'linear';
39
+ case Types.easeIn:
40
+ return 'easeIn';
41
+ case Types.easeOut:
42
+ return 'easeOut';
43
+ case Types.easeInEaseOut:
44
+ case Types.keyboard:
45
+ default:
46
+ return 'easeInOut';
47
+ }
48
+ }
49
+ /**
50
+ * Reduces an RN LayoutAnimation config ({ duration, create, update, delete }) to the engine's flat
51
+ * config. The engine tweens the *position transition*, which is RN's `update`; create/delete opacity
52
+ * are accepted for parity but not separately animated.
53
+ */
54
+ export function toEngineConfig(config) {
55
+ const options = config || {};
56
+ const duration = typeof options.duration === 'number'
57
+ ? options.duration
58
+ : DEFAULT_DURATION_MS;
59
+ const update = options.update || {};
60
+ const type = update.type || options.type || Types.easeInEaseOut;
61
+ if (type === Types.spring) {
62
+ return { type: 'spring', duration };
63
+ }
64
+ return { type: 'timing', duration, easing: easingForType(type) };
65
+ }
66
+ /** Builds an RN-shaped config (duration + create/update/delete) from a type + creation property. */
67
+ export function create(duration, type = Types.easeInEaseOut, creationProp = Properties.opacity) {
68
+ return {
69
+ duration,
70
+ create: { type, property: creationProp },
71
+ update: { type },
72
+ delete: { type, property: creationProp },
73
+ };
74
+ }
75
+ /** RN-compatible preset configs. */
76
+ export const Presets = {
77
+ easeInEaseOut: create(300, Types.easeInEaseOut, Properties.opacity),
78
+ linear: create(500, Types.linear, Properties.opacity),
79
+ spring: {
80
+ duration: 700,
81
+ create: { type: Types.linear, property: Properties.opacity },
82
+ update: { type: Types.spring, springDamping: 0.4 },
83
+ delete: { type: Types.linear, property: Properties.opacity },
84
+ },
85
+ };
@@ -13,20 +13,14 @@
13
13
  * See the License for the specific language governing permissions and
14
14
  * limitations under the License.
15
15
  */
16
-
17
16
  // Shared row handling for the list wrappers (<FlatList>, <SectionList>). Both turn a render callback's
18
17
  // result into a keyed child of one <ScrollView>, and the awkward cases are the same for both: a row
19
18
  // that renders to nothing, and a row that isn't an element at all.
20
- import {cloneElement} from 'react';
21
-
19
+ import { cloneElement } from 'react';
22
20
  /** True for a render result that puts nothing on screen — the `{cond && <Row/>}` of a row callback. */
23
- export const rendersNothing = node =>
24
- node === null || node === undefined || node === false;
25
-
21
+ export const rendersNothing = (node) => node === null || node === undefined || node === false;
26
22
  /** True for something cloneElement can key — a React element, as opposed to a string/number row. */
27
- export const isElement = node =>
28
- node !== null && typeof node === 'object' && node.$$typeof !== undefined;
29
-
23
+ export const isElement = (node) => node !== null && typeof node === 'object' && node.$$typeof !== undefined;
30
24
  /**
31
25
  * Appends one rendered row to `children`, keyed, or drops it if it rendered nothing.
32
26
  *
@@ -38,17 +32,14 @@ export const isElement = node =>
38
32
  * can actually carry one. `keyExtractor` is the app's code — running it for a row that rendered
39
33
  * nothing, or for a raw string that cannot be cloned, is both wasted work on the commit path and a
40
34
  * side effect the app never asked for. Passing the key by value invites exactly that, and did.
41
- *
42
- * @param {Array} children The child list being built.
43
- * @param {*} node Whatever the render callback returned.
44
- * @param {(element: object) => string} keyFor Builds the React key, given the keyable element.
45
35
  */
46
36
  export function pushKeyedChild(children, node, keyFor) {
47
- if (rendersNothing(node)) return;
48
- if (!isElement(node)) {
49
- children.push(node);
50
- return;
51
- }
52
- const key = keyFor(node);
53
- children.push(node.key === key ? node : cloneElement(node, {key}));
37
+ if (rendersNothing(node))
38
+ return;
39
+ if (!isElement(node)) {
40
+ children.push(node);
41
+ return;
42
+ }
43
+ const key = keyFor(node);
44
+ children.push(node.key === key ? node : cloneElement(node, { key }));
54
45
  }
@@ -13,14 +13,11 @@
13
13
  * See the License for the specific language governing permissions and
14
14
  * limitations under the License.
15
15
  */
16
-
17
16
  // The named colors every path accepts, as ARGB8888 with their CSS values. Keys are lowercase; callers
18
17
  // lowercase the name first. The bridge's k_named_colors table (native_ui_bridge.c) must list the same entries.
19
18
  // No prototype, so `name in NAMED_COLORS` never finds `toString` and friends.
20
-
21
19
  /** @type {Readonly<Record<string, number>>} */
22
- export const NAMED_COLORS = Object.freeze(
23
- Object.assign(Object.create(null), {
20
+ export const NAMED_COLORS = Object.freeze(Object.assign(Object.create(null), {
24
21
  transparent: 0x00000000,
25
22
  black: 0xff000000,
26
23
  white: 0xffffffff,
@@ -33,5 +30,4 @@ export const NAMED_COLORS = Object.freeze(
33
30
  cyan: 0xff00ffff,
34
31
  magenta: 0xffff00ff,
35
32
  orange: 0xffffa500,
36
- }),
37
- );
33
+ }));
@@ -0,0 +1,371 @@
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
+ // nativeModule — a module the firmware provides in C, declared by a TypeScript interface of its methods and events.
17
+ //
18
+ // Flow B (AOT): the compiler reads the interface and turns each method called into a native import, which the
19
+ // runtime matches with what the firmware registers when it loads the package. Each useNativeEvent is a handler the
20
+ // runtime runs when the firmware posts the event, while its component is mounted.
21
+ //
22
+ // Flow A: the bundler reads the same interface and passes each method's and event's signature, since the types are
23
+ // gone by then. Each is looked up in the firmware's natives (the bridge's __erNative) here, as the app loads. A method
24
+ // calls the firmware through the bridge, which converts the arguments by the signature, and the bridge hands each
25
+ // event the firmware posts to __erNativeEvent, which calls its subscribers.
26
+ //
27
+ // A record passes the bridge as its fields one by one, in the order the signature names them, and is built again from
28
+ // them here: a result, and an event's value.
29
+ //
30
+ // The simulators: the bundler also passes the module's mock, which stands in for the firmware. Its values are
31
+ // converted as the bridge converts them, so the app sees what it would on a board. A mock that posts events is a
32
+ // function, which is given `emit` and returns the methods.
33
+ //
34
+ // nativeModule.optional: a module only some boards have. Its `available` is whether the firmware has every method
35
+ // and event, and in the simulators whether it has a mock.
36
+ import { useEffect, useRef } from 'react';
37
+ // The values an int64 holds, which it wraps around.
38
+ const INT64_SPAN = 2 ** 64;
39
+ // What a value becomes in C, by its signature code: as the bridge converts it. An int64 is truncated and wraps, and
40
+ // comes back as the nearest number; a string ends at its first NUL.
41
+ const CONVERSIONS = {
42
+ i: value => value | 0,
43
+ b: value => !!value,
44
+ f: value => Math.fround(value),
45
+ l: value => {
46
+ const whole = Math.trunc(Number(value));
47
+ if (!Number.isFinite(whole)) {
48
+ return 0;
49
+ }
50
+ // -0 is 0 in C.
51
+ if (whole >= -INT64_SPAN / 2 && whole < INT64_SPAN / 2) {
52
+ return whole || 0;
53
+ }
54
+ // Past 2^63 a number is a multiple of 2^11, so this is exact.
55
+ const wrapped = whole - Math.floor(whole / INT64_SPAN) * INT64_SPAN;
56
+ return wrapped >= INT64_SPAN / 2 ? wrapped - INT64_SPAN : wrapped;
57
+ },
58
+ s: value => String(value).split('\0')[0],
59
+ v: () => undefined,
60
+ };
61
+ // Each module's events, by event name: its values' shapes and the handlers subscribed to it, or why it can't be used.
62
+ const MODULE_EVENTS = new WeakMap();
63
+ // The handlers subscribed to each of the firmware's events, by its index in the natives, as the bridge posts them.
64
+ // An app-only hot reload evaluates the app again in this context, so every evaluation's modules share these: a post
65
+ // reaches each mounted subscriber, whichever evaluation it came from.
66
+ const HANDLERS_BY_INDEX = new Map();
67
+ // Calls an event's handlers with its values; a handler that unsubscribes another doesn't skip it in this post.
68
+ function deliver(handlers, values) {
69
+ for (const handler of [...handlers]) {
70
+ handler(...values);
71
+ }
72
+ }
73
+ // The bridge posts each event here: the event's index in the natives, and its values.
74
+ function installDispatcher() {
75
+ globalThis.__erNativeEvent = (index, values) => {
76
+ const handlers = HANDLERS_BY_INDEX.get(index);
77
+ if (handlers) {
78
+ deliver(handlers, values);
79
+ }
80
+ };
81
+ }
82
+ // A value's shape, read from a signature at `at`: its code, or a record's fields in order, each [name, shape].
83
+ function readShape(signature, at) {
84
+ if (signature[at] !== '{') {
85
+ return { shape: signature[at], next: at + 1 };
86
+ }
87
+ const fields = [];
88
+ let next = at + 1;
89
+ for (;;) {
90
+ const colon = signature.indexOf(':', next);
91
+ const field = readShape(signature, colon + 1);
92
+ fields.push([signature.slice(next, colon), field.shape]);
93
+ next = field.next + 1;
94
+ if (signature[field.next] === '}') {
95
+ return { shape: fields, next };
96
+ }
97
+ }
98
+ }
99
+ // A signature's result, null for none, and its parameters, as shapes.
100
+ function shapesOf(signature) {
101
+ let result = null;
102
+ let next = 1;
103
+ if (signature[0] !== 'v') {
104
+ ({ shape: result, next } = readShape(signature, 0));
105
+ }
106
+ const parameters = [];
107
+ for (next++; next < signature.length;) {
108
+ const parameter = readShape(signature, next);
109
+ parameters.push(parameter.shape);
110
+ next = parameter.next;
111
+ }
112
+ return { result, parameters };
113
+ }
114
+ const isRecord = (shape) => Array.isArray(shape);
115
+ // A value's fields one by one, into `cells`, as the bridge takes them; each converted as it converts them when
116
+ // `convert`. `what` names the value for errors.
117
+ function flatten(shape, value, what, cells, convert) {
118
+ if (!isRecord(shape)) {
119
+ cells.push(convert ? CONVERSIONS[shape](value) : value);
120
+ return;
121
+ }
122
+ if (typeof value !== 'object' || value === null) {
123
+ throw new TypeError(`${what} is a record, not ${value === null ? 'null' : typeof value}`);
124
+ }
125
+ for (const [field, fieldShape] of shape) {
126
+ if (!(field in value)) {
127
+ throw new TypeError(`${what} has no field ${field}`);
128
+ }
129
+ flatten(fieldShape, value[field], `${what}.${field}`, cells, convert);
130
+ }
131
+ }
132
+ // A value built from its fields' values, from `cells[at]`.
133
+ function build(shape, cells, at) {
134
+ if (!isRecord(shape)) {
135
+ return { value: cells[at], next: at + 1 };
136
+ }
137
+ const record = {};
138
+ let next = at;
139
+ for (const [field, fieldShape] of shape) {
140
+ const built = build(fieldShape, cells, next);
141
+ record[field] = built.value;
142
+ next = built.next;
143
+ }
144
+ return { value: record, next };
145
+ }
146
+ // Values built from the fields' values the bridge passes, a record's one by one.
147
+ function built(shapes, cells) {
148
+ const values = [];
149
+ let next = 0;
150
+ for (const shape of shapes) {
151
+ const value = build(shape, cells, next);
152
+ values.push(value.value);
153
+ next = value.next;
154
+ }
155
+ return values;
156
+ }
157
+ // Values passed through C: each converted as the bridge converts it, a record built again from its fields.
158
+ function converted(shape, value, what) {
159
+ const cells = [];
160
+ flatten(shape, value, what, cells, true);
161
+ return build(shape, cells, 0).value;
162
+ }
163
+ // The fields' values an event's values are, converted by its signature, as the bridge posts them.
164
+ function convertedValues(event, values) {
165
+ const { parameters } = event.shapes;
166
+ if (values.length !== parameters.length) {
167
+ throw new TypeError(`${event.qualifiedName} is posted with ${parameters.length} value${parameters.length === 1 ? '' : 's'}, ` +
168
+ `not ${values.length}`);
169
+ }
170
+ const cells = [];
171
+ parameters.forEach((shape, position) => flatten(shape, values[position], `${event.qualifiedName}'s value`, cells, true));
172
+ return cells;
173
+ }
174
+ // A mock's method, called as the bridge calls the firmware's. `calls` counts the mock's calls running now.
175
+ function mockMethod(implementation, name, method, signature, calls) {
176
+ const qualifiedName = `${name}.${method}`;
177
+ const found = implementation[method];
178
+ // A method a plain object inherits, like toString, isn't the mock's.
179
+ if (typeof found !== 'function' ||
180
+ found === Object.prototype[method]) {
181
+ throw new Error(`the mock of native module "${name}" has no ${method}()`);
182
+ }
183
+ const { result, parameters } = shapesOf(signature);
184
+ return (...callArguments) => {
185
+ if (callArguments.length !== parameters.length) {
186
+ throw new TypeError(`${qualifiedName}() takes ${parameters.length} argument${parameters.length === 1 ? '' : 's'}, ` +
187
+ `not ${callArguments.length}`);
188
+ }
189
+ const convertedArguments = callArguments.map((argument, position) => converted(parameters[position], argument, `${qualifiedName}()'s argument`));
190
+ calls.running++;
191
+ try {
192
+ const returned = found.apply(implementation, convertedArguments);
193
+ return result === null
194
+ ? undefined
195
+ : converted(result, returned, `${qualifiedName}()'s result`);
196
+ }
197
+ finally {
198
+ calls.running--;
199
+ }
200
+ };
201
+ }
202
+ // A method that calls the firmware through the bridge. A record goes as its fields, and comes back as an array of
203
+ // them; without one, the bridge takes the arguments as they are.
204
+ function bridgeMethod(host, index, name, method, signature) {
205
+ const qualifiedName = `${name}.${method}`;
206
+ const { result, parameters } = shapesOf(signature);
207
+ if (!isRecord(result) && !parameters.some(isRecord)) {
208
+ return host.call.bind(host, index);
209
+ }
210
+ return (...callArguments) => {
211
+ if (callArguments.length !== parameters.length) {
212
+ throw new TypeError(`${qualifiedName}() takes ${parameters.length} argument${parameters.length === 1 ? '' : 's'}, ` +
213
+ `not ${callArguments.length}`);
214
+ }
215
+ const cells = [];
216
+ parameters.forEach((shape, position) => flatten(shape, callArguments[position], `${qualifiedName}()'s argument`, cells, false));
217
+ const returned = host.call(index, ...cells);
218
+ return isRecord(result)
219
+ ? build(result, returned, 0).value
220
+ : returned;
221
+ };
222
+ }
223
+ // Where the firmware has each of a module's methods and events, by name: -1 for one it doesn't have.
224
+ function lookUp(host, name, version, signatures, finder) {
225
+ const indices = new Map();
226
+ for (const member of Object.keys(signatures)) {
227
+ const signature = signatures[member];
228
+ if (typeof signature === 'string') {
229
+ indices.set(member, host ? host[finder](`${name}.${member}`, version, signature) : -1);
230
+ }
231
+ }
232
+ return indices;
233
+ }
234
+ // The module nativeModule() and nativeModule.optional() return. An optional module that isn't there has methods
235
+ // that throw, as a call to one stops the app in Flow B, and events that never arrive.
236
+ function declareModule(name, version, signatures, mock, optional) {
237
+ if (!signatures) {
238
+ throw new Error(`native module "${name}" has no signatures; build the app with the embedded-react CLI, which reads its interface`);
239
+ }
240
+ if (mock === null && !optional) {
241
+ throw new Error(`native module "${name}" has no mock for the simulator; add ${name}.mock.ts beside its interface`);
242
+ }
243
+ const host = globalThis.__erNative;
244
+ const module = {};
245
+ const events = new Map();
246
+ MODULE_EVENTS.set(module, { name, events });
247
+ // On a board, every method and event is looked up as the app loads; in the simulators, the mock is the firmware.
248
+ const onBoard = mock === undefined;
249
+ const methodIndices = onBoard
250
+ ? lookUp(host, name, version, signatures.methods, 'find')
251
+ : new Map();
252
+ const eventIndices = onBoard
253
+ ? lookUp(host, name, version, signatures.events, 'findEvent')
254
+ : new Map();
255
+ const missing = [...eventIndices, ...methodIndices].find(([, index]) => index < 0);
256
+ if (missing && !optional) {
257
+ const [member] = missing;
258
+ const signature = eventIndices.has(member)
259
+ ? signatures.events[member]
260
+ : signatures.methods[member];
261
+ throw new Error(`missing native module: ${name}.${member} (version ${version}, signature "${signature}")`);
262
+ }
263
+ const available = mock !== null && !missing;
264
+ if (optional) {
265
+ Object.defineProperty(module, 'available', {
266
+ value: available,
267
+ enumerable: true,
268
+ });
269
+ }
270
+ // The events first, so a mock is given an emit that knows them.
271
+ for (const event of Object.keys(signatures.events)) {
272
+ const signature = signatures.events[event];
273
+ const qualifiedName = `${name}.${event}`;
274
+ if (typeof signature !== 'string') {
275
+ events.set(event, { qualifiedName, reason: signature.reason });
276
+ continue;
277
+ }
278
+ const shapes = shapesOf(signature);
279
+ if (!onBoard || !available) {
280
+ events.set(event, { qualifiedName, shapes, handlers: new Set() });
281
+ continue;
282
+ }
283
+ const index = eventIndices.get(event);
284
+ if (!HANDLERS_BY_INDEX.has(index)) {
285
+ HANDLERS_BY_INDEX.set(index, new Set());
286
+ }
287
+ events.set(event, {
288
+ qualifiedName,
289
+ shapes,
290
+ handlers: HANDLERS_BY_INDEX.get(index),
291
+ });
292
+ installDispatcher();
293
+ }
294
+ // A mock's emit posts as the firmware does, so it is refused while one of the mock's methods runs.
295
+ let implementation = mock;
296
+ const calls = { running: 0 };
297
+ if (typeof mock === 'function') {
298
+ const emit = (event, ...values) => {
299
+ const entry = events.get(event);
300
+ if (!entry || !entry.shapes) {
301
+ throw new Error(entry
302
+ ? `${entry.qualifiedName} ${entry.reason}`
303
+ : `native module "${name}" has no event ${event}`);
304
+ }
305
+ const cells = convertedValues(entry, values);
306
+ if (calls.running) {
307
+ return false;
308
+ }
309
+ deliver(entry.handlers, cells);
310
+ return true;
311
+ };
312
+ implementation = mock(emit);
313
+ }
314
+ for (const method of Object.keys(signatures.methods)) {
315
+ const signature = signatures.methods[method];
316
+ const qualifiedName = `${name}.${method}`;
317
+ if (typeof signature !== 'string') {
318
+ module[method] = () => {
319
+ throw new Error(`${qualifiedName} ${signature.reason}`);
320
+ };
321
+ continue;
322
+ }
323
+ if (!available) {
324
+ module[method] = () => {
325
+ throw new Error(`missing native module: ${qualifiedName} (the optional module "${name}" isn't available; ` +
326
+ 'read its available before calling it)');
327
+ };
328
+ continue;
329
+ }
330
+ if (implementation) {
331
+ module[method] = mockMethod(implementation, name, method, signature, calls);
332
+ continue;
333
+ }
334
+ module[method] = bridgeMethod(host, methodIndices.get(method), name, method, signature);
335
+ }
336
+ return module;
337
+ }
338
+ // `name` is the module's name, as the firmware registers it. The bundler passes `signatures`. In the simulators,
339
+ // `mock` is the module's mock (its default export), or null when it has none.
340
+ export function nativeModule(name, version, signatures, mock) {
341
+ return declareModule(name, version, signatures, mock, false);
342
+ }
343
+ // A module only some boards have: it loads without the firmware's, and its `available` says whether it is there.
344
+ // In the simulators, it is there when it has a mock. Takes what nativeModule() takes.
345
+ nativeModule.optional = (name, version, signatures, mock) => declareModule(name, version, signatures, mock, true);
346
+ // useNativeEvent — runs `handler` with an event's values each time the firmware posts it, while the component is
347
+ // mounted. The handler may change from render to render; the latest one runs.
348
+ // A record among the values is an object of its fields.
349
+ export function useNativeEvent(module, event, handler) {
350
+ const known = MODULE_EVENTS.get(module);
351
+ if (!known) {
352
+ throw new Error('useNativeEvent() takes a native module, as nativeModule() returns it');
353
+ }
354
+ const entry = known.events.get(event);
355
+ if (!entry) {
356
+ throw new Error(`native module "${known.name}" has no event ${event}`);
357
+ }
358
+ if (!entry.shapes) {
359
+ throw new Error(`${entry.qualifiedName} ${entry.reason}`);
360
+ }
361
+ const latest = useRef(handler);
362
+ latest.current = handler;
363
+ useEffect(() => {
364
+ // Handlers are given the fields' values; a record is built again from its own.
365
+ const subscriber = (...cells) => latest.current(...built(entry.shapes.parameters, cells));
366
+ entry.handlers.add(subscriber);
367
+ return () => {
368
+ entry.handlers.delete(subscriber);
369
+ };
370
+ }, [entry]);
371
+ }
@@ -0,0 +1,57 @@
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
+ // Separates a style object into the static props (passed straight to the node) and the animated
17
+ // bindings (Animated.Value / interpolation, bound to the node's prop so the engine drives them).
18
+ // Pure (no NativeUI), so it's unit-testable. An animated entry is anything with an `__animated`
19
+ // marker — `transform: [{ translateX: value }]` entries are handled too (scale binds both axes).
20
+ import { flattenStyle } from '../props.mjs';
21
+ export function splitAnimatedStyle(style) {
22
+ const staticStyle = {};
23
+ const bindings = [];
24
+ const flat = {};
25
+ flattenStyle(style, flat);
26
+ for (const key in flat) {
27
+ const value = flat[key];
28
+ if (key === 'transform' && Array.isArray(value)) {
29
+ const staticTransform = [];
30
+ for (const entry of value) {
31
+ const axis = Object.keys(entry)[0];
32
+ const axisValue = entry[axis];
33
+ if (axisValue && axisValue.__animated) {
34
+ if (axis === 'scale') {
35
+ bindings.push({ prop: 'scaleX', value: axisValue });
36
+ bindings.push({ prop: 'scaleY', value: axisValue });
37
+ }
38
+ else {
39
+ bindings.push({ prop: axis, value: axisValue });
40
+ }
41
+ }
42
+ else {
43
+ staticTransform.push(entry);
44
+ }
45
+ }
46
+ if (staticTransform.length > 0)
47
+ staticStyle.transform = staticTransform;
48
+ }
49
+ else if (value && value.__animated) {
50
+ bindings.push({ prop: key, value });
51
+ }
52
+ else {
53
+ staticStyle[key] = value;
54
+ }
55
+ }
56
+ return { staticStyle, bindings };
57
+ }