embedded-react 0.10.1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -144,7 +144,11 @@ firmware that prefers to **compile assets into the image** and call it once at b
144
144
  `er_font_register`, both flash-resident, zero runtime RAM). Either way the asset name/family is the
145
145
  file's basename.
146
146
 
147
- - **Images:** PNG → premultiplied ARGB8888 (`bake-image.mjs`, via `pngjs`).
147
+ - **Images:** PNG → premultiplied ARGB8888 (`bake-image.mjs`, via `pngjs`). Fully opaque art —
148
+ full-screen backgrounds especially — can opt into a 16-bit **RGB565** bake per image (see the
149
+ config below): half the flash and half the source-read bandwidth on every repaint. The baker
150
+ rejects a non-opaque source rather than silently dropping transparency, and the engine renders
151
+ RGB565 images through its opaque copy fast path (no per-pixel blending).
148
152
  - **Fonts:** TTF/OTF → pre-rasterized `BitmapFont` glyphs (`bake-font.mjs`, via `opentype.js` + a
149
153
  pure-JS rasterizer). The engine has no runtime rasterizer, so the baker rasterizes **exactly the
150
154
  literal `fontSize` values the bundle uses**. Computed/dynamic sizes snap to the nearest baked size
@@ -157,6 +161,9 @@ export default {
157
161
  fonts: {
158
162
  Inter: { sizes: [14, 18, 24], bpp: 4, glyphs: 'common' }, // bpp 1|2|4|8 (4 default); glyphs: 'ascii'|'common'|'minimal'|'greek'|[codepoints]
159
163
  },
164
+ images: {
165
+ bg: { format: 'rgb565' }, // 16-bit bake for opaque art; default is 'argb8888'
166
+ },
160
167
  };
161
168
  ```
162
169
 
@@ -14,28 +14,66 @@
14
14
  * limitations under the License.
15
15
  */
16
16
 
17
- // Build-time image baker: PNG → premultiplied ARGB8888, the format the engine's image registry
18
- // references by pointer (er_image_load). Pure JS (pngjs) — no native deps, no Python. The engine
19
- // scales at render time, so bake at whatever source resolution you want to ship.
17
+ // Build-time image baker: PNG → premultiplied ARGB8888 (the default) or RGB565, the two formats
18
+ // the engine's image registry references by pointer (er_image_load / er_image_load_rgb565).
19
+ // Pure JS (pngjs) — no native deps, no Python. The engine scales at render time, so bake at
20
+ // whatever source resolution you want to ship.
20
21
  import fs from 'node:fs';
21
22
  import {PNG} from 'pngjs';
22
23
 
23
24
  /**
24
- * Decodes an image and returns its premultiplied ARGB8888 pixels (row-major, 0xAARRGGBB).
25
+ * Decodes an image and returns its baked pixels.
26
+ *
27
+ * The default format is premultiplied ARGB8888 (row-major, 0xAARRGGBB). Pass format 'rgb565' to bake
28
+ * 16-bit RGB565 instead — half the flash and half the source-read bandwidth on every repaint,
29
+ * meant for opaque full-screen backgrounds. RGB565 has no alpha channel, so a source image with
30
+ * any non-opaque pixel is rejected with an error rather than silently dropping its transparency.
25
31
  *
26
32
  * @param {object} opts
27
- * @param {string} opts.path Path to the source image.
28
- * @param {string} opts.name Asset name an <Image source>/imageName looks up.
29
- * @returns {{name:string, width:number, height:number, pixels:Uint32Array}}
33
+ * @param {string} opts.path Path to the source image.
34
+ * @param {string} opts.name Asset name an <Image source>/imageName looks up.
35
+ * @param {string} [opts.format] 'argb8888' (default) or 'rgb565'.
36
+ * @returns {{name:string, width:number, height:number, format:'argb8888'|'rgb565',
37
+ * pixels:Uint32Array|Uint16Array}}
30
38
  */
31
- export function bakeImage({path, name}) {
39
+ export function bakeImage({path, name, format = 'argb8888'}) {
32
40
  if (!/\.png$/i.test(path)) {
33
41
  throw new Error(
34
42
  `image "${path}": only PNG is supported by the baker (convert to PNG, or extend bake-image.mjs)`,
35
43
  );
36
44
  }
45
+ if (format !== 'argb8888' && format !== 'rgb565') {
46
+ throw new Error(
47
+ `image "${name}": unknown format "${format}" (expected "argb8888" or "rgb565")`,
48
+ );
49
+ }
37
50
  const png = PNG.sync.read(fs.readFileSync(path));
38
51
  const {width, height, data} = png; // data = RGBA, 8-bit, row-major
52
+
53
+ if (format === 'rgb565') {
54
+ const pixels = new Uint16Array(width * height);
55
+ for (let i = 0; i < width * height; i++) {
56
+ const r = data[i * 4];
57
+ const g = data[i * 4 + 1];
58
+ const b = data[i * 4 + 2];
59
+ const a = data[i * 4 + 3];
60
+ if (a !== 255) {
61
+ const x = i % width;
62
+ const y = (i - x) / width;
63
+ throw new Error(
64
+ `image "${name}": rgb565 requires a fully opaque source, but pixel (${x},${y}) has alpha ${a} — ` +
65
+ `flatten the art onto its background, or keep the default argb8888 format`,
66
+ );
67
+ }
68
+ // Round-to-nearest 8→5/6/5 bit reduction (the engine bit-replicates back on expand).
69
+ const r5 = Math.round((r * 31) / 255);
70
+ const g6 = Math.round((g * 63) / 255);
71
+ const b5 = Math.round((b * 31) / 255);
72
+ pixels[i] = ((r5 << 11) | (g6 << 5) | b5) & 0xffff;
73
+ }
74
+ return {name, width, height, format, pixels};
75
+ }
76
+
39
77
  const pixels = new Uint32Array(width * height);
40
78
  for (let i = 0; i < width * height; i++) {
41
79
  const r = data[i * 4];
@@ -48,5 +86,5 @@ export function bakeImage({path, name}) {
48
86
  const bp = Math.floor((b * a + 127) / 255);
49
87
  pixels[i] = ((a << 24) | (rp << 16) | (gp << 8) | bp) >>> 0;
50
88
  }
51
- return {name, width, height, pixels};
89
+ return {name, width, height, format, pixels};
52
90
  }
package/assets/emit-c.mjs CHANGED
@@ -67,7 +67,7 @@ export function emitAssetsC({headerName, images = [], fonts = []}) {
67
67
  const lines = [];
68
68
  lines.push(`/* Generated by bridges/quickjs/js/assets — DO NOT EDIT. */`);
69
69
  lines.push(
70
- `/* Images: premultiplied ARGB8888, referenced by pointer. Fonts: baked BitmapFont per size. */`,
70
+ `/* Images: premultiplied ARGB8888 (or RGB565 when baked 16-bit), referenced by pointer. Fonts: baked BitmapFont per size. */`,
71
71
  );
72
72
  lines.push(``);
73
73
  lines.push(`#include "${headerName}"`);
@@ -81,13 +81,16 @@ export function emitAssetsC({headerName, images = [], fonts = []}) {
81
81
  // --- Images ---------------------------------------------------------------------------------
82
82
  for (const img of images) {
83
83
  const id = cIdent(img.name);
84
+ const is565 = img.format === 'rgb565';
84
85
  const hex = Array.from(
85
86
  img.pixels,
86
- p => '0x' + p.toString(16).toUpperCase().padStart(8, '0') + 'u',
87
+ p => '0x' + p.toString(16).toUpperCase().padStart(is565 ? 4 : 8, '0') + 'u',
87
88
  );
88
- lines.push(`/* image "${img.name}" — ${img.width}x${img.height} */`);
89
- lines.push(`static const uint32_t ${id}_px[] = {`);
90
- lines.push(rows(hex, 8));
89
+ lines.push(
90
+ `/* image "${img.name}" — ${img.width}x${img.height}${is565 ? ' (RGB565)' : ''} */`,
91
+ );
92
+ lines.push(`static const ${is565 ? 'uint16_t' : 'uint32_t'} ${id}_px[] = {`);
93
+ lines.push(rows(hex, is565 ? 12 : 8));
91
94
  lines.push(`};`);
92
95
  lines.push(``);
93
96
  }
@@ -111,8 +114,10 @@ export function emitAssetsC({headerName, images = [], fonts = []}) {
111
114
  lines.push(`void er_register_assets(void)`);
112
115
  lines.push(`{`);
113
116
  for (const img of images) {
117
+ const loadFn =
118
+ img.format === 'rgb565' ? 'er_image_load_rgb565' : 'er_image_load';
114
119
  lines.push(
115
- ` er_image_load(${JSON.stringify(img.name)}, ${cIdent(img.name)}_px, ${img.width}, ${img.height});`,
120
+ ` ${loadFn}(${JSON.stringify(img.name)}, ${cIdent(img.name)}_px, ${img.width}, ${img.height});`,
116
121
  );
117
122
  }
118
123
  for (const reg of fontRegistrations) lines.push(reg);
@@ -32,14 +32,25 @@
32
32
  // qjs_tag u16 len + bytes — QuickJS release the bytecode targets (loader rejects mismatch)
33
33
  // section_count u32
34
34
  // sections[section_count]: type u32, len u32, bytes
35
+ // type 0 = alignment padding (zero bytes — carries no payload, skipped by loaders)
35
36
  // type 1 = QuickJS bytecode (the app — run last)
36
37
  // type 2 = ERPK asset pack (registered before the app mounts)
37
38
  // type 3 = QuickJS vendor bytecode (react + reconciler + lib — run FIRST, before the app). Optional;
38
39
  // present only for the vendor/app split used by incremental hot reload. A container with no
39
40
  // type-3 section is a plain monolithic app, loaded exactly as before (backwards-compatible).
41
+ //
42
+ // Alignment contract: the engine reads asset pixels IN PLACE from wherever the container sits (e.g.
43
+ // memory-mapped flash), and the pack's internal pixel padding is computed relative to the pack's own
44
+ // first byte. Those pads only mean anything at the absolute addresses the engine reads if the pack
45
+ // itself starts on a 4-byte boundary — so the emitter inserts a type-0 padding section before the
46
+ // asset pack whenever needed to 4-align the pack's first byte RELATIVE TO THE CONTAINER, and the host
47
+ // must place the container at a 4-byte-aligned base address (linker scripts typically give 16; malloc
48
+ // guarantees it). Loaders bounds-walk every section and dispatch only on types they know, so old
49
+ // loaders skip the padding section untouched — no format version bump.
40
50
 
41
51
  const FORMAT_VERSION = 1;
42
52
 
53
+ export const SECTION_PAD = 0;
43
54
  export const SECTION_BYTECODE = 1;
44
55
  export const SECTION_ASSET_PACK = 2;
45
56
  export const SECTION_VENDOR_BYTECODE = 3;
@@ -118,8 +129,26 @@ export function emitContainer({bytecode, vendorBytecode, assetPack, qjsTag}) {
118
129
  if (assetPack && assetPack.length)
119
130
  sections.push([SECTION_ASSET_PACK, assetPack]);
120
131
  sections.push([SECTION_BYTECODE, bytecode]);
121
- body.u32(sections.length);
132
+
133
+ // 4-align the asset pack's first byte relative to the container (see the alignment contract above)
134
+ // by inserting a type-0 padding section ahead of it when the layout calls for one. Walk the layout
135
+ // once to place pads, then write — section_count must already include them.
136
+ const withPads = [];
137
+ let off = 12 + 2 + Buffer.byteLength(qjsTag, 'utf8') + 4; // header + tag + section_count
122
138
  for (const [type, data] of sections) {
139
+ if (type === SECTION_ASSET_PACK) {
140
+ const pad = (4 - ((off + 8) % 4)) % 4; // +8 = this section's own type+len header
141
+ if (pad) {
142
+ withPads.push([SECTION_PAD, Buffer.alloc(pad)]);
143
+ off += 8 + pad;
144
+ }
145
+ }
146
+ withPads.push([type, data]);
147
+ off += 8 + data.length;
148
+ }
149
+
150
+ body.u32(withPads.length);
151
+ for (const [type, data] of withPads) {
123
152
  body.u32(type);
124
153
  body.u32(data.length);
125
154
  body.bytes(data);
@@ -21,15 +21,21 @@
21
21
  // loads this at runtime and calls er_image_load / er_font_register, so assets hot-reload without a
22
22
  // sim rebuild. Little-endian (the simulator is x86). Format:
23
23
  //
24
- // magic "ERPK" (4 bytes), version u32=1, n_images u32, n_font_sizes u32
25
- // images[n_images]: name(u16 len + bytes), width u32, height u32, pixels (w*h * u32 ARGB)
24
+ // magic "ERPK" (4 bytes), version u32 (1 or 2), n_images u32, n_font_sizes u32
25
+ // images[n_images]: name(u16 len + bytes), width u32, height u32,
26
+ // [v2 only: format u8 (0=ARGB8888, 1=RGB565), zero-pad to 4-byte alignment],
27
+ // pixels (w*h * u32 ARGB, or w*h * u16 RGB565 when format=1)
26
28
  // fonts[n_font_sizes]: family(u16 len + bytes), pixel_size/line_height/baseline/format (4*u8),
27
29
  // first u16, last u16, glyph_count u16, extras_count u16, bitmap_len u32,
28
30
  // glyphs[glyph_count] (9B: off u32, w/h u8, xo/yo i8, adv u8),
29
31
  // extras[extras_count] (13B: codepoint u32 + the 9B glyph),
30
32
  // bitmap (bitmap_len bytes)
31
-
32
- const VERSION = 1;
33
+ //
34
+ // Version 2 is now emitted ALWAYS. It was introduced for the 16-bit image bake, but its real value
35
+ // is the per-image alignment pad: the engine reads pixels in place, and a DMA2D-class backend
36
+ // refuses a word-misaligned ARGB8888 source (configuration error — silently absent image). v1 had
37
+ // no alignment machinery, so whether an image's pixels landed word-aligned in flash was an accident
38
+ // of the name strings — it varied build to build. Parsers still accept v1 packs from older tooling.
33
39
 
34
40
  /** Accumulates little-endian binary chunks. */
35
41
  class Writer {
@@ -64,6 +70,12 @@ class Writer {
64
70
  bytes(buf) {
65
71
  this.chunks.push(Buffer.from(buf));
66
72
  }
73
+ /** Zero-pads so the next write lands on an n-byte boundary from the pack start. */
74
+ align(n) {
75
+ const len = this.chunks.reduce((a, b) => a + b.length, 0);
76
+ const pad = (n - (len % n)) % n;
77
+ if (pad) this.chunks.push(Buffer.alloc(pad));
78
+ }
67
79
  done() {
68
80
  return Buffer.concat(this.chunks);
69
81
  }
@@ -88,9 +100,17 @@ function writeGlyph(w, g) {
88
100
  * @returns {Buffer} The pack bytes.
89
101
  */
90
102
  export function emitAssetPack({images = [], fonts = []}) {
103
+ // Emit in a locale-independent sorted order: the discovery maps upstream are filled by esbuild
104
+ // onLoad callbacks in whatever order the bundler visits files, which varies run to run — and an
105
+ // unstable pack means unstable in-flash addresses and non-reproducible builds.
106
+ const byName = k => (a, b) => (a[k] < b[k] ? -1 : a[k] > b[k] ? 1 : 0);
107
+ images = [...images].sort(byName('name'));
108
+ fonts = [...fonts].sort(byName('family'));
109
+
110
+ const version = 2;
91
111
  const w = new Writer();
92
112
  w.bytes(Buffer.from('ERPK', 'ascii'));
93
- w.u32(VERSION);
113
+ w.u32(version);
94
114
  w.u32(images.length);
95
115
  const fontSizes = fonts.reduce((n, f) => n + f.sizes.length, 0);
96
116
  w.u32(fontSizes);
@@ -99,7 +119,12 @@ export function emitAssetPack({images = [], fonts = []}) {
99
119
  w.str(img.name);
100
120
  w.u32(img.width);
101
121
  w.u32(img.height);
102
- // pixels is a Uint32Array (premultiplied ARGB words); copy its LE bytes verbatim.
122
+ if (version >= 2) {
123
+ w.u8(img.format === 'rgb565' ? 1 : 0);
124
+ w.align(4); // the engine reads the pixels in place; keep the pointer 4-byte aligned
125
+ }
126
+ // pixels is a Uint32Array (premultiplied ARGB words) or Uint16Array (RGB565);
127
+ // copy its LE bytes verbatim.
103
128
  w.bytes(
104
129
  Buffer.from(
105
130
  img.pixels.buffer,
package/assets/index.mjs CHANGED
@@ -28,7 +28,8 @@ import {emitAssetPack} from './emit-pack.mjs';
28
28
  * Bakes the given assets and writes assets.generated.{c,h} into outDir.
29
29
  *
30
30
  * @param {object} opts
31
- * @param {Array<{path:string,name:string}>} [opts.images] Discovered image imports.
31
+ * @param {Array<{path:string,name:string,format?:string}>} [opts.images] Discovered image
32
+ * imports; format 'rgb565' bakes 16-bit (see bake-image.mjs), default ARGB8888.
32
33
  * @param {Array<{path:string,family:string,sizes:number[],bpp:number,glyphs:any}>} [opts.fonts]
33
34
  * Discovered font imports with their resolved size/bpp/glyph config.
34
35
  * @param {string} opts.outDir Directory to write the generated files into.
package/build.mjs CHANGED
@@ -139,6 +139,7 @@ if (existsSync(configPath)) {
139
139
  config = (await import(pathToFileURL(configPath).href)).default || {};
140
140
  }
141
141
  const fontConfig = config.fonts || {};
142
+ const imageConfig = config.images || {};
142
143
 
143
144
  const fontJobs = [...fonts.entries()].map(([family, path]) => {
144
145
  const fc = fontConfig[family] || {};
@@ -150,7 +151,11 @@ const fontJobs = [...fonts.entries()].map(([family, path]) => {
150
151
  : [16];
151
152
  return {path, family, sizes, bpp: fc.bpp ?? 4, glyphs: fc.glyphs ?? 'ascii'};
152
153
  });
153
- const imageJobs = [...images.entries()].map(([name, path]) => ({path, name}));
154
+ const imageJobs = [...images.entries()].map(([name, path]) => ({
155
+ path,
156
+ name,
157
+ format: imageConfig[name]?.format,
158
+ }));
154
159
 
155
160
  const summary = bakeAssets({
156
161
  images: imageJobs,
package/cli.mjs CHANGED
@@ -30,7 +30,7 @@ import {
30
30
  readFileSync,
31
31
  writeFileSync,
32
32
  } from 'node:fs';
33
- import {fileURLToPath} from 'node:url';
33
+ import {fileURLToPath, pathToFileURL} from 'node:url';
34
34
  import {dirname, relative, resolve} from 'node:path';
35
35
  import {tmpdir} from 'node:os';
36
36
  import {buildApp, runDevServer} from './sim-server.mjs';
@@ -383,9 +383,18 @@ async function buildAot(cwd, explicit, outDir, screen) {
383
383
  writeFileSync(resolve(outDir, 'app.gen.c'), result.c);
384
384
  writeFileSync(resolve(outDir, 'app.gen.h'), result.h);
385
385
 
386
+ // Optional per-image overrides (same file the JS flows read): assets.config.js
387
+ // export default { images: { 'bg': { format: 'rgb565' } } }
388
+ let cfg = {};
389
+ const cp = resolve(cwd, 'assets.config.js');
390
+ if (existsSync(cp))
391
+ cfg = (await import(pathToFileURL(cp).href)).default || {};
392
+ const imageConfig = cfg.images || {};
393
+
386
394
  const imageJobs = result.images.map(im => ({
387
395
  name: im.name,
388
396
  path: resolve(appDir, im.importPath),
397
+ format: imageConfig[im.name]?.format,
389
398
  }));
390
399
  for (const j of imageJobs) {
391
400
  if (!existsSync(j.path)) {
@@ -157,6 +157,7 @@ export async function packAppContainer({
157
157
  if (existsSync(cp))
158
158
  cfg = (await import(pathToFileURL(cp).href)).default || {};
159
159
  const fontConfig = cfg.fonts || {};
160
+ const imageConfig = cfg.images || {};
160
161
  const fontJobs = [...fonts.entries()].map(([family, path]) => {
161
162
  const fc = fontConfig[family] || {};
162
163
  return {
@@ -171,7 +172,11 @@ export async function packAppContainer({
171
172
  glyphs: fc.glyphs ?? 'ascii',
172
173
  };
173
174
  });
174
- const imageJobs = [...images.entries()].map(([name, path]) => ({path, name}));
175
+ const imageJobs = [...images.entries()].map(([name, path]) => ({
176
+ path,
177
+ name,
178
+ format: imageConfig[name]?.format,
179
+ }));
175
180
  const bakedImages = imageJobs.map(bakeImage);
176
181
  const bakedFonts = fontJobs.map(bakeFont);
177
182
  const assetPack =
@@ -218,6 +218,7 @@ async function bakeAssets({images, fonts, source, projectRoot}) {
218
218
  if (existsSync(cp))
219
219
  cfg = (await import(pathToFileURL(cp).href)).default || {};
220
220
  const fontConfig = cfg.fonts || {};
221
+ const imageConfig = cfg.images || {};
221
222
 
222
223
  const fontJobs = [...fonts.entries()].map(([family, path]) => {
223
224
  const fc = fontConfig[family] || {};
@@ -233,7 +234,11 @@ async function bakeAssets({images, fonts, source, projectRoot}) {
233
234
  glyphs: fc.glyphs ?? 'ascii',
234
235
  };
235
236
  });
236
- const imageJobs = [...images.entries()].map(([name, path]) => ({path, name}));
237
+ const imageJobs = [...images.entries()].map(([name, path]) => ({
238
+ path,
239
+ name,
240
+ format: imageConfig[name]?.format,
241
+ }));
237
242
  const bakedImages = imageJobs.map(bakeImage);
238
243
  const bakedFonts = fontJobs.map(bakeFont);
239
244
  return bakedImages.length || bakedFonts.length
@@ -183,6 +183,7 @@ const configPath = resolve(demoDir, 'assets.config.js');
183
183
  if (existsSync(configPath))
184
184
  config = (await import(pathToFileURL(configPath).href)).default || {};
185
185
  const fontConfig = config.fonts || {};
186
+ const imageConfig = config.images || {};
186
187
 
187
188
  const fontJobs = [...fonts.entries()].map(([family, path]) => {
188
189
  const fc = fontConfig[family] || {};
@@ -194,7 +195,11 @@ const fontJobs = [...fonts.entries()].map(([family, path]) => {
194
195
  : [16];
195
196
  return {path, family, sizes, bpp: fc.bpp ?? 4, glyphs: fc.glyphs ?? 'ascii'};
196
197
  });
197
- const imageJobs = [...images.entries()].map(([name, path]) => ({path, name}));
198
+ const imageJobs = [...images.entries()].map(([name, path]) => ({
199
+ path,
200
+ name,
201
+ format: imageConfig[name]?.format,
202
+ }));
198
203
 
199
204
  const bakedImages = imageJobs.map(i => bakeImage(i));
200
205
  const bakedFonts = fontJobs.map(f => bakeFont(f));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "embedded-react",
3
- "version": "0.10.1",
3
+ "version": "0.11.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
@@ -111,6 +111,7 @@ function createBundle({
111
111
  (await import(`${pathToFileURL(cp).href}?t=${mtime(cp)}`)).default ||
112
112
  {};
113
113
  const fontConfig = cfg.fonts || {};
114
+ const imageConfig = cfg.images || {};
114
115
 
115
116
  const fontJobs = [...fonts.entries()].map(([family, path]) => {
116
117
  const fc = fontConfig[family] || {};
@@ -131,10 +132,11 @@ function createBundle({
131
132
  const imageJobs = [...images.entries()].map(([name, path]) => ({
132
133
  path,
133
134
  name,
135
+ format: imageConfig[name]?.format,
134
136
  }));
135
137
 
136
138
  const sig = JSON.stringify({
137
- i: imageJobs.map(j => [j.name, j.path, mtime(j.path)]).sort(),
139
+ i: imageJobs.map(j => [j.name, j.path, mtime(j.path), j.format]).sort(),
138
140
  f: fontJobs
139
141
  .map(j => [j.family, j.path, mtime(j.path), j.sizes, j.bpp, j.glyphs])
140
142
  .sort(),
@@ -23,6 +23,7 @@ import {NativeUI} from './native-ui.js';
23
23
  import {
24
24
  buildProps,
25
25
  buildTextSpans,
26
+ deepEqualProps,
26
27
  isEventProp,
27
28
  isTextContent,
28
29
  } from './props.js';
@@ -40,23 +41,28 @@ import {splitAnimatedStyle} from './embedded-react/split-style.js';
40
41
  * style={{ transform: [{ scale: v }] }}>` binds without an Animated.* wrapper — which is what the
41
42
  * Flow B AOT compiler does too, so the two render paths stay in parity. An Animated.* wrapper has
42
43
  * already stripped its bindings into a ref, so splitAnimatedStyle finds none here (no double bind).
44
+ *
45
+ * Returns the resolved flat style so a paired applyTextSpans call can reuse it instead of
46
+ * re-flattening props.style from scratch — style flattening (recursive array walk and object merge)
47
+ * is one of the costlier steps in commitUpdate's JS-side work on a bytecode-interpreted MCU target.
43
48
  */
44
49
  function applyProps(type, handle, props) {
45
50
  const {staticStyle, bindings} = splitAnimatedStyle(props.style);
46
- NativeUI.setProps(
47
- handle,
48
- buildProps(type, bindings.length ? {...props, style: staticStyle} : props),
49
- );
51
+ NativeUI.setProps(handle, buildProps(type, props, staticStyle));
50
52
  for (const b of bindings) b.value.__bind(handle, b.prop);
53
+ return staticStyle;
51
54
  }
52
55
 
53
56
  /**
54
57
  * Applies inline-styled text spans for a <Text> node (no-op for other types). buildTextSpans returns
55
58
  * [] for uniform text, which reverts the node to plain-text rendering — so this also clears stale
56
- * spans when a Text changes from styled-runs to a single style across renders.
59
+ * spans when a Text changes from styled-runs to a single style across renders. `flatStyle`, when
60
+ * given, is the already-resolved style from a paired applyProps call on the same props (avoids a
61
+ * second full flattening of props.style).
57
62
  */
58
- function applyTextSpans(type, handle, props) {
59
- if (type === 'Text') NativeUI.setTextSpans(handle, buildTextSpans(props));
63
+ function applyTextSpans(type, handle, props, flatStyle) {
64
+ if (type === 'Text')
65
+ NativeUI.setTextSpans(handle, buildTextSpans(props, flatStyle));
60
66
  }
61
67
 
62
68
  /** Resolves an <Svg>'s render-box dimension from style/props, falling back to the source's intrinsic size. */
@@ -132,20 +138,12 @@ function applyVectorOps(type, handle, props) {
132
138
  }
133
139
 
134
140
  /**
135
- * Decides whether a committed <Svg> update actually needs its op-tape re-uploaded.
136
- *
137
- * Re-marshaling a baked vector op-tape across the JS->C bridge every frame is expensive (it dominates an
138
- * interactive drag on PSRAM-QuickJS), and it's pure waste when only the node's POSITION changed: a
139
- * `<Svg source>` whose imported artifact and resolved box are unchanged renders identical geometry, and its
140
- * on-screen movement is already handled by the layout props (left/top/width/height) via applyProps. So we
141
- * re-upload only when the source artifact reference changes or the resolved box size changes. Declarative
142
- * `<Svg><Path/></Svg>` has no `source` — its shapes live in props/children, which we can't cheaply diff
143
- * here, so it always re-flattens (unchanged behavior).
141
+ * True when a `<Svg source={vectorArtifact}>`'s resolved render box changed between renders — the
142
+ * one style-driven input to the op-tape (the tape is scaled from the artifact's intrinsic px to the
143
+ * box, see scaleVectorArtifact). A style change that leaves the box alone (a position move during a
144
+ * drag, a color tweak) does not need the tape re-uploaded.
144
145
  */
145
- function vectorNeedsUpload(type, prevProps, nextProps) {
146
- if (type !== 'Svg') return false;
147
- if (!nextProps.source) return true; // declarative children: re-flatten as before
148
- if (!prevProps || prevProps.source !== nextProps.source) return true;
146
+ function svgSourceBoxChanged(prevProps, nextProps) {
149
147
  const src = nextProps.source;
150
148
  const iw = src && src.kind === 'vector' ? src.width : undefined;
151
149
  const ih = src && src.kind === 'vector' ? src.height : undefined;
@@ -155,6 +153,88 @@ function vectorNeedsUpload(type, prevProps, nextProps) {
155
153
  );
156
154
  }
157
155
 
156
+ /**
157
+ * Diffs a re-rendered host element's props and returns what commitUpdate must re-apply — or null
158
+ * when nothing observable changed, which makes React skip the commit entirely (no Update effect, no
159
+ * bridge traffic). Re-marshaling props across the JS->C bridge is the dominant cost of a Flow A
160
+ * re-render, and a parent's state change re-renders every non-memoized child with identical props,
161
+ * so the null case is the common one on interactive screens.
162
+ *
163
+ * The payload is a set of section flags, so a partial change re-applies only its section:
164
+ * props — NativeUI.setProps (resolved style + passthrough props + text)
165
+ * spans — inline text spans (<Text> only; derived from children + style)
166
+ * vector — the <Svg> op-tape upload (flattenSvg/scaleVectorArtifact + setVectorOps)
167
+ * events — on* handler registration (an inline closure has a new identity every render and must be
168
+ * re-stored — its captures went stale — but that alone shouldn't re-serialize the props)
169
+ *
170
+ * The vector flag tracks the op-tape's actual inputs. A source artifact tape depends on the source
171
+ * reference and the resolved box; a declarative <Svg><Path/></Svg> tape depends on the shape
172
+ * children, viewBox, and the direct width/height props (flattenSvg never reads style). So a
173
+ * position-only style move of either kind — the interactive-drag hot path — skips the upload.
174
+ *
175
+ * Props buildProps never reads still set the props flag when they change — conservative, and only
176
+ * paid when such a value actually changed.
177
+ */
178
+ function diffUpdate(type, prevProps, nextProps) {
179
+ let props = false;
180
+ let spans = false;
181
+ let events = false;
182
+ let vector = false;
183
+ const diffKey = key => {
184
+ const a = prevProps[key];
185
+ const b = nextProps[key];
186
+ if (Object.is(a, b)) return;
187
+ if (isEventProp(key, a) || isEventProp(key, b)) {
188
+ events = true;
189
+ return;
190
+ }
191
+ switch (key) {
192
+ case 'children':
193
+ // Only subtree-owning types render children through their OWN props (shouldSetTextContent);
194
+ // everywhere else children are separate host instances React mutates directly.
195
+ if (type === 'Text') {
196
+ if (!deepEqualProps(a, b)) {
197
+ props = true; // flat.text is built from children
198
+ spans = true;
199
+ }
200
+ } else if (type === 'Svg') {
201
+ if (!deepEqualProps(a, b)) vector = true;
202
+ }
203
+ return;
204
+ case 'style':
205
+ if (!deepEqualProps(a, b)) {
206
+ props = true;
207
+ if (type === 'Text') spans = true;
208
+ if (type === 'Svg' && nextProps.source)
209
+ vector = vector || svgSourceBoxChanged(prevProps, nextProps);
210
+ }
211
+ return;
212
+ case 'source':
213
+ props = true; // imageName (Image / raster Svg fallback)
214
+ if (type === 'Svg') vector = true; // artifact swap → new tape
215
+ return;
216
+ case 'width':
217
+ case 'height':
218
+ case 'viewBox':
219
+ if (type === 'Svg') {
220
+ props = true; // width/height fold into the resolved style box
221
+ vector = true; // and drive the tape's root transform / artifact scale
222
+ return;
223
+ }
224
+ // fall through: on other types these are ordinary (ignored or passthrough) props
225
+ default:
226
+ if (!deepEqualProps(a, b)) props = true;
227
+ }
228
+ };
229
+ for (const key in prevProps) diffKey(key);
230
+ for (const key in nextProps) {
231
+ if (!Object.prototype.hasOwnProperty.call(prevProps, key)) diffKey(key);
232
+ }
233
+ return props || spans || events || vector
234
+ ? {props, spans, events, vector}
235
+ : null;
236
+ }
237
+
158
238
  /**
159
239
  * Registers/clears on* event handlers. A handler present in old but not new props is cleared.
160
240
  */
@@ -214,8 +294,8 @@ export const hostConfig = {
214
294
  return handle;
215
295
  }
216
296
  const handle = NativeUI.createNode(type);
217
- applyProps(type, handle, props);
218
- applyTextSpans(type, handle, props);
297
+ const flatStyle = applyProps(type, handle, props);
298
+ applyTextSpans(type, handle, props, flatStyle);
219
299
  applyVectorOps(type, handle, props);
220
300
  applyEvents(handle, null, props);
221
301
  return handle;
@@ -266,23 +346,27 @@ export const hostConfig = {
266
346
  clearContainer() {
267
347
  // Children are removed individually via removeChildFromContainer.
268
348
  },
269
- prepareUpdate() {
270
- // Always re-apply: NativeUI.setProps is fully declarative, so a non-null payload is enough.
271
- return true;
349
+ prepareUpdate(instance, type, oldProps, newProps) {
350
+ // Runs in the render phase. null → React schedules no Update effect and commitUpdate never
351
+ // fires for this node — the win that makes an unchanged re-render bridge-free.
352
+ return diffUpdate(type, oldProps, newProps);
272
353
  },
273
- commitUpdate(instance, _payload, type, prevProps, nextProps) {
354
+ commitUpdate(instance, payload, type, prevProps, nextProps) {
274
355
  const raster = rasterSvgArtifact(type, nextProps);
275
356
  if (raster) {
276
357
  // The Svg instance is an Image node (raster fallback); re-apply as image props, never vector ops.
277
- applyProps('Image', instance, rasterImageProps(nextProps, raster));
278
- applyEvents(instance, prevProps, nextProps);
358
+ if (payload.props)
359
+ applyProps('Image', instance, rasterImageProps(nextProps, raster));
360
+ if (payload.events) applyEvents(instance, prevProps, nextProps);
279
361
  return;
280
362
  }
281
- applyProps(type, instance, nextProps);
282
- applyTextSpans(type, instance, nextProps);
283
- if (vectorNeedsUpload(type, prevProps, nextProps))
284
- applyVectorOps(type, instance, nextProps);
285
- applyEvents(instance, prevProps, nextProps);
363
+ // payload.spans is only ever set alongside payload.props for Text nodes (see diffUpdate), so
364
+ // flatStyle is defined whenever applyTextSpans actually needs it.
365
+ let flatStyle;
366
+ if (payload.props) flatStyle = applyProps(type, instance, nextProps);
367
+ if (payload.spans) applyTextSpans(type, instance, nextProps, flatStyle);
368
+ if (payload.vector) applyVectorOps(type, instance, nextProps);
369
+ if (payload.events) applyEvents(instance, prevProps, nextProps);
286
370
  },
287
371
  commitTextUpdate(textInstance, _oldText, newText) {
288
372
  NativeUI.setProps(textInstance, {text: String(newText)});
package/src/props.js CHANGED
@@ -118,9 +118,9 @@ export function flattenTextChildren(children, baseStyle) {
118
118
  * is uniformly the base style (plain text — no spans needed); otherwise one span per styled segment,
119
119
  * each carrying only the span-relevant style keys (the engine inherits the rest from the node).
120
120
  */
121
- export function buildTextSpans(props) {
121
+ export function buildTextSpans(props, flatStyle) {
122
122
  if (!isTextContent(props.children)) return [];
123
- const baseStyle = flattenStyleObj(props.style);
123
+ const baseStyle = flatStyle || flattenStyleObj(props.style);
124
124
  const segments = flattenTextChildren(props.children, baseStyle);
125
125
  if (!segments.some(s => s.style !== baseStyle)) return [];
126
126
  return segments.map(s => {
@@ -148,9 +148,9 @@ export function resolveImageSource(source) {
148
148
  return null;
149
149
  }
150
150
 
151
- export function buildProps(type, props) {
152
- const flat = {};
153
- flattenStyle(props.style, flat);
151
+ export function buildProps(type, props, flatStyle) {
152
+ const flat = flatStyle ? {...flatStyle} : {};
153
+ if (!flatStyle) flattenStyle(props.style, flat);
154
154
  for (const k of PASSTHROUGH) {
155
155
  if (props[k] !== undefined) flat[k] = props[k];
156
156
  }
@@ -172,7 +172,7 @@ export function buildProps(type, props) {
172
172
  // The engine renders this when no spans are set; with spans (buildTextSpans) it carries the same
173
173
  // text for the plain-text fallback. Non-flattenable children fall back to mounted child instances.
174
174
  if (type === 'Text' && isTextContent(props.children)) {
175
- const base = flattenStyleObj(props.style);
175
+ const base = flatStyle || flattenStyleObj(props.style);
176
176
  flat.text = flattenTextChildren(props.children, base)
177
177
  .map(s => s.text)
178
178
  .join('');
@@ -180,6 +180,60 @@ export function buildProps(type, props) {
180
180
  return flat;
181
181
  }
182
182
 
183
+ // Bail-out depth for deepEqualProps. Real host props are shallow (style ≈ 2 levels, a nested-<Text>
184
+ // span or <Svg> shape tree ≈ 3 levels per element); anything deeper is pathological and bails to
185
+ // "changed", whose worst case is a redundant re-apply — exactly the pre-diff behavior.
186
+ const DEEP_EQUAL_MAX_DEPTH = 24;
187
+
188
+ /**
189
+ * Deep value equality for host-prop diffing (the reconciler's prepareUpdate). Re-renders recreate
190
+ * prop objects every time, so identity alone can't tell "nothing changed" — this compares by value:
191
+ * primitives via Object.is, arrays elementwise, React elements by type and props (keys don't affect a
192
+ * flattened <Text>/<Svg> subtree's output), and plain objects key-by-key. Class instances (e.g.,
193
+ * Animated.Value) compare by IDENTITY only: a fresh instance must read as changed, so it gets bound
194
+ * to the node, while the same instance is already bound and can be skipped.
195
+ */
196
+ export function deepEqualProps(a, b, depth = 0) {
197
+ if (Object.is(a, b)) return true;
198
+ if (depth >= DEEP_EQUAL_MAX_DEPTH) return false;
199
+ if (
200
+ typeof a !== 'object' ||
201
+ typeof b !== 'object' ||
202
+ a === null ||
203
+ b === null
204
+ )
205
+ return false;
206
+ if (Array.isArray(a) || Array.isArray(b)) {
207
+ if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length)
208
+ return false;
209
+ for (let i = 0; i < a.length; i++) {
210
+ if (!deepEqualProps(a[i], b[i], depth + 1)) return false;
211
+ }
212
+ return true;
213
+ }
214
+ // React elements: equal when they render the same host output — same type, same props.
215
+ if (a.$$typeof !== b.$$typeof) return false;
216
+ if (a.$$typeof !== undefined) {
217
+ return a.type === b.type && deepEqualProps(a.props, b.props, depth + 1);
218
+ }
219
+ // Plain objects only; class instances fall through to "changed" (identity already ruled equal out).
220
+ const protoA = Object.getPrototypeOf(a);
221
+ const protoB = Object.getPrototypeOf(b);
222
+ if (
223
+ (protoA !== null && protoA !== Object.prototype) ||
224
+ (protoB !== null && protoB !== Object.prototype)
225
+ )
226
+ return false;
227
+ const keysA = Object.keys(a);
228
+ const keysB = Object.keys(b);
229
+ if (keysA.length !== keysB.length) return false;
230
+ for (const k of keysA) {
231
+ if (!Object.prototype.hasOwnProperty.call(b, k)) return false;
232
+ if (!deepEqualProps(a[k], b[k], depth + 1)) return false;
233
+ }
234
+ return true;
235
+ }
236
+
183
237
  /**
184
238
  * True for an `onXxx` prop whose value is a function (an event handler to route via setEvent).
185
239
  */