embedded-react 0.19.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 (148) hide show
  1. package/NOTICE +5 -0
  2. package/README.md +8 -3
  3. package/aot/app-file-loader.mjs +116 -0
  4. package/aot/compile.mjs +180 -90
  5. package/aot/compiler/animations.mjs +568 -317
  6. package/aot/compiler/boot.mjs +97 -35
  7. package/aot/compiler/branch-merge.mjs +4 -3
  8. package/aot/compiler/check.mjs +70 -18
  9. package/aot/compiler/collect.mjs +787 -288
  10. package/aot/compiler/contexts.mjs +391 -0
  11. package/aot/compiler/control-flow.mjs +439 -268
  12. package/aot/compiler/custom-hooks.mjs +686 -0
  13. package/aot/compiler/diagnostics.mjs +22 -25
  14. package/aot/compiler/elements/activity-indicator.mjs +25 -24
  15. package/aot/compiler/elements/button.mjs +182 -0
  16. package/aot/compiler/elements/dial.mjs +91 -77
  17. package/aot/compiler/elements/flat-list.mjs +24 -22
  18. package/aot/compiler/elements/image-background.mjs +76 -0
  19. package/aot/compiler/elements/image.mjs +52 -50
  20. package/aot/compiler/elements/modal.mjs +31 -30
  21. package/aot/compiler/elements/props.mjs +61 -26
  22. package/aot/compiler/elements/rewrite.mjs +118 -0
  23. package/aot/compiler/elements/section-list.mjs +370 -0
  24. package/aot/compiler/elements/switch.mjs +42 -34
  25. package/aot/compiler/elements/text-input.mjs +34 -32
  26. package/aot/compiler/expressions.mjs +1685 -392
  27. package/aot/compiler/handlers.mjs +2029 -547
  28. package/aot/compiler/helper-values.mjs +312 -0
  29. package/aot/compiler/ir/functions.mjs +11 -1
  30. package/aot/compiler/ir/nodes.mjs +43 -4
  31. package/aot/compiler/ir/reads.mjs +223 -22
  32. package/aot/compiler/ir/text.mjs +5 -1
  33. package/aot/compiler/ir/types.mjs +26 -14
  34. package/aot/compiler/ir/vectors.mjs +5 -1
  35. package/aot/compiler/kept-states.mjs +177 -0
  36. package/aot/compiler/keyboard.mjs +17 -7
  37. package/aot/compiler/list-items.mjs +226 -0
  38. package/aot/compiler/list-order.mjs +586 -0
  39. package/aot/compiler/list-split.mjs +259 -0
  40. package/aot/compiler/loops.mjs +582 -0
  41. package/aot/compiler/lower.mjs +246 -111
  42. package/aot/compiler/native-files.mjs +439 -0
  43. package/aot/compiler/native-header.mjs +335 -0
  44. package/aot/compiler/native-modules.mjs +1173 -0
  45. package/aot/compiler/nodes.mjs +195 -172
  46. package/aot/compiler/options.mjs +37 -31
  47. package/aot/compiler/out.mjs +32 -23
  48. package/aot/compiler/package/animations.mjs +779 -0
  49. package/aot/compiler/package/arena.mjs +252 -0
  50. package/aot/compiler/package/assemble.mjs +175 -0
  51. package/aot/compiler/package/bytecode.mjs +315 -0
  52. package/aot/compiler/package/checks.mjs +1026 -0
  53. package/aot/compiler/package/codegen.mjs +2168 -0
  54. package/aot/compiler/package/enums.mjs +148 -0
  55. package/aot/compiler/package/format.mjs +771 -0
  56. package/aot/compiler/package/layouts.mjs +136 -0
  57. package/aot/compiler/package/lower.mjs +2103 -0
  58. package/aot/compiler/package/props.mjs +118 -0
  59. package/aot/compiler/package/string-caps.mjs +515 -0
  60. package/aot/compiler/package/tables.mjs +127 -0
  61. package/aot/compiler/package/vectors.mjs +502 -0
  62. package/aot/compiler/package/writer.mjs +686 -0
  63. package/aot/compiler/pan-responder.mjs +69 -61
  64. package/aot/compiler/parse.mjs +23 -21
  65. package/aot/compiler/record-shapes.mjs +246 -0
  66. package/aot/compiler/records.mjs +654 -0
  67. package/aot/compiler/reducers.mjs +272 -0
  68. package/aot/compiler/static-eval.mjs +340 -30
  69. package/aot/compiler/style-text.mjs +178 -174
  70. package/aot/compiler/svg.mjs +480 -251
  71. package/aot/compiler/switch-cases.mjs +198 -0
  72. package/aot/compiler/tagged-records.mjs +450 -0
  73. package/aot/compiler/typing.mjs +307 -0
  74. package/aot/compiler/updaters.mjs +320 -0
  75. package/aot/compiler/window-dimensions.mjs +94 -0
  76. package/aot/compiler/worked-values.mjs +319 -0
  77. package/aot/demo-file.mjs +30 -0
  78. package/aot/screenshot-smoke.mjs +54 -40
  79. package/aot/style-map.mjs +152 -92
  80. package/assets/bake-font.mjs +123 -77
  81. package/assets/bake-image.mjs +39 -22
  82. package/assets/bake-svg.mjs +361 -262
  83. package/assets/build-builtin-font.mjs +11 -7
  84. package/assets/emit-c.mjs +77 -58
  85. package/assets/emit-container.mjs +123 -37
  86. package/assets/emit-pack.mjs +77 -67
  87. package/assets/font-config.mjs +9 -6
  88. package/assets/font-sizes.mjs +163 -123
  89. package/assets/glyph-coverage.mjs +74 -54
  90. package/assets/index.mjs +31 -9
  91. package/assets/rasterize.mjs +126 -99
  92. package/assets/svg-loader.mjs +8 -8
  93. package/build.mjs +23 -13
  94. package/cli.mjs +402 -172
  95. package/compile-bin.mjs +3 -3
  96. package/flash.mjs +537 -0
  97. package/hotreload/dev-device.mjs +90 -33
  98. package/hotreload/pack-app.mjs +55 -43
  99. package/hotreload/pack-split.mjs +62 -64
  100. package/hotreload/package-transfer.mjs +175 -0
  101. package/hotreload/protocol.mjs +50 -37
  102. package/hotreload/uploader.mjs +38 -27
  103. package/hotreload/watch-tree.mjs +19 -19
  104. package/pack-container.mjs +37 -21
  105. package/package.json +7 -8
  106. package/persist-transform.mjs +34 -28
  107. package/qjsc-wasm.mjs +25 -14
  108. package/sim/embedded-react.cjs +1 -1
  109. package/sim/embedded-react.js +1 -1
  110. package/sim/embedded-react.wasm +0 -0
  111. package/sim/index.html +94 -85
  112. package/sim-server.mjs +113 -94
  113. package/src/embedded-react/Animated.js +24 -24
  114. package/src/embedded-react/Dimensions.js +37 -0
  115. package/src/embedded-react/Easing.js +1 -1
  116. package/src/embedded-react/FlatList.js +3 -3
  117. package/src/embedded-react/LayoutAnimation.js +8 -5
  118. package/src/embedded-react/PanResponder.js +75 -71
  119. package/src/embedded-react/Pressable.js +2 -8
  120. package/src/embedded-react/SectionList.js +7 -9
  121. package/src/embedded-react/StyleSheet.js +4 -3
  122. package/src/embedded-react/TouchableOpacity.js +13 -8
  123. package/src/embedded-react/index.d.ts +88 -8
  124. package/src/embedded-react/index.js +2 -0
  125. package/src/embedded-react/layout-anim-config.js +10 -4
  126. package/src/embedded-react/list-child.js +5 -5
  127. package/src/embedded-react/named-colors.js +1 -1
  128. package/src/embedded-react/nativeModule.js +462 -0
  129. package/src/embedded-react/split-style.js +11 -11
  130. package/src/embedded-react/svg-ops.js +760 -593
  131. package/src/embedded-react/useHostValue.js +3 -3
  132. package/src/embedded-react/usePersistentState.js +6 -6
  133. package/src/embedded-react/warn-props.js +1 -1
  134. package/src/host-config.js +60 -53
  135. package/src/props.js +49 -41
  136. package/src/renderer.js +7 -4
  137. package/aot/compiler/assemble.mjs +0 -944
  138. package/aot/compiler/c/animations.mjs +0 -436
  139. package/aot/compiler/c/boot.mjs +0 -127
  140. package/aot/compiler/c/expressions.mjs +0 -270
  141. package/aot/compiler/c/functions.mjs +0 -268
  142. package/aot/compiler/c/keyboard.mjs +0 -96
  143. package/aot/compiler/c/nodes.mjs +0 -303
  144. package/aot/compiler/c/pan-responder.mjs +0 -136
  145. package/aot/compiler/c/statements.mjs +0 -319
  146. package/aot/compiler/c/text.mjs +0 -83
  147. package/aot/compiler/c/vectors.mjs +0 -381
  148. package/aot/compiler/c-syntax.mjs +0 -127
@@ -32,6 +32,10 @@ import {
32
32
  /** Name used for the engine's fallback font in warnings (it has no family of its own). */
33
33
  export const BUILTIN_FAMILY = 'the built-in font';
34
34
 
35
+ const MAX_CODEPOINT = 0x10ffff;
36
+ const CODEPOINT_HEX_DIGITS = 4;
37
+ const EXCERPT_CONTEXT = 12; // characters shown either side of the one found
38
+
35
39
  // Comments first so an apostrophe inside one can't open a bogus string; then the three literal
36
40
  // forms. Bundled output is machine-generated, so the simple form is enough (a regex literal
37
41
  // containing a lone quote is the only realistic misread, and it costs at most a stray sample).
@@ -44,26 +48,29 @@ const SIMPLE_ESCAPES = {n: '\n', t: '\t', r: '\r', b: '\b', f: '\f', v: '\v'};
44
48
  function decodeEscapes(body) {
45
49
  return body.replace(
46
50
  /\\u\{([0-9a-fA-F]{1,6})\}|\\u([0-9a-fA-F]{4})|\\x([0-9a-fA-F]{2})|\\([\s\S])/g,
47
- (_m, braced, u, x, other) => {
51
+ (_match, braced, unicode, hex, other) => {
48
52
  if (braced !== undefined) {
49
- const cp = parseInt(braced, 16);
50
- return cp <= 0x10ffff ? String.fromCodePoint(cp) : '';
53
+ const codepoint = parseInt(braced, 16);
54
+ return codepoint <= MAX_CODEPOINT
55
+ ? String.fromCodePoint(codepoint)
56
+ : '';
51
57
  }
52
- if (u !== undefined) return String.fromCharCode(parseInt(u, 16));
53
- if (x !== undefined) return String.fromCharCode(parseInt(x, 16));
58
+ if (unicode !== undefined)
59
+ return String.fromCharCode(parseInt(unicode, 16));
60
+ if (hex !== undefined) return String.fromCharCode(parseInt(hex, 16));
54
61
  return SIMPLE_ESCAPES[other] ?? other; // \\ \' \" \` and friends: the character itself
55
62
  },
56
63
  );
57
64
  }
58
65
 
59
66
  /** Invisible/formatting characters that are never baked and never render — not worth warning about. */
60
- function ignorable(cp) {
67
+ function ignorable(codepoint) {
61
68
  return (
62
- (cp >= 0x7f && cp <= 0x9f) || // DEL + C1 controls
63
- (cp >= 0x200b && cp <= 0x200f) || // zero-width + bidi marks
64
- (cp >= 0x2028 && cp <= 0x202e) || // line/paragraph separators + bidi overrides
65
- (cp >= 0xfe00 && cp <= 0xfe0f) || // variation selectors
66
- cp === 0xfeff // BOM
69
+ (codepoint >= 0x7f && codepoint <= 0x9f) || // DEL + C1 controls
70
+ (codepoint >= 0x200b && codepoint <= 0x200f) || // zero-width + bidi marks
71
+ (codepoint >= 0x2028 && codepoint <= 0x202e) || // line/paragraph separators + bidi overrides
72
+ (codepoint >= 0xfe00 && codepoint <= 0xfe0f) || // variation selectors
73
+ codepoint === 0xfeff // BOM
67
74
  );
68
75
  }
69
76
 
@@ -84,22 +91,26 @@ const JSX_TEXT = />([^<>{}]+)</g;
84
91
  export function scanTextCodepoints(source, {jsx = false} = {}) {
85
92
  const found = new Map();
86
93
  const collect = text => {
87
- let i = 0;
88
- for (const ch of text) {
89
- const cp = ch.codePointAt(0);
90
- if (cp > ASCII_LAST && !ignorable(cp) && !found.has(cp))
91
- found.set(cp, excerpt(text, i, ch.length));
92
- i += ch.length;
94
+ let offset = 0;
95
+ for (const character of text) {
96
+ const codepoint = character.codePointAt(0);
97
+ if (
98
+ codepoint > ASCII_LAST &&
99
+ !ignorable(codepoint) &&
100
+ !found.has(codepoint)
101
+ )
102
+ found.set(codepoint, excerpt(text, offset, character.length));
103
+ offset += character.length;
93
104
  }
94
105
  };
95
106
 
96
107
  // Blank each token out as it is read, so the JSX pass below sees neither strings (already
97
108
  // collected) nor comments (never rendered) — only real element text.
98
- const bare = source.replace(LITERALS, tok => {
99
- if (tok[0] !== '/') collect(decodeEscapes(tok.slice(1, -1)));
100
- return ' '.repeat(tok.length);
109
+ const bare = source.replace(LITERALS, token => {
110
+ if (token[0] !== '/') collect(decodeEscapes(token.slice(1, -1)));
111
+ return ' '.repeat(token.length);
101
112
  });
102
- if (jsx) for (const m of bare.matchAll(JSX_TEXT)) collect(m[1]);
113
+ if (jsx) for (const match of bare.matchAll(JSX_TEXT)) collect(match[1]);
103
114
  return found;
104
115
  }
105
116
 
@@ -113,14 +124,14 @@ export function scanTextCodepoints(source, {jsx = false} = {}) {
113
124
  */
114
125
  export function textSignature(source, opts) {
115
126
  return [...scanTextCodepoints(source, opts).keys()]
116
- .sort((a, b) => a - b)
127
+ .sort((left, right) => left - right)
117
128
  .join(',');
118
129
  }
119
130
 
120
131
  /** A one-line, printable window of `text` around the character at `at` (a UTF-16 index). */
121
- function excerpt(text, at, len) {
122
- const start = Math.max(0, at - 12);
123
- const end = Math.min(text.length, at + len + 12);
132
+ function excerpt(text, at, length) {
133
+ const start = Math.max(0, at - EXCERPT_CONTEXT);
134
+ const end = Math.min(text.length, at + length + EXCERPT_CONTEXT);
124
135
  const body = text
125
136
  .slice(start, end)
126
137
  .replace(/[\n\r\t]/g, ' ')
@@ -135,8 +146,9 @@ function coverageOf(baked) {
135
146
  const covered = new Set();
136
147
  const first = size ? size.first : ASCII_FIRST;
137
148
  const last = size ? size.last : ASCII_LAST;
138
- for (let cp = first; cp <= last; cp++) covered.add(cp);
139
- for (const e of size?.extras ?? []) covered.add(e.codepoint);
149
+ for (let codepoint = first; codepoint <= last; codepoint++)
150
+ covered.add(codepoint);
151
+ for (const extra of size?.extras ?? []) covered.add(extra.codepoint);
140
152
  return covered;
141
153
  }
142
154
 
@@ -172,33 +184,35 @@ function builtinFont() {
172
184
  */
173
185
  export function findMissingGlyphs({source, fonts = [], jsx = false}) {
174
186
  const checked = fonts.length ? fonts : [builtinFont()];
175
- const coverage = checked.map(f => ({
176
- family: f.family,
177
- path: f.path,
178
- covered: coverageOf(f),
187
+ const coverage = checked.map(font => ({
188
+ family: font.family,
189
+ path: font.path,
190
+ covered: coverageOf(font),
179
191
  }));
180
192
  // Opened lazily and only for a font with a gap: most builds have none and pay nothing.
181
193
  const probes = new Map();
182
- const hasGlyph = (font, cp) => {
194
+ const hasGlyph = (font, codepoint) => {
183
195
  if (!font.path) return true; // the built-in font's coverage is its bake, nothing more to ask
184
196
  if (!probes.has(font.path))
185
197
  probes.set(font.path, loadGlyphProbe(font.path));
186
- return probes.get(font.path)(cp);
198
+ return probes.get(font.path)(codepoint);
187
199
  };
188
200
 
189
201
  const missing = [];
190
- for (const [cp, sample] of scanTextCodepoints(source, {jsx})) {
191
- const gaps = coverage.filter(c => !c.covered.has(cp));
202
+ for (const [codepoint, sample] of scanTextCodepoints(source, {jsx})) {
203
+ const gaps = coverage.filter(entry => !entry.covered.has(codepoint));
192
204
  if (!gaps.length) continue;
193
205
  missing.push({
194
- codepoint: cp,
195
- char: String.fromCodePoint(cp),
206
+ codepoint,
207
+ char: String.fromCodePoint(codepoint),
196
208
  sample,
197
- missingFrom: gaps.map(g => g.family),
198
- noGlyphIn: gaps.filter(g => !hasGlyph(g, cp)).map(g => g.family),
209
+ missingFrom: gaps.map(gap => gap.family),
210
+ noGlyphIn: gaps
211
+ .filter(gap => !hasGlyph(gap, codepoint))
212
+ .map(gap => gap.family),
199
213
  });
200
214
  }
201
- return missing.sort((a, b) => a.codepoint - b.codepoint);
215
+ return missing.sort((left, right) => left.codepoint - right.codepoint);
202
216
  }
203
217
 
204
218
  const MAX_LISTED = 12;
@@ -213,31 +227,37 @@ const MAX_LISTED = 12;
213
227
  */
214
228
  export function formatMissingGlyphs(missing, fonts = []) {
215
229
  if (!missing.length) return '';
216
- const lines = missing.slice(0, MAX_LISTED).map(m => {
217
- const hex = m.codepoint.toString(16).toUpperCase().padStart(4, '0');
218
- const note = m.noGlyphIn.length
230
+ const lines = missing.slice(0, MAX_LISTED).map(glyph => {
231
+ const hex = glyph.codepoint
232
+ .toString(16)
233
+ .toUpperCase()
234
+ .padStart(CODEPOINT_HEX_DIGITS, '0');
235
+ const note = glyph.noGlyphIn.length
219
236
  ? ` (the font file itself has no glyph for it — pick a font that covers it)`
220
237
  : '';
221
- return ` U+${hex} '${m.char}' missing from ${m.missingFrom.join(', ')}${note} in "${m.sample}"`;
238
+ return ` U+${hex} '${glyph.char}' missing from ${glyph.missingFrom.join(', ')}${note} in "${glyph.sample}"`;
222
239
  });
223
240
  if (missing.length > MAX_LISTED)
224
241
  lines.push(` … and ${missing.length - MAX_LISTED} more`);
225
242
 
226
243
  // One config entry per font, listing only what baking it there would actually fix.
227
244
  const perFamily = fonts
228
- .map(f => {
229
- const chars = missing
245
+ .map(font => {
246
+ const characters = missing
230
247
  .filter(
231
- m =>
232
- m.missingFrom.includes(f.family) && !m.noGlyphIn.includes(f.family),
248
+ glyph =>
249
+ glyph.missingFrom.includes(font.family) &&
250
+ !glyph.noGlyphIn.includes(font.family),
233
251
  )
234
- .map(m => m.char)
252
+ .map(glyph => glyph.char)
235
253
  .join('');
236
254
  // A family is a file basename, so it often needs quoting to be a valid key ('Inter-Regular').
237
- const key = /^[A-Za-z_$][\w$]*$/.test(f.family)
238
- ? f.family
239
- : JSON.stringify(f.family);
240
- return chars ? `${key}: {extraGlyphs: ${JSON.stringify(chars)}}` : null;
255
+ const key = /^[A-Za-z_$][\w$]*$/.test(font.family)
256
+ ? font.family
257
+ : JSON.stringify(font.family);
258
+ return characters
259
+ ? `${key}: {extraGlyphs: ${JSON.stringify(characters)}}`
260
+ : null;
241
261
  })
242
262
  .filter(Boolean);
243
263
 
@@ -246,7 +266,7 @@ export function formatMissingGlyphs(missing, fonts = []) {
246
266
  : fonts.length
247
267
  ? ` fix: bake these from a font that has them (assets.config.js → fonts: {<Family>: {extraGlyphs: ...}})`
248
268
  : ` fix: the built-in font covers ASCII + common symbols only — import a .ttf/.otf and bake the\n` +
249
- ` rest with assets.config.js → fonts: {<Family>: {extraGlyphs: ${JSON.stringify(missing.map(m => m.char).join(''))}}}`;
269
+ ` rest with assets.config.js → fonts: {<Family>: {extraGlyphs: ${JSON.stringify(missing.map(glyph => glyph.char).join(''))}}}`;
250
270
 
251
271
  return (
252
272
  `embedded-react: ${missing.length} character(s) in the app's text have no baked glyph and will ` +
package/assets/index.mjs CHANGED
@@ -47,13 +47,13 @@ export function bakeAssets({
47
47
  source,
48
48
  usedSizes,
49
49
  }) {
50
- const bakedImages = images.map(i => bakeImage(i));
51
- const bakedFonts = fonts.map(f => bakeFont(f));
50
+ const bakedImages = images.map(image => bakeImage(image));
51
+ const bakedFonts = fonts.map(font => bakeFont(font));
52
52
  if (source) warnMissingGlyphs({source, fonts: bakedFonts});
53
53
  if (usedSizes) warnFontSizes({used: usedSizes, fonts: bakedFonts});
54
54
 
55
55
  const headerName = 'assets.generated.h';
56
- const {c, h} = emitAssetsC({
56
+ const {c: cSource, h: header} = emitAssetsC({
57
57
  headerName,
58
58
  images: bakedImages,
59
59
  fonts: bakedFonts,
@@ -62,13 +62,32 @@ export function bakeAssets({
62
62
  fs.mkdirSync(outDir, {recursive: true});
63
63
  const cPath = path.join(outDir, 'assets.generated.c');
64
64
  const hPath = path.join(outDir, headerName);
65
- fs.writeFileSync(cPath, c);
66
- fs.writeFileSync(hPath, h);
65
+ fs.writeFileSync(cPath, cSource);
66
+ fs.writeFileSync(hPath, header);
67
67
 
68
- const fontSizes = bakedFonts.reduce((n, f) => n + f.sizes.length, 0);
68
+ const fontSizes = bakedFonts.reduce(
69
+ (total, font) => total + font.sizes.length,
70
+ 0,
71
+ );
69
72
  return {cPath, hPath, images: bakedImages.length, fonts: fontSizes};
70
73
  }
71
74
 
75
+ /**
76
+ * Bakes the given assets into ERPK pack bytes, with the same bakers as bakeAssets, without writing a file.
77
+ *
78
+ * @param {object} opts
79
+ * @param {Array<{path:string,name:string}>} [opts.images]
80
+ * @param {Array<{path:string,family:string,sizes:number[],bpp:number,glyphs:any,extraGlyphs:any}>}
81
+ * [opts.fonts]
82
+ * @returns {Buffer} The pack.
83
+ */
84
+ export function bakeAssetPackBytes({images = [], fonts = []}) {
85
+ return emitAssetPack({
86
+ images: images.map(image => bakeImage(image)),
87
+ fonts: fonts.map(font => bakeFont(font)),
88
+ });
89
+ }
90
+
72
91
  /**
73
92
  * Bakes the given assets into a binary ERPK pack the simulator loads at runtime (hot-reloadable),
74
93
  * using the same bakers as bakeAssets so the result is pixel-identical.
@@ -89,14 +108,17 @@ export function bakeAssetPack({
89
108
  source,
90
109
  usedSizes,
91
110
  }) {
92
- const bakedImages = images.map(i => bakeImage(i));
93
- const bakedFonts = fonts.map(f => bakeFont(f));
111
+ const bakedImages = images.map(image => bakeImage(image));
112
+ const bakedFonts = fonts.map(font => bakeFont(font));
94
113
  if (source) warnMissingGlyphs({source, fonts: bakedFonts});
95
114
  if (usedSizes) warnFontSizes({used: usedSizes, fonts: bakedFonts});
96
115
  const pack = emitAssetPack({images: bakedImages, fonts: bakedFonts});
97
116
  fs.mkdirSync(path.dirname(outPath), {recursive: true});
98
117
  fs.writeFileSync(outPath, pack);
99
- const fontSizes = bakedFonts.reduce((n, f) => n + f.sizes.length, 0);
118
+ const fontSizes = bakedFonts.reduce(
119
+ (total, font) => total + font.sizes.length,
120
+ 0,
121
+ );
100
122
  return {
101
123
  path: outPath,
102
124
  bytes: pack.length,
@@ -23,6 +23,11 @@
23
23
  // pixelSize), so xOffset is the glyph's left bearing from the pen and yOffset is the distance from
24
24
  // the line box top (y = 0) down to the top of the glyph ink.
25
25
 
26
+ const DEFAULT_SUPERSAMPLE = 4;
27
+ const DEFAULT_CURVE_STEPS = 12;
28
+ const COVERAGE_MAX = 255;
29
+ const SAMPLE_CENTER = 0.5;
30
+
26
31
  /**
27
32
  * Flattens opentype path commands into closed contours of {x, y} points.
28
33
  *
@@ -32,60 +37,66 @@
32
37
  */
33
38
  function flattenCommands(commands, steps) {
34
39
  const contours = [];
35
- let cur = null;
36
- let cx = 0;
37
- let cy = 0; // current point
38
- let sx = 0;
39
- let sy = 0; // contour start
40
- for (const c of commands) {
41
- if (c.type === 'M') {
42
- if (cur && cur.length > 1) contours.push(cur);
43
- cur = [{x: c.x, y: c.y}];
44
- cx = sx = c.x;
45
- cy = sy = c.y;
46
- } else if (c.type === 'L') {
47
- cur.push({x: c.x, y: c.y});
48
- cx = c.x;
49
- cy = c.y;
50
- } else if (c.type === 'Q') {
51
- for (let i = 1; i <= steps; i++) {
52
- const t = i / steps;
53
- const mt = 1 - t;
54
- cur.push({
55
- x: mt * mt * cx + 2 * mt * t * c.x1 + t * t * c.x,
56
- y: mt * mt * cy + 2 * mt * t * c.y1 + t * t * c.y,
40
+ let contour = null;
41
+ let currentX = 0;
42
+ let currentY = 0;
43
+ let startX = 0;
44
+ let startY = 0;
45
+ for (const command of commands) {
46
+ if (command.type === 'M') {
47
+ if (contour && contour.length > 1) contours.push(contour);
48
+ contour = [{x: command.x, y: command.y}];
49
+ currentX = startX = command.x;
50
+ currentY = startY = command.y;
51
+ } else if (command.type === 'L') {
52
+ contour.push({x: command.x, y: command.y});
53
+ currentX = command.x;
54
+ currentY = command.y;
55
+ } else if (command.type === 'Q') {
56
+ for (let step = 1; step <= steps; step++) {
57
+ const t = step / steps;
58
+ const oneMinusT = 1 - t;
59
+ contour.push({
60
+ x:
61
+ oneMinusT * oneMinusT * currentX +
62
+ 2 * oneMinusT * t * command.x1 +
63
+ t * t * command.x,
64
+ y:
65
+ oneMinusT * oneMinusT * currentY +
66
+ 2 * oneMinusT * t * command.y1 +
67
+ t * t * command.y,
57
68
  });
58
69
  }
59
- cx = c.x;
60
- cy = c.y;
61
- } else if (c.type === 'C') {
62
- for (let i = 1; i <= steps; i++) {
63
- const t = i / steps;
64
- const mt = 1 - t;
65
- cur.push({
70
+ currentX = command.x;
71
+ currentY = command.y;
72
+ } else if (command.type === 'C') {
73
+ for (let step = 1; step <= steps; step++) {
74
+ const t = step / steps;
75
+ const oneMinusT = 1 - t;
76
+ contour.push({
66
77
  x:
67
- mt * mt * mt * cx +
68
- 3 * mt * mt * t * c.x1 +
69
- 3 * mt * t * t * c.x2 +
70
- t * t * t * c.x,
78
+ oneMinusT * oneMinusT * oneMinusT * currentX +
79
+ 3 * oneMinusT * oneMinusT * t * command.x1 +
80
+ 3 * oneMinusT * t * t * command.x2 +
81
+ t * t * t * command.x,
71
82
  y:
72
- mt * mt * mt * cy +
73
- 3 * mt * mt * t * c.y1 +
74
- 3 * mt * t * t * c.y2 +
75
- t * t * t * c.y,
83
+ oneMinusT * oneMinusT * oneMinusT * currentY +
84
+ 3 * oneMinusT * oneMinusT * t * command.y1 +
85
+ 3 * oneMinusT * t * t * command.y2 +
86
+ t * t * t * command.y,
76
87
  });
77
88
  }
78
- cx = c.x;
79
- cy = c.y;
80
- } else if (c.type === 'Z') {
81
- if (cur) {
82
- cur.push({x: sx, y: sy}); // close the contour
83
- if (cur.length > 1) contours.push(cur);
84
- cur = null;
89
+ currentX = command.x;
90
+ currentY = command.y;
91
+ } else if (command.type === 'Z') {
92
+ if (contour) {
93
+ contour.push({x: startX, y: startY}); // close the contour
94
+ if (contour.length > 1) contours.push(contour);
95
+ contour = null;
85
96
  }
86
97
  }
87
98
  }
88
- if (cur && cur.length > 1) contours.push(cur);
99
+ if (contour && contour.length > 1) contours.push(contour);
89
100
  return contours;
90
101
  }
91
102
 
@@ -100,20 +111,20 @@ function flattenCommands(commands, steps) {
100
111
  * An empty (width 0, height 0) result for whitespace / glyphs with no ink.
101
112
  */
102
113
  export function rasterize(path, opts = {}) {
103
- const ss = opts.ss || 4;
104
- const steps = opts.steps || 12;
114
+ const supersample = opts.ss || DEFAULT_SUPERSAMPLE;
115
+ const steps = opts.steps || DEFAULT_CURVE_STEPS;
105
116
  const contours = flattenCommands(path.commands, steps);
106
117
 
107
118
  let minX = Infinity;
108
119
  let minY = Infinity;
109
120
  let maxX = -Infinity;
110
121
  let maxY = -Infinity;
111
- for (const ct of contours) {
112
- for (const p of ct) {
113
- if (p.x < minX) minX = p.x;
114
- if (p.x > maxX) maxX = p.x;
115
- if (p.y < minY) minY = p.y;
116
- if (p.y > maxY) maxY = p.y;
122
+ for (const contour of contours) {
123
+ for (const point of contour) {
124
+ if (point.x < minX) minX = point.x;
125
+ if (point.x > maxX) maxX = point.x;
126
+ if (point.y < minY) minY = point.y;
127
+ if (point.y > maxY) maxY = point.y;
117
128
  }
118
129
  }
119
130
  if (!Number.isFinite(minX)) {
@@ -126,10 +137,10 @@ export function rasterize(path, opts = {}) {
126
137
  };
127
138
  }
128
139
 
129
- const x0 = Math.floor(minX);
130
- const y0 = Math.floor(minY);
131
- const width = Math.ceil(maxX) - x0;
132
- const height = Math.ceil(maxY) - y0;
140
+ const originX = Math.floor(minX);
141
+ const originY = Math.floor(minY);
142
+ const width = Math.ceil(maxX) - originX;
143
+ const height = Math.ceil(maxY) - originY;
133
144
  if (width <= 0 || height <= 0) {
134
145
  return {
135
146
  width: 0,
@@ -140,64 +151,80 @@ export function rasterize(path, opts = {}) {
140
151
  };
141
152
  }
142
153
 
143
- // Non-horizontal edges, normalized so ylo < yhi; dir is the winding contribution.
154
+ // Non-horizontal edges, normalized so yLow < yHigh; winding is the edge's winding contribution.
144
155
  const edges = [];
145
- for (const ct of contours) {
146
- for (let i = 0; i + 1 < ct.length; i++) {
147
- const a = ct[i];
148
- const b = ct[i + 1];
149
- if (a.y === b.y) continue;
150
- if (a.y < b.y)
156
+ for (const contour of contours) {
157
+ for (let index = 0; index + 1 < contour.length; index++) {
158
+ const from = contour[index];
159
+ const to = contour[index + 1];
160
+ if (from.y === to.y) continue;
161
+ if (from.y < to.y)
151
162
  edges.push({
152
- ylo: a.y,
153
- yhi: b.y,
154
- x: a.x,
155
- dxdy: (b.x - a.x) / (b.y - a.y),
156
- dir: 1,
163
+ yLow: from.y,
164
+ yHigh: to.y,
165
+ x: from.x,
166
+ slope: (to.x - from.x) / (to.y - from.y),
167
+ winding: 1,
157
168
  });
158
169
  else
159
170
  edges.push({
160
- ylo: b.y,
161
- yhi: a.y,
162
- x: b.x,
163
- dxdy: (a.x - b.x) / (a.y - b.y),
164
- dir: -1,
171
+ yLow: to.y,
172
+ yHigh: from.y,
173
+ x: to.x,
174
+ slope: (from.x - to.x) / (from.y - to.y),
175
+ winding: -1,
165
176
  });
166
177
  }
167
178
  }
168
179
 
169
180
  const counts = new Uint16Array(width * height); // covered subsamples per output pixel
170
- const subW = width * ss;
171
- for (let sy = 0; sy < height * ss; sy++) {
172
- const sampleY = y0 + (sy + 0.5) / ss;
173
- const xs = [];
174
- for (const e of edges) {
175
- if (sampleY >= e.ylo && sampleY < e.yhi) {
176
- xs.push({x: e.x + (sampleY - e.ylo) * e.dxdy, dir: e.dir});
181
+ const subsampleWidth = width * supersample;
182
+ for (
183
+ let subsampleRow = 0;
184
+ subsampleRow < height * supersample;
185
+ subsampleRow++
186
+ ) {
187
+ const sampleY = originY + (subsampleRow + SAMPLE_CENTER) / supersample;
188
+ const crossings = [];
189
+ for (const edge of edges) {
190
+ if (sampleY >= edge.yLow && sampleY < edge.yHigh) {
191
+ crossings.push({
192
+ x: edge.x + (sampleY - edge.yLow) * edge.slope,
193
+ winding: edge.winding,
194
+ });
177
195
  }
178
196
  }
179
- if (xs.length < 2) continue;
180
- xs.sort((p, q) => p.x - q.x);
181
- const outRow = (sy / ss) | 0;
182
- let wind = 0;
183
- for (let i = 0; i + 1 < xs.length; i++) {
184
- wind += xs[i].dir;
185
- if (wind === 0) continue;
186
- // Interior span [xs[i].x, xs[i+1].x): tally the subsample columns whose centre falls inside.
187
- let sxa = Math.ceil((xs[i].x - x0) * ss - 0.5);
188
- let sxb = Math.ceil((xs[i + 1].x - x0) * ss - 0.5);
189
- if (sxa < 0) sxa = 0;
190
- if (sxb > subW) sxb = subW;
191
- for (let sx = sxa; sx < sxb; sx++) {
192
- counts[outRow * width + ((sx / ss) | 0)]++;
197
+ if (crossings.length < 2) continue;
198
+ crossings.sort((left, right) => left.x - right.x);
199
+ const outputRow = (subsampleRow / supersample) | 0;
200
+ let winding = 0;
201
+ for (let index = 0; index + 1 < crossings.length; index++) {
202
+ winding += crossings[index].winding;
203
+ if (winding === 0) continue;
204
+ // Interior span [crossings[index].x, crossings[index+1].x): tally the subsample columns whose
205
+ // centre falls inside.
206
+ let spanStart = Math.ceil(
207
+ (crossings[index].x - originX) * supersample - SAMPLE_CENTER,
208
+ );
209
+ let spanEnd = Math.ceil(
210
+ (crossings[index + 1].x - originX) * supersample - SAMPLE_CENTER,
211
+ );
212
+ if (spanStart < 0) spanStart = 0;
213
+ if (spanEnd > subsampleWidth) spanEnd = subsampleWidth;
214
+ for (
215
+ let subsampleColumn = spanStart;
216
+ subsampleColumn < spanEnd;
217
+ subsampleColumn++
218
+ ) {
219
+ counts[outputRow * width + ((subsampleColumn / supersample) | 0)]++;
193
220
  }
194
221
  }
195
222
  }
196
223
 
197
- const maxCov = ss * ss;
224
+ const maxCoverage = supersample * supersample;
198
225
  const coverage = new Uint8Array(width * height);
199
- for (let i = 0; i < coverage.length; i++) {
200
- coverage[i] = Math.round((counts[i] * 255) / maxCov);
226
+ for (let index = 0; index < coverage.length; index++) {
227
+ coverage[index] = Math.round((counts[index] * COVERAGE_MAX) / maxCoverage);
201
228
  }
202
- return {width, height, xOffset: x0, yOffset: y0, coverage};
229
+ return {width, height, xOffset: originX, yOffset: originY, coverage};
203
230
  }
@@ -27,7 +27,7 @@ import {readFileSync} from 'node:fs';
27
27
  import {basename} from 'node:path';
28
28
  import {svgToVector, svgToRaster, writeRasterPng} from './bake-svg.mjs';
29
29
 
30
- const assetName = p => basename(p).replace(/\.[^.]+$/, '');
30
+ const assetName = filePath => basename(filePath).replace(/\.[^.]+$/, '');
31
31
 
32
32
  /**
33
33
  * Registers a `.svg` onLoad on an esbuild build.
@@ -41,12 +41,12 @@ export function registerSvgVectorLoader(build, addRasterAsset) {
41
41
  build.onLoad({filter: /\.svg$/i}, async args => {
42
42
  try {
43
43
  const svg = readFileSync(args.path, 'utf8');
44
- const {dropped = [], ...vec} = await svgToVector(svg);
44
+ const {dropped = [], ...vector} = await svgToVector(svg);
45
45
  if (dropped.length) {
46
- const feats = dropped.join(', ');
46
+ const features = dropped.join(', ');
47
47
  if (addRasterAsset) {
48
48
  console.warn(
49
- `embedded-react: ${basename(args.path)} uses unsupported SVG feature(s) [${feats}] — rasterizing ` +
49
+ `embedded-react: ${basename(args.path)} uses unsupported SVG feature(s) [${features}] — rasterizing ` +
50
50
  `it as a fallback image. (Raster loses scalability and costs RAM; simplify the SVG to keep it a ` +
51
51
  `live vector.)`,
52
52
  );
@@ -59,20 +59,20 @@ export function registerSvgVectorLoader(build, addRasterAsset) {
59
59
  };
60
60
  }
61
61
  console.warn(
62
- `embedded-react: ${basename(args.path)} uses unsupported SVG feature(s) [${feats}] and this build has ` +
62
+ `embedded-react: ${basename(args.path)} uses unsupported SVG feature(s) [${features}] and this build has ` +
63
63
  `no raster fallback — that content will NOT render. Simplify the SVG, or import it via a bundler that ` +
64
64
  `supports the image pipeline.`,
65
65
  );
66
66
  }
67
67
  return {
68
- contents: `module.exports = ${JSON.stringify({kind: 'vector', ...vec})};`,
68
+ contents: `module.exports = ${JSON.stringify({kind: 'vector', ...vector})};`,
69
69
  loader: 'js',
70
70
  };
71
- } catch (e) {
71
+ } catch (error) {
72
72
  return {
73
73
  errors: [
74
74
  {
75
- text: `embedded-react: failed to bake SVG ${args.path}: ${e.message}`,
75
+ text: `embedded-react: failed to bake SVG ${args.path}: ${error.message}`,
76
76
  },
77
77
  ],
78
78
  };