embedded-react 0.18.0 → 0.20.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 (117) hide show
  1. package/NOTICE +1 -1
  2. package/README.md +8 -4
  3. package/aot/compile.mjs +178 -58
  4. package/aot/compiler/animations.mjs +290 -281
  5. package/aot/compiler/boot.mjs +70 -33
  6. package/aot/compiler/branch-merge.mjs +4 -3
  7. package/aot/compiler/check.mjs +9 -9
  8. package/aot/compiler/collect.mjs +324 -205
  9. package/aot/compiler/control-flow.mjs +209 -197
  10. package/aot/compiler/diagnostics.mjs +22 -25
  11. package/aot/compiler/elements/activity-indicator.mjs +25 -24
  12. package/aot/compiler/elements/dial.mjs +91 -77
  13. package/aot/compiler/elements/flat-list.mjs +24 -22
  14. package/aot/compiler/elements/image.mjs +51 -50
  15. package/aot/compiler/elements/modal.mjs +31 -30
  16. package/aot/compiler/elements/props.mjs +23 -23
  17. package/aot/compiler/elements/switch.mjs +42 -34
  18. package/aot/compiler/elements/text-input.mjs +34 -32
  19. package/aot/compiler/expressions.mjs +372 -333
  20. package/aot/compiler/handlers.mjs +473 -387
  21. package/aot/compiler/ir/functions.mjs +11 -1
  22. package/aot/compiler/ir/nodes.mjs +4 -4
  23. package/aot/compiler/ir/reads.mjs +19 -19
  24. package/aot/compiler/ir/types.mjs +14 -14
  25. package/aot/compiler/ir/vectors.mjs +5 -1
  26. package/aot/compiler/keyboard.mjs +17 -7
  27. package/aot/compiler/lower.mjs +77 -80
  28. package/aot/compiler/nodes.mjs +169 -152
  29. package/aot/compiler/options.mjs +35 -30
  30. package/aot/compiler/out.mjs +18 -22
  31. package/aot/compiler/package/animations.mjs +669 -0
  32. package/aot/compiler/package/arena.mjs +252 -0
  33. package/aot/compiler/package/assemble.mjs +177 -0
  34. package/aot/compiler/package/bytecode.mjs +286 -0
  35. package/aot/compiler/package/checks.mjs +1022 -0
  36. package/aot/compiler/package/codegen.mjs +1329 -0
  37. package/aot/compiler/package/enums.mjs +138 -0
  38. package/aot/compiler/package/format.mjs +760 -0
  39. package/aot/compiler/package/layouts.mjs +136 -0
  40. package/aot/compiler/package/lower.mjs +1606 -0
  41. package/aot/compiler/package/props.mjs +118 -0
  42. package/aot/compiler/package/tables.mjs +103 -0
  43. package/aot/compiler/package/vectors.mjs +502 -0
  44. package/aot/compiler/package/writer.mjs +664 -0
  45. package/aot/compiler/pan-responder.mjs +69 -61
  46. package/aot/compiler/parse.mjs +21 -21
  47. package/aot/compiler/static-eval.mjs +25 -23
  48. package/aot/compiler/style-text.mjs +161 -172
  49. package/aot/compiler/svg.mjs +477 -251
  50. package/aot/screenshot-smoke.mjs +55 -41
  51. package/aot/style-map.mjs +102 -90
  52. package/assets/bake-font.mjs +123 -77
  53. package/assets/bake-image.mjs +39 -22
  54. package/assets/bake-svg.mjs +361 -262
  55. package/assets/build-builtin-font.mjs +14 -10
  56. package/assets/emit-c.mjs +83 -62
  57. package/assets/emit-container.mjs +124 -38
  58. package/assets/emit-pack.mjs +77 -67
  59. package/assets/font-config.mjs +9 -6
  60. package/assets/font-sizes.mjs +163 -123
  61. package/assets/glyph-coverage.mjs +74 -54
  62. package/assets/index.mjs +31 -9
  63. package/assets/rasterize.mjs +126 -99
  64. package/assets/svg-loader.mjs +8 -8
  65. package/build.mjs +16 -14
  66. package/cli.mjs +359 -172
  67. package/compile-bin.mjs +5 -5
  68. package/flash.mjs +537 -0
  69. package/hotreload/dev-device.mjs +90 -33
  70. package/hotreload/pack-app.mjs +55 -43
  71. package/hotreload/pack-split.mjs +46 -37
  72. package/hotreload/package-transfer.mjs +175 -0
  73. package/hotreload/protocol.mjs +51 -38
  74. package/hotreload/uploader.mjs +38 -27
  75. package/hotreload/watch-tree.mjs +19 -19
  76. package/pack-container.mjs +31 -23
  77. package/package.json +11 -12
  78. package/persist-transform.mjs +34 -28
  79. package/qjsc-wasm.mjs +25 -14
  80. package/sim/embedded-react.cjs +1 -1
  81. package/sim/embedded-react.js +1 -1
  82. package/sim/embedded-react.wasm +0 -0
  83. package/sim/index.html +94 -85
  84. package/sim-server.mjs +101 -82
  85. package/src/embedded-react/Animated.js +24 -24
  86. package/src/embedded-react/Easing.js +1 -1
  87. package/src/embedded-react/FlatList.js +4 -4
  88. package/src/embedded-react/LayoutAnimation.js +8 -5
  89. package/src/embedded-react/PanResponder.js +75 -71
  90. package/src/embedded-react/Pressable.js +2 -8
  91. package/src/embedded-react/SectionList.js +6 -6
  92. package/src/embedded-react/StyleSheet.js +4 -3
  93. package/src/embedded-react/TouchableOpacity.js +13 -8
  94. package/src/embedded-react/index.d.ts +5 -5
  95. package/src/embedded-react/layout-anim-config.js +10 -4
  96. package/src/embedded-react/list-child.js +5 -5
  97. package/src/embedded-react/named-colors.js +1 -1
  98. package/src/embedded-react/split-style.js +11 -11
  99. package/src/embedded-react/svg-ops.js +760 -593
  100. package/src/embedded-react/useHostValue.js +3 -3
  101. package/src/embedded-react/usePersistentState.js +6 -6
  102. package/src/embedded-react/warn-props.js +1 -1
  103. package/src/host-config.js +60 -53
  104. package/src/props.js +49 -41
  105. package/src/renderer.js +7 -4
  106. package/aot/compiler/assemble.mjs +0 -944
  107. package/aot/compiler/c/animations.mjs +0 -436
  108. package/aot/compiler/c/boot.mjs +0 -127
  109. package/aot/compiler/c/expressions.mjs +0 -270
  110. package/aot/compiler/c/functions.mjs +0 -268
  111. package/aot/compiler/c/keyboard.mjs +0 -96
  112. package/aot/compiler/c/nodes.mjs +0 -303
  113. package/aot/compiler/c/pan-responder.mjs +0 -136
  114. package/aot/compiler/c/statements.mjs +0 -319
  115. package/aot/compiler/c/text.mjs +0 -83
  116. package/aot/compiler/c/vectors.mjs +0 -381
  117. package/aot/compiler/c-syntax.mjs +0 -127
@@ -47,13 +47,25 @@ import {
47
47
  GRAD_CONIC,
48
48
  } from '../src/embedded-react/svg-ops.js';
49
49
 
50
+ const HALF_TURN_DEGREES = 180;
51
+ const PERCENT = 100;
52
+ const DEFAULT_SVG_SIZE = 100;
53
+ const DEFAULT_STROKE_WIDTH = 1;
54
+ const DEFAULT_MITER_LIMIT = 4;
55
+ const FILL_RULE_NONZERO = 0;
56
+ const FILL_RULE_EVEN_ODD = 1;
57
+ const GRADIENT_CENTER = 0.5; // objectBoundingBox defaults
58
+ const GRADIENT_RADIUS = 0.5;
59
+ const MIN_GRADIENT_STOPS = 2;
60
+ const RASTER_HASH_LENGTH = 8;
61
+
50
62
  // --- 2D affine matrix [a, b, c, d, e, f]: x' = a*x + c*y + e ; y' = b*x + d*y + f ------------------
51
- const IDENT = [1, 0, 0, 1, 0, 0];
63
+ const IDENTITY = [1, 0, 0, 1, 0, 0];
52
64
 
53
- /** Compose m1 ∘ m2 (apply m2 first, then m1). */
54
- function mul(m1, m2) {
55
- const [a1, b1, c1, d1, e1, f1] = m1;
56
- const [a2, b2, c2, d2, e2, f2] = m2;
65
+ /** Compose outer ∘ inner (apply inner first, then outer). */
66
+ function mul(outer, inner) {
67
+ const [a1, b1, c1, d1, e1, f1] = outer;
68
+ const [a2, b2, c2, d2, e2, f2] = inner;
57
69
  return [
58
70
  a1 * a2 + c1 * b2,
59
71
  b1 * a2 + d1 * b2,
@@ -65,128 +77,170 @@ function mul(m1, m2) {
65
77
  }
66
78
 
67
79
  /** Parses an SVG `transform` attribute (a chain of functions) into a single matrix. */
68
- function parseTransform(str) {
69
- let m = IDENT;
70
- if (!str) return m;
71
- const re = /(matrix|translate|scale|rotate|skewX|skewY)\s*\(([^)]*)\)/g;
72
- let t;
73
- while ((t = re.exec(str)) !== null) {
74
- const fn = t[1];
75
- const p = t[2]
80
+ function parseTransform(transform) {
81
+ let matrix = IDENTITY;
82
+ if (!transform) return matrix;
83
+ const pattern = /(matrix|translate|scale|rotate|skewX|skewY)\s*\(([^)]*)\)/g;
84
+ let match;
85
+ while ((match = pattern.exec(transform)) !== null) {
86
+ const functionName = match[1];
87
+ const values = match[2]
76
88
  .split(/[\s,]+/)
77
89
  .map(Number)
78
- .filter(n => !Number.isNaN(n));
79
- let lm = IDENT;
80
- if (fn === 'matrix')
81
- lm = [p[0] || 0, p[1] || 0, p[2] || 0, p[3] || 0, p[4] || 0, p[5] || 0];
82
- else if (fn === 'translate') lm = [1, 0, 0, 1, p[0] || 0, p[1] || 0];
83
- else if (fn === 'scale')
84
- lm = [p[0] ?? 1, 0, 0, p.length > 1 ? p[1] : (p[0] ?? 1), 0, 0];
85
- else if (fn === 'rotate') {
86
- const a = ((p[0] || 0) * Math.PI) / 180;
87
- const cos = Math.cos(a);
88
- const sin = Math.sin(a);
89
- const rot = [cos, sin, -sin, cos, 0, 0];
90
+ .filter(value => !Number.isNaN(value));
91
+ let stepMatrix = IDENTITY;
92
+ if (functionName === 'matrix')
93
+ stepMatrix = [
94
+ values[0] || 0,
95
+ values[1] || 0,
96
+ values[2] || 0,
97
+ values[3] || 0,
98
+ values[4] || 0,
99
+ values[5] || 0,
100
+ ];
101
+ else if (functionName === 'translate')
102
+ stepMatrix = [1, 0, 0, 1, values[0] || 0, values[1] || 0];
103
+ else if (functionName === 'scale')
104
+ stepMatrix = [
105
+ values[0] ?? 1,
106
+ 0,
107
+ 0,
108
+ values.length > 1 ? values[1] : (values[0] ?? 1),
109
+ 0,
110
+ 0,
111
+ ];
112
+ else if (functionName === 'rotate') {
113
+ const radians = ((values[0] || 0) * Math.PI) / HALF_TURN_DEGREES;
114
+ const cos = Math.cos(radians);
115
+ const sin = Math.sin(radians);
116
+ const rotation = [cos, sin, -sin, cos, 0, 0];
90
117
  // rotate(angle cx cy) rotates around a point.
91
- lm =
92
- p.length >= 3
93
- ? mul(mul([1, 0, 0, 1, p[1], p[2]], rot), [1, 0, 0, 1, -p[1], -p[2]])
94
- : rot;
95
- } else if (fn === 'skewX')
96
- lm = [1, 0, Math.tan(((p[0] || 0) * Math.PI) / 180), 1, 0, 0];
97
- else if (fn === 'skewY')
98
- lm = [1, Math.tan(((p[0] || 0) * Math.PI) / 180), 0, 1, 0, 0];
99
- m = mul(m, lm);
118
+ stepMatrix =
119
+ values.length >= 3
120
+ ? mul(mul([1, 0, 0, 1, values[1], values[2]], rotation), [
121
+ 1,
122
+ 0,
123
+ 0,
124
+ 1,
125
+ -values[1],
126
+ -values[2],
127
+ ])
128
+ : rotation;
129
+ } else if (functionName === 'skewX')
130
+ stepMatrix = [
131
+ 1,
132
+ 0,
133
+ Math.tan(((values[0] || 0) * Math.PI) / HALF_TURN_DEGREES),
134
+ 1,
135
+ 0,
136
+ 0,
137
+ ];
138
+ else if (functionName === 'skewY')
139
+ stepMatrix = [
140
+ 1,
141
+ Math.tan(((values[0] || 0) * Math.PI) / HALF_TURN_DEGREES),
142
+ 0,
143
+ 1,
144
+ 0,
145
+ 0,
146
+ ];
147
+ matrix = mul(matrix, stepMatrix);
100
148
  }
101
- return m;
149
+ return matrix;
102
150
  }
103
151
 
104
- /** Applies matrix @p m to a point. */
105
- function pt(m, x, y) {
106
- return [m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]];
152
+ /** Applies @p matrix to a point. */
153
+ function pt(matrix, x, y) {
154
+ return [
155
+ matrix[0] * x + matrix[2] * y + matrix[4],
156
+ matrix[1] * x + matrix[3] * y + matrix[5],
157
+ ];
107
158
  }
108
159
 
109
- /** Transforms a path op array (no leading SHAPE op) by matrix @p m. parsePath only emits MOVE/LINE/QUAD/
160
+ /** Transforms a path op array (no leading SHAPE op) by @p matrix. parsePath only emits MOVE/LINE/QUAD/
110
161
  * CUBIC/CLOSE (it converts arcs to cubics), so every coordinate pair is a plain point — matrix-safe. */
111
- function transformOps(ops, m) {
112
- const out = [];
113
- let i = 0;
114
- while (i < ops.length) {
115
- const op = ops[i++];
116
- out.push(op);
117
- if (op === VOP_MOVE || op === VOP_LINE) {
118
- const [x, y] = pt(m, ops[i++], ops[i++]);
119
- out.push(x, y);
120
- } else if (op === VOP_QUAD) {
121
- const [cx, cy] = pt(m, ops[i++], ops[i++]);
122
- const [x, y] = pt(m, ops[i++], ops[i++]);
123
- out.push(cx, cy, x, y);
124
- } else if (op === VOP_CUBIC) {
125
- const [c1x, c1y] = pt(m, ops[i++], ops[i++]);
126
- const [c2x, c2y] = pt(m, ops[i++], ops[i++]);
127
- const [x, y] = pt(m, ops[i++], ops[i++]);
128
- out.push(c1x, c1y, c2x, c2y, x, y);
162
+ function transformOps(ops, matrix) {
163
+ const transformed = [];
164
+ let index = 0;
165
+ while (index < ops.length) {
166
+ const opcode = ops[index++];
167
+ transformed.push(opcode);
168
+ if (opcode === VOP_MOVE || opcode === VOP_LINE) {
169
+ const [x, y] = pt(matrix, ops[index++], ops[index++]);
170
+ transformed.push(x, y);
171
+ } else if (opcode === VOP_QUAD) {
172
+ const [controlX, controlY] = pt(matrix, ops[index++], ops[index++]);
173
+ const [x, y] = pt(matrix, ops[index++], ops[index++]);
174
+ transformed.push(controlX, controlY, x, y);
175
+ } else if (opcode === VOP_CUBIC) {
176
+ const [control1X, control1Y] = pt(matrix, ops[index++], ops[index++]);
177
+ const [control2X, control2Y] = pt(matrix, ops[index++], ops[index++]);
178
+ const [x, y] = pt(matrix, ops[index++], ops[index++]);
179
+ transformed.push(control1X, control1Y, control2X, control2Y, x, y);
129
180
  }
130
181
  // VOP_CLOSE has no args.
131
182
  }
132
- return out;
183
+ return transformed;
133
184
  }
134
185
 
135
186
  /** Uniform stroke-width scale factor for a matrix (geometric mean of the axis scales). */
136
- function scaleOf(m) {
137
- return Math.sqrt(Math.abs(m[0] * m[3] - m[1] * m[2])) || 1;
187
+ function scaleOf(matrix) {
188
+ return (
189
+ Math.sqrt(Math.abs(matrix[0] * matrix[3] - matrix[1] * matrix[2])) || 1
190
+ );
138
191
  }
139
192
 
140
- function num(v, dflt = 0) {
141
- const n = parseFloat(v);
142
- return Number.isNaN(n) ? dflt : n;
193
+ function num(value, fallback = 0) {
194
+ const parsed = parseFloat(value);
195
+ return Number.isNaN(parsed) ? fallback : parsed;
143
196
  }
144
197
 
145
198
  // --- Primitive shapes -> path `d` (emitted as lines/arcs; parsePath turns arcs into cubics) ----------
146
- function rectPath(a) {
147
- const x = num(a.x);
148
- const y = num(a.y);
149
- const w = num(a.width);
150
- const h = num(a.height);
151
- if (w <= 0 || h <= 0) return '';
152
- const [rx, ry] = rectRadii(a.rx, a.ry, w, h);
199
+ function rectPath(attributes) {
200
+ const x = num(attributes.x);
201
+ const y = num(attributes.y);
202
+ const width = num(attributes.width);
203
+ const height = num(attributes.height);
204
+ if (width <= 0 || height <= 0) return '';
205
+ const [rx, ry] = rectRadii(attributes.rx, attributes.ry, width, height);
153
206
  if (!rx || !ry)
154
- return `M${x} ${y}L${x + w} ${y}L${x + w} ${y + h}L${x} ${y + h}Z`;
207
+ return `M${x} ${y}L${x + width} ${y}L${x + width} ${y + height}L${x} ${y + height}Z`;
155
208
  // Quarter-ellipse corners; parsePath lowers each `A` to the same single cubic the runtime emits.
156
209
  return (
157
- `M${x + rx} ${y}L${x + w - rx} ${y}A${rx} ${ry} 0 0 1 ${x + w} ${y + ry}` +
158
- `L${x + w} ${y + h - ry}A${rx} ${ry} 0 0 1 ${x + w - rx} ${y + h}` +
159
- `L${x + rx} ${y + h}A${rx} ${ry} 0 0 1 ${x} ${y + h - ry}` +
210
+ `M${x + rx} ${y}L${x + width - rx} ${y}A${rx} ${ry} 0 0 1 ${x + width} ${y + ry}` +
211
+ `L${x + width} ${y + height - ry}A${rx} ${ry} 0 0 1 ${x + width - rx} ${y + height}` +
212
+ `L${x + rx} ${y + height}A${rx} ${ry} 0 0 1 ${x} ${y + height - ry}` +
160
213
  `L${x} ${y + ry}A${rx} ${ry} 0 0 1 ${x + rx} ${y}Z`
161
214
  );
162
215
  }
163
- function circlePath(a) {
164
- const cx = num(a.cx);
165
- const cy = num(a.cy);
166
- const r = num(a.r);
216
+ function circlePath(attributes) {
217
+ const cx = num(attributes.cx);
218
+ const cy = num(attributes.cy);
219
+ const r = num(attributes.r);
167
220
  if (r <= 0) return '';
168
221
  return `M${cx - r} ${cy}A${r} ${r} 0 1 0 ${cx + r} ${cy}A${r} ${r} 0 1 0 ${cx - r} ${cy}Z`;
169
222
  }
170
- function ellipsePath(a) {
171
- const cx = num(a.cx);
172
- const cy = num(a.cy);
173
- const rx = num(a.rx);
174
- const ry = num(a.ry);
223
+ function ellipsePath(attributes) {
224
+ const cx = num(attributes.cx);
225
+ const cy = num(attributes.cy);
226
+ const rx = num(attributes.rx);
227
+ const ry = num(attributes.ry);
175
228
  if (rx <= 0 || ry <= 0) return '';
176
229
  return `M${cx - rx} ${cy}A${rx} ${ry} 0 1 0 ${cx + rx} ${cy}A${rx} ${ry} 0 1 0 ${cx - rx} ${cy}Z`;
177
230
  }
178
- function linePath(a) {
179
- return `M${num(a.x1)} ${num(a.y1)}L${num(a.x2)} ${num(a.y2)}`;
231
+ function linePath(attributes) {
232
+ return `M${num(attributes.x1)} ${num(attributes.y1)}L${num(attributes.x2)} ${num(attributes.y2)}`;
180
233
  }
181
- function polyPath(a, close) {
182
- const v = String(a.points || '')
234
+ function polyPath(attributes, close) {
235
+ const coordinates = String(attributes.points || '')
183
236
  .trim()
184
237
  .split(/[\s,]+/)
185
238
  .map(Number)
186
- .filter(n => !Number.isNaN(n));
187
- if (v.length < 4) return '';
188
- let d = `M${v[0]} ${v[1]}`;
189
- for (let i = 2; i + 1 < v.length; i += 2) d += `L${v[i]} ${v[i + 1]}`;
239
+ .filter(value => !Number.isNaN(value));
240
+ if (coordinates.length < 4) return '';
241
+ let d = `M${coordinates[0]} ${coordinates[1]}`;
242
+ for (let index = 2; index + 1 < coordinates.length; index += 2)
243
+ d += `L${coordinates[index]} ${coordinates[index + 1]}`;
190
244
  return close ? `${d}Z` : d;
191
245
  }
192
246
 
@@ -214,132 +268,142 @@ const DEFAULT_PAINT = {
214
268
  'fill-rule': 'nonzero',
215
269
  };
216
270
 
217
- function parseStyle(s) {
218
- const o = {};
219
- if (!s) return o;
220
- for (const decl of String(s).split(';')) {
221
- const i = decl.indexOf(':');
222
- if (i > 0) o[decl.slice(0, i).trim()] = decl.slice(i + 1).trim();
271
+ function parseStyle(style) {
272
+ const declarations = {};
273
+ if (!style) return declarations;
274
+ for (const declaration of String(style).split(';')) {
275
+ const colon = declaration.indexOf(':');
276
+ if (colon > 0)
277
+ declarations[declaration.slice(0, colon).trim()] = declaration
278
+ .slice(colon + 1)
279
+ .trim();
223
280
  }
224
- return o;
281
+ return declarations;
225
282
  }
226
283
 
227
- function resolvePaint(attrs, inherited) {
228
- const style = parseStyle(attrs.style);
229
- const out = {...inherited};
230
- for (const k of PAINT_KEYS) {
231
- const v = style[k] ?? attrs[k];
232
- if (v != null) out[k] = v;
284
+ function resolvePaint(attributes, inherited) {
285
+ const style = parseStyle(attributes.style);
286
+ const paint = {...inherited};
287
+ for (const key of PAINT_KEYS) {
288
+ const value = style[key] ?? attributes[key];
289
+ if (value != null) paint[key] = value;
233
290
  }
234
- return out;
291
+ return paint;
235
292
  }
236
293
 
237
294
  /** Resolves a CSS color to a uint32 ARGB. url(...) paints (gradients/patterns) bake to nothing in v1. */
238
- function colorOf(v) {
239
- if (typeof v === 'string' && v.trim().startsWith('url(')) return 0;
240
- return parseColor(v);
295
+ function colorOf(value) {
296
+ if (typeof value === 'string' && value.trim().startsWith('url(')) return 0;
297
+ return parseColor(value);
241
298
  }
242
299
 
243
- function clamp01(v) {
244
- return v < 0 ? 0 : v > 1 ? 1 : v;
300
+ function clamp01(value) {
301
+ return value < 0 ? 0 : value > 1 ? 1 : value;
245
302
  }
246
303
 
247
- /** Multiplies an ARGB color's alpha by @p f (SVG opacity / fill-opacity / stroke-opacity, baked in). */
248
- function applyAlpha(argb, f) {
249
- if (f >= 1) return argb >>> 0;
250
- const a = Math.round(((argb >>> 24) & 0xff) * clamp01(f));
251
- return ((a << 24) | (argb & 0xffffff)) >>> 0;
304
+ /** Multiplies an ARGB color's alpha by @p factor (SVG opacity / fill-opacity / stroke-opacity, baked in). */
305
+ function applyAlpha(argb, factor) {
306
+ if (factor >= 1) return argb >>> 0;
307
+ const alpha = Math.round(((argb >>> 24) & 0xff) * clamp01(factor));
308
+ return ((alpha << 24) | (argb & 0xffffff)) >>> 0;
252
309
  }
253
310
 
254
311
  // --- Gradients (<linearGradient> / <radialGradient>) -------------------------------------------------
255
312
 
256
313
  /** Parses <stop>s into [{ color: uint32 (stop-opacity baked in), offset: 0..1 }], in authored order. */
257
314
  function parseStops(node) {
258
- const out = [];
259
- for (const c of node.children || []) {
260
- if (c.type !== 'element' || c.name !== 'stop') continue;
261
- const a = c.attributes || {};
262
- const style = parseStyle(a.style);
263
- const col = style['stop-color'] ?? a['stop-color'] ?? 'black';
264
- const so = clamp01(num(style['stop-opacity'] ?? a['stop-opacity'], 1));
265
- let off = String(a.offset ?? '0').trim();
266
- off = off.endsWith('%') ? parseFloat(off) / 100 : parseFloat(off);
267
- out.push({
268
- color: applyAlpha(parseColor(col), so),
269
- offset: clamp01(Number.isNaN(off) ? 0 : off),
315
+ const stops = [];
316
+ for (const child of node.children || []) {
317
+ if (child.type !== 'element' || child.name !== 'stop') continue;
318
+ const attributes = child.attributes || {};
319
+ const style = parseStyle(attributes.style);
320
+ const color = style['stop-color'] ?? attributes['stop-color'] ?? 'black';
321
+ const stopOpacity = clamp01(
322
+ num(style['stop-opacity'] ?? attributes['stop-opacity'], 1),
323
+ );
324
+ let offset = String(attributes.offset ?? '0').trim();
325
+ offset = offset.endsWith('%')
326
+ ? parseFloat(offset) / PERCENT
327
+ : parseFloat(offset);
328
+ stops.push({
329
+ color: applyAlpha(parseColor(color), stopOpacity),
330
+ offset: clamp01(Number.isNaN(offset) ? 0 : offset),
270
331
  });
271
332
  }
272
- return out;
333
+ return stops;
273
334
  }
274
335
 
275
336
  /** Collects every <linearGradient>/<radialGradient> by id (searched anywhere, including <defs>). */
276
337
  function collectGradients(root) {
277
- const map = new Map();
338
+ const gradients = new Map();
278
339
  const visit = node => {
279
- for (const c of node.children || []) {
280
- if (c.type !== 'element') continue;
340
+ for (const child of node.children || []) {
341
+ if (child.type !== 'element') continue;
281
342
  if (
282
- (c.name === 'linearGradient' ||
283
- c.name === 'radialGradient' ||
284
- c.name === 'conicGradient') &&
285
- c.attributes &&
286
- c.attributes.id
343
+ (child.name === 'linearGradient' ||
344
+ child.name === 'radialGradient' ||
345
+ child.name === 'conicGradient') &&
346
+ child.attributes &&
347
+ child.attributes.id
287
348
  )
288
- map.set(c.attributes.id, {
289
- name: c.name,
290
- attrs: c.attributes,
291
- stops: parseStops(c),
349
+ gradients.set(child.attributes.id, {
350
+ name: child.name,
351
+ attributes: child.attributes,
352
+ stops: parseStops(child),
292
353
  });
293
- visit(c);
354
+ visit(child);
294
355
  }
295
356
  };
296
357
  visit(root);
297
- return map;
358
+ return gradients;
298
359
  }
299
360
 
300
361
  /** "url(#id)" -> "id" (else null). */
301
- function urlRef(v) {
302
- const m = typeof v === 'string' && v.trim().match(/^url\(\s*#([^)\s]+)\s*\)/);
303
- return m ? m[1] : null;
362
+ function urlRef(value) {
363
+ const match =
364
+ typeof value === 'string' && value.trim().match(/^url\(\s*#([^)\s]+)\s*\)/);
365
+ return match ? match[1] : null;
304
366
  }
305
367
 
306
- /** A gradient coordinate: "50%" -> 0.5; a plain number passes through; NaN or infinite falls back to dflt. */
307
- function gradCoord(v, dflt) {
308
- if (v == null) return dflt;
309
- const s = String(v).trim();
310
- const n = s.endsWith('%') ? parseFloat(s) / 100 : parseFloat(s);
311
- return Number.isFinite(n) ? n : dflt;
368
+ /** A gradient coordinate: "50%" -> 0.5; a plain number passes through; NaN or infinite returns `fallback`. */
369
+ function gradCoord(value, fallback) {
370
+ if (value == null) return fallback;
371
+ const text = String(value).trim();
372
+ const parsed = text.endsWith('%')
373
+ ? parseFloat(text) / PERCENT
374
+ : parseFloat(text);
375
+ return Number.isFinite(parsed) ? parsed : fallback;
312
376
  }
313
377
 
314
378
  /** Local-space bounding box of a path-op array (no SHAPE header; MOVE/LINE/QUAD/CUBIC, CLOSE has no args). */
315
379
  function opsBBox(ops) {
316
- let minx = Infinity;
317
- let miny = Infinity;
318
- let maxx = -Infinity;
319
- let maxy = -Infinity;
320
- let i = 0;
321
- while (i < ops.length) {
322
- const op = ops[i++];
323
- const n =
324
- op === VOP_MOVE || op === VOP_LINE
380
+ let minX = Infinity;
381
+ let minY = Infinity;
382
+ let maxX = -Infinity;
383
+ let maxY = -Infinity;
384
+ let index = 0;
385
+ while (index < ops.length) {
386
+ const opcode = ops[index++];
387
+ const coordinateCount =
388
+ opcode === VOP_MOVE || opcode === VOP_LINE
325
389
  ? 2
326
- : op === VOP_QUAD
390
+ : opcode === VOP_QUAD
327
391
  ? 4
328
- : op === VOP_CUBIC
392
+ : opcode === VOP_CUBIC
329
393
  ? 6
330
394
  : 0;
331
- for (let k = 0; k < n; k += 2) {
332
- const x = ops[i + k];
333
- const y = ops[i + k + 1];
334
- if (x < minx) minx = x;
335
- if (x > maxx) maxx = x;
336
- if (y < miny) miny = y;
337
- if (y > maxy) maxy = y;
395
+ for (let offset = 0; offset < coordinateCount; offset += 2) {
396
+ const x = ops[index + offset];
397
+ const y = ops[index + offset + 1];
398
+ if (x < minX) minX = x;
399
+ if (x > maxX) maxX = x;
400
+ if (y < minY) minY = y;
401
+ if (y > maxY) maxY = y;
338
402
  }
339
- i += n;
403
+ index += coordinateCount;
340
404
  }
341
- if (!Number.isFinite(minx)) return {x: 0, y: 0, w: 0, h: 0};
342
- return {x: minx, y: miny, w: maxx - minx, h: maxy - miny};
405
+ if (!Number.isFinite(minX)) return {x: 0, y: 0, width: 0, height: 0};
406
+ return {x: minX, y: minY, width: maxX - minX, height: maxY - minY};
343
407
  }
344
408
 
345
409
  /**
@@ -351,51 +415,71 @@ function opsBBox(ops) {
351
415
  * its best-fit circle: the radius is the geometric mean of the two axis radii (radii multiply by sqrt(|det|)
352
416
  * under a transform, and a non-square OBB contributes sqrt(w*h)). Conic likewise keeps only the rotation.
353
417
  */
354
- function bakeGradient(def, cm, bbox) {
355
- const a = def.attrs;
356
- const obb = (a.gradientUnits || 'objectBoundingBox') !== 'userSpaceOnUse';
357
- const gt = parseTransform(a.gradientTransform);
358
- const toBaked = (gx, gy) => {
359
- const ux = obb ? bbox.x + gx * bbox.w : gx;
360
- const uy = obb ? bbox.y + gy * bbox.h : gy;
361
- const [tx, ty] = pt(gt, ux, uy);
362
- return pt(cm, tx, ty);
418
+ function bakeGradient(definition, shapeMatrix, bbox) {
419
+ const attributes = definition.attributes;
420
+ const objectBoundingBox =
421
+ (attributes.gradientUnits || 'objectBoundingBox') !== 'userSpaceOnUse';
422
+ const gradientMatrix = parseTransform(attributes.gradientTransform);
423
+ const toBaked = (gradientX, gradientY) => {
424
+ const userX = objectBoundingBox
425
+ ? bbox.x + gradientX * bbox.width
426
+ : gradientX;
427
+ const userY = objectBoundingBox
428
+ ? bbox.y + gradientY * bbox.height
429
+ : gradientY;
430
+ const [transformedX, transformedY] = pt(gradientMatrix, userX, userY);
431
+ return pt(shapeMatrix, transformedX, transformedY);
363
432
  };
364
- if (def.name === 'radialGradient') {
365
- const [bcx, bcy] = toBaked(gradCoord(a.cx, 0.5), gradCoord(a.cy, 0.5));
433
+ if (definition.name === 'radialGradient') {
434
+ const [centerX, centerY] = toBaked(
435
+ gradCoord(attributes.cx, GRADIENT_CENTER),
436
+ gradCoord(attributes.cy, GRADIENT_CENTER),
437
+ );
366
438
  // objectBoundingBox radius r=0.5 spans half the box; for a non-square box the geometric mean sqrt(w*h)
367
439
  // is the best-fit circle (vs the diagonal, which oversizes a wide/tall box).
368
- const rUser = obb
369
- ? gradCoord(a.r, 0.5) * Math.sqrt(bbox.w * bbox.h)
370
- : gradCoord(a.r, 0.5);
440
+ const userRadius = objectBoundingBox
441
+ ? gradCoord(attributes.r, GRADIENT_RADIUS) *
442
+ Math.sqrt(bbox.width * bbox.height)
443
+ : gradCoord(attributes.r, GRADIENT_RADIUS);
371
444
  return {
372
445
  type: GRAD_RADIAL,
373
- stops: def.stops,
374
- ax: bcx,
375
- ay: bcy,
446
+ stops: definition.stops,
447
+ ax: centerX,
448
+ ay: centerY,
376
449
  bx: 0,
377
450
  by: 0,
378
- r: rUser * scaleOf(cm) * scaleOf(gt),
451
+ r: userRadius * scaleOf(shapeMatrix) * scaleOf(gradientMatrix),
379
452
  };
380
453
  }
381
- if (def.name === 'conicGradient') {
382
- const [bcx, bcy] = toBaked(gradCoord(a.cx, 0.5), gradCoord(a.cy, 0.5));
454
+ if (definition.name === 'conicGradient') {
455
+ const [centerX, centerY] = toBaked(
456
+ gradCoord(attributes.cx, GRADIENT_CENTER),
457
+ gradCoord(attributes.cy, GRADIENT_CENTER),
458
+ );
383
459
  // `from` (degrees, clockwise from the top, CSS conic-gradient convention) -> radians, plus the rotation
384
460
  // baked into the gradient + path transforms so the sweep orients correctly in the final coordinate space.
385
- const rot = Math.atan2(cm[1], cm[0]) + Math.atan2(gt[1], gt[0]);
461
+ const rotation =
462
+ Math.atan2(shapeMatrix[1], shapeMatrix[0]) +
463
+ Math.atan2(gradientMatrix[1], gradientMatrix[0]);
386
464
  return {
387
465
  type: GRAD_CONIC,
388
- stops: def.stops,
389
- ax: bcx,
390
- ay: bcy,
466
+ stops: definition.stops,
467
+ ax: centerX,
468
+ ay: centerY,
391
469
  bx: 0,
392
470
  by: 0,
393
- r: (num(a.from, 0) * Math.PI) / 180 + rot,
471
+ r: (num(attributes.from, 0) * Math.PI) / HALF_TURN_DEGREES + rotation,
394
472
  };
395
473
  }
396
- const [ax, ay] = toBaked(gradCoord(a.x1, 0), gradCoord(a.y1, 0));
397
- const [bx, by] = toBaked(gradCoord(a.x2, 1), gradCoord(a.y2, 0));
398
- return {type: GRAD_LINEAR, stops: def.stops, ax, ay, bx, by, r: 0};
474
+ const [ax, ay] = toBaked(
475
+ gradCoord(attributes.x1, 0),
476
+ gradCoord(attributes.y1, 0),
477
+ );
478
+ const [bx, by] = toBaked(
479
+ gradCoord(attributes.x2, 1),
480
+ gradCoord(attributes.y2, 0),
481
+ );
482
+ return {type: GRAD_LINEAR, stops: definition.stops, ax, ay, bx, by, r: 0};
399
483
  }
400
484
 
401
485
  /**
@@ -408,30 +492,35 @@ function bakeGradient(def, cm, bbox) {
408
492
  */
409
493
  export async function svgToVector(svgString) {
410
494
  const root = await parse(String(svgString));
411
- const a = root.attributes || {};
495
+ const attributes = root.attributes || {};
412
496
 
413
- let vb = String(a.viewBox || '')
497
+ let viewBox = String(attributes.viewBox || '')
414
498
  .trim()
415
499
  .split(/[\s,]+/)
416
500
  .map(Number);
417
- if (vb.length !== 4 || vb.some(n => Number.isNaN(n)))
418
- vb = [0, 0, num(a.width, 100), num(a.height, 100)];
419
- const [vx, vy, vw, vh] = vb;
420
- const width = num(a.width, vw);
421
- const height = num(a.height, vh);
501
+ if (viewBox.length !== 4 || viewBox.some(value => Number.isNaN(value)))
502
+ viewBox = [
503
+ 0,
504
+ 0,
505
+ num(attributes.width, DEFAULT_SVG_SIZE),
506
+ num(attributes.height, DEFAULT_SVG_SIZE),
507
+ ];
508
+ const [viewBoxX, viewBoxY, viewBoxWidth, viewBoxHeight] = viewBox;
509
+ const width = num(attributes.width, viewBoxWidth);
510
+ const height = num(attributes.height, viewBoxHeight);
422
511
 
423
512
  // Root transform: map the viewBox user-units onto the intrinsic px box (like the inline <Svg> path).
424
- const sx = vw ? width / vw : 1;
425
- const sy = vh ? height / vh : 1;
426
- const rootM = mul(
427
- [sx, 0, 0, sy, -vx * sx, -vy * sy],
428
- parseTransform(a.transform),
513
+ const scaleX = viewBoxWidth ? width / viewBoxWidth : 1;
514
+ const scaleY = viewBoxHeight ? height / viewBoxHeight : 1;
515
+ const rootMatrix = mul(
516
+ [scaleX, 0, 0, scaleY, -viewBoxX * scaleX, -viewBoxY * scaleY],
517
+ parseTransform(attributes.transform),
429
518
  );
430
519
 
431
520
  const ops = [];
432
521
  const paints = [];
433
522
  const gradients = [];
434
- const gradDefs = collectGradients(root);
523
+ const gradientDefinitions = collectGradients(root);
435
524
 
436
525
  // Elements we intentionally skip without losing visible content (gradient defs are collected separately,
437
526
  // the rest are metadata). Anything else hitting the skip branch — text/image/use/mask/filter/pattern/… —
@@ -447,26 +536,29 @@ export async function svgToVector(svgString) {
447
536
  ]);
448
537
  const dropped = new Set();
449
538
 
450
- const walk = (node, m, paint) => {
539
+ const walk = (node, matrix, paint) => {
451
540
  for (const child of node.children || []) {
452
541
  if (child.type !== 'element') continue;
453
- const attrs = child.attributes || {};
454
- const cm = mul(m, parseTransform(attrs.transform));
455
- const cp = resolvePaint(attrs, paint);
542
+ const childAttributes = child.attributes || {};
543
+ const childMatrix = mul(
544
+ matrix,
545
+ parseTransform(childAttributes.transform),
546
+ );
547
+ const childPaint = resolvePaint(childAttributes, paint);
456
548
 
457
549
  if (child.name === 'g' || child.name === 'svg') {
458
- walk(child, cm, cp);
550
+ walk(child, childMatrix, childPaint);
459
551
  continue;
460
552
  }
461
553
 
462
554
  let d = '';
463
- if (child.name === 'path') d = attrs.d || '';
464
- else if (child.name === 'rect') d = rectPath(attrs);
465
- else if (child.name === 'circle') d = circlePath(attrs);
466
- else if (child.name === 'ellipse') d = ellipsePath(attrs);
467
- else if (child.name === 'line') d = linePath(attrs);
468
- else if (child.name === 'polygon') d = polyPath(attrs, true);
469
- else if (child.name === 'polyline') d = polyPath(attrs, false);
555
+ if (child.name === 'path') d = childAttributes.d || '';
556
+ else if (child.name === 'rect') d = rectPath(childAttributes);
557
+ else if (child.name === 'circle') d = circlePath(childAttributes);
558
+ else if (child.name === 'ellipse') d = ellipsePath(childAttributes);
559
+ else if (child.name === 'line') d = linePath(childAttributes);
560
+ else if (child.name === 'polygon') d = polyPath(childAttributes, true);
561
+ else if (child.name === 'polyline') d = polyPath(childAttributes, false);
470
562
  else {
471
563
  if (!SVG_IGNORABLE.has(child.name)) dropped.add(child.name); // unsupported visual element → raster
472
564
  continue;
@@ -474,15 +566,18 @@ export async function svgToVector(svgString) {
474
566
  if (!d) continue;
475
567
 
476
568
  // A filter/mask/clip applied to an otherwise-bakeable shape still loses fidelity as a vector → flag it.
477
- for (const fk of ['filter', 'mask', 'clip-path']) {
478
- if (attrs[fk] && attrs[fk] !== 'none') dropped.add(fk);
569
+ for (const feature of ['filter', 'mask', 'clip-path']) {
570
+ if (childAttributes[feature] && childAttributes[feature] !== 'none')
571
+ dropped.add(feature);
479
572
  }
480
573
  // A dashed stroke can't be represented in the op-tape (the stroke is baked solid). Flag it so the SVG
481
574
  // falls back to raster (resvg renders the dashes) — but only when a visible stroke is actually dashed
482
575
  // by a positive pattern, so a stray stroke-dasharray on an unstroked/zero-width shape isn't penalized.
483
- const dash = cp['stroke-dasharray'];
576
+ const dash = childPaint['stroke-dasharray'];
484
577
  const stroked =
485
- cp.stroke && cp.stroke !== 'none' && num(cp['stroke-width'], 1) > 0;
578
+ childPaint.stroke &&
579
+ childPaint.stroke !== 'none' &&
580
+ num(childPaint['stroke-width'], DEFAULT_STROKE_WIDTH) > 0;
486
581
  if (stroked && dash && dash !== 'none' && /[1-9]/.test(dash))
487
582
  dropped.add('stroke-dasharray');
488
583
 
@@ -490,42 +585,46 @@ export async function svgToVector(svgString) {
490
585
  if (!shapeOps.length) continue;
491
586
 
492
587
  const paintIndex = paints.length / PAINT_STRIDE;
493
- const op = clamp01(num(cp.opacity, 1));
588
+ const opacity = clamp01(num(childPaint.opacity, 1));
494
589
  // A url(#id) fill/stroke referencing a parsed gradient bakes to a 1-based gradient-table index; the
495
590
  // solid color stays 0 (colorOf returns 0 for url()). The shape's bbox is computed once, lazily.
496
591
  let bbox = null;
497
- const refGrad = ref => {
498
- if (!ref) return 0;
499
- const def = gradDefs.get(ref);
500
- if (!def || def.stops.length < 2) return 0;
592
+ const gradientIndex = reference => {
593
+ if (!reference) return 0;
594
+ const definition = gradientDefinitions.get(reference);
595
+ if (!definition || definition.stops.length < MIN_GRADIENT_STOPS)
596
+ return 0;
501
597
  if (!bbox) bbox = opsBBox(shapeOps);
502
- gradients.push(bakeGradient(def, cm, bbox));
598
+ gradients.push(bakeGradient(definition, childMatrix, bbox));
503
599
  return gradients.length; // 1-based
504
600
  };
505
- const fillGrad = refGrad(urlRef(cp.fill));
506
- const strokeGrad = refGrad(urlRef(cp.stroke));
507
- ops.push(VOP_SHAPE, paintIndex, ...transformOps(shapeOps, cm));
601
+ const fillGradient = gradientIndex(urlRef(childPaint.fill));
602
+ const strokeGradient = gradientIndex(urlRef(childPaint.stroke));
603
+ ops.push(VOP_SHAPE, paintIndex, ...transformOps(shapeOps, childMatrix));
508
604
  paints.push(
509
605
  applyAlpha(
510
- colorOf(cp.fill ?? 'black'),
511
- op * clamp01(num(cp['fill-opacity'], 1)),
606
+ colorOf(childPaint.fill ?? 'black'),
607
+ opacity * clamp01(num(childPaint['fill-opacity'], 1)),
512
608
  ),
513
609
  applyAlpha(
514
- colorOf(cp.stroke ?? 'none'),
515
- op * clamp01(num(cp['stroke-opacity'], 1)),
610
+ colorOf(childPaint.stroke ?? 'none'),
611
+ opacity * clamp01(num(childPaint['stroke-opacity'], 1)),
516
612
  ),
517
- num(cp['stroke-width'], 1) * scaleOf(cm),
518
- num(cp['stroke-miterlimit'], 4),
519
- CAP[cp['stroke-linecap']] ?? 0,
520
- JOIN[cp['stroke-linejoin']] ?? 0,
521
- cp['fill-rule'] === 'evenodd' ? 1 : 0,
522
- fillGrad,
523
- strokeGrad,
613
+ num(childPaint['stroke-width'], DEFAULT_STROKE_WIDTH) *
614
+ scaleOf(childMatrix),
615
+ num(childPaint['stroke-miterlimit'], DEFAULT_MITER_LIMIT),
616
+ CAP[childPaint['stroke-linecap']] ?? 0,
617
+ JOIN[childPaint['stroke-linejoin']] ?? 0,
618
+ childPaint['fill-rule'] === 'evenodd'
619
+ ? FILL_RULE_EVEN_ODD
620
+ : FILL_RULE_NONZERO,
621
+ fillGradient,
622
+ strokeGradient,
524
623
  );
525
624
  }
526
625
  };
527
626
 
528
- walk(root, rootM, DEFAULT_PAINT);
627
+ walk(root, rootMatrix, DEFAULT_PAINT);
529
628
  return {ops, paints, gradients, width, height, dropped: [...dropped].sort()};
530
629
  }
531
630
 
@@ -542,14 +641,14 @@ export async function svgToRaster(svgString) {
542
641
  const {Resvg} = await import('@resvg/resvg-js');
543
642
  // resvg (usvg) requires the SVG namespace; svgson (the vector baker) is lenient and many hand-authored
544
643
  // SVGs omit it, so inject it when absent or resvg rejects the document ("does not have a root node").
545
- let s = String(svgString);
546
- if (!/<svg\b[^>]*\sxmlns\s*=/i.test(s))
547
- s = s.replace(/<svg\b/i, '<svg xmlns="http://www.w3.org/2000/svg"');
548
- const r = new Resvg(s, {background: 'rgba(0,0,0,0)'}); // transparent so it composites
549
- const img = r.render();
550
- const png = img.asPng();
551
- const {width, height} = img;
552
- img.free?.();
644
+ let svg = String(svgString);
645
+ if (!/<svg\b[^>]*\sxmlns\s*=/i.test(svg))
646
+ svg = svg.replace(/<svg\b/i, '<svg xmlns="http://www.w3.org/2000/svg"');
647
+ const resvg = new Resvg(svg, {background: 'rgba(0,0,0,0)'}); // transparent so it composites
648
+ const rendered = resvg.render();
649
+ const png = rendered.asPng();
650
+ const {width, height} = rendered;
651
+ rendered.free?.();
553
652
  return {width, height, png};
554
653
  }
555
654
 
@@ -563,11 +662,11 @@ export async function svgToRaster(svgString) {
563
662
  * @returns {string} Absolute path to the written .png.
564
663
  */
565
664
  export function writeRasterPng(name, png) {
566
- const dir = join(tmpdir(), 'embedded-react-svg-raster');
567
- mkdirSync(dir, {recursive: true});
665
+ const directory = join(tmpdir(), 'embedded-react-svg-raster');
666
+ mkdirSync(directory, {recursive: true});
568
667
  const file = join(
569
- dir,
570
- `${name}-${createHash('sha1').update(png).digest('hex').slice(0, 8)}.png`,
668
+ directory,
669
+ `${name}-${createHash('sha1').update(png).digest('hex').slice(0, RASTER_HASH_LENGTH)}.png`,
571
670
  );
572
671
  writeFileSync(file, png);
573
672
  return file;