embedded-react 0.19.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 (116) hide show
  1. package/README.md +7 -3
  2. package/aot/compile.mjs +178 -58
  3. package/aot/compiler/animations.mjs +290 -281
  4. package/aot/compiler/boot.mjs +70 -33
  5. package/aot/compiler/branch-merge.mjs +4 -3
  6. package/aot/compiler/check.mjs +9 -9
  7. package/aot/compiler/collect.mjs +324 -205
  8. package/aot/compiler/control-flow.mjs +209 -197
  9. package/aot/compiler/diagnostics.mjs +22 -25
  10. package/aot/compiler/elements/activity-indicator.mjs +25 -24
  11. package/aot/compiler/elements/dial.mjs +91 -77
  12. package/aot/compiler/elements/flat-list.mjs +24 -22
  13. package/aot/compiler/elements/image.mjs +51 -50
  14. package/aot/compiler/elements/modal.mjs +31 -30
  15. package/aot/compiler/elements/props.mjs +23 -23
  16. package/aot/compiler/elements/switch.mjs +42 -34
  17. package/aot/compiler/elements/text-input.mjs +34 -32
  18. package/aot/compiler/expressions.mjs +372 -333
  19. package/aot/compiler/handlers.mjs +473 -387
  20. package/aot/compiler/ir/functions.mjs +11 -1
  21. package/aot/compiler/ir/nodes.mjs +4 -4
  22. package/aot/compiler/ir/reads.mjs +19 -19
  23. package/aot/compiler/ir/types.mjs +14 -14
  24. package/aot/compiler/ir/vectors.mjs +5 -1
  25. package/aot/compiler/keyboard.mjs +17 -7
  26. package/aot/compiler/lower.mjs +77 -80
  27. package/aot/compiler/nodes.mjs +169 -152
  28. package/aot/compiler/options.mjs +35 -30
  29. package/aot/compiler/out.mjs +18 -22
  30. package/aot/compiler/package/animations.mjs +669 -0
  31. package/aot/compiler/package/arena.mjs +252 -0
  32. package/aot/compiler/package/assemble.mjs +177 -0
  33. package/aot/compiler/package/bytecode.mjs +286 -0
  34. package/aot/compiler/package/checks.mjs +1022 -0
  35. package/aot/compiler/package/codegen.mjs +1329 -0
  36. package/aot/compiler/package/enums.mjs +138 -0
  37. package/aot/compiler/package/format.mjs +760 -0
  38. package/aot/compiler/package/layouts.mjs +136 -0
  39. package/aot/compiler/package/lower.mjs +1606 -0
  40. package/aot/compiler/package/props.mjs +118 -0
  41. package/aot/compiler/package/tables.mjs +103 -0
  42. package/aot/compiler/package/vectors.mjs +502 -0
  43. package/aot/compiler/package/writer.mjs +664 -0
  44. package/aot/compiler/pan-responder.mjs +69 -61
  45. package/aot/compiler/parse.mjs +21 -21
  46. package/aot/compiler/static-eval.mjs +25 -23
  47. package/aot/compiler/style-text.mjs +161 -172
  48. package/aot/compiler/svg.mjs +477 -251
  49. package/aot/screenshot-smoke.mjs +54 -40
  50. package/aot/style-map.mjs +102 -90
  51. package/assets/bake-font.mjs +123 -77
  52. package/assets/bake-image.mjs +39 -22
  53. package/assets/bake-svg.mjs +361 -262
  54. package/assets/build-builtin-font.mjs +11 -7
  55. package/assets/emit-c.mjs +77 -58
  56. package/assets/emit-container.mjs +123 -37
  57. package/assets/emit-pack.mjs +77 -67
  58. package/assets/font-config.mjs +9 -6
  59. package/assets/font-sizes.mjs +163 -123
  60. package/assets/glyph-coverage.mjs +74 -54
  61. package/assets/index.mjs +31 -9
  62. package/assets/rasterize.mjs +126 -99
  63. package/assets/svg-loader.mjs +8 -8
  64. package/build.mjs +14 -12
  65. package/cli.mjs +359 -172
  66. package/compile-bin.mjs +3 -3
  67. package/flash.mjs +537 -0
  68. package/hotreload/dev-device.mjs +90 -33
  69. package/hotreload/pack-app.mjs +55 -43
  70. package/hotreload/pack-split.mjs +46 -37
  71. package/hotreload/package-transfer.mjs +175 -0
  72. package/hotreload/protocol.mjs +50 -37
  73. package/hotreload/uploader.mjs +38 -27
  74. package/hotreload/watch-tree.mjs +19 -19
  75. package/pack-container.mjs +28 -20
  76. package/package.json +7 -8
  77. package/persist-transform.mjs +34 -28
  78. package/qjsc-wasm.mjs +25 -14
  79. package/sim/embedded-react.cjs +1 -1
  80. package/sim/embedded-react.js +1 -1
  81. package/sim/embedded-react.wasm +0 -0
  82. package/sim/index.html +94 -85
  83. package/sim-server.mjs +101 -82
  84. package/src/embedded-react/Animated.js +24 -24
  85. package/src/embedded-react/Easing.js +1 -1
  86. package/src/embedded-react/FlatList.js +3 -3
  87. package/src/embedded-react/LayoutAnimation.js +8 -5
  88. package/src/embedded-react/PanResponder.js +75 -71
  89. package/src/embedded-react/Pressable.js +2 -8
  90. package/src/embedded-react/SectionList.js +6 -6
  91. package/src/embedded-react/StyleSheet.js +4 -3
  92. package/src/embedded-react/TouchableOpacity.js +13 -8
  93. package/src/embedded-react/index.d.ts +5 -5
  94. package/src/embedded-react/layout-anim-config.js +10 -4
  95. package/src/embedded-react/list-child.js +5 -5
  96. package/src/embedded-react/named-colors.js +1 -1
  97. package/src/embedded-react/split-style.js +11 -11
  98. package/src/embedded-react/svg-ops.js +760 -593
  99. package/src/embedded-react/useHostValue.js +3 -3
  100. package/src/embedded-react/usePersistentState.js +6 -6
  101. package/src/embedded-react/warn-props.js +1 -1
  102. package/src/host-config.js +60 -53
  103. package/src/props.js +49 -41
  104. package/src/renderer.js +7 -4
  105. package/aot/compiler/assemble.mjs +0 -944
  106. package/aot/compiler/c/animations.mjs +0 -436
  107. package/aot/compiler/c/boot.mjs +0 -127
  108. package/aot/compiler/c/expressions.mjs +0 -270
  109. package/aot/compiler/c/functions.mjs +0 -268
  110. package/aot/compiler/c/keyboard.mjs +0 -96
  111. package/aot/compiler/c/nodes.mjs +0 -303
  112. package/aot/compiler/c/pan-responder.mjs +0 -136
  113. package/aot/compiler/c/statements.mjs +0 -319
  114. package/aot/compiler/c/text.mjs +0 -83
  115. package/aot/compiler/c/vectors.mjs +0 -381
  116. package/aot/compiler/c-syntax.mjs +0 -127
@@ -17,7 +17,7 @@
17
17
  // Pure SVG -> engine op-tape compiler. No engine/React imports, so it is unit-testable in isolation.
18
18
  //
19
19
  // The engine's ER_NODE_VECTOR node takes a flat float "op-tape" plus a flat paint table (see the
20
- // ER_VOP_* contract in er_scene.h). This module compiles a declarative <Svg> subtree (Path/Circle/
20
+ // ER_VECTOR_OP_* contract in er_scene.h). This module compiles a declarative <Svg> subtree (Path/Circle/
21
21
  // Rect/Line/Ellipse/G elements) into that form: it parses SVG `d` path data, converts primitive
22
22
  // shapes to path ops, bakes viewBox + <G> translate/scale into coordinates, and resolves inherited
23
23
  // paint. The opcodes below MUST stay in sync with er_scene.h.
@@ -42,83 +42,120 @@ export const CAP = {butt: 0, round: 1, square: 2};
42
42
  export const JOIN = {miter: 0, round: 1, bevel: 2};
43
43
 
44
44
  // Paint record width in the flat paint table: [fill, stroke, strokeWidth, miter, cap, join, fillRule,
45
- // fillGrad, strokeGrad]. fillGrad/strokeGrad are 1-based indices into the gradient table (0 = solid). MUST
45
+ // fillGradient, strokeGradient]. fillGradient/strokeGradient are 1-based indices into the gradient table (0 = solid). MUST
46
46
  // match the bridge's VEC_PAINT_STRIDE (native_ui_bridge.c) and the AOT's paint emission.
47
47
  export const PAINT_STRIDE = 9;
48
48
 
49
49
  // Gradient table encoding — a gradient descriptor is { type, stops: [{color, offset}], ax, ay, bx, by, r }.
50
50
  // type 1 = linear (axis (ax,ay)->(bx,by)), 2 = radial (centre (ax,ay), radius r). The flat float record is
51
51
  // [type, stopCount, (color, offset) × GRAD_MAX_STOPS, ax, ay, bx, by, r]; MUST match the bridge's
52
- // VEC_GRAD_STRIDE and the engine's ER_VGRAD_MAX_STOPS.
53
- export const GRAD_MAX_STOPS = 8; // MUST match the engine's ER_VGRAD_MAX_STOPS (er_scene.h)
52
+ // VEC_GRADIENT_STRIDE and the engine's ER_VECTOR_GRADIENT_MAX_STOPS.
53
+ export const GRAD_MAX_STOPS = 8; // MUST match the engine's ER_VECTOR_GRADIENT_MAX_STOPS (er_scene.h)
54
54
  export const GRAD_STRIDE = 2 + GRAD_MAX_STOPS * 2 + 5; // 23
55
55
  export const GRAD_LINEAR = 1;
56
56
  export const GRAD_RADIAL = 2;
57
57
  export const GRAD_CONIC = 3;
58
58
 
59
+ const ALPHA_OPAQUE = 255;
60
+ const CHANNEL_MAX = 255;
61
+ const OPAQUE_BLACK = 0xff000000;
62
+
63
+ const HALF_TURN_DEGREES = 180;
64
+ const QUARTER_TURN_RADIANS = Math.PI / 2;
65
+ const FULL_TURN_RADIANS = 2 * Math.PI;
66
+ // Arc convenience angles start at 12 o'clock; the engine's start at +X, a quarter turn earlier.
67
+ const TWELVE_OCLOCK_DEGREES = 90;
68
+
69
+ const DEFAULT_STROKE_WIDTH = 1;
70
+ const DEFAULT_MITER_LIMIT = 4;
71
+ const FILL_RULE_NONZERO = 0;
72
+ const FILL_RULE_EVEN_ODD = 1;
73
+
74
+ // A shape's tape starts with VOP_SHAPE and its paint index.
75
+ const SHAPE_HEADER_LENGTH = 2;
76
+ // Where strokeWidth sits in a paint record (see PAINT_STRIDE).
77
+ const PAINT_STROKE_WIDTH_SLOT = 2;
78
+
59
79
  /** Linearly interpolates two straight-alpha ARGB8888 colors, per channel. */
60
- function lerpArgb(c0, c1, t) {
61
- const lp = sh => {
62
- const a = (c0 >>> sh) & 0xff;
63
- const b = (c1 >>> sh) & 0xff;
64
- return Math.round(a + (b - a) * t) & 0xff;
80
+ function lerpArgb(fromColor, toColor, fraction) {
81
+ const channel = shift => {
82
+ const fromChannel = (fromColor >>> shift) & 0xff;
83
+ const toChannel = (toColor >>> shift) & 0xff;
84
+ return (
85
+ Math.round(fromChannel + (toChannel - fromChannel) * fraction) & 0xff
86
+ );
65
87
  };
66
- return ((lp(24) << 24) | (lp(16) << 16) | (lp(8) << 8) | lp(0)) >>> 0;
88
+ return (
89
+ ((channel(24) << 24) |
90
+ (channel(16) << 16) |
91
+ (channel(8) << 8) |
92
+ channel(0)) >>>
93
+ 0
94
+ );
67
95
  }
68
96
 
69
- /** Gradient color at position t (stops ascending by offset; clamps to the endpoint colors). */
70
- function evalStopsAt(stops, t) {
97
+ /** Gradient color at `position` (stops ascending by offset; clamps to the endpoint colors). */
98
+ function evalStopsAt(stops, position) {
71
99
  if (!stops.length) return 0;
72
- if (t <= stops[0].offset) return stops[0].color >>> 0;
100
+ if (position <= stops[0].offset) return stops[0].color >>> 0;
73
101
  const last = stops[stops.length - 1];
74
- if (t >= last.offset) return last.color >>> 0;
75
- for (let i = 0; i < stops.length - 1; i++) {
76
- const a = stops[i];
77
- const b = stops[i + 1];
78
- if (t <= b.offset) {
79
- const span = b.offset - a.offset;
102
+ if (position >= last.offset) return last.color >>> 0;
103
+ for (let index = 0; index < stops.length - 1; index++) {
104
+ const before = stops[index];
105
+ const after = stops[index + 1];
106
+ if (position <= after.offset) {
107
+ const span = after.offset - before.offset;
80
108
  return lerpArgb(
81
- a.color >>> 0,
82
- b.color >>> 0,
83
- span > 0 ? (t - a.offset) / span : 0,
109
+ before.color >>> 0,
110
+ after.color >>> 0,
111
+ span > 0 ? (position - before.offset) / span : 0,
84
112
  );
85
113
  }
86
114
  }
87
115
  return last.color >>> 0;
88
116
  }
89
117
 
90
- /** Reduces a stop list to at most `max` entries, resampling evenly across the stop range when it's over. */
91
- function capStops(stops, max) {
92
- if (stops.length <= max) return stops;
93
- const lo = stops[0].offset;
94
- const hi = stops[stops.length - 1].offset;
95
- const out = [];
96
- for (let i = 0; i < max; i++) {
97
- const t = max === 1 ? lo : lo + (hi - lo) * (i / (max - 1));
98
- out.push({color: evalStopsAt(stops, t), offset: t});
118
+ /** Reduces a stop list to at most `maxStops` entries, resampling evenly across the stop range when it's over. */
119
+ function capStops(stops, maxStops) {
120
+ if (stops.length <= maxStops) return stops;
121
+ const firstOffset = stops[0].offset;
122
+ const lastOffset = stops[stops.length - 1].offset;
123
+ const resampled = [];
124
+ for (let index = 0; index < maxStops; index++) {
125
+ const offset =
126
+ maxStops === 1
127
+ ? firstOffset
128
+ : firstOffset + (lastOffset - firstOffset) * (index / (maxStops - 1));
129
+ resampled.push({color: evalStopsAt(stops, offset), offset: offset});
99
130
  }
100
- return out;
131
+ return resampled;
101
132
  }
102
133
 
103
134
  /** Encodes gradient descriptors into the flat float array NativeUI.setVectorOps takes (GRAD_STRIDE/gradient).
104
135
  * A gradient with more than GRAD_MAX_STOPS stops is resampled down (not truncated) so it still ramps right. */
105
- export function encodeVectorGradients(grads) {
106
- const out = [];
107
- if (!grads) return out;
108
- for (const g of grads) {
109
- const stops = capStops(g.stops || [], GRAD_MAX_STOPS);
110
- out.push(g.type, stops.length);
111
- for (let s = 0; s < GRAD_MAX_STOPS; s++) {
112
- const st = stops[s];
113
- out.push(st ? st.color >>> 0 : 0, st ? st.offset : 0);
136
+ export function encodeVectorGradients(gradients) {
137
+ const encoded = [];
138
+ if (!gradients) return encoded;
139
+ for (const gradient of gradients) {
140
+ const stops = capStops(gradient.stops || [], GRAD_MAX_STOPS);
141
+ encoded.push(gradient.type, stops.length);
142
+ for (let stopIndex = 0; stopIndex < GRAD_MAX_STOPS; stopIndex++) {
143
+ const stop = stops[stopIndex];
144
+ encoded.push(stop ? stop.color >>> 0 : 0, stop ? stop.offset : 0);
114
145
  }
115
- out.push(g.ax || 0, g.ay || 0, g.bx || 0, g.by || 0, g.r || 0);
146
+ encoded.push(
147
+ gradient.ax || 0,
148
+ gradient.ay || 0,
149
+ gradient.bx || 0,
150
+ gradient.by || 0,
151
+ gradient.r || 0,
152
+ );
116
153
  }
117
- return out;
154
+ return encoded;
118
155
  }
119
156
 
120
157
  // The shared named colors plus SVG's `none`; everything else goes through hex/rgb parsing.
121
- const NAMED = Object.freeze(
158
+ const SVG_NAMED_COLORS = Object.freeze(
122
159
  Object.assign(Object.create(null), NAMED_COLORS, {none: 0}),
123
160
  );
124
161
 
@@ -131,52 +168,55 @@ const _colorCache = new Map();
131
168
  * null, so the engine treats it as "no fill"/"no stroke". Accepts #rgb, #rgba, #rrggbb, #rrggbbaa,
132
169
  * rgb()/rgba(), and the named colors above. String results are memoised (see _colorCache).
133
170
  */
134
- export function parseColor(c) {
135
- if (c == null || c === false) return 0;
136
- if (typeof c === 'number') return c >>> 0;
137
- const cached = _colorCache.get(c);
171
+ export function parseColor(color) {
172
+ if (color == null || color === false) return 0;
173
+ if (typeof color === 'number') return color >>> 0;
174
+ const cached = _colorCache.get(color);
138
175
  if (cached !== undefined) return cached;
139
- const v = parseColorString(c);
140
- _colorCache.set(c, v);
141
- return v;
176
+ const parsed = parseColorString(color);
177
+ _colorCache.set(color, parsed);
178
+ return parsed;
142
179
  }
143
180
 
144
- function parseColorString(c) {
145
- let s = String(c).trim().toLowerCase();
146
- if (s in NAMED) return NAMED[s] >>> 0;
147
- if (s[0] === '#') {
148
- s = s.slice(1);
149
- let r,
150
- g,
151
- b,
152
- a = 255;
153
- if (s.length === 3 || s.length === 4) {
154
- r = parseInt(s[0] + s[0], 16);
155
- g = parseInt(s[1] + s[1], 16);
156
- b = parseInt(s[2] + s[2], 16);
157
- if (s.length === 4) a = parseInt(s[3] + s[3], 16);
158
- } else if (s.length === 6 || s.length === 8) {
159
- r = parseInt(s.slice(0, 2), 16);
160
- g = parseInt(s.slice(2, 4), 16);
161
- b = parseInt(s.slice(4, 6), 16);
162
- if (s.length === 8) a = parseInt(s.slice(6, 8), 16);
181
+ function parseColorString(color) {
182
+ let text = String(color).trim().toLowerCase();
183
+ if (text in SVG_NAMED_COLORS) return SVG_NAMED_COLORS[text] >>> 0;
184
+ if (text[0] === '#') {
185
+ text = text.slice(1);
186
+ let red,
187
+ green,
188
+ blue,
189
+ alpha = ALPHA_OPAQUE;
190
+ if (text.length === 3 || text.length === 4) {
191
+ red = parseInt(text[0] + text[0], 16);
192
+ green = parseInt(text[1] + text[1], 16);
193
+ blue = parseInt(text[2] + text[2], 16);
194
+ if (text.length === 4) alpha = parseInt(text[3] + text[3], 16);
195
+ } else if (text.length === 6 || text.length === 8) {
196
+ red = parseInt(text.slice(0, 2), 16);
197
+ green = parseInt(text.slice(2, 4), 16);
198
+ blue = parseInt(text.slice(4, 6), 16);
199
+ if (text.length === 8) alpha = parseInt(text.slice(6, 8), 16);
163
200
  } else {
164
- return 0xff000000;
201
+ return OPAQUE_BLACK;
165
202
  }
166
- return ((a << 24) | (r << 16) | (g << 8) | b) >>> 0;
203
+ return ((alpha << 24) | (red << 16) | (green << 8) | blue) >>> 0;
167
204
  }
168
- if (s.startsWith('rgb')) {
169
- const m = s.match(/rgba?\(([^)]+)\)/);
170
- if (m) {
171
- const p = m[1].split(',').map(x => x.trim());
172
- const r = parseInt(p[0], 10) || 0;
173
- const g = parseInt(p[1], 10) || 0;
174
- const b = parseInt(p[2], 10) || 0;
175
- const a = p[3] != null ? Math.round(parseFloat(p[3]) * 255) : 255;
176
- return ((a << 24) | (r << 16) | (g << 8) | b) >>> 0;
205
+ if (text.startsWith('rgb')) {
206
+ const match = text.match(/rgba?\(([^)]+)\)/);
207
+ if (match) {
208
+ const parts = match[1].split(',').map(part => part.trim());
209
+ const red = parseInt(parts[0], 10) || 0;
210
+ const green = parseInt(parts[1], 10) || 0;
211
+ const blue = parseInt(parts[2], 10) || 0;
212
+ const alpha =
213
+ parts[3] != null
214
+ ? Math.round(parseFloat(parts[3]) * CHANNEL_MAX)
215
+ : ALPHA_OPAQUE;
216
+ return ((alpha << 24) | (red << 16) | (green << 8) | blue) >>> 0;
177
217
  }
178
218
  }
179
- return 0xff000000; // unknown -> opaque black (SVG-ish default)
219
+ return OPAQUE_BLACK; // unknown -> opaque black (SVG-ish default)
180
220
  }
181
221
 
182
222
  // --- SVG `d` path-data parser -------------------------------------------------------------------
@@ -184,110 +224,131 @@ function parseColorString(c) {
184
224
  // Hoisted so the pattern is compiled once at module load, not on every parsePath call. The /g lastIndex is reset below.
185
225
  const PATH_RE = /([MmLlHhVvCcSsQqTtAaZz])|(-?\d*\.?\d+(?:[eE][-+]?\d+)?)/g;
186
226
 
187
- /** Tokenizes a `d` string into {cmd, args[]} groups (one per command letter). */
227
+ /** Tokenizes a `d` string into {command, values[]} groups (one per command letter). */
188
228
  function tokenizePath(d) {
189
- const out = [];
190
- const re = PATH_RE;
191
- re.lastIndex = 0;
192
- let m;
193
- let cur = null;
194
- while ((m = re.exec(d)) !== null) {
195
- if (m[1]) {
196
- cur = {cmd: m[1], args: []};
197
- out.push(cur);
198
- } else if (cur) {
199
- cur.args.push(parseFloat(m[2]));
229
+ const commands = [];
230
+ const pattern = PATH_RE;
231
+ pattern.lastIndex = 0;
232
+ let match;
233
+ let current = null;
234
+ while ((match = pattern.exec(d)) !== null) {
235
+ if (match[1]) {
236
+ current = {command: match[1], values: []};
237
+ commands.push(current);
238
+ } else if (current) {
239
+ current.values.push(parseFloat(match[2]));
200
240
  }
201
241
  }
202
- return out;
242
+ return commands;
203
243
  }
204
244
 
205
245
  /** Converts an SVG elliptical arc (endpoint form) to a list of cubic bezier segments. */
206
- function arcToCubics(x0, y0, rx, ry, phiDeg, largeArc, sweep, x, y) {
207
- const out = [];
246
+ function arcToCubics(x0, y0, rx, ry, rotationDegrees, largeArc, sweep, x, y) {
247
+ const cubics = [];
208
248
  if (rx === 0 || ry === 0) {
209
- out.push([x0, y0, x, y, x, y]); // degenerate -> straight line as a cubic
210
- return out;
249
+ cubics.push([x0, y0, x, y, x, y]); // degenerate -> straight line as a cubic
250
+ return cubics;
211
251
  }
212
252
  rx = Math.abs(rx);
213
253
  ry = Math.abs(ry);
214
- const phi = (phiDeg * Math.PI) / 180;
215
- const cosP = Math.cos(phi);
216
- const sinP = Math.sin(phi);
217
- const dx = (x0 - x) / 2;
218
- const dy = (y0 - y) / 2;
219
- const x1p = cosP * dx + sinP * dy;
220
- const y1p = -sinP * dx + cosP * dy;
221
- let rxs = rx * rx;
222
- let rys = ry * ry;
223
- const x1ps = x1p * x1p;
224
- const y1ps = y1p * y1p;
254
+ const rotation = (rotationDegrees * Math.PI) / HALF_TURN_DEGREES;
255
+ const cosRotation = Math.cos(rotation);
256
+ const sinRotation = Math.sin(rotation);
257
+ const halfDeltaX = (x0 - x) / 2;
258
+ const halfDeltaY = (y0 - y) / 2;
259
+ const primeX = cosRotation * halfDeltaX + sinRotation * halfDeltaY;
260
+ const primeY = -sinRotation * halfDeltaX + cosRotation * halfDeltaY;
261
+ let rxSquared = rx * rx;
262
+ let rySquared = ry * ry;
263
+ const primeXSquared = primeX * primeX;
264
+ const primeYSquared = primeY * primeY;
225
265
  // Correct out-of-range radii.
226
- const lam = x1ps / rxs + y1ps / rys;
227
- if (lam > 1) {
228
- const s = Math.sqrt(lam);
229
- rx *= s;
230
- ry *= s;
231
- rxs = rx * rx;
232
- rys = ry * ry;
266
+ const radiiScale = primeXSquared / rxSquared + primeYSquared / rySquared;
267
+ if (radiiScale > 1) {
268
+ const scale = Math.sqrt(radiiScale);
269
+ rx *= scale;
270
+ ry *= scale;
271
+ rxSquared = rx * rx;
272
+ rySquared = ry * ry;
233
273
  }
234
274
  let sign = largeArc !== sweep ? 1 : -1;
235
- let num = rxs * rys - rxs * y1ps - rys * x1ps;
236
- if (num < 0) num = 0;
237
- const co = sign * Math.sqrt(num / (rxs * y1ps + rys * x1ps || 1));
238
- const cxp = (co * rx * y1p) / ry;
239
- const cyp = (-co * ry * x1p) / rx;
240
- const cx = cosP * cxp - sinP * cyp + (x0 + x) / 2;
241
- const cy = sinP * cxp + cosP * cyp + (y0 + y) / 2;
242
- const ang = (ux, uy, vx, vy) => {
243
- const dot = ux * vx + uy * vy;
244
- const len = Math.sqrt((ux * ux + uy * uy) * (vx * vx + vy * vy)) || 1;
245
- let a = Math.acos(Math.max(-1, Math.min(1, dot / len)));
246
- if (ux * vy - uy * vx < 0) a = -a;
247
- return a;
275
+ let numerator =
276
+ rxSquared * rySquared -
277
+ rxSquared * primeYSquared -
278
+ rySquared * primeXSquared;
279
+ if (numerator < 0) numerator = 0;
280
+ const coefficient =
281
+ sign *
282
+ Math.sqrt(
283
+ numerator / (rxSquared * primeYSquared + rySquared * primeXSquared || 1),
284
+ );
285
+ const primeCenterX = (coefficient * rx * primeY) / ry;
286
+ const primeCenterY = (-coefficient * ry * primeX) / rx;
287
+ const cx =
288
+ cosRotation * primeCenterX - sinRotation * primeCenterY + (x0 + x) / 2;
289
+ const cy =
290
+ sinRotation * primeCenterX + cosRotation * primeCenterY + (y0 + y) / 2;
291
+ const angleBetween = (fromX, fromY, toX, toY) => {
292
+ const dot = fromX * toX + fromY * toY;
293
+ const lengthProduct =
294
+ Math.sqrt((fromX * fromX + fromY * fromY) * (toX * toX + toY * toY)) || 1;
295
+ let angle = Math.acos(Math.max(-1, Math.min(1, dot / lengthProduct)));
296
+ if (fromX * toY - fromY * toX < 0) angle = -angle;
297
+ return angle;
248
298
  };
249
- const theta1 = ang(1, 0, (x1p - cxp) / rx, (y1p - cyp) / ry);
250
- let dtheta = ang(
251
- (x1p - cxp) / rx,
252
- (y1p - cyp) / ry,
253
- (-x1p - cxp) / rx,
254
- (-y1p - cyp) / ry,
299
+ const startAngle = angleBetween(
300
+ 1,
301
+ 0,
302
+ (primeX - primeCenterX) / rx,
303
+ (primeY - primeCenterY) / ry,
255
304
  );
256
- if (!sweep && dtheta > 0) dtheta -= 2 * Math.PI;
257
- if (sweep && dtheta < 0) dtheta += 2 * Math.PI;
258
- const segs = Math.ceil(Math.abs(dtheta) / (Math.PI / 2));
259
- const delta = dtheta / segs;
260
- const t = (4 / 3) * Math.tan(delta / 4);
261
- let th = theta1;
262
- let px = x0;
263
- let py = y0;
264
- for (let i = 0; i < segs; i++) {
265
- const th2 = th + delta;
266
- const cos1 = Math.cos(th);
267
- const sin1 = Math.sin(th);
268
- const cos2 = Math.cos(th2);
269
- const sin2 = Math.sin(th2);
270
- const e1x = cx + rx * cosP * cos1 - ry * sinP * sin1;
271
- const e1y = cy + rx * sinP * cos1 + ry * cosP * sin1;
272
- const e2x = cx + rx * cosP * cos2 - ry * sinP * sin2;
273
- const e2y = cy + rx * sinP * cos2 + ry * cosP * sin2;
274
- const d1x = -rx * cosP * sin1 - ry * sinP * cos1;
275
- const d1y = -rx * sinP * sin1 + ry * cosP * cos1;
276
- const d2x = -rx * cosP * sin2 - ry * sinP * cos2;
277
- const d2y = -rx * sinP * sin2 + ry * cosP * cos2;
278
- out.push([
279
- px + t * d1x,
280
- py + t * d1y,
281
- e2x - t * d2x,
282
- e2y - t * d2y,
283
- e2x,
284
- e2y,
305
+ let sweepAngle = angleBetween(
306
+ (primeX - primeCenterX) / rx,
307
+ (primeY - primeCenterY) / ry,
308
+ (-primeX - primeCenterX) / rx,
309
+ (-primeY - primeCenterY) / ry,
310
+ );
311
+ if (!sweep && sweepAngle > 0) sweepAngle -= FULL_TURN_RADIANS;
312
+ if (sweep && sweepAngle < 0) sweepAngle += FULL_TURN_RADIANS;
313
+ const segmentCount = Math.ceil(Math.abs(sweepAngle) / QUARTER_TURN_RADIANS);
314
+ const segmentAngle = sweepAngle / segmentCount;
315
+ const handleScale = (4 / 3) * Math.tan(segmentAngle / 4);
316
+ let segmentStart = startAngle;
317
+ let previousX = x0;
318
+ let previousY = y0;
319
+ for (let segment = 0; segment < segmentCount; segment++) {
320
+ const segmentEnd = segmentStart + segmentAngle;
321
+ const cosStart = Math.cos(segmentStart);
322
+ const sinStart = Math.sin(segmentStart);
323
+ const cosEnd = Math.cos(segmentEnd);
324
+ const sinEnd = Math.sin(segmentEnd);
325
+ const startPointX =
326
+ cx + rx * cosRotation * cosStart - ry * sinRotation * sinStart;
327
+ const startPointY =
328
+ cy + rx * sinRotation * cosStart + ry * cosRotation * sinStart;
329
+ const endPointX =
330
+ cx + rx * cosRotation * cosEnd - ry * sinRotation * sinEnd;
331
+ const endPointY =
332
+ cy + rx * sinRotation * cosEnd + ry * cosRotation * sinEnd;
333
+ const startTangentX =
334
+ -rx * cosRotation * sinStart - ry * sinRotation * cosStart;
335
+ const startTangentY =
336
+ -rx * sinRotation * sinStart + ry * cosRotation * cosStart;
337
+ const endTangentX = -rx * cosRotation * sinEnd - ry * sinRotation * cosEnd;
338
+ const endTangentY = -rx * sinRotation * sinEnd + ry * cosRotation * cosEnd;
339
+ cubics.push([
340
+ previousX + handleScale * startTangentX,
341
+ previousY + handleScale * startTangentY,
342
+ endPointX - handleScale * endTangentX,
343
+ endPointY - handleScale * endTangentY,
344
+ endPointX,
345
+ endPointY,
285
346
  ]);
286
- px = e2x;
287
- py = e2y;
288
- th = th2;
347
+ previousX = endPointX;
348
+ previousY = endPointY;
349
+ segmentStart = segmentEnd;
289
350
  }
290
- return out;
351
+ return cubics;
291
352
  }
292
353
 
293
354
  /**
@@ -305,14 +366,14 @@ export function parsePath(d) {
305
366
  // conversion over every static path beside it, only for the engine to memcmp the result and throw
306
367
  // the identical bytes away. Held to both an op budget and an entry count, and a path too big to fit
307
368
  // the budget on its own is never stored, so nothing can push it over; an entry also holds one
308
- // transformed copy (see xf), so the real footprint is ~2x the op budget. The bridge caps a single
369
+ // transformed copy (see lastTransform), so the real footprint is ~2x the op budget. The bridge caps a single
309
370
  // <Svg> at 1024 ops and 16 shapes, so this holds several screens' worth.
310
371
  const PATH_CACHE = new Map();
311
372
  const PATH_CACHE_MAX_OPS = 4096;
312
373
  const PATH_CACHE_MAX_ENTRIES = 128;
313
374
  let _pathCacheOps = 0;
314
375
 
315
- /** Cache record for one `d` string: `ops` are the parsed path ops, `xf` the last transform applied
376
+ /** Cache record for one `d` string: `ops` are the parsed path ops, `lastTransform` the last transform applied
316
377
  * to them (see transformCached). Coerces its key, so a non-string `d` still hits the cache instead
317
378
  * of keying a fresh entry off object identity every call. */
318
379
  function pathEntry(d) {
@@ -325,7 +386,7 @@ function pathEntry(d) {
325
386
  PATH_CACHE.set(key, hit);
326
387
  return hit;
327
388
  }
328
- const entry = {ops: parsePathUncached(key), xf: null};
389
+ const entry = {ops: parsePathUncached(key), lastTransform: null};
329
390
  // A path that alone exceeds the whole budget is parsed but not stored: caching it would blow the
330
391
  // bound it is measured against, and at that size it is already past the bridge's per-<Svg> op cap.
331
392
  if (entry.ops.length > PATH_CACHE_MAX_OPS) return entry;
@@ -350,140 +411,178 @@ export function clearPathCache() {
350
411
 
351
412
  function parsePathUncached(d) {
352
413
  const ops = [];
353
- const toks = tokenizePath(d);
354
- let cx = 0;
355
- let cy = 0;
356
- let sx = 0;
357
- let sy = 0; // subpath start
358
- let prevCtrlX = 0;
359
- let prevCtrlY = 0;
360
- let prevCmd = '';
361
- for (const tk of toks) {
362
- const C = tk.cmd;
363
- const rel = C >= 'a' && C <= 'z';
364
- const a = tk.args;
365
- const U = C.toUpperCase();
366
- let i = 0;
367
- const rx = v => (rel ? cx + v : v);
368
- const ry = v => (rel ? cy + v : v);
369
- if (U === 'M') {
414
+ const tokens = tokenizePath(d);
415
+ let currentX = 0;
416
+ let currentY = 0;
417
+ let subpathStartX = 0;
418
+ let subpathStartY = 0; // subpath start
419
+ let previousControlX = 0;
420
+ let previousControlY = 0;
421
+ let previousCommand = '';
422
+ for (const token of tokens) {
423
+ const command = token.command;
424
+ const relative = command >= 'a' && command <= 'z';
425
+ const values = token.values;
426
+ const absoluteCommand = command.toUpperCase();
427
+ let index = 0;
428
+ const resolveX = value => (relative ? currentX + value : value);
429
+ const resolveY = value => (relative ? currentY + value : value);
430
+ if (absoluteCommand === 'M') {
370
431
  // First pair is moveto; later pairs are implicit linetos.
371
- cx = rx(a[i++]);
372
- cy = ry(a[i++]);
373
- sx = cx;
374
- sy = cy;
375
- ops.push(VOP_MOVE, cx, cy);
376
- while (i + 1 < a.length) {
377
- cx = rel ? cx + a[i++] : a[i++];
378
- cy = rel ? cy + a[i++] : a[i++];
379
- ops.push(VOP_LINE, cx, cy);
432
+ currentX = resolveX(values[index++]);
433
+ currentY = resolveY(values[index++]);
434
+ subpathStartX = currentX;
435
+ subpathStartY = currentY;
436
+ ops.push(VOP_MOVE, currentX, currentY);
437
+ while (index + 1 < values.length) {
438
+ currentX = relative ? currentX + values[index++] : values[index++];
439
+ currentY = relative ? currentY + values[index++] : values[index++];
440
+ ops.push(VOP_LINE, currentX, currentY);
380
441
  }
381
- } else if (U === 'L') {
382
- while (i + 1 < a.length) {
383
- cx = rel ? cx + a[i++] : a[i++];
384
- cy = rel ? cy + a[i++] : a[i++];
385
- ops.push(VOP_LINE, cx, cy);
442
+ } else if (absoluteCommand === 'L') {
443
+ while (index + 1 < values.length) {
444
+ currentX = relative ? currentX + values[index++] : values[index++];
445
+ currentY = relative ? currentY + values[index++] : values[index++];
446
+ ops.push(VOP_LINE, currentX, currentY);
386
447
  }
387
- } else if (U === 'H') {
388
- while (i < a.length) {
389
- cx = rel ? cx + a[i++] : a[i++];
390
- ops.push(VOP_LINE, cx, cy);
448
+ } else if (absoluteCommand === 'H') {
449
+ while (index < values.length) {
450
+ currentX = relative ? currentX + values[index++] : values[index++];
451
+ ops.push(VOP_LINE, currentX, currentY);
391
452
  }
392
- } else if (U === 'V') {
393
- while (i < a.length) {
394
- cy = rel ? cy + a[i++] : a[i++];
395
- ops.push(VOP_LINE, cx, cy);
453
+ } else if (absoluteCommand === 'V') {
454
+ while (index < values.length) {
455
+ currentY = relative ? currentY + values[index++] : values[index++];
456
+ ops.push(VOP_LINE, currentX, currentY);
396
457
  }
397
- } else if (U === 'C') {
398
- while (i + 5 < a.length) {
399
- const c1x = rx(a[i++]);
400
- const c1y = ry(a[i++]);
401
- const c2x = rx(a[i++]);
402
- const c2y = ry(a[i++]);
403
- const ex = rx(a[i++]);
404
- const ey = ry(a[i++]);
405
- ops.push(VOP_CUBIC, c1x, c1y, c2x, c2y, ex, ey);
406
- prevCtrlX = c2x;
407
- prevCtrlY = c2y;
408
- cx = ex;
409
- cy = ey;
458
+ } else if (absoluteCommand === 'C') {
459
+ while (index + 5 < values.length) {
460
+ const control1X = resolveX(values[index++]);
461
+ const control1Y = resolveY(values[index++]);
462
+ const control2X = resolveX(values[index++]);
463
+ const control2Y = resolveY(values[index++]);
464
+ const endX = resolveX(values[index++]);
465
+ const endY = resolveY(values[index++]);
466
+ ops.push(
467
+ VOP_CUBIC,
468
+ control1X,
469
+ control1Y,
470
+ control2X,
471
+ control2Y,
472
+ endX,
473
+ endY,
474
+ );
475
+ previousControlX = control2X;
476
+ previousControlY = control2Y;
477
+ currentX = endX;
478
+ currentY = endY;
410
479
  }
411
- } else if (U === 'S') {
412
- while (i + 3 < a.length) {
413
- const refl = prevCmd === 'C' || prevCmd === 'S';
414
- const c1x = refl ? 2 * cx - prevCtrlX : cx;
415
- const c1y = refl ? 2 * cy - prevCtrlY : cy;
416
- const c2x = rx(a[i++]);
417
- const c2y = ry(a[i++]);
418
- const ex = rx(a[i++]);
419
- const ey = ry(a[i++]);
420
- ops.push(VOP_CUBIC, c1x, c1y, c2x, c2y, ex, ey);
421
- prevCtrlX = c2x;
422
- prevCtrlY = c2y;
423
- cx = ex;
424
- cy = ey;
480
+ } else if (absoluteCommand === 'S') {
481
+ while (index + 3 < values.length) {
482
+ const reflected = previousCommand === 'C' || previousCommand === 'S';
483
+ const control1X = reflected
484
+ ? 2 * currentX - previousControlX
485
+ : currentX;
486
+ const control1Y = reflected
487
+ ? 2 * currentY - previousControlY
488
+ : currentY;
489
+ const control2X = resolveX(values[index++]);
490
+ const control2Y = resolveY(values[index++]);
491
+ const endX = resolveX(values[index++]);
492
+ const endY = resolveY(values[index++]);
493
+ ops.push(
494
+ VOP_CUBIC,
495
+ control1X,
496
+ control1Y,
497
+ control2X,
498
+ control2Y,
499
+ endX,
500
+ endY,
501
+ );
502
+ previousControlX = control2X;
503
+ previousControlY = control2Y;
504
+ currentX = endX;
505
+ currentY = endY;
425
506
  }
426
- } else if (U === 'Q') {
427
- while (i + 3 < a.length) {
428
- const qx = rx(a[i++]);
429
- const qy = ry(a[i++]);
430
- const ex = rx(a[i++]);
431
- const ey = ry(a[i++]);
432
- ops.push(VOP_QUAD, qx, qy, ex, ey);
433
- prevCtrlX = qx;
434
- prevCtrlY = qy;
435
- cx = ex;
436
- cy = ey;
507
+ } else if (absoluteCommand === 'Q') {
508
+ while (index + 3 < values.length) {
509
+ const controlX = resolveX(values[index++]);
510
+ const controlY = resolveY(values[index++]);
511
+ const endX = resolveX(values[index++]);
512
+ const endY = resolveY(values[index++]);
513
+ ops.push(VOP_QUAD, controlX, controlY, endX, endY);
514
+ previousControlX = controlX;
515
+ previousControlY = controlY;
516
+ currentX = endX;
517
+ currentY = endY;
437
518
  }
438
- } else if (U === 'T') {
439
- while (i + 1 < a.length) {
440
- const refl = prevCmd === 'Q' || prevCmd === 'T';
441
- const qx = refl ? 2 * cx - prevCtrlX : cx;
442
- const qy = refl ? 2 * cy - prevCtrlY : cy;
443
- const ex = rx(a[i++]);
444
- const ey = ry(a[i++]);
445
- ops.push(VOP_QUAD, qx, qy, ex, ey);
446
- prevCtrlX = qx;
447
- prevCtrlY = qy;
448
- cx = ex;
449
- cy = ey;
519
+ } else if (absoluteCommand === 'T') {
520
+ while (index + 1 < values.length) {
521
+ const reflected = previousCommand === 'Q' || previousCommand === 'T';
522
+ const controlX = reflected ? 2 * currentX - previousControlX : currentX;
523
+ const controlY = reflected ? 2 * currentY - previousControlY : currentY;
524
+ const endX = resolveX(values[index++]);
525
+ const endY = resolveY(values[index++]);
526
+ ops.push(VOP_QUAD, controlX, controlY, endX, endY);
527
+ previousControlX = controlX;
528
+ previousControlY = controlY;
529
+ currentX = endX;
530
+ currentY = endY;
450
531
  }
451
- } else if (U === 'A') {
452
- while (i + 6 < a.length) {
453
- const arx = a[i++];
454
- const ary = a[i++];
455
- const rot = a[i++];
456
- const laf = a[i++];
457
- const swf = a[i++];
458
- const ex = rx(a[i++]);
459
- const ey = ry(a[i++]);
460
- const cubics = arcToCubics(cx, cy, arx, ary, rot, laf, swf, ex, ey);
461
- for (const c of cubics)
462
- ops.push(VOP_CUBIC, c[0], c[1], c[2], c[3], c[4], c[5]);
463
- cx = ex;
464
- cy = ey;
532
+ } else if (absoluteCommand === 'A') {
533
+ while (index + 6 < values.length) {
534
+ const radiusX = values[index++];
535
+ const radiusY = values[index++];
536
+ const rotation = values[index++];
537
+ const largeArcFlag = values[index++];
538
+ const sweepFlag = values[index++];
539
+ const endX = resolveX(values[index++]);
540
+ const endY = resolveY(values[index++]);
541
+ const cubics = arcToCubics(
542
+ currentX,
543
+ currentY,
544
+ radiusX,
545
+ radiusY,
546
+ rotation,
547
+ largeArcFlag,
548
+ sweepFlag,
549
+ endX,
550
+ endY,
551
+ );
552
+ for (const cubic of cubics)
553
+ ops.push(
554
+ VOP_CUBIC,
555
+ cubic[0],
556
+ cubic[1],
557
+ cubic[2],
558
+ cubic[3],
559
+ cubic[4],
560
+ cubic[5],
561
+ );
562
+ currentX = endX;
563
+ currentY = endY;
465
564
  }
466
- } else if (U === 'Z') {
565
+ } else if (absoluteCommand === 'Z') {
467
566
  ops.push(VOP_CLOSE);
468
- cx = sx;
469
- cy = sy;
567
+ currentX = subpathStartX;
568
+ currentY = subpathStartY;
470
569
  }
471
- prevCmd = U;
570
+ previousCommand = absoluteCommand;
472
571
  }
473
572
  return ops;
474
573
  }
475
574
 
476
575
  // --- Primitive shapes -> path ops ----------------------------------------------------------------
477
576
 
478
- function num(v, dflt) {
479
- const n = typeof v === 'number' ? v : parseFloat(v);
480
- return isNaN(n) ? dflt : n;
577
+ function num(value, fallback) {
578
+ const parsed = typeof value === 'number' ? value : parseFloat(value);
579
+ return isNaN(parsed) ? fallback : parsed;
481
580
  }
482
581
 
483
- function circleOps(p) {
484
- const cx = num(p.cx, 0);
485
- const cy = num(p.cy, 0);
486
- const r = num(p.r, 0);
582
+ function circleOps(props) {
583
+ const cx = num(props.cx, 0);
584
+ const cy = num(props.cy, 0);
585
+ const r = num(props.r, 0);
487
586
  // Start at angle 0, full circular arc.
488
587
  return [
489
588
  VOP_MOVE,
@@ -494,7 +593,7 @@ function circleOps(p) {
494
593
  cy,
495
594
  r,
496
595
  0,
497
- 2 * Math.PI,
596
+ FULL_TURN_RADIANS,
498
597
  0,
499
598
  VOP_CLOSE,
500
599
  ];
@@ -502,11 +601,11 @@ function circleOps(p) {
502
601
 
503
602
  /** An ellipse as a `d` string: an arc-free path of four cubic Béziers (kappa) once parsePath lowers
504
603
  * the two `A` commands. Returned as a string so it goes through the same parse cache as <Path d>. */
505
- function ellipsePathD(p) {
506
- const cx = num(p.cx, 0);
507
- const cy = num(p.cy, 0);
508
- const rx = num(p.rx, 0);
509
- const ry = num(p.ry, 0);
604
+ function ellipsePathD(props) {
605
+ const cx = num(props.cx, 0);
606
+ const cy = num(props.cy, 0);
607
+ const rx = num(props.rx, 0);
608
+ const ry = num(props.ry, 0);
510
609
  return `M ${cx - rx} ${cy} A ${rx} ${ry} 0 1 0 ${cx + rx} ${cy} A ${rx} ${ry} 0 1 0 ${cx - rx} ${cy} Z`;
511
610
  }
512
611
 
@@ -517,13 +616,13 @@ function ellipsePathD(p) {
517
616
  * corners, and each radius is clamped to half its own side. Returns [rx, ry] — [0, 0] for a
518
617
  * square-cornered rect. Exported so the AOT and the SVG baker apply the same rules.
519
618
  */
520
- export function rectRadii(rxAttr, ryAttr, w, h) {
619
+ export function rectRadii(rxAttr, ryAttr, width, height) {
521
620
  let rx = num(rxAttr, -1);
522
621
  let ry = num(ryAttr, -1);
523
622
  if (rx < 0) rx = ry; // rx omitted -> ry
524
623
  if (ry < 0) ry = rx; // ry omitted -> rx
525
- rx = Math.min(rx, w / 2);
526
- ry = Math.min(ry, h / 2);
624
+ rx = Math.min(rx, width / 2);
625
+ ry = Math.min(ry, height / 2);
527
626
  return rx > 0 && ry > 0 ? [rx, ry] : [0, 0];
528
627
  }
529
628
 
@@ -533,107 +632,109 @@ export function rectRadii(rxAttr, ryAttr, w, h) {
533
632
  * exactly the preceding line's endpoint — an arc recomputes that point from cos/sin and can miss the
534
633
  * engine's exact-equality join dedupe by a ULP, which spikes the miter join on a stroked rect.
535
634
  */
536
- function rectOpsXY(x, y, w, h, rx, ry) {
635
+ function rectOpsXY(x, y, width, height, rx, ry) {
537
636
  if (rx <= 0 || ry <= 0)
538
637
  return [
539
638
  VOP_MOVE,
540
639
  x,
541
640
  y,
542
641
  VOP_LINE,
543
- x + w,
642
+ x + width,
544
643
  y,
545
644
  VOP_LINE,
546
- x + w,
547
- y + h,
645
+ x + width,
646
+ y + height,
548
647
  VOP_LINE,
549
648
  x,
550
- y + h,
649
+ y + height,
551
650
  VOP_CLOSE,
552
651
  ];
553
- const kx = rx * KAPPA;
554
- const ky = ry * KAPPA;
555
- const x1 = x + rx; // where the top/bottom edges start, past the left corners
556
- const x2 = x + w - rx; // ... and end, before the right corners
557
- const y1 = y + ry;
558
- const y2 = y + h - ry;
559
- const r = x + w;
560
- const b = y + h;
652
+ const controlOffsetX = rx * KAPPA;
653
+ const controlOffsetY = ry * KAPPA;
654
+ const innerLeft = x + rx; // where the top/bottom edges start, past the left corners
655
+ const innerRight = x + width - rx; // ... and end, before the right corners
656
+ const innerTop = y + ry;
657
+ const innerBottom = y + height - ry;
658
+ const right = x + width;
659
+ const bottom = y + height;
561
660
  return [
562
661
  VOP_MOVE,
563
- x1,
662
+ innerLeft,
564
663
  y,
565
664
  VOP_LINE,
566
- x2,
665
+ innerRight,
567
666
  y,
568
667
  VOP_CUBIC,
569
- x2 + kx,
668
+ innerRight + controlOffsetX,
570
669
  y,
571
- r,
572
- y1 - ky,
573
- r,
574
- y1,
670
+ right,
671
+ innerTop - controlOffsetY,
672
+ right,
673
+ innerTop,
575
674
  VOP_LINE,
576
- r,
577
- y2,
675
+ right,
676
+ innerBottom,
578
677
  VOP_CUBIC,
579
- r,
580
- y2 + ky,
581
- x2 + kx,
582
- b,
583
- x2,
584
- b,
678
+ right,
679
+ innerBottom + controlOffsetY,
680
+ innerRight + controlOffsetX,
681
+ bottom,
682
+ innerRight,
683
+ bottom,
585
684
  VOP_LINE,
586
- x1,
587
- b,
685
+ innerLeft,
686
+ bottom,
588
687
  VOP_CUBIC,
589
- x1 - kx,
590
- b,
688
+ innerLeft - controlOffsetX,
689
+ bottom,
591
690
  x,
592
- y2 + ky,
691
+ innerBottom + controlOffsetY,
593
692
  x,
594
- y2,
693
+ innerBottom,
595
694
  VOP_LINE,
596
695
  x,
597
- y1,
696
+ innerTop,
598
697
  VOP_CUBIC,
599
698
  x,
600
- y1 - ky,
601
- x1 - kx,
699
+ innerTop - controlOffsetY,
700
+ innerLeft - controlOffsetX,
602
701
  y,
603
- x1,
702
+ innerLeft,
604
703
  y,
605
704
  VOP_CLOSE,
606
705
  ];
607
706
  }
608
707
 
609
- function rectOps(p) {
610
- const x = num(p.x, 0);
611
- const y = num(p.y, 0);
612
- const w = num(p.width, 0);
613
- const h = num(p.height, 0);
614
- const [rx, ry] = rectRadii(p.rx, p.ry, w, h);
615
- return rectOpsXY(x, y, w, h, rx, ry);
708
+ function rectOps(props) {
709
+ const x = num(props.x, 0);
710
+ const y = num(props.y, 0);
711
+ const width = num(props.width, 0);
712
+ const height = num(props.height, 0);
713
+ const [rx, ry] = rectRadii(props.rx, props.ry, width, height);
714
+ return rectOpsXY(x, y, width, height, rx, ry);
616
715
  }
617
716
 
618
- function lineOps(p) {
717
+ function lineOps(props) {
619
718
  return [
620
719
  VOP_MOVE,
621
- num(p.x1, 0),
622
- num(p.y1, 0),
720
+ num(props.x1, 0),
721
+ num(props.y1, 0),
623
722
  VOP_LINE,
624
- num(p.x2, 0),
625
- num(p.y2, 0),
723
+ num(props.x2, 0),
724
+ num(props.y2, 0),
626
725
  ];
627
726
  }
628
727
 
629
728
  // Arc convenience: angles in DEGREES, clockwise from 12 o'clock (the gauge/dial convention). Emits a
630
729
  // native VOP_ARC (no d-string regex / bezier conversion), so it is cheap enough to rebuild every drag
631
730
  // frame — the key to fast imperative updates.
632
- function arcOpsCW(cx, cy, r, a0deg, a1deg) {
731
+ function arcOpsCW(cx, cy, r, startDegrees, endDegrees) {
633
732
  // The engine's arc angle runs from +X (cos/sin); top-clockwise => subtract 90°.
634
- const a0 = ((a0deg - 90) * Math.PI) / 180;
635
- const a1 = ((a1deg - 90) * Math.PI) / 180;
636
- return [VOP_ARC, cx, cy, r, a0, a1, 0];
733
+ const startRadians =
734
+ ((startDegrees - TWELVE_OCLOCK_DEGREES) * Math.PI) / HALF_TURN_DEGREES;
735
+ const endRadians =
736
+ ((endDegrees - TWELVE_OCLOCK_DEGREES) * Math.PI) / HALF_TURN_DEGREES;
737
+ return [VOP_ARC, cx, cy, r, startRadians, endRadians, 0];
637
738
  }
638
739
 
639
740
  // --- Imperative shapes -> op-tape (the fast path; no JSX, no React) -------------------------------
@@ -644,7 +745,7 @@ function arcOpsCW(cx, cy, r, a0deg, a1deg) {
644
745
  * { arc: [cx, cy, r, startDeg, endDeg], stroke: '#f4a261', strokeWidth: 14, cap: 'round' }
645
746
  * { circle: [cx, cy, r], fill: '#16202f', stroke: '#f4a261', strokeWidth: 3 }
646
747
  * { line: [x1, y1, x2, y2], stroke, strokeWidth }
647
- * { rect: [x, y, w, h], fill } // optional [x, y, w, h, rx, ry] for rounded corners
748
+ * { rect: [x, y, width, height], fill } // optional [x, y, width, height, rx, ry] for rounded corners
648
749
  * { path: 'M..A..', stroke } // d-string supported but slower (regex + bezier)
649
750
  * Arc angles are degrees, clockwise from 12 o'clock. This avoids the d-string parser entirely, so it's
650
751
  * cheap enough to call on every pointer move (the imperative drag path).
@@ -652,33 +753,35 @@ function arcOpsCW(cx, cy, r, a0deg, a1deg) {
652
753
  // Reused output buffers — shapesToVector is on the drag hot path and its result is consumed
653
754
  // synchronously by NativeUI.setVectorOps, so growing fresh arrays (plus per-shape arrays + spreads)
654
755
  // every move is pure GC. Push directly into these instead.
655
- const _vecOps = [];
656
- const _vecPaints = [];
657
- const _vecGrads = [];
756
+ const _vectorOps = [];
757
+ const _vectorPaints = [];
758
+ const _vectorGradients = [];
658
759
 
659
760
  export function shapesToVector(shapes) {
660
- const ops = _vecOps;
661
- const paints = _vecPaints;
662
- const gradients = _vecGrads;
761
+ const ops = _vectorOps;
762
+ const paints = _vectorPaints;
763
+ const gradients = _vectorGradients;
663
764
  ops.length = 0;
664
765
  paints.length = 0;
665
766
  gradients.length = 0;
666
- for (let si = 0; si < shapes.length; si++) {
667
- const s = shapes[si];
767
+ for (let shapeIndex = 0; shapeIndex < shapes.length; shapeIndex++) {
768
+ const shape = shapes[shapeIndex];
668
769
  const opStart = ops.length;
669
770
  const paintIndex = paints.length / PAINT_STRIDE;
670
771
  ops.push(VOP_SHAPE, paintIndex);
671
- if (s.arc) {
672
- const cx = s.arc[0];
673
- const cy = s.arc[1];
674
- const r = s.arc[2];
675
- const a0 = ((s.arc[3] - 90) * Math.PI) / 180;
676
- const a1 = ((s.arc[4] - 90) * Math.PI) / 180;
677
- ops.push(VOP_ARC, cx, cy, r, a0, a1, 0);
678
- } else if (s.circle) {
679
- const cx = s.circle[0];
680
- const cy = s.circle[1];
681
- const r = s.circle[2];
772
+ if (shape.arc) {
773
+ const cx = shape.arc[0];
774
+ const cy = shape.arc[1];
775
+ const r = shape.arc[2];
776
+ const startRadians =
777
+ ((shape.arc[3] - TWELVE_OCLOCK_DEGREES) * Math.PI) / HALF_TURN_DEGREES;
778
+ const endRadians =
779
+ ((shape.arc[4] - TWELVE_OCLOCK_DEGREES) * Math.PI) / HALF_TURN_DEGREES;
780
+ ops.push(VOP_ARC, cx, cy, r, startRadians, endRadians, 0);
781
+ } else if (shape.circle) {
782
+ const cx = shape.circle[0];
783
+ const cy = shape.circle[1];
784
+ const r = shape.circle[2];
682
785
  ops.push(
683
786
  VOP_MOVE,
684
787
  cx + r,
@@ -688,78 +791,88 @@ export function shapesToVector(shapes) {
688
791
  cy,
689
792
  r,
690
793
  0,
691
- 2 * Math.PI,
794
+ FULL_TURN_RADIANS,
692
795
  0,
693
796
  VOP_CLOSE,
694
797
  );
695
- } else if (s.rect) {
696
- const x = s.rect[0];
697
- const y = s.rect[1];
698
- const w = s.rect[2];
699
- const h = s.rect[3];
700
- if (s.rect.length > 4) {
798
+ } else if (shape.rect) {
799
+ const x = shape.rect[0];
800
+ const y = shape.rect[1];
801
+ const width = shape.rect[2];
802
+ const height = shape.rect[3];
803
+ if (shape.rect.length > 4) {
701
804
  // Rounded — the optional trailing [rx, ry]. Off the allocation-free path below, but a rounded
702
805
  // rect is a chrome/backing shape, not something a drag rebuilds every move.
703
- const [rx, ry] = rectRadii(s.rect[4], s.rect[5], w, h);
704
- const ro = rectOpsXY(x, y, w, h, rx, ry);
705
- for (let k = 0; k < ro.length; k++) ops.push(ro[k]);
806
+ const [rx, ry] = rectRadii(shape.rect[4], shape.rect[5], width, height);
807
+ const roundedOps = rectOpsXY(x, y, width, height, rx, ry);
808
+ for (let index = 0; index < roundedOps.length; index++)
809
+ ops.push(roundedOps[index]);
706
810
  } else {
707
811
  ops.push(
708
812
  VOP_MOVE,
709
813
  x,
710
814
  y,
711
815
  VOP_LINE,
712
- x + w,
816
+ x + width,
713
817
  y,
714
818
  VOP_LINE,
715
- x + w,
716
- y + h,
819
+ x + width,
820
+ y + height,
717
821
  VOP_LINE,
718
822
  x,
719
- y + h,
823
+ y + height,
720
824
  VOP_CLOSE,
721
825
  );
722
826
  }
723
- } else if (s.line) {
724
- ops.push(VOP_MOVE, s.line[0], s.line[1], VOP_LINE, s.line[2], s.line[3]);
725
- } else if (s.path) {
726
- const so = parsePath(s.path);
727
- for (let k = 0; k < so.length; k++) ops.push(so[k]);
827
+ } else if (shape.line) {
828
+ ops.push(
829
+ VOP_MOVE,
830
+ shape.line[0],
831
+ shape.line[1],
832
+ VOP_LINE,
833
+ shape.line[2],
834
+ shape.line[3],
835
+ );
836
+ } else if (shape.path) {
837
+ const pathOps = parsePath(shape.path);
838
+ for (let index = 0; index < pathOps.length; index++)
839
+ ops.push(pathOps[index]);
728
840
  }
729
- if (ops.length <= opStart + 2) {
841
+ if (ops.length <= opStart + SHAPE_HEADER_LENGTH) {
730
842
  ops.length = opStart; // nothing emitted — roll back the SHAPE header
731
843
  continue;
732
844
  }
733
- // Optional gradients. `paint.fill_grad` / `stroke_grad` are 1-BASED indices into the gradient table
845
+ // Optional gradients. `paint.fill_gradient` / `stroke_gradient` are 1-BASED indices into the gradient table
734
846
  // (0 = solid), which is what lets one shape carry a smooth ramp instead of being chopped into many
735
847
  // solid pieces. Stop colors may be strings here; the engine wants packed ARGB.
736
848
  paints.push(
737
- parseColor(s.fill),
738
- parseColor(s.stroke),
739
- num(s.strokeWidth, 1),
740
- num(s.miter, 4),
741
- CAP[s.cap] ?? 0,
742
- JOIN[s.join] ?? 0,
743
- s.fillRule === 'evenodd' ? 1 : 0,
744
- s.fillGrad ? pushGrad(gradients, s.fillGrad) : 0,
745
- s.strokeGrad ? pushGrad(gradients, s.strokeGrad) : 0,
849
+ parseColor(shape.fill),
850
+ parseColor(shape.stroke),
851
+ num(shape.strokeWidth, DEFAULT_STROKE_WIDTH),
852
+ num(shape.miter, DEFAULT_MITER_LIMIT),
853
+ CAP[shape.cap] ?? CAP.butt,
854
+ JOIN[shape.join] ?? JOIN.miter,
855
+ shape.fillRule === 'evenodd' ? FILL_RULE_EVEN_ODD : FILL_RULE_NONZERO,
856
+ shape.fillGradient ? pushGrad(gradients, shape.fillGradient) : 0,
857
+ shape.strokeGradient ? pushGrad(gradients, shape.strokeGradient) : 0,
746
858
  );
747
859
  }
748
860
  return {ops, paints, gradients};
749
861
  }
750
862
 
751
863
  /** Appends a gradient descriptor (normalizing string stop colours) and returns its 1-based index. */
752
- function pushGrad(gradients, g) {
864
+ function pushGrad(gradients, gradient) {
753
865
  gradients.push({
754
- type: g.type,
755
- ax: g.ax,
756
- ay: g.ay,
757
- bx: g.bx,
758
- by: g.by,
759
- r: g.r,
760
- stops: (g.stops || []).map(st => ({
761
- color: typeof st.color === 'string' ? parseColor(st.color) : st.color,
762
- offset: st.offset,
866
+ type: gradient.type,
867
+ ax: gradient.ax,
868
+ ay: gradient.ay,
869
+ bx: gradient.bx,
870
+ by: gradient.by,
871
+ r: gradient.r,
872
+ stops: (gradient.stops || []).map(stop => ({
873
+ color:
874
+ typeof stop.color === 'string' ? parseColor(stop.color) : stop.color,
875
+ offset: stop.offset,
763
876
  })),
764
877
  });
765
878
  return gradients.length;
@@ -770,77 +883,89 @@ function pushGrad(gradients, g) {
770
883
  const PAINT_DEFAULT = {
771
884
  fill: 'black',
772
885
  stroke: 'none',
773
- strokeWidth: 1,
886
+ strokeWidth: DEFAULT_STROKE_WIDTH,
774
887
  strokeLinecap: 'butt',
775
888
  strokeLinejoin: 'miter',
776
- strokeMiterlimit: 4,
889
+ strokeMiterlimit: DEFAULT_MITER_LIMIT,
777
890
  fillRule: 'nonzero',
778
- fillGrad: null,
779
- strokeGrad: null,
891
+ fillGradient: null,
892
+ strokeGradient: null,
780
893
  };
781
894
 
782
895
  /** The props that make up a shape's paint; a <G> or the <Svg> itself passes them down. */
783
896
  export const PAINT_PROPS = Object.keys(PAINT_DEFAULT);
784
897
 
785
898
  function mergePaint(base, props) {
786
- const out = {...base};
787
- for (const k of PAINT_PROPS) if (props[k] != null) out[k] = props[k];
788
- return out;
899
+ const merged = {...base};
900
+ for (const key of PAINT_PROPS)
901
+ if (props[key] != null) merged[key] = props[key];
902
+ return merged;
789
903
  }
790
904
 
791
- /** Maps the resolved paint to the PAINT_STRIDE-number record [fill,stroke, w,miter,cap,join,rule,
792
- * fillGrad, strokeGrad]. Any gradient descriptor is appended to `gradients` and referenced by its
905
+ /** Maps the resolved paint to the PAINT_STRIDE-number record [fill, stroke, strokeWidth, miter, cap, join, rule,
906
+ * fillGradient, strokeGradient]. Any gradient descriptor is appended to `gradients` and referenced by its
793
907
  * 1-BASED index (0 = solid), the same encoding shapesToVector uses. */
794
908
  function paintRecord(paint, scale, gradients) {
795
909
  return [
796
910
  parseColor(paint.fill),
797
911
  parseColor(paint.stroke),
798
- num(paint.strokeWidth, 1) * scale,
799
- num(paint.strokeMiterlimit, 4),
800
- CAP[paint.strokeLinecap] ?? 0,
801
- JOIN[paint.strokeLinejoin] ?? 0,
802
- paint.fillRule === 'evenodd' ? 1 : 0,
803
- paint.fillGrad && gradients ? pushGrad(gradients, paint.fillGrad) : 0,
804
- paint.strokeGrad && gradients ? pushGrad(gradients, paint.strokeGrad) : 0,
912
+ num(paint.strokeWidth, DEFAULT_STROKE_WIDTH) * scale,
913
+ num(paint.strokeMiterlimit, DEFAULT_MITER_LIMIT),
914
+ CAP[paint.strokeLinecap] ?? CAP.butt,
915
+ JOIN[paint.strokeLinejoin] ?? JOIN.miter,
916
+ paint.fillRule === 'evenodd' ? FILL_RULE_EVEN_ODD : FILL_RULE_NONZERO,
917
+ paint.fillGradient && gradients
918
+ ? pushGrad(gradients, paint.fillGradient)
919
+ : 0,
920
+ paint.strokeGradient && gradients
921
+ ? pushGrad(gradients, paint.strokeGradient)
922
+ : 0,
805
923
  ];
806
924
  }
807
925
 
808
- /** Applies a {sx,sy,tx,ty} transform in place to a path-op array (no leading SHAPE op). */
809
- function transformOps(ops, T) {
810
- const out = [];
811
- let i = 0;
812
- const ax = v => v * T.sx + T.tx;
813
- const ay = v => v * T.sy + T.ty;
814
- while (i < ops.length) {
815
- const op = ops[i++];
816
- out.push(op);
817
- if (op === VOP_MOVE || op === VOP_LINE) {
818
- out.push(ax(ops[i++]), ay(ops[i++]));
819
- } else if (op === VOP_QUAD) {
820
- out.push(ax(ops[i++]), ay(ops[i++]), ax(ops[i++]), ay(ops[i++]));
821
- } else if (op === VOP_CUBIC) {
822
- out.push(
823
- ax(ops[i++]),
824
- ay(ops[i++]),
825
- ax(ops[i++]),
826
- ay(ops[i++]),
827
- ax(ops[i++]),
828
- ay(ops[i++]),
926
+ /** Applies a {scaleX, scaleY, translateX, translateY} transform to a path-op array (no leading SHAPE op). */
927
+ function transformOps(ops, transform) {
928
+ const transformed = [];
929
+ let index = 0;
930
+ const mapX = coordinate =>
931
+ coordinate * transform.scaleX + transform.translateX;
932
+ const mapY = coordinate =>
933
+ coordinate * transform.scaleY + transform.translateY;
934
+ while (index < ops.length) {
935
+ const opcode = ops[index++];
936
+ transformed.push(opcode);
937
+ if (opcode === VOP_MOVE || opcode === VOP_LINE) {
938
+ transformed.push(mapX(ops[index++]), mapY(ops[index++]));
939
+ } else if (opcode === VOP_QUAD) {
940
+ transformed.push(
941
+ mapX(ops[index++]),
942
+ mapY(ops[index++]),
943
+ mapX(ops[index++]),
944
+ mapY(ops[index++]),
945
+ );
946
+ } else if (opcode === VOP_CUBIC) {
947
+ transformed.push(
948
+ mapX(ops[index++]),
949
+ mapY(ops[index++]),
950
+ mapX(ops[index++]),
951
+ mapY(ops[index++]),
952
+ mapX(ops[index++]),
953
+ mapY(ops[index++]),
829
954
  );
830
- } else if (op === VOP_ARC) {
955
+ } else if (opcode === VOP_ARC) {
831
956
  // center + radius scale (uniform scale assumed for arcs)
832
- out.push(
833
- ax(ops[i++]),
834
- ay(ops[i++]),
835
- ops[i++] * T.sx,
836
- ops[i++],
837
- ops[i++],
838
- ops[i++],
957
+ transformed.push(
958
+ mapX(ops[index++]),
959
+ mapY(ops[index++]),
960
+ ops[index++] * transform.scaleX,
961
+ ops[index++],
962
+ ops[index++],
963
+ ops[index++],
839
964
  );
840
965
  }
841
966
  // VOP_CLOSE has no args
842
967
  }
843
- return out;
968
+ return transformed;
844
969
  }
845
970
 
846
971
  /**
@@ -849,23 +974,34 @@ function transformOps(ops, T) {
849
974
  * never moves between commits, so an untouched shape costs a compare instead of a rebuild. The same
850
975
  * `d` drawn under several different transforms just misses and pays the full transform.
851
976
  */
852
- function transformCached(entry, T) {
853
- const xf = entry.xf;
977
+ function transformCached(entry, transform) {
978
+ const lastTransform = entry.lastTransform;
854
979
  if (
855
- xf &&
856
- xf.sx === T.sx &&
857
- xf.sy === T.sy &&
858
- xf.tx === T.tx &&
859
- xf.ty === T.ty
980
+ lastTransform &&
981
+ lastTransform.scaleX === transform.scaleX &&
982
+ lastTransform.scaleY === transform.scaleY &&
983
+ lastTransform.translateX === transform.translateX &&
984
+ lastTransform.translateY === transform.translateY
860
985
  )
861
- return xf.out;
862
- const out = transformOps(entry.ops, T);
863
- entry.xf = {sx: T.sx, sy: T.sy, tx: T.tx, ty: T.ty, out};
864
- return out;
986
+ return lastTransform.ops;
987
+ const transformedOps = transformOps(entry.ops, transform);
988
+ entry.lastTransform = {
989
+ scaleX: transform.scaleX,
990
+ scaleY: transform.scaleY,
991
+ translateX: transform.translateX,
992
+ translateY: transform.translateY,
993
+ ops: transformedOps,
994
+ };
995
+ return transformedOps;
865
996
  }
866
997
 
867
- function isElement(c) {
868
- return c && typeof c === 'object' && c.type != null && c.props != null;
998
+ function isElement(child) {
999
+ return (
1000
+ child &&
1001
+ typeof child === 'object' &&
1002
+ child.type != null &&
1003
+ child.props != null
1004
+ );
869
1005
  }
870
1006
 
871
1007
  // React's fragment tag. Read from the global symbol registry rather than importing React, which this
@@ -874,11 +1010,11 @@ const REACT_FRAGMENT = Symbol.for('react.fragment');
874
1010
 
875
1011
  /** Children JSX produces for "draw nothing": a bare `{cond && <Path/>}` that failed, a hole in a
876
1012
  * list, and the whitespace JSX leaves between elements. Skipped without a word. */
877
- function isEmptyChild(c) {
1013
+ function isEmptyChild(child) {
878
1014
  return (
879
- c == null ||
880
- typeof c === 'boolean' ||
881
- (typeof c === 'string' && c.trim() === '')
1015
+ child == null ||
1016
+ typeof child === 'boolean' ||
1017
+ (typeof child === 'string' && child.trim() === '')
882
1018
  );
883
1019
  }
884
1020
 
@@ -898,18 +1034,18 @@ let _warnedSvgChild = false;
898
1034
  * or an array of them) straight into children, where the walk sees it. Having it return an array does
899
1035
  * nothing for `<Needle/>`: that form is never invoked at all.
900
1036
  */
901
- function warnSvgChild(c) {
1037
+ function warnSvgChild(child) {
902
1038
  if (_warnedSvgChild) return;
903
1039
  _warnedSvgChild = true;
904
- const what = !isElement(c)
905
- ? typeof c === 'string'
906
- ? `the text ${JSON.stringify(c)}`
907
- : `a ${typeof c} child`
908
- : typeof c.type === 'function'
909
- ? `<${c.type.displayName || c.type.name || 'Component'}>, a component`
910
- : `<${String(c.type)}>`;
1040
+ const description = !isElement(child)
1041
+ ? typeof child === 'string'
1042
+ ? `the text ${JSON.stringify(child)}`
1043
+ : `a ${typeof child} child`
1044
+ : typeof child.type === 'function'
1045
+ ? `<${child.type.displayName || child.type.name || 'Component'}>, a component`
1046
+ : `<${String(child.type)}>`;
911
1047
  console.warn(
912
- `embedded-react: <Svg> can't draw ${what}, and skipped it. Children must be ${SVG_TAGS.join('/')} ` +
1048
+ `embedded-react: <Svg> can't draw ${description}, and skipped it. Children must be ${SVG_TAGS.join('/')} ` +
913
1049
  `elements (arrays and fragments around them are unwrapped). <Svg> flattens its subtree instead of ` +
914
1050
  `mounting it, so a component is never rendered — inline its shapes, or call it as a plain ` +
915
1051
  `function: {needle()}.`,
@@ -920,7 +1056,7 @@ function warnSvgChild(c) {
920
1056
  * Flattens an <Svg> element's props into {ops, paints, gradients} flat arrays for NativeUI.setVectorOps.
921
1057
  * Handles Path/Circle/Ellipse/Rect/Line shapes, <G> grouping (inherited paint + translate/scale), and
922
1058
  * a root viewBox -> width/height scale. Arrays and fragments are unwrapped at any depth, so a mapped
923
- * list of shapes draws like an inline one. A shape's fillGrad/strokeGrad descriptor lands in
1059
+ * list of shapes draws like an inline one. A shape's fillGradient/strokeGradient descriptor lands in
924
1060
  * `gradients` and is referenced 1-based from its paint record. Returns empty arrays when there is
925
1061
  * nothing to draw.
926
1062
  */
@@ -930,76 +1066,86 @@ export function flattenSvg(props) {
930
1066
  const gradients = [];
931
1067
 
932
1068
  // Root transform from viewBox vs width/height.
933
- let root = {sx: 1, sy: 1, tx: 0, ty: 0};
1069
+ let root = {scaleX: 1, scaleY: 1, translateX: 0, translateY: 0};
934
1070
  if (props.viewBox && props.width && props.height) {
935
- const vb = String(props.viewBox)
1071
+ const viewBox = String(props.viewBox)
936
1072
  .trim()
937
1073
  .split(/[\s,]+/)
938
1074
  .map(parseFloat);
939
- if (vb.length === 4 && vb[2] > 0 && vb[3] > 0) {
940
- const sx = num(props.width, vb[2]) / vb[2];
941
- const sy = num(props.height, vb[3]) / vb[3];
942
- root = {sx, sy, tx: -vb[0] * sx, ty: -vb[1] * sy};
1075
+ if (viewBox.length === 4 && viewBox[2] > 0 && viewBox[3] > 0) {
1076
+ const scaleX = num(props.width, viewBox[2]) / viewBox[2];
1077
+ const scaleY = num(props.height, viewBox[3]) / viewBox[3];
1078
+ root = {
1079
+ scaleX: scaleX,
1080
+ scaleY: scaleY,
1081
+ translateX: -viewBox[0] * scaleX,
1082
+ translateY: -viewBox[1] * scaleY,
1083
+ };
943
1084
  }
944
1085
  }
945
1086
 
946
1087
  // One child at a time, recursing through the wrappers, JSX inserts around shapes: an array (every
947
1088
  // `{shapes.map(...)}`, and arrays of arrays when those nest) and a fragment, either of which can
948
1089
  // sit anywhere a shape can. Both are transparent — they carry no paint and no transform.
949
- const walk = (c, paint, T) => {
950
- if (isEmptyChild(c)) return;
951
- if (Array.isArray(c)) {
952
- for (const item of c) walk(item, paint, T);
1090
+ const walk = (child, paint, transform) => {
1091
+ if (isEmptyChild(child)) return;
1092
+ if (Array.isArray(child)) {
1093
+ for (const item of child) walk(item, paint, transform);
953
1094
  return;
954
1095
  }
955
- if (!isElement(c)) return warnSvgChild(c);
956
- const p = c.props || {};
957
- if (c.type === REACT_FRAGMENT) return walk(p.children, paint, T);
958
- const merged = mergePaint(paint, p);
959
- if (c.type === 'G') {
1096
+ if (!isElement(child)) return warnSvgChild(child);
1097
+ const childProps = child.props || {};
1098
+ if (child.type === REACT_FRAGMENT)
1099
+ return walk(childProps.children, paint, transform);
1100
+ const merged = mergePaint(paint, childProps);
1101
+ if (child.type === 'G') {
960
1102
  // Compose a translate/scale for the group, then recurse.
961
- const s = num(p.scale, 1);
962
- const gx = num(p.x ?? p.translateX, 0);
963
- const gy = num(p.y ?? p.translateY, 0);
964
- const childT = {
965
- sx: T.sx * s,
966
- sy: T.sy * s,
967
- tx: gx * T.sx + T.tx,
968
- ty: gy * T.sy + T.ty,
1103
+ const groupScale = num(childProps.scale, 1);
1104
+ const groupX = num(childProps.x ?? childProps.translateX, 0);
1105
+ const groupY = num(childProps.y ?? childProps.translateY, 0);
1106
+ const childTransform = {
1107
+ scaleX: transform.scaleX * groupScale,
1108
+ scaleY: transform.scaleY * groupScale,
1109
+ translateX: groupX * transform.scaleX + transform.translateX,
1110
+ translateY: groupY * transform.scaleY + transform.translateY,
969
1111
  };
970
- return walk(p.children, merged, childT);
1112
+ return walk(childProps.children, merged, childTransform);
971
1113
  }
972
- if (!SVG_TAGS.includes(c.type)) return warnSvgChild(c);
1114
+ if (!SVG_TAGS.includes(child.type)) return warnSvgChild(child);
973
1115
 
974
1116
  // Path/Ellipse geometry comes from a `d` string and is cached (parse + transform) by that string;
975
1117
  // the primitives build a fixed handful of numbers, which is cheaper than any cache lookup.
976
1118
  let entry = null;
977
1119
  let shapeOps = null;
978
- if (c.type === 'Path' && p.d)
979
- entry = pathEntry(p.d); // pathEntry coerces the key
980
- else if (c.type === 'Ellipse') entry = pathEntry(ellipsePathD(p));
981
- else if (c.type === 'Circle') shapeOps = circleOps(p);
982
- else if (c.type === 'Rect') shapeOps = rectOps(p);
983
- else if (c.type === 'Line') shapeOps = lineOps(p);
984
- else if (c.type === 'Arc')
1120
+ if (child.type === 'Path' && childProps.d)
1121
+ entry = pathEntry(childProps.d); // pathEntry coerces the key
1122
+ else if (child.type === 'Ellipse')
1123
+ entry = pathEntry(ellipsePathD(childProps));
1124
+ else if (child.type === 'Circle') shapeOps = circleOps(childProps);
1125
+ else if (child.type === 'Rect') shapeOps = rectOps(childProps);
1126
+ else if (child.type === 'Line') shapeOps = lineOps(childProps);
1127
+ else if (child.type === 'Arc')
985
1128
  shapeOps = arcOpsCW(
986
- num(p.cx, 0),
987
- num(p.cy, 0),
988
- num(p.r, 0),
989
- num(p.startAngle, 0),
990
- num(p.endAngle, 0),
1129
+ num(childProps.cx, 0),
1130
+ num(childProps.cy, 0),
1131
+ num(childProps.r, 0),
1132
+ num(childProps.startAngle, 0),
1133
+ num(childProps.endAngle, 0),
991
1134
  );
992
1135
  const baseOps = entry ? entry.ops : shapeOps;
993
1136
  if (!baseOps || baseOps.length === 0) return;
994
1137
 
995
- const seg = entry ? transformCached(entry, T) : transformOps(baseOps, T);
1138
+ const shapeTape = entry
1139
+ ? transformCached(entry, transform)
1140
+ : transformOps(baseOps, transform);
996
1141
  const paintIndex = paints.length / PAINT_STRIDE;
997
- const scale = (T.sx + T.sy) / 2; // stroke-width scale (uniform assumed)
1142
+ const scale = (transform.scaleX + transform.scaleY) / 2; // stroke-width scale (uniform assumed)
998
1143
  paints.push(...paintRecord(merged, scale, gradients));
999
- // Appended one at a time: `seg` can be a long cached tape, and spreading it into push() both
1144
+ // Appended one at a time: `shapeTape` can be a long cached tape, and spreading it into push() both
1000
1145
  // copies it into an argument list and risks the call-argument limit.
1001
1146
  ops.push(VOP_SHAPE, paintIndex);
1002
- for (let k = 0; k < seg.length; k++) ops.push(seg[k]);
1147
+ for (let index = 0; index < shapeTape.length; index++)
1148
+ ops.push(shapeTape[index]);
1003
1149
  };
1004
1150
 
1005
1151
  // The <Svg>'s own paint cascades to every shape, like a <G> wrapping them all.
@@ -1009,40 +1155,45 @@ export function flattenSvg(props) {
1009
1155
 
1010
1156
  // --- Imported SVG artifacts (<Svg source>) -------------------------------------------------------
1011
1157
 
1012
- /** Scales a full op-tape (with SHAPE headers) by (sx, sy): coordinates only, paint indices untouched. */
1013
- function scaleTape(ops, sx, sy) {
1014
- const out = [];
1015
- let i = 0;
1016
- while (i < ops.length) {
1017
- const op = ops[i++];
1018
- out.push(op);
1019
- if (op === VOP_SHAPE)
1020
- out.push(ops[i++]); // paint index — copy, do not scale
1021
- else if (op === VOP_MOVE || op === VOP_LINE)
1022
- out.push(ops[i++] * sx, ops[i++] * sy);
1023
- else if (op === VOP_QUAD)
1024
- out.push(ops[i++] * sx, ops[i++] * sy, ops[i++] * sx, ops[i++] * sy);
1025
- else if (op === VOP_CUBIC)
1026
- out.push(
1027
- ops[i++] * sx,
1028
- ops[i++] * sy,
1029
- ops[i++] * sx,
1030
- ops[i++] * sy,
1031
- ops[i++] * sx,
1032
- ops[i++] * sy,
1158
+ /** Scales a full op-tape (with SHAPE headers) by (scaleX, scaleY): coordinates only, paint indices untouched. */
1159
+ function scaleTape(ops, scaleX, scaleY) {
1160
+ const scaled = [];
1161
+ let index = 0;
1162
+ while (index < ops.length) {
1163
+ const opcode = ops[index++];
1164
+ scaled.push(opcode);
1165
+ if (opcode === VOP_SHAPE)
1166
+ scaled.push(ops[index++]); // paint index — copy, do not scale
1167
+ else if (opcode === VOP_MOVE || opcode === VOP_LINE)
1168
+ scaled.push(ops[index++] * scaleX, ops[index++] * scaleY);
1169
+ else if (opcode === VOP_QUAD)
1170
+ scaled.push(
1171
+ ops[index++] * scaleX,
1172
+ ops[index++] * scaleY,
1173
+ ops[index++] * scaleX,
1174
+ ops[index++] * scaleY,
1033
1175
  );
1034
- else if (op === VOP_ARC)
1035
- out.push(
1036
- ops[i++] * sx,
1037
- ops[i++] * sy,
1038
- ops[i++] * sx,
1039
- ops[i++],
1040
- ops[i++],
1041
- ops[i++],
1176
+ else if (opcode === VOP_CUBIC)
1177
+ scaled.push(
1178
+ ops[index++] * scaleX,
1179
+ ops[index++] * scaleY,
1180
+ ops[index++] * scaleX,
1181
+ ops[index++] * scaleY,
1182
+ ops[index++] * scaleX,
1183
+ ops[index++] * scaleY,
1184
+ );
1185
+ else if (opcode === VOP_ARC)
1186
+ scaled.push(
1187
+ ops[index++] * scaleX,
1188
+ ops[index++] * scaleY,
1189
+ ops[index++] * scaleX,
1190
+ ops[index++],
1191
+ ops[index++],
1192
+ ops[index++],
1042
1193
  );
1043
1194
  // VOP_CLOSE has no args.
1044
1195
  }
1045
- return out;
1196
+ return scaled;
1046
1197
  }
1047
1198
 
1048
1199
  /**
@@ -1050,33 +1201,45 @@ function scaleTape(ops, sx, sy) {
1050
1201
  * size to a target box, also scaling stroke widths. Returns the original arrays untouched when no scaling
1051
1202
  * is needed (the common <Svg source> case where the box equals the intrinsic size).
1052
1203
  */
1053
- export function scaleVectorArtifact(art, targetW, targetH) {
1054
- const sx = art.width ? targetW / art.width : 1;
1055
- const sy = art.height ? targetH / art.height : 1;
1056
- const grads = art.gradients || [];
1057
- if (sx === 1 && sy === 1)
1058
- return {ops: art.ops, paints: art.paints, gradients: grads};
1059
- const sw = Math.sqrt(Math.abs(sx * sy)) || 1; // uniform stroke-width / radius scale
1060
- const paints = art.paints.slice();
1061
- for (let k = 2; k < paints.length; k += PAINT_STRIDE) paints[k] *= sw; // index 2 of each record = strokeWidth
1204
+ export function scaleVectorArtifact(artifact, targetWidth, targetHeight) {
1205
+ const scaleX = artifact.width ? targetWidth / artifact.width : 1;
1206
+ const scaleY = artifact.height ? targetHeight / artifact.height : 1;
1207
+ const sourceGradients = artifact.gradients || [];
1208
+ if (scaleX === 1 && scaleY === 1)
1209
+ return {
1210
+ ops: artifact.ops,
1211
+ paints: artifact.paints,
1212
+ gradients: sourceGradients,
1213
+ };
1214
+ const strokeScale = Math.sqrt(Math.abs(scaleX * scaleY)) || 1; // uniform stroke-width / radius scale
1215
+ const paints = artifact.paints.slice();
1216
+ for (
1217
+ let index = PAINT_STROKE_WIDTH_SLOT;
1218
+ index < paints.length;
1219
+ index += PAINT_STRIDE
1220
+ )
1221
+ paints[index] *= strokeScale;
1062
1222
  // Gradient geometry lives in the same coordinate space as the path, so it scales with it (radius uniformly).
1063
- const gradients = grads.map(g => ({
1064
- ...g,
1065
- ax: (g.ax || 0) * sx,
1066
- ay: (g.ay || 0) * sy,
1067
- bx: (g.bx || 0) * sx,
1068
- by: (g.by || 0) * sy,
1223
+ const gradients = sourceGradients.map(gradient => ({
1224
+ ...gradient,
1225
+ ax: (gradient.ax || 0) * scaleX,
1226
+ ay: (gradient.ay || 0) * scaleY,
1227
+ bx: (gradient.bx || 0) * scaleX,
1228
+ by: (gradient.by || 0) * scaleY,
1069
1229
  // Radial r is a length (scales); conic r is a start angle (invariant under uniform scale) — don't scale it.
1070
- r: g.type === GRAD_CONIC ? g.r || 0 : (g.r || 0) * sw,
1230
+ r:
1231
+ gradient.type === GRAD_CONIC
1232
+ ? gradient.r || 0
1233
+ : (gradient.r || 0) * strokeScale,
1071
1234
  }));
1072
- return {ops: scaleTape(art.ops, sx, sy), paints, gradients};
1235
+ return {ops: scaleTape(artifact.ops, scaleX, scaleY), paints, gradients};
1073
1236
  }
1074
1237
 
1075
1238
  // --- Bridge-cap diagnostics ----------------------------------------------------------------------
1076
1239
 
1077
- let _warnedVecOps = false;
1078
- let _warnedVecPaints = false;
1079
- let _warnedVecGrads = false;
1240
+ let _warnedVectorOps = false;
1241
+ let _warnedVectorPaints = false;
1242
+ let _warnedVectorGradients = false;
1080
1243
 
1081
1244
  /**
1082
1245
  * Warns (once per kind) when an <Svg>'s compiled geometry exceeds the native bridge's caps and will be
@@ -1086,43 +1249,47 @@ let _warnedVecGrads = false;
1086
1249
  * the developer's console. Pass the live caps from NativeUI.maxVectorOps / maxVectorPaints / maxVectorGrads
1087
1250
  * (undefined on an older bridge => no-op).
1088
1251
  *
1089
- * @param {number} opsLen Op-tape length (flat float count).
1090
- * @param {number} paintsLen Paint-table length (PAINT_STRIDE numbers per shape).
1091
- * @param {number} maxOps Bridge op-tape cap (NativeUI.maxVectorOps).
1092
- * @param {number} maxPaints Bridge paint cap, in SHAPES (NativeUI.maxVectorPaints).
1093
- * @param {number} [gradsLen] Gradient count (number of gradients referenced by the shapes).
1094
- * @param {number} [maxGrads] Bridge gradient cap (NativeUI.maxVectorGrads).
1252
+ * @param {number} opsLength Op-tape length (flat float count).
1253
+ * @param {number} paintsLength Paint-table length (PAINT_STRIDE numbers per shape).
1254
+ * @param {number} maxOps Bridge op-tape cap (NativeUI.maxVectorOps).
1255
+ * @param {number} maxPaints Bridge paint cap, in SHAPES (NativeUI.maxVectorPaints).
1256
+ * @param {number} [gradientsLength] Gradient count (number of gradients referenced by the shapes).
1257
+ * @param {number} [maxGradients] Bridge gradient cap (NativeUI.maxVectorGrads).
1095
1258
  */
1096
1259
  export function warnVectorCaps(
1097
- opsLen,
1098
- paintsLen,
1260
+ opsLength,
1261
+ paintsLength,
1099
1262
  maxOps,
1100
1263
  maxPaints,
1101
- gradsLen,
1102
- maxGrads,
1264
+ gradientsLength,
1265
+ maxGradients,
1103
1266
  ) {
1104
- if (!_warnedVecOps && maxOps > 0 && opsLen > maxOps) {
1105
- _warnedVecOps = true;
1267
+ if (!_warnedVectorOps && maxOps > 0 && opsLength > maxOps) {
1268
+ _warnedVectorOps = true;
1106
1269
  console.warn(
1107
- `embedded-react: an <Svg> op-tape is too long (${opsLen} > ${maxOps} floats) and will be truncated — ` +
1270
+ `embedded-react: an <Svg> op-tape is too long (${opsLength} > ${maxOps} floats) and will be truncated — ` +
1108
1271
  `the shape gets cut off. Simplify the path (fewer/coarser curves) or split it across <Svg> nodes; ` +
1109
1272
  `raising the limit needs ERUI_VECTOR_TAPE_MAX.`,
1110
1273
  );
1111
1274
  }
1112
- const shapes = (paintsLen / PAINT_STRIDE) | 0;
1113
- if (!_warnedVecPaints && maxPaints > 0 && shapes > maxPaints) {
1114
- _warnedVecPaints = true;
1275
+ const shapes = (paintsLength / PAINT_STRIDE) | 0;
1276
+ if (!_warnedVectorPaints && maxPaints > 0 && shapes > maxPaints) {
1277
+ _warnedVectorPaints = true;
1115
1278
  console.warn(
1116
1279
  `embedded-react: an <Svg> has ${shapes} shapes (> ${maxPaints}) — the extra shapes won't render. ` +
1117
1280
  `Split them across multiple <Svg> nodes; raising the limit needs ERUI_VECTOR_PAINTS_MAX.`,
1118
1281
  );
1119
1282
  }
1120
- if (!_warnedVecGrads && maxGrads > 0 && gradsLen > maxGrads) {
1121
- _warnedVecGrads = true;
1283
+ if (
1284
+ !_warnedVectorGradients &&
1285
+ maxGradients > 0 &&
1286
+ gradientsLength > maxGradients
1287
+ ) {
1288
+ _warnedVectorGradients = true;
1122
1289
  console.warn(
1123
- `embedded-react: an <Svg> references ${gradsLen} gradients (> ${maxGrads}) — the extra gradients are ` +
1290
+ `embedded-react: an <Svg> references ${gradientsLength} gradients (> ${maxGradients}) — the extra gradients are ` +
1124
1291
  `dropped and shapes that use them fall back to solid fills/strokes. Reuse fewer distinct gradients across ` +
1125
- `shapes; raising the limit needs ERUI_VECTOR_GRADS_MAX.`,
1292
+ `shapes; raising the limit needs ERUI_VECTOR_GRADIENTS_MAX.`,
1126
1293
  );
1127
1294
  }
1128
1295
  }