embedded-react 0.14.1 → 0.16.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 (61) hide show
  1. package/README.md +51 -486
  2. package/aot/compile.mjs +173 -8272
  3. package/aot/compiler/animations.mjs +1001 -0
  4. package/aot/compiler/assemble.mjs +806 -0
  5. package/aot/compiler/c/animations.mjs +362 -0
  6. package/aot/compiler/c/expressions.mjs +215 -0
  7. package/aot/compiler/c/functions.mjs +268 -0
  8. package/aot/compiler/c/keyboard.mjs +96 -0
  9. package/aot/compiler/c/nodes.mjs +282 -0
  10. package/aot/compiler/c/pan-responder.mjs +136 -0
  11. package/aot/compiler/c/statements.mjs +242 -0
  12. package/aot/compiler/c/text.mjs +83 -0
  13. package/aot/compiler/c/vectors.mjs +381 -0
  14. package/aot/compiler/c-syntax.mjs +127 -0
  15. package/aot/compiler/check.mjs +165 -0
  16. package/aot/compiler/collect.mjs +743 -0
  17. package/aot/compiler/control-flow.mjs +683 -0
  18. package/aot/compiler/diagnostics.mjs +137 -0
  19. package/aot/compiler/elements/activity-indicator.mjs +160 -0
  20. package/aot/compiler/elements/dial.mjs +343 -0
  21. package/aot/compiler/elements/flat-list.mjs +139 -0
  22. package/aot/compiler/elements/image.mjs +151 -0
  23. package/aot/compiler/elements/modal.mjs +158 -0
  24. package/aot/compiler/elements/props.mjs +474 -0
  25. package/aot/compiler/elements/switch.mjs +183 -0
  26. package/aot/compiler/elements/text-input.mjs +171 -0
  27. package/aot/compiler/expressions.mjs +1479 -0
  28. package/aot/compiler/handlers.mjs +1072 -0
  29. package/aot/compiler/ir/animations.mjs +16 -0
  30. package/aot/compiler/ir/app.mjs +16 -0
  31. package/aot/compiler/ir/expressions.mjs +16 -0
  32. package/aot/compiler/ir/functions.mjs +16 -0
  33. package/aot/compiler/ir/keyboard.mjs +16 -0
  34. package/aot/compiler/ir/nodes.mjs +83 -0
  35. package/aot/compiler/ir/pan-responder.mjs +16 -0
  36. package/aot/compiler/ir/source.mjs +16 -0
  37. package/aot/compiler/ir/statements.mjs +16 -0
  38. package/aot/compiler/ir/text.mjs +16 -0
  39. package/aot/compiler/ir/types.mjs +185 -0
  40. package/aot/compiler/ir/vectors.mjs +16 -0
  41. package/aot/compiler/keyboard.mjs +152 -0
  42. package/aot/compiler/lower.mjs +282 -0
  43. package/aot/compiler/nodes.mjs +683 -0
  44. package/aot/compiler/options.mjs +55 -0
  45. package/aot/compiler/out.mjs +94 -0
  46. package/aot/compiler/pan-responder.mjs +354 -0
  47. package/aot/compiler/parse.mjs +300 -0
  48. package/aot/compiler/static-eval.mjs +228 -0
  49. package/aot/compiler/style-text.mjs +648 -0
  50. package/aot/compiler/svg.mjs +1167 -0
  51. package/aot/compiler/types.mjs +16 -0
  52. package/aot/screenshot-smoke.mjs +95 -55
  53. package/aot/style-map.mjs +366 -304
  54. package/cli.mjs +5 -8
  55. package/package.json +14 -6
  56. package/sim/embedded-react.cjs +1 -1
  57. package/sim/embedded-react.js +1 -1
  58. package/sim/embedded-react.wasm +0 -0
  59. package/src/embedded-react/FlatList.js +4 -4
  60. package/src/embedded-react/index.d.ts +2 -1
  61. package/src/props.js +1 -1
package/README.md CHANGED
@@ -1,510 +1,75 @@
1
- # embedded-react
1
+ <h1 align="center">
2
+ <img src="https://raw.githubusercontent.com/TheMasterCoder007/embedded-react/master/assets/icons/embedded-react-readme-header-v3.png" alt="Embedded React" width="100%">
3
+ </h1>
2
4
 
3
- **React Native for embedded MCUs** — write JSX, run it on a microcontroller. This npm package is the
4
- **JavaScript layer**: the React-Native-style component API you import, the
5
- [`react-reconciler`](https://www.npmjs.com/package/react-reconciler) host config that drives the C engine
6
- at runtime (**Flow A**), and the JSX→C ahead-of-time compiler (**Flow B**, `aot/`).
5
+ **React Native for embedded MCUs**: write JSX, run it on a microcontroller. This package is the
6
+ JavaScript layer: the React Native-style component API you import, the
7
+ [`react-reconciler`](https://www.npmjs.com/package/react-reconciler) host config that drives the C
8
+ engine at runtime (Flow A), the JSX-to-C ahead-of-time compiler (Flow B), and the `embedded-react`
9
+ CLI with the browser simulator.
7
10
 
8
- ```
9
- React → react-reconciler → host-config.js → NativeUI.* → er_scene.h (engine)
10
- ```
11
-
12
- > ### Part of a monorepo
13
- > This package is just the `bridges/quickjs/js` folder of the **embedded-react** project. The C rendering
14
- > engine, the hardware backends, the runnable examples, the demo apps, and the simulator all live in the
15
- > main repo — **https://github.com/TheMasterCoder007/embedded-react**. The engine itself is distributed
16
- > separately as C source (CMake `FetchContent`, the ESP-IDF Component Registry, and PlatformIO) — see the
17
- > repos **Install** section. Everything ships at one lockstep version (this package's version == the engine's).
18
- >
19
- > **`npx embedded-react dev` works in your own project** — it runs the WASM simulator on your app with hot
20
- > reload, no clone, and no native toolchain (the simulator `.wasm` ships prebuilt in this package). The other
21
- > end-to-end CLIs below (`npm run pack`/`build`/AOT, running on a board) still operate on the repo's `demos/`
22
- > and `examples/`. To start a **fresh standalone project** in your own directory, use the scaffolder:
23
- > `npm create embedded-react@latest my-app`.
24
-
25
- ## What an app imports
26
-
27
- The package is the React Native analog — same idiom (hooks from `react`, everything else here):
28
-
29
- ```jsx
30
- import { useState } from 'react';
31
- import { View, Text, Pressable, StyleSheet, AppRegistry } from 'embedded-react';
32
-
33
- function App() { /* ... */ }
34
- AppRegistry.registerComponent('demo', () => App);
35
- ```
36
-
37
- `embedded-react` resolves as a Node **package self-reference** (`package.json` `name` + `exports`),
38
- so esbuild and Vitest find it with no aliases.
11
+ **Documentation: [embedded-react.dev](https://embedded-react.dev)**
39
12
 
40
- `<FlatList>` renders, but it is a thin `<ScrollView>` alias — no virtualization, every row mounts and
41
- stays mounted, and only `data` / `renderItem` / `keyExtractor` / `style` are honored. See [`FlatList` is
42
- a `ScrollView`
43
- alias](https://github.com/TheMasterCoder007/embedded-react#flatlist-is-a-scrollview-alias) for the node
44
- budget it costs and what to do with a long list.
45
-
46
- `<Button>`, `<ImageBackground>` and `<SectionList>` are JavaScript wrappers over the primitives, the
47
- way RN implements them — a styled `<Pressable>` + `<Text>`, a `<View>` with an absolutely-filled
48
- `<Image>` behind its children, and a `<ScrollView>` whose sections lay out as flat siblings. They add
49
- no engine node, they are **Flow A only** (the AOT names them and tells you the tree to write instead),
50
- and `<SectionList>` inherits every `<FlatList>` caveat plus a header and footer per section. See
51
- [`Button`, `ImageBackground` and `SectionList` are JSX, not
52
- nodes](https://github.com/TheMasterCoder007/embedded-react#button-imagebackground-and-sectionlist-are-jsx-not-nodes).
53
-
54
- `<TouchableOpacity>` is a wrapper too, but a cheaper one: it is a `<Pressable>` whose opacity is bound to
55
- a press animation, so it costs no extra node and it compiles in **both flows**. The dim runs on the
56
- native driver — no JS per frame — and every `<Pressable>` prop works on it unchanged. See
57
- [`<TouchableOpacity>` dims on the native
58
- driver](https://github.com/TheMasterCoder007/embedded-react#touchableopacity-dims-on-the-native-driver).
59
-
60
- RN modules that wrap an operating system — `StatusBar`, `SafeAreaView`, `AppState`, `Appearance`,
61
- `Linking`, `AccessibilityInfo` — are **intentionally absent**; a microcontroller has no OS for them to
62
- wrap. See [Intentionally absent React Native
63
- APIs](https://github.com/TheMasterCoder007/embedded-react#intentionally-absent-react-native-apis) for
64
- the full list and what to use instead.
65
-
66
- ## Simulate — `npx embedded-react dev`
67
-
68
- Run your app in a browser with hot reload — no native toolchain, no repo clone. The engine is compiled to
69
- WebAssembly and ships **prebuilt** in this package; the CLI bundles your JSX, serves it, and re-loads on save
70
- (your `useState` survives the reload).
13
+ ## Start here
71
14
 
72
15
  ```bash
73
- npx embedded-react dev # finds ./index.jsx, ./src/index.jsx, or package.json "main"
74
- npx embedded-react dev app.jsx # or pass the entry explicitly
75
- npx embedded-react dev --port 4000
16
+ npm create embedded-react@latest my-app # add -- --ts for TypeScript
17
+ cd my-app && npm install && npm run dev # the simulator, with hot reload, at http://localhost:3333
76
18
  ```
77
19
 
78
- Open the printed URL. The canvas fills the viewport, so the browser's device toolbar drives the board size
79
- (e.g., 240×320) — pixel-accurate to a hardware ARGB panel. Imported images/fonts are baked and hot-reload too.
80
- A floating gear chip locks to a specific panel size and can wrap the screen in a **device frame** (bezel) for a
81
- true-to-hardware preview. This is the same simulator as the repo's `tools/web-sim` (see
82
- [tools/web-sim](https://github.com/TheMasterCoder007/embedded-react/blob/master/tools/web-sim/README.md)).
83
-
84
- To **share** a UI, export a self-contained static playground — `index.html` + the prebuilt `.wasm` + your
85
- bundled app — that runs in any browser with no server, ready for GitHub Pages / Netlify / a docs' iframe:
20
+ Or add it to an existing project:
86
21
 
87
22
  ```bash
88
- npx embedded-react export --out sim-export # then: npx serve sim-export (or deploy the folder anywhere)
89
- ```
90
-
91
- ## Layout
92
-
93
- ```
94
- src/
95
- embedded-react/ the public package surface (what apps import)
96
- index.js barrel: components, StyleSheet, Platform, AppRegistry, Animated, PanResponder, Easing
97
- components.js host component tags (View, Text, … → ERNodeType)
98
- StyleSheet.js create() / flatten()
99
- Platform.js { OS: 'embedded', select }
100
- AppRegistry.js registerComponent(...) → mounts into a screen-sized root
101
- Animated.js Value / timing / spring / decay / View|Text|Image / interpolate
102
- PanResponder.js create(config) → panHandlers: drag/swipe/fling over the responder system
103
- Easing.js easing tokens (+ bezier) → engine curves
104
- split-style.js pure: split style into static props + animated bindings
105
- __tests__/ co-located UNIT tests for the pure surface
106
- host-config.js reconciler host config → NativeUI.* (internal runtime)
107
- renderer.js createRoot(props).render(...); LegacyRoot (sync) (internal)
108
- props.js pure prop helpers (flattenStyle / buildProps / isEventProp)
109
- native-ui.js re-exports globalThis.NativeUI (installed by the C bridge)
110
- __tests__/ co-located UNIT tests (Vitest, *.unit.test.js, no engine)
111
- test/runtime/ e2e tests that need the real engine host
112
- *.runtime.test.jsx run inside QuickJS + engine via the headless harness
113
- harness.js check()/report() — records failures for the C runner
114
- run.mjs bundles each runtime test + runs er-bridge-quickjs-runtest
115
- assets/ build-time asset bakers (pure JS, no native deps) — see "Assets" below
116
- rasterize.mjs glyph path → coverage bitmap (supersampled, nonzero winding)
117
- bake-font.mjs TTF/OTF → engine BitmapFont glyph data (opentype.js)
118
- bake-image.mjs PNG → premultiplied ARGB8888 (pngjs)
119
- emit-c.mjs assemble assets.generated.c + the built-in font_data.c
120
- build-builtin-font.mjs regenerate the engine's default Inter font (npm run build:builtin-font)
121
- build.mjs esbuild a demo's index.jsx → dist/app.bundle.js + bake its imported assets
122
- pack-container.mjs bundle + bytecode-compile + bake → dist/app.erpkg config container (npm run pack)
123
- assets/emit-container.mjs ERCF container writer (sections + QuickJS version stamp + CRC32)
124
- compile-bin.mjs finds er-bridge-quickjs-compile (shared with the parity harness)
125
- vitest.config.js unit test config
126
- ```
127
-
128
- The demo apps themselves live in the repo's top-level **`demos/`** folder (one folder per demo), *not*
129
- in this package — this package is the library + reconciler + AOT compiler + tests. `build.mjs` bundles a
130
- selected demo and resolves its `'embedded-react'` import to `src/embedded-react/index.js`. See
131
- [demos/ in the repo](https://github.com/TheMasterCoder007/embedded-react/tree/master/demos).
132
-
133
- The host config flattens RN `style` (+ nested arrays) into the flat prop bag, routes `on*`
134
- handlers to `setEvent`, and uses `shouldSetTextContent` so a flattenable `<Text>` subtree (a string,
135
- interpolation like `Hi {name}`, or nested `<Text>` runs) becomes the node's `text` + inline spans.
136
- `Animated`, `Easing`, and the web timer globals (`setTimeout` / `setInterval`) are all available;
137
- `useEffect` flushes via the host pump.
138
-
139
- ### Hiding a subtree (`display: 'none'`) — page caching
140
-
141
- ```jsx
142
- <View style={{display: page === 'home' ? 'flex' : 'none'}}><Home /></View>
143
- <View style={{display: page === 'settings' ? 'flex' : 'none'}}><Settings /></View>
144
- ```
145
-
146
- A hidden subtree drops out of layout, rendering, and hit-testing, but stays **mounted** — its React
147
- state and effects survive, and the native nodes behind it keep their props. That is the difference
148
- from the conditional render (`{page === 'home' && <Home/>}`) it replaces: a conditional unmounts the
149
- page and rebuilds every node in interpreted QuickJS on the way back, which is the dominant cost of a
150
- page change. Hiding costs a repaint, and a hidden page costs nothing per frame even while React keeps
151
- rendering into it.
152
-
153
- `visible={false}` is the same switch under the other spelling, with an explicit `style.display`
154
- winning over it (`<Modal visible>` is unaffected — that is the Modal's own show/hide prop). Both work
155
- in Flow B too, where `display` can be static or state-driven — `display: page === 'home' ? 'flex' : 'none'`
156
- compiles, but a state-driven one has to be a string literal or a ternary of them, whereas `visible` takes
157
- any boolean expression. Either spelling lowers to a `p.display` write in `app_update`, so hiding costs no
158
- node churn there either. The one gap is `visible` on an `<Svg>`, which the AOT rejects outright: wrap it
159
- (`<View visible={…}><Svg …/></View>`) and the whole subtree goes with the View.
160
- The trade is memory: a cached page holds its nodes for the life of the app, so cache
161
- the pages you flip between, not every page.
162
-
163
- ### Gestures — `PanResponder`
164
-
165
- The raw touch events already carry the travel and the speed (`e.dx`/`e.dy`, `e.vx`/`e.vy` — see below),
166
- which is enough for a one-off flick. A real drag wants more: an anchor that starts at zero, however, the
167
- gesture was won, ownership against a scrolling ancestor, and a teardown hook for when the gesture is
168
- taken away. `PanResponder` is that, in the RN shape (and it compiles in Flow B as well as Flow A):
169
-
170
- ```jsx
171
- const pan = useRef(
172
- PanResponder.create({
173
- onStartShouldSetPanResponder: () => true,
174
- onPanResponderMove: (e, g) => setX(g.dx),
175
- onPanResponderRelease: (e, g) => (g.vx > 0.5 ? next() : settle()),
176
- }),
177
- ).current;
178
-
179
- <View style={styles.overlay} {...pan.panHandlers} />;
180
- ```
181
-
182
- Create it **once** per component and keep it in a ref — the handlers close over one gesture state, so
183
- re-creating it per render throws the drag away. `gestureState` carries `x0`/`y0` (the grant point),
184
- `dx`/`dy` (travel since the grant), `vx`/`vy` (px per ms), `moveX`/`moveY`, `numberActiveTouches` and
185
- `stateID`. Returning `true` from `onMoveShouldSetPanResponder` claims the gesture mid-pan and re-anchors
186
- `dx`/`dy` at that point, so a slop threshold never shows up as a jump. With neither should-set callback
187
- supplied nothing is ever granted — same as RN.
188
-
189
- `panHandlers` are the RN **responder props** — should-set queries plus `onResponderGrant`/`Move`/
190
- `Release`/`Terminate` — wired straight into the engine's C responder system, so claiming is real
191
- *negotiation*, not just listening:
192
-
193
- - **A granted pan OWNS the gesture.** A `ScrollView` ancestor will not auto-scroll under it, and a
194
- `onMoveShouldSetPanResponder` claim takes the gesture *back* from a scroller that already started
195
- (which then stops dead — no coasting).
196
- - **Negotiation covers the subtree.** The engine asks every node on the hit chain — capture phase
197
- root→leaf first (the `*Capture` config keys), then bubble leaf→root — so one responder on a wrapper
198
- claims its children's touches, and an outer responder can pre-empt an inner one.
199
- - **Losing and defending are callbacks.** A refused claim lands on `onPanResponderReject` (and is
200
- re-asked on every later move while the predicate keeps returning true); a challenger asking for the
201
- gesture hits the holder's `onPanResponderTerminationRequest` — return `false` to keep it (absent =
202
- yield, as in RN).
203
- - **`onPanResponderTerminate` is the undo hook.** It fires when the host cancels the touch sequence,
204
- when a fresh touch-down arrives on a finger whose previous sequence never ended, and when the
205
- responder yields to a challenger.
206
- - **Single gesture.** The engine events carry no finger id, so extra fingers fold into ONE gesture:
207
- `numberActiveTouches` counts them and the last to lift releases — both true in either flow. Flow A
208
- additionally reports each join and leave through `onPanResponderStart`/`End`; Flow B has no
209
- equivalent (next bullet).
210
- - **Flow B compiles it too.** The AOT recognises `useRef(PanResponder.create({…})).current` and the
211
- `{...pan.panHandlers}` spread as a whole and lowers them onto the same C responder system — the
212
- should-set predicates become `er_responder_query_set` callbacks and the rest become responder event
213
- handlers, with `g.dx`/`g.vx` reading the engine's own payload. No JS state machine is copied into the
214
- generated C. Only `onPanResponderStart`/`End` — the two that fold EXTRA fingers into one gesture —
215
- are Flow A only, and the AOT fails the build by name rather than dropping them. The watch-face demo's
216
- swipe pager is the worked example: one source, both flows.
217
-
218
- As promised above: the raw touch events carry the same fields the responder ones do — `e.dx`/`e.dy` from
219
- touch-down and `e.vx`/`e.vy` in px per ms — so `onTouchEnd={e => e.vx > 0.4 && next()}` needs no
220
- recognizer at all, in either flow.
221
-
222
- The low-level responder props (`onStartShouldSetResponder`, `onResponderGrant`, …) are themselves
223
- public on every component for gestures that don't fit the pan shape. Only RN's Android-specific
224
- `onShouldBlockNativeResponder` is unsupported — holding the responder already blocks the native one
225
- (the built-in adjustable-Arc drag deliberately still wins). Passing it, or a typo, warns.
226
-
227
- ### Dragging faster than React — `updateVector` / `updateText`
228
-
229
- A render per pointer move is the expensive way to drive a gesture. Measured on an ESP32-S3 dragging a
230
- JS-drawn knob (a `<Path d>` rebuilt every move, state at the root), one frame cost ~103 ms of JS —
231
- roughly half React's render and half re-marshaling the tree — plus ~51 ms of engine commit. Pushing
232
- the same geometry straight at the node instead costs **~10 µs of JS**, and about a third of the
233
- raster, because only that node is dirtied rather than the whole tree.
234
-
235
- Take a handle from a ref on the `<Svg>` and write to it during the gesture:
236
-
237
- ```jsx
238
- const arc = useRef(0);
239
-
240
- const pan = useRef(
241
- PanResponder.create({
242
- onStartShouldSetPanResponder: () => true,
243
- onPanResponderMove: (e, g) => {
244
- const deg = angleFor(g.moveX, g.moveY);
245
- updateVector(arc.current, [
246
- {arc: [CX, CY, R, 0, deg], stroke: '#f4a261', strokeWidth: 14, cap: 'round'},
247
- {circle: [handleX(deg), handleY(deg), 8], fill: '#fff'},
248
- ]);
249
- },
250
- onPanResponderRelease: (e, g) => setValue(valueFor(g.moveX, g.moveY)), // re-sync React
251
- }),
252
- ).current;
253
-
254
- <View {...pan.panHandlers} style={{width: W, height: H}}>
255
- <Svg ref={h => (arc.current = h)} width={W} height={H} />
256
- </View>;
257
- ```
258
-
259
- Each shape is **one geometry key plus its paint** — `arc`/`circle`/`line`/`rect`/`path`, with
260
- `fill`, `stroke`, `strokeWidth`, `cap`, `join`, `miter`, `fillRule`, `fillGrad`, `strokeGrad`. Note the
261
- short paint spellings: this is the allocation-free path, not the JSX attribute set. `path` takes a `d`
262
- string but pays the parser, so prefer the primitives on a hot path. **Arc angles are degrees clockwise
263
- from 12 o'clock**, which is not the convention an SVG `A` command uses.
264
-
265
- The optional third argument is a node-local `[x, y, w, h]` bounding the change — give it and only that
266
- region repaints and flushes, which is a large win for a small update on a big vector node.
267
-
268
- `updateText(handle, text)` is the same idea for a `<Text>`: it sets the content through a single
269
- inherited span, so the node's own color/size are untouched.
270
-
271
- This is a **write-through**, not a new source of truth: the node keeps what you pushed until React next
272
- renders that element, which overwrites it cleanly. So commit the final value to state when the gesture
273
- ends — the release handler above — and the declarative tree takes over again. Both flows compile it;
274
- the AOT lowers `updateVector` the same way.
275
-
276
- If the shape you are drawing is a dial, reach for `<Dial>` first — it tracks the finger and repaints
277
- the arc in C, with no JS per move at all.
278
-
279
- ## Build
280
-
281
- ```
282
- npm install
283
- npm run pack # default demo → dist/app.erpkg (deployable config: bytecode + assets + CRC)
284
- npm run pack -- marine-dash # pack a specific demo (demos/<name>) instead
285
- npm run build # lower-level: just bundle → dist/app.bundle.js (+ bake assets.generated.c)
286
- npm run create -- my-app # scaffold a new app at demos/my-app (App.jsx + scripts); then `cd` + npm run sim
23
+ npm install embedded-react react@18.3.1
287
24
  ```
288
25
 
289
- `npm run pack` is the deployable artifact the desktop demo and the ESP32 both load — see **Config
290
- container** below. `npm run build` is the lower-level bundle step (used by the bytecode/asset tooling
291
- and by firmware that prefers to compile assets in); both bake the demo's imported images and fonts
292
- (see **Assets**).
293
-
294
- ## Assets (images and fonts)
295
-
296
- Asset handling is **import-driven** and fully build-time — there is no runtime decoder or font
297
- rasterizer on the device, and no Python toolchain. An app just imports a file and uses the name it
298
- returns:
299
-
300
26
  ```jsx
301
- import logo from './assets/logo.png'; // → the baked image NAME ("logo")
302
- import Inter from './assets/Inter.ttf'; // → the baked font FAMILY ("Inter")
303
-
304
- <Image source={logo} style={{ width: 64, height: 64 }} />
305
- <Text style={{ fontFamily: Inter, fontSize: 18 }}>Hi</Text>
306
- ```
307
-
308
- The baker produces the assets two ways, from the same bytes: `npm run pack` packs them **into the
309
- config container** (`app.erpkg`), registered at load time — this is what the desktop demo and ESP32
310
- use. `npm run build` also emits `dist/assets.generated.c` exposing **`er_register_assets()`**, for
311
- firmware that prefers to **compile assets into the image** and call it once at boot (`er_image_load` /
312
- `er_font_register`, both flash-resident, zero runtime RAM). Either way the asset name/family is the
313
- file's basename.
314
-
315
- - **Images:** PNG → premultiplied ARGB8888 (`bake-image.mjs`, via `pngjs`). Fully opaque art —
316
- full-screen backgrounds especially — can opt into a 16-bit **RGB565** bake per image (see the
317
- config below): half the flash and half the source-read bandwidth on every repaint. The baker
318
- rejects a non-opaque source rather than silently dropping transparency, and the engine renders
319
- RGB565 images through its opaque copy fast path (no per-pixel blending).
320
- - **Fonts:** TTF/OTF → pre-rasterized `BitmapFont` glyphs (`bake-font.mjs`, via `opentype.js` + a
321
- pure-JS rasterizer). The engine has no runtime rasterizer, so the baker rasterizes **exactly the
322
- `fontSize` values the app uses**. Discovery folds constants, so a token-driven type scale bakes
323
- what it means — `const TYPE = {body: 14, title: 22}` read as `fontSize: TYPE.title`, including a
324
- scale handed to a component as a prop, and both arms of a `screen.width` ternary. A size that only
325
- exists at runtime can't be seen; the build **warns** and names the expression, because at runtime
326
- it silently snaps to the nearest baked size. Sizes the bake missed are warned about the same way,
327
- against your fonts or against the built-in one — pin them in `assets.config.js` if you want a
328
- different set. Only the glyphs you ask for are baked: printable ASCII, plus a named symbol set and
329
- any per-app characters you add.
330
-
331
- Optional per-demo overrides live in `demos/<demo>/assets.config.js`:
332
-
333
- ```js
334
- export default {
335
- fonts: {
336
- Inter: {
337
- sizes: [14, 18, 24], // bpp 1|2|4|8 (4 default)
338
- bpp: 4,
339
- glyphs: 'common', // 'ascii'|'minimal'|'common'|'greek'|'common-greek'|[codepoints]
340
- extraGlyphs: '⌘⏻№', // this app's own characters, on top of `glyphs`
341
- },
342
- },
343
- images: {
344
- bg: { format: 'rgb565' }, // 16-bit bake for opaque art; default is 'argb8888'
345
- },
346
- };
347
- ```
348
-
349
- `extraGlyphs` takes the characters themselves or their codepoints (`[0x2318, '⏻']`) — the named sets
350
- can't anticipate every UI. Every bake path checks the app's text against what it baked and **warns
351
- about characters that have no glyph**, since the engine silently substitutes `?` for them on the
352
- device and nothing else tells you:
27
+ import {useState} from 'react';
28
+ import {View, Text, Pressable, StyleSheet, AppRegistry} from 'embedded-react';
353
29
 
30
+ function App() { /* ... */ }
31
+ AppRegistry.registerComponent('demo', () => App);
354
32
  ```
355
- embedded-react: 1 character(s) in the app's text have no baked glyph and will render as '?':
356
- U+2318 '⌘' missing from Inter in "press ⌘S to save"
357
- fix: assets.config.js → fonts: {Inter: {extraGlyphs: "⌘"}}
358
- ```
359
-
360
- The check reads string literals (and, for Flow B's unbundled JSX, element text), so text assembled
361
- at runtime is out of its reach. It also says when the .ttf itself has no such glyph — then no config
362
- change helps and the font is the thing to change.
363
-
364
- The engine's **built-in default font** (`engine/font/font_data.c`, the Inter fallback used by any
365
- text without a custom `fontFamily`) is generated by the same baker — regenerate it with
366
- `npm run build:builtin-font` (then re-run the engine text tests, as glyph metrics shift slightly).
367
-
368
- ## Config container
369
33
 
370
- `npm run pack` wraps the app into one deployable file — **`dist/app.erpkg`** (format `ERCF`):
34
+ The package is the React Native analog: hooks come from `react`, everything else from here.
371
35
 
372
- ```
373
- magic "ERCF" | format_version | crc32 | qjs_tag | sections[ bytecode, asset pack ]
374
- ```
36
+ | Command | What it does |
37
+ |---|---|
38
+ | `npx embedded-react dev` | Runs your app in the browser simulator with hot reload; the engine `.wasm` ships prebuilt, so there is no native toolchain |
39
+ | `npx embedded-react dev --device` | The same, streamed to a connected board over USB (a firmware built with hot reload) |
40
+ | `npx embedded-react build` | The Flow A device artifact, `dist/app.erpkg` (bytecode + baked assets + CRC) |
41
+ | `npx embedded-react build --aot --screen WxH` | The Flow B artifact, `app.gen.c` + `assets.generated.c`, to compile into firmware |
42
+ | `npx embedded-react export` | A self-contained static copy of the simulator with your app, for any static host |
375
43
 
376
- It bundles the demo, precompiles it to **QuickJS bytecode** (no parser/source shipped), bakes the
377
- imported assets into an ERPK pack, and wraps both with a **QuickJS version stamp** and an **integrity
378
- CRC32**. That one `.erpkg` is "the config": loaded by `er_runtime_load_container()` on the desktop, or
379
- flashed to a device's config partition. The loader verifies CRC + version (a config built for a
380
- different QuickJS is rejected, not run as garbage) and registers the assets before the app mounts. This
381
- is the firmware-vs-config split: the firmware (desktop exe / ESP32 image) ships once; the `.erpkg`
382
- ships and updates independently.
44
+ ## Where to read more
383
45
 
384
- > Two CRCs are different things: the container's internal CRC32 is embedded-react's own integrity
385
- > check (universal). A bootloader's transfer/flash CRC is a separate,
386
- > project-specific step layered on the `.erpkg` by your upload toolchain.
46
+ - [Getting started](https://embedded-react.dev/getting-started): install, the simulator, your first board
47
+ - [Components](https://embedded-react.dev/api/components), [hooks](https://embedded-react.dev/api/hooks), [styles](https://embedded-react.dev/api/styles), [Animated](https://embedded-react.dev/api/animated)
48
+ - [Assets](https://embedded-react.dev/concepts/assets): images and fonts are baked at build time from plain imports
49
+ - [Hot reload](https://embedded-react.dev/guides/hot-reload): what survives a reload and why
50
+ - [The AOT subset](https://embedded-react.dev/guides/aot-subset): what the Flow B compiler accepts
51
+ - [Intentionally absent React Native APIs](https://embedded-react.dev/api/components#intentionally-absent-react-native-apis): what a microcontroller has no OS for
387
52
 
388
- The precompiler tool must be built once (`pack` looks for it in the usual build dirs, or set
389
- `ER_COMPILE_BIN`): `cmake -S bridges/quickjs -B bridges/quickjs/build && cmake --build
390
- bridges/quickjs/build --target er-bridge-quickjs-compile`.
53
+ ## Part of a monorepo
391
54
 
392
- ## Run (desktop)
55
+ This package is the `bridges/quickjs/js` folder of the
56
+ [Embedded React](https://github.com/TheMasterCoder007/embedded-react) repository. The C engine, the
57
+ hardware backends, the board examples, the demo apps and the simulators live there, and the engine is
58
+ distributed separately as C source (CMake `FetchContent`, the ESP-IDF Component Registry, PlatformIO)
59
+ at the same version as this package.
393
60
 
394
- After `npm run pack`, **rebuild the `embedded-react-desktop` target** — its build copies
395
- `dist/app.erpkg` into the "config slot" next to the executable, and the host loads it **by default**
396
- (no argument), exactly as the ESP32 loads its config from flash:
61
+ Inside the repository, `npm run pack -- <demo>`, `npm run aot -- <demo>` and `npm run sim -- <demo>`
62
+ build one of the apps in `demos/` against the in-repo library, `npm test` runs the unit tests, and
63
+ `npm run test:runtime` / `npm run test:bytecode` run the end-to-end tiers against a built bridge.
64
+ [Testing](https://embedded-react.dev/internals/testing) and
65
+ [Architecture](https://embedded-react.dev/internals/architecture) describe both.
397
66
 
398
67
  ```
399
- examples/linux/build/embedded-react-desktop # runs the config in the slot
400
- examples/linux/build/embedded-react-desktop other.erpkg # or an explicit container / .qbc / .js path
68
+ src/embedded-react/ the public package surface (components, StyleSheet, Animated, PanResponder, hooks)
69
+ src/host-config.js the react-reconciler host config → NativeUI.* (the C bridge)
70
+ aot/ the Flow B JSX→C compiler
71
+ assets/ build-time bakers: images, fonts, SVG, the ERPK container writer
72
+ cli.mjs, sim-server.mjs the `embedded-react` CLI and the shared simulator dev server
73
+ sim/ the prebuilt engine .wasm the simulator runs
74
+ test/runtime/ end-to-end tests that run inside QuickJS + the real engine
401
75
  ```
402
-
403
- The firmware ships no app and no baked assets — everything rides in the container. No config / a
404
- corrupt one shows an on-screen panel (no built-in fallback). The C host injects the globals the app
405
- expects: `NativeUI` (the bridge), `screen` (`{ width, height, scale }`), and `console`.
406
-
407
- > Iteration loop: edit `src/*` (library) or `demos/<name>/*` (app) → `npm run pack` → rebuild
408
- > `embedded-react-desktop` (re-copies the container into the slot) → run. Or, for an instant
409
- > edit-save-see loop, use the **simulator** (`npm run sim`).
410
-
411
- ## Tests
412
-
413
- Two tiers, by what they need:
414
-
415
- ```
416
- npm test # unit: Vitest over src/**/__tests__/*.unit.test.js (pure JS, no engine)
417
- npm run test:runtime # e2e: bundles test/runtime/*.runtime.test.jsx, runs each in the headless
418
- # QuickJS+engine harness (no window) and checks the result
419
- npm run test:bytecode # same suite, but each bundle is precompiled to a .qbc bytecode blob and run
420
- # via the bytecode path (JS_ReadObject) — proves the MCU load path
421
- ```
422
-
423
- The runtime tiers need the harness exe built once (no SDL); `test:bytecode` also needs the compiler:
424
-
425
- ```
426
- cmake --build bridges/quickjs/build --target er-bridge-quickjs-runtest er-bridge-quickjs-compile
427
- ```
428
-
429
- To use a bridge build in another directory, point `ER_BRIDGE_BUILD_DIR` at it. CI runs both runtime tiers
430
- this way, against the bridge job's two Release builds on Linux (the native and the bare-metal allocator).
431
-
432
- Pick the tier by what the code touches: pure marshaling/logic → a co-located `*.unit.test.js`;
433
- anything that exercises the reconciler → engine pipeline → a `test/runtime/*.runtime.test.jsx`.
434
-
435
- ## Status & known gaps
436
-
437
- - ✅ **Render, state, keyed-list reorder, and Animated all work end-to-end.** `<App/>` mounts, taps
438
- re-render via `setState`, keyed reorder moves nodes (`insertBefore`/`appendChild`), and
439
- `Animated.View` runs **native-driver** animations in the engine (no per-frame JS). Covered by
440
- `test/runtime/reorder.runtime.test.jsx` and `animated.runtime.test.jsx`.
441
- - ✅ **Timers, Promises, and `useEffect` work.** `setTimeout`/`setInterval`/`clearTimeout`/
442
- `clearInterval` and the Promise job queue are serviced each frame by the host pump
443
- (`er_bridge_pump`, off the engine clock). React passive effects (`useEffect`) flush on the pump.
444
- Covered by `timers.runtime.test.js` and `effects.runtime.test.jsx`.
445
- - ✅ **`Date.now()` / `performance.now()` in both flows.** Both run on the engine clock, with the same
446
- surface as the lite JS profile (no `Date` objects). Until the host sets the real time —
447
- `er_runtime_set_wall_clock()` in Flow A, `er_app_set_wall_clock()` in Flow B — `Date.now()` reads as
448
- uptime. Flow B holds a timestamp as 64-bit whole milliseconds: keep it in state, a ref, or a local,
449
- compare it, show it in text, and divide it by a constant with `%` or `Math.floor`/`ceil`/`round`/
450
- `trunc(a / b)`; a plain `/`, a divisor from state, or mixing it with a float or a boolean is a
451
- compiler error. Covered by
452
- `date-now.runtime.test.js`, the AOT's `date-now`, `cc-compile` and `text-lowering` cases, and the
453
- engine's `test_node_pool`.
454
- - ✅ **Whole-number math in Flow B is defined.** C leaves a signed overflow, a zero divisor and an
455
- out-of-range float-to-int conversion undefined, so the generated C gives each an answer: `+`, `-`,
456
- `*` and negation saturate at the limit of their C type (JS would keep a bigger number; the nearest
457
- one the type holds keeps its sign and order); `%`, an int ref's `/=`, and `Math.floor`/`ceil`/`round`/
458
- `trunc` of an int divided by an int give JS's result kept whole and exact, so `x % 0` is 0 and `x / 0`
459
- saturates; and a float that is NaN or past the int range becomes 0 or
460
- the nearest int. Constant math is worked out at compile time, as JS would, so `30 * DAY_MS` is an
461
- exact 64-bit value. Beside a timestamp, or stored into a 64-bit slot, whole-number math is done in
462
- 64 bits all the way through: `+`, `-`, `*`, negation, `%`, and `Math.floor`/`ceil`/`round`/`trunc`/
463
- `abs`/`min`/`max`, so `Date.now() + Math.trunc(n * 100000 / 2)` is exact. A handler local or a ternary
464
- branch is still worked out on its own terms. `Math.abs`, `min` and `max` of ints stay whole numbers,
465
- and `Math.round` rounds halves up, as JS does. Covered by the AOT's `compile`, `date-now`, `cc-compile` and `text-lowering` cases,
466
- the last run under UBSan.
467
- - ✅ **Animated composition + completion.** `sequence`/`parallel`/`stagger`/`delay`/`loop` and
468
- `.start(({ finished }) => …)` all work — composition is pure JS over each child's start/stop, with
469
- completion wired through the engine's `on_complete`. Covered by `anim-compose.runtime.test.js`.
470
- - ✅ **Multi-child `<Text>` + nested spans.** Interpolation (`Hi {name}`) and nested styled
471
- `<Text>` runs both work — a flattenable `<Text>` owns its subtree and renders as the node's text
472
- plus, when runs differ in style, an inline span array (`NativeUI.setTextSpans`, max 4). Covered by
473
- `text-spans` unit + runtime tests.
474
- - ✅ **LayoutAnimation.** `LayoutAnimation.configureNext(...)` before a layout-changing state update
475
- tweens every node whose computed rect moved on the next commit (in C — no per-frame JS). `Presets`
476
- / `create` / `Types` / `Properties` and the `easeInEaseOut`/`linear`/`spring` shorthands. Covered
477
- by `layout-animation` unit + `layout-anim.runtime.test.jsx`.
478
- - ✅ **`PanResponder` + the gesture responder system.** The full RN config minus only the
479
- Android-specific `onShouldBlockNativeResponder`: should-set predicates (with `*Capture` variants),
480
- grant / move / release / terminate / reject / termination-request, `onPanResponderStart`/`End` for
481
- extra fingers, and a `gestureState` (`x0`/`y0`, `dx`/`dy`, `vx`/`vy`, `numberActiveTouches`) — wired
482
- to the ENGINE's responder negotiation, so a granted pan blocks a ScrollView's auto-scroll and can
483
- take a started scroll over. The low-level responder props are public on every component, and **Flow B
484
- compiles the same config** — the AOT lowers it onto that C responder system, minus only
485
- `onPanResponderStart`/`End`. Covered by `pan-responder` unit + `pan-responder.runtime.test.jsx` + the
486
- AOT's `compile`/`cc-compile` PanResponder cases + the engine's `test_input` responder cases.
487
- - ✅ **Interpolate `extrapolate`.** `interpolate({ inputRange, outputRange, extrapolate })` supports
488
- `'extend'` (default) / `'clamp'` / `'identity'`, with per-end `extrapolateLeft`/`extrapolateRight`
489
- overrides. Math is engine-tested (`test_interpolate`); the bridge path by
490
- `interpolate-extrapolate.runtime.test.js`.
491
- - ✅ **Bytecode + assets + `useAnimatedValue`.** The build compiles the bundle to a `.qbc` bytecode
492
- blob (the MCU load path) and bakes imported images/fonts to flash-resident C; `useAnimatedValue` is
493
- exported. Runs end-to-end on the desktop host and on ESP32-S3 hardware.
494
- - ✅ **State survives hot reload** — in the simulator, plain `useState` transparently persists across
495
- saves (a sim-only build transform rewrites it to a persisting helper; press R to reset). On a device
496
- it's just `useState`, so the same app code runs everywhere. `usePersistentState` is the underlying
497
- helper, also exported for explicit use. See
498
- [tools/simulator in the repo](https://github.com/TheMasterCoder007/embedded-react/blob/master/tools/simulator/README.md).
499
- - ✅ **`<Dial>` — the native arc widget.** Dials, gauges and progress rings as ONE engine node
500
- (`ER_NODE_ARC`) instead of a re-tessellated `<Svg>`: track + value indicator, optional backing band,
501
- segment gaps, round caps, a circle / image / child-anchored knob, solid / conic / radial indicator paint.
502
- `value` accepts an `Animated.Value` (bound natively — no JS per frame; each tick repaints only the swept
503
- sliver), and `adjustable` gives built-in drag-to-set with the quantized value delivered to `onChange(v)`.
504
- `<Switch onValueChange>` now also fires in Flow A (it was AOT-only). Covered by `dial.runtime.test.jsx`
505
- and the engine's `test_arc`.
506
- - ✅ **`npx embedded-react dev`** — the WASM simulator runs your app in a browser with hot reload, from your
507
- own project directory, with the engine `.wasm` shipped prebuilt (no Emscripten for consumers). See above.
508
- - ✅ **`npm create embedded-react@latest my-app`** — scaffolds a fresh standalone project (a styled card with a
509
- pulsing logo + a `count is N` button) wired for `npm run dev` (simulator) and `npm run export` (static
510
- playground). Published as the `create-embedded-react` package.