embedded-react 0.20.0 → 0.21.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 (74) hide show
  1. package/NOTICE +5 -0
  2. package/README.md +1 -0
  3. package/aot/app-file-loader.mjs +116 -0
  4. package/aot/compile.mjs +16 -46
  5. package/aot/compiler/animations.mjs +299 -57
  6. package/aot/compiler/boot.mjs +27 -2
  7. package/aot/compiler/check.mjs +61 -9
  8. package/aot/compiler/collect.mjs +516 -136
  9. package/aot/compiler/contexts.mjs +391 -0
  10. package/aot/compiler/control-flow.mjs +276 -117
  11. package/aot/compiler/custom-hooks.mjs +686 -0
  12. package/aot/compiler/elements/button.mjs +182 -0
  13. package/aot/compiler/elements/image-background.mjs +76 -0
  14. package/aot/compiler/elements/image.mjs +2 -1
  15. package/aot/compiler/elements/props.mjs +38 -3
  16. package/aot/compiler/elements/rewrite.mjs +118 -0
  17. package/aot/compiler/elements/section-list.mjs +370 -0
  18. package/aot/compiler/expressions.mjs +1351 -97
  19. package/aot/compiler/handlers.mjs +1761 -365
  20. package/aot/compiler/helper-values.mjs +312 -0
  21. package/aot/compiler/ir/nodes.mjs +40 -1
  22. package/aot/compiler/ir/reads.mjs +206 -5
  23. package/aot/compiler/ir/text.mjs +5 -1
  24. package/aot/compiler/ir/types.mjs +12 -0
  25. package/aot/compiler/kept-states.mjs +177 -0
  26. package/aot/compiler/list-items.mjs +226 -0
  27. package/aot/compiler/list-order.mjs +586 -0
  28. package/aot/compiler/list-split.mjs +259 -0
  29. package/aot/compiler/loops.mjs +582 -0
  30. package/aot/compiler/lower.mjs +191 -53
  31. package/aot/compiler/native-files.mjs +439 -0
  32. package/aot/compiler/native-header.mjs +335 -0
  33. package/aot/compiler/native-modules.mjs +1173 -0
  34. package/aot/compiler/nodes.mjs +28 -22
  35. package/aot/compiler/options.mjs +3 -2
  36. package/aot/compiler/out.mjs +14 -1
  37. package/aot/compiler/package/animations.mjs +133 -23
  38. package/aot/compiler/package/assemble.mjs +2 -4
  39. package/aot/compiler/package/bytecode.mjs +37 -8
  40. package/aot/compiler/package/checks.mjs +4 -0
  41. package/aot/compiler/package/codegen.mjs +870 -31
  42. package/aot/compiler/package/enums.mjs +10 -0
  43. package/aot/compiler/package/format.mjs +12 -1
  44. package/aot/compiler/package/lower.mjs +658 -161
  45. package/aot/compiler/package/string-caps.mjs +515 -0
  46. package/aot/compiler/package/tables.mjs +24 -0
  47. package/aot/compiler/package/writer.mjs +22 -0
  48. package/aot/compiler/parse.mjs +3 -1
  49. package/aot/compiler/record-shapes.mjs +246 -0
  50. package/aot/compiler/records.mjs +654 -0
  51. package/aot/compiler/reducers.mjs +272 -0
  52. package/aot/compiler/static-eval.mjs +315 -7
  53. package/aot/compiler/style-text.mjs +18 -3
  54. package/aot/compiler/svg.mjs +7 -4
  55. package/aot/compiler/switch-cases.mjs +198 -0
  56. package/aot/compiler/tagged-records.mjs +450 -0
  57. package/aot/compiler/typing.mjs +307 -0
  58. package/aot/compiler/updaters.mjs +320 -0
  59. package/aot/compiler/window-dimensions.mjs +94 -0
  60. package/aot/compiler/worked-values.mjs +319 -0
  61. package/aot/demo-file.mjs +30 -0
  62. package/aot/style-map.mjs +50 -2
  63. package/build.mjs +9 -1
  64. package/cli.mjs +44 -1
  65. package/hotreload/pack-split.mjs +29 -40
  66. package/pack-container.mjs +9 -1
  67. package/package.json +1 -1
  68. package/sim/embedded-react.wasm +0 -0
  69. package/sim-server.mjs +22 -22
  70. package/src/embedded-react/Dimensions.js +37 -0
  71. package/src/embedded-react/SectionList.js +1 -3
  72. package/src/embedded-react/index.d.ts +83 -3
  73. package/src/embedded-react/index.js +2 -0
  74. package/src/embedded-react/nativeModule.js +462 -0
@@ -36,7 +36,7 @@
36
36
  import {createRequire} from 'node:module';
37
37
  import {pathToFileURL} from 'node:url';
38
38
  import {basename, dirname, resolve, relative} from 'node:path';
39
- import {existsSync, readFileSync, statSync} from 'node:fs';
39
+ import {existsSync, statSync} from 'node:fs';
40
40
 
41
41
  const require = createRequire(import.meta.url);
42
42
 
@@ -110,40 +110,40 @@ export async function bundleVendorSource({libSrc, nodePaths}) {
110
110
 
111
111
  /**
112
112
  * Build an asset-discovering esbuild plugin shared with the monolithic packer's behavior: image/font/svg
113
- * imports become bare string names (the bytes live in the ERPK pack), and — when persist is on — the app's
114
- * own source gets the useState→persist transform so state survives a live reload.
113
+ * imports become bare string names (the bytes live in the ERPK pack). The app's own source gives its native modules
114
+ * their signatures and, when persist is on, gets the useState→persist transform so state survives a live reload.
115
115
  */
116
- function makeAssetPlugin({images, fonts, persistHooks, projectRoot}) {
116
+ function makeAssetPlugin({images, fonts, persist, projectRoot}) {
117
117
  const assetName = filePath => basename(filePath).replace(/\.[^.]+$/, '');
118
118
  return {
119
119
  name: 'embedded-react-assets',
120
120
  async setup(build) {
121
121
  const {registerSvgVectorLoader} =
122
122
  await import('../assets/svg-loader.mjs');
123
- if (persistHooks) {
124
- build.onLoad({filter: /\.(jsx?|tsx?)$/}, args => {
125
- const {transformPersist, shouldPersist, normalizedProjectRoot} =
126
- persistHooks;
127
- if (!shouldPersist(args.path, normalizedProjectRoot))
128
- return undefined;
129
- try {
130
- const loader = args.path.endsWith('.tsx')
131
- ? 'tsx'
132
- : args.path.endsWith('.ts')
133
- ? 'ts'
134
- : 'jsx';
135
- return {
136
- contents: transformPersist(
137
- readFileSync(args.path, 'utf8'),
138
- relative(projectRoot, args.path).replace(/\\/g, '/'),
139
- ),
140
- loader,
141
- };
142
- } catch (error) {
143
- return {errors: [{text: `persist transform: ${error.message}`}]};
144
- }
145
- });
146
- }
123
+ const {shouldPersist, transformPersist} =
124
+ await import('../persist-transform.mjs');
125
+ const {loadAppFile, loadDependencyFile} =
126
+ await import('../aot/app-file-loader.mjs');
127
+ const normalizedProjectRoot = projectRoot.replace(/\\/g, '/');
128
+ build.onLoad({filter: /\.(jsx?|tsx?)$/}, async args => {
129
+ if (!shouldPersist(args.path, normalizedProjectRoot)) {
130
+ return loadDependencyFile(args.path);
131
+ }
132
+ try {
133
+ return await loadAppFile(
134
+ args.path,
135
+ persist
136
+ ? source =>
137
+ transformPersist(
138
+ source,
139
+ relative(projectRoot, args.path).replace(/\\/g, '/'),
140
+ )
141
+ : undefined,
142
+ );
143
+ } catch (error) {
144
+ return {errors: [{text: `persist transform: ${error.message}`}]};
145
+ }
146
+ });
147
147
  build.onLoad({filter: /\.(png|jpe?g|webp|gif|bmp)$/i}, args => {
148
148
  const name = assetName(args.path);
149
149
  images.set(name, args.path);
@@ -181,22 +181,11 @@ export async function bundleAppSource({
181
181
  const images = new Map();
182
182
  const fonts = new Map();
183
183
 
184
- let persistHooks = null;
185
- if (persist) {
186
- const {transformPersist, shouldPersist} =
187
- await import('../persist-transform.mjs');
188
- persistHooks = {
189
- transformPersist,
190
- shouldPersist,
191
- normalizedProjectRoot: projectRoot.replace(/\\/g, '/'),
192
- };
193
- }
194
-
195
184
  const result = await esbuild.build({
196
185
  ...esbuildCommon(nodePaths),
197
186
  entryPoints: [entry],
198
187
  external: VENDOR_EXTERNALS,
199
- plugins: [makeAssetPlugin({images, fonts, persistHooks, projectRoot})],
188
+ plugins: [makeAssetPlugin({images, fonts, persist, projectRoot})],
200
189
  });
201
190
  return {source: result.outputFiles[0].text, images, fonts};
202
191
  }
@@ -48,6 +48,8 @@ import {emitAssetPack} from './assets/emit-pack.mjs';
48
48
  import {emitContainer} from './assets/emit-container.mjs';
49
49
  import {registerSvgVectorLoader} from './assets/svg-loader.mjs';
50
50
  import {findCompileBin, compileBinHelp} from './compile-bin.mjs';
51
+ import {loadAppFile, loadDependencyFile} from './aot/app-file-loader.mjs';
52
+ import {demoFile} from './aot/demo-file.mjs';
51
53
 
52
54
  // QuickJS release the bytecode targets — MUST match the FetchContent pin in
53
55
  // bridges/quickjs/CMakeLists.txt and ER_QUICKJS_TAG in er_runtime.c. The loader rejects a mismatch.
@@ -63,7 +65,7 @@ const distDir = resolve(here, 'dist');
63
65
 
64
66
  const demo = process.argv[2] || process.env.DEMO || 'thermostat';
65
67
  const demoDir = resolve(demosDir, demo);
66
- const entry = resolve(demoDir, 'index.jsx');
68
+ const entry = demoFile(demoDir, 'index');
67
69
  if (!existsSync(entry)) {
68
70
  const available = existsSync(demosDir)
69
71
  ? readdirSync(demosDir, {withFileTypes: true})
@@ -88,6 +90,12 @@ const fonts = new Map(); // family -> path
88
90
  const assetPlugin = {
89
91
  name: 'embedded-react-assets',
90
92
  setup(pluginBuild) {
93
+ // The demo's own files give its native modules their signatures, and so do a package's.
94
+ pluginBuild.onLoad({filter: /\.(jsx?|tsx?)$/}, args =>
95
+ args.path.startsWith(demoDir)
96
+ ? loadAppFile(args.path)
97
+ : loadDependencyFile(args.path),
98
+ );
91
99
  pluginBuild.onLoad({filter: /\.(png|jpe?g|webp|gif|bmp)$/i}, args => {
92
100
  const name = basename(args.path).replace(/\.[^.]+$/, '');
93
101
  images.set(name, args.path);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "embedded-react",
3
- "version": "0.20.0",
3
+ "version": "0.21.0",
4
4
  "type": "module",
5
5
  "description": "React Native-style component package + reconciler that drives the embedded-react C engine through the QuickJS NativeUI bridge (Flow A).",
6
6
  "license": "Apache-2.0",
Binary file
package/sim-server.mjs CHANGED
@@ -53,6 +53,8 @@ const {registerSvgVectorLoader} = await import(
53
53
  const {transformPersist, shouldPersist} = await import(
54
54
  pathToFileURL(resolve(HERE, 'persist-transform.mjs')).href
55
55
  );
56
+ const {loadAppFile, loadDependencyFile} =
57
+ await import('./aot/app-file-loader.mjs');
56
58
 
57
59
  const REACT_PIN = Object.fromEntries(
58
60
  ['react', 'react-reconciler', 'scheduler']
@@ -194,29 +196,27 @@ function createBundle({
194
196
  images.clear();
195
197
  fonts.clear();
196
198
  });
197
- pluginBuild.onLoad({filter: /\.(jsx?|tsx?)$/}, loadArgs => {
198
- // Transform ONLY the app's own source — never dependencies (see shouldPersist: excluding
199
- // node_modules is what stops the library's usePersistentState being rewritten to call itself).
200
- if (
201
- !persist ||
202
- !shouldPersist(loadArgs.path, projectRootNormalized)
203
- )
204
- return undefined;
199
+ pluginBuild.onLoad({filter: /\.(jsx?|tsx?)$/}, async loadArgs => {
200
+ // Only the app's own source — never dependencies (see shouldPersist: excluding node_modules is what
201
+ // stops the library's usePersistentState being rewritten to call itself). Native modules get their
202
+ // signatures and mocks, and with persist on, useState persists. A package's native modules get theirs too.
203
+ if (!shouldPersist(loadArgs.path, projectRootNormalized))
204
+ return loadDependencyFile(loadArgs.path, {mocks: true});
205
205
  try {
206
- // Match the esbuild loader to the source extension so TS type syntax (preserved by the
207
- // persist transform) is stripped: .tsx → tsx, .ts → ts, .jsx/.js → jsx.
208
- const loader = loadArgs.path.endsWith('.tsx')
209
- ? 'tsx'
210
- : loadArgs.path.endsWith('.ts')
211
- ? 'ts'
212
- : 'jsx';
213
- return {
214
- contents: transformPersist(
215
- readFileSync(loadArgs.path, 'utf8'),
216
- relative(projectRoot, loadArgs.path).replace(/\\/g, '/'),
217
- ),
218
- loader,
219
- };
206
+ return await loadAppFile(
207
+ loadArgs.path,
208
+ persist
209
+ ? source =>
210
+ transformPersist(
211
+ source,
212
+ relative(projectRoot, loadArgs.path).replace(
213
+ /\\/g,
214
+ '/',
215
+ ),
216
+ )
217
+ : undefined,
218
+ {mocks: true},
219
+ );
220
220
  } catch (error) {
221
221
  return {errors: [{text: `persist transform: ${error.message}`}]};
222
222
  }
@@ -0,0 +1,37 @@
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
+ // Dimensions — RN analog over the host-injected `screen` global. A panel has no pixel-density or font
18
+ // setting, so `scale` and `fontScale` are 1, and 'window' and 'screen' are the same size.
19
+ export const Dimensions = {
20
+ get(dimension) {
21
+ if (dimension !== 'window' && dimension !== 'screen') {
22
+ throw new Error(`Dimensions.get: no dimension named "${dimension}"`);
23
+ }
24
+
25
+ return {
26
+ width: screen.width,
27
+ height: screen.height,
28
+ scale: 1,
29
+ fontScale: 1,
30
+ };
31
+ },
32
+ };
33
+
34
+ // The panel's size. It is fixed while the app runs, so this never re-renders.
35
+ export function useWindowDimensions() {
36
+ return Dimensions.get('window');
37
+ }
@@ -33,9 +33,7 @@
33
33
  // stays mounted. Size `sections x (1 + rows) x nodes-per-row` against ERUI_MAX_NODES before writing
34
34
  // the screen.
35
35
  //
36
- // Unlike <FlatList>, this has no Flow B counterpart yet — the AOT unrolls one `.map` per container
37
- // and a section expands to a header AND a variable number of rows. It is a Flow A / simulator
38
- // component until that lands; the AOT says so by name rather than "unknown element".
36
+ // Flow B builds the same tree, unrolling the sections at build time (aot/compiler/elements/section-list.mts).
39
37
  import {createElement} from 'react';
40
38
  import {ScrollView} from './components.js';
41
39
  import {pushKeyedChild} from './list-child.js';
@@ -182,7 +182,7 @@ export interface ViewStyle {
182
182
  transform?: TransformStyle[];
183
183
  transformOrigin?: TransformOrigin;
184
184
 
185
- // Shadow. Rendered only in a build with shadows enabled (ERUI_SHADOWS) and `shadowOpacity` above 0.
185
+ // Shadow. Rendered only in a build with shadows enabled (ERUI_SHADOWS), by `shadowOpacity` above 0 or an `elevation`.
186
186
  shadowColor?: string;
187
187
  shadowOffset?: ShadowOffset;
188
188
  shadowOpacity?: number;
@@ -434,8 +434,8 @@ export interface FlatListProps<T = unknown> {
434
434
  /**
435
435
  * `<SectionList>` is a thin `<ScrollView>` alias like `<FlatList>` — no virtualization, no sticky
436
436
  * headers, and every header, row and footer mounts as a real engine node and stays mounted. Header,
437
- * rows and footer are flat siblings, exactly as in RN. Flow A / simulator only for now: the AOT has no
438
- * `<SectionList>` lowering yet.
437
+ * rows and footer are flat siblings, exactly as in RN. Flow B unrolls the sections at build time, so
438
+ * write them out in place or use a constant array.
439
439
  */
440
440
  export interface SectionListProps<ItemT = unknown, SectionT = DefaultSectionT> {
441
441
  sections?: ReadonlyArray<SectionListData<ItemT, SectionT>>;
@@ -788,6 +788,23 @@ export const Platform: {
788
788
  select<T>(specifics: Record<string, T>): T | undefined;
789
789
  };
790
790
 
791
+ // --- Dimensions ------------------------------------------------------------
792
+ /** The panel's size in pixels. `scale` and `fontScale` are always 1. */
793
+ export interface ScaledSize {
794
+ width: number;
795
+ height: number;
796
+ scale: number;
797
+ fontScale: number;
798
+ }
799
+
800
+ export const Dimensions: {
801
+ /** The panel's size. 'window' and 'screen' are the same on a panel. */
802
+ get(dimension: 'window' | 'screen'): ScaledSize;
803
+ };
804
+
805
+ /** The panel's size. It is fixed while the app runs. */
806
+ export function useWindowDimensions(): ScaledSize;
807
+
791
808
  // --- AppRegistry -----------------------------------------------------------
792
809
  export const AppRegistry: {
793
810
  registerComponent(
@@ -929,6 +946,69 @@ export function usePersistentState<S>(
929
946
  ): [S, (value: S | ((prev: S) => S)) => void];
930
947
 
931
948
  export function useHostValue(initial: number): number;
949
+
950
+ /** A whole number. A native method's `Int` is an int in C, where a `number` is a float. */
951
+ export type Int = number;
952
+
953
+ /**
954
+ * A whole number that may be past an Int's range: a native method's `Int64` is an int64_t in C. In JS it is a number,
955
+ * so it is exact up to 2^53.
956
+ */
957
+ export type Int64 = number;
958
+
959
+ /** An optional native module, as nativeModule.optional returns it. */
960
+ export type OptionalNativeModule<T> = T & {
961
+ /** Whether the firmware has every method and event of the module. Set at load, and it never changes. */
962
+ readonly available: boolean;
963
+ };
964
+
965
+ /**
966
+ * A module the firmware provides in C, declared at module level by an interface of its methods, which take and
967
+ * return Int, Int64, number, boolean, string and records of them:
968
+ * `const Sensors = nativeModule<Sensors>('sensors', 1)`. Its events are the interface's `events`:
969
+ * `events: {reading(celsius: number): void}`.
970
+ */
971
+ export const nativeModule: {
972
+ <T>(name: string, version: number): T;
973
+ /**
974
+ * A module only some boards have: `const Wifi = nativeModule.optional<Wifi>('wifi', 1)`. A package that uses it
975
+ * loads without it, and `Wifi.available` says whether it is there. Calling a method of a module that isn't stops
976
+ * the app; its events never arrive.
977
+ */
978
+ optional<T>(name: string, version: number): OptionalNativeModule<T>;
979
+ };
980
+
981
+ /** The events a native module's interface declares. */
982
+ export type NativeEvents<T> = T extends {events: infer E} ? E : {};
983
+
984
+ /** The values an event is posted with. */
985
+ export type NativeEventValues<
986
+ T,
987
+ K extends keyof NativeEvents<T>,
988
+ > = NativeEvents<T>[K] extends (...values: infer V) => void ? V : never;
989
+
990
+ /**
991
+ * Runs `handler` with an event's values each time the firmware posts it, while the component is mounted:
992
+ * `useNativeEvent(Sensors, 'reading', celsius => setTemperature(celsius))`.
993
+ */
994
+ export function useNativeEvent<T, K extends keyof NativeEvents<T> & string>(
995
+ module: T,
996
+ event: K,
997
+ handler: (...values: NativeEventValues<T, K>) => void,
998
+ ): void;
999
+
1000
+ /** Posts one of a mocked module's events, as the firmware would. false while one of the mock's methods runs. */
1001
+ export type NativeEmit<T> = <K extends keyof NativeEvents<T> & string>(
1002
+ event: K,
1003
+ ...values: NativeEventValues<T, K>
1004
+ ) => boolean;
1005
+
1006
+ /**
1007
+ * A native module's mock for the simulators, the default export of `<name>.mock.ts`: its methods, or a function
1008
+ * that is given `emit` and returns them.
1009
+ */
1010
+ export type NativeMock<T> =
1011
+ Omit<T, 'events'> | ((emit: NativeEmit<T>) => Omit<T, 'events'>);
932
1012
  export const Easing: {readonly [K in EasingName]: K} & {
933
1013
  bezier(x1: number, y1: number, x2: number, y2: number): BezierEasing;
934
1014
  };
@@ -49,10 +49,12 @@ export {SectionList} from './SectionList.js';
49
49
  export {updateVector, updateText, setKeyboardConfig} from './imperative.js';
50
50
  export {StyleSheet} from './StyleSheet.js';
51
51
  export {Platform} from './Platform.js';
52
+ export {Dimensions, useWindowDimensions} from './Dimensions.js';
52
53
  export {AppRegistry} from './AppRegistry.js';
53
54
  export {Animated, useAnimatedValue} from './Animated.js';
54
55
  export {PanResponder} from './PanResponder.js';
55
56
  export {usePersistentState} from './usePersistentState.js';
56
57
  export {useHostValue} from './useHostValue.js';
58
+ export {nativeModule, useNativeEvent} from './nativeModule.js';
57
59
  export {Easing} from './Easing.js';
58
60
  export {LayoutAnimation} from './LayoutAnimation.js';