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