-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsvg-extractor.ts
More file actions
1079 lines (944 loc) · 37.8 KB
/
svg-extractor.ts
File metadata and controls
1079 lines (944 loc) · 37.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* SVG geometry extraction using SVG-native APIs.
* This is a SEPARATE path from HTML extraction — SVG never uses getBoxQuads.
*/
import type { Point, Quad, Style, IRNode, Options } from "../types.js";
import { extractStyle } from "../traversal.js";
import { getSvgScreenCtm, getElementQuad } from "../geometry.js";
import { buildSourceMetadata } from "../shared/source-metadata.js";
/** Number of sample points for path/circle/ellipse approximation. */
const PATH_SAMPLE_COUNT = 64;
const CIRCLE_SEGMENTS = 32;
const sampledPathGeometryCache = new Map<string, { points: Point[]; closed: boolean } | null>();
/**
* Extract geometry from an entire SVG subtree.
* SVG DOM order defines paint order (z-index does not apply inside SVG).
*/
export function extractSVGSubtree(
svgRoot: SVGSVGElement,
baseZIndex: number,
options: Options,
htmlParentOpacity: number = 1
): IRNode[] {
const results: IRNode[] = [];
let orderIndex = baseZIndex;
// Pass htmlParentOpacity as the initial parent opacity;
// walkSVGTree will read the SVG root's own opacity and multiply it in.
walkSVGTree(svgRoot, results, () => orderIndex++, options, htmlParentOpacity);
return results;
}
function walkSVGTree(
el: Element,
results: IRNode[],
nextIndex: () => number,
options: Options,
parentOpacity: number
): void {
// Skip non-rendering container elements — their children are referenced
// indirectly (e.g. via <use>, marker-end, clip-path) and should not be
// painted during the normal tree walk.
const tag = el.tagName.toLowerCase();
if (tag === "defs" || tag === "symbol" || tag === "clippath" ||
tag === "mask" || tag === "pattern") {
return;
}
// Skip hidden SVG elements (display:none removes from layout entirely).
// visibility:hidden hides the element but children can override it,
// so we must still walk children.
const cs = getComputedStyle(el);
if (cs.display === "none") return;
// Compute this element's effective opacity
const ownOpacity = cs.opacity ? parseFloat(cs.opacity) : 1;
const effectiveOpacity = parentOpacity * ownOpacity;
// Process this element if it's a renderable SVG shape and visible
if (el instanceof SVGGraphicsElement && el !== el.ownerSVGElement && cs.visibility !== "hidden") {
const nodes = extractSVGElement(el, nextIndex(), options, effectiveOpacity, cs);
if (options.includeSourceMetadata && nodes.length > 0) {
const source = buildSourceMetadata(el, tag);
for (const node of nodes) {
node.source = source;
}
}
results.push(...nodes);
}
// <use> elements render referenced content via a shadow DOM.
// Walk the <use> shadow root's children to extract the cloned geometry.
if (tag === "use" && el.shadowRoot) {
for (const child of Array.from(el.shadowRoot.children)) {
walkSVGTree(child, results, nextIndex, options, effectiveOpacity);
}
return;
}
// Walk children (DOM order = paint order in SVG)
// Handle <switch>: only process the first child element that is actually
// rendered (the browser evaluates systemLanguage/requiredFeatures/etc.)
if (tag === "switch") {
for (const child of Array.from(el.children)) {
if (child instanceof SVGGraphicsElement) {
try {
const bbox = child.getBBox();
if (bbox.width > 0 || bbox.height > 0) {
walkSVGTree(child, results, nextIndex, options, effectiveOpacity);
return; // only the first matching child is rendered
}
} catch { /* getBBox can throw for non-rendered elements */ }
}
}
return;
}
for (const child of Array.from(el.children)) {
walkSVGTree(child, results, nextIndex, options, effectiveOpacity);
}
}
/** Extract geometry from a single SVG element. */
function extractSVGElement(
el: SVGGraphicsElement,
zIndex: number,
options: Options,
effectiveOpacity: number,
preComputedStyle?: CSSStyleDeclaration
): IRNode[] {
const cs = preComputedStyle ?? getComputedStyle(el);
const ctm = getCtm(el);
const style = extractSVGStyle(cs, el, ctm);
// Override opacity with the effective (inherited) opacity
style.opacity = effectiveOpacity;
const tag = el.tagName.toLowerCase();
switch (tag) {
case "rect":
return extractRect(el as SVGRectElement, style, zIndex, ctm);
case "circle":
return extractCircle(el as SVGCircleElement, style, zIndex, ctm);
case "ellipse":
return extractEllipse(el as SVGEllipseElement, style, zIndex, ctm);
case "line":
return extractLine(el as SVGLineElement, style, zIndex, ctm);
case "polyline":
return extractPolyline(el as SVGPolylineElement, style, zIndex, false, ctm);
case "polygon":
return extractPolyline(el as SVGPolygonElement, style, zIndex, true, ctm);
case "path":
return extractPath(el as SVGPathElement, style, zIndex, ctm);
case "text":
if (options.includeText !== false) {
return extractText(el as SVGTextElement, style, zIndex, ctm);
}
return [];
default:
return [];
}
}
/** Extract SVG-specific styles, scaling stroke width by the CTM. */
function extractSVGStyle(cs: CSSStyleDeclaration, el: SVGGraphicsElement, ctm: DOMMatrix): Style {
const base = extractStyle(cs);
// SVG uses fill/stroke attributes directly
let fill = cs.fill || el.getAttribute("fill") || undefined;
const fillRule = cs.fillRule || el.getAttribute("fill-rule") || undefined;
let stroke = cs.stroke || el.getAttribute("stroke") || undefined;
let strokeImage: string | undefined;
let strokeWidth = cs.strokeWidth || el.getAttribute("stroke-width") || undefined;
// Scale stroke width by the CTM's average scale factor.
// The CSS/attribute strokeWidth is in the element's local coordinate space,
// but extracted points are in screen coordinates after CTM transformation.
if (strokeWidth) {
const sw = parseFloat(strokeWidth);
if (!isNaN(sw) && sw > 0) {
// Geometric mean of the CTM's x and y scale factors
const sx = Math.sqrt(ctm.a * ctm.a + ctm.b * ctm.b);
const sy = Math.sqrt(ctm.c * ctm.c + ctm.d * ctm.d);
const scale = Math.sqrt(sx * sy);
strokeWidth = `${sw * scale}px`;
}
}
// Extract stroke-dasharray and scale by CTM
let strokeDasharray = cs.strokeDasharray || el.getAttribute("stroke-dasharray") || undefined;
if (strokeDasharray && strokeDasharray !== "none") {
const sx = Math.sqrt(ctm.a * ctm.a + ctm.b * ctm.b);
const sy = Math.sqrt(ctm.c * ctm.c + ctm.d * ctm.d);
const scale = Math.sqrt(sx * sy);
strokeDasharray = strokeDasharray.split(/[\s,]+/).map(v => {
const n = parseFloat(v);
return isNaN(n) ? v : String(n * scale);
}).join(",");
} else {
strokeDasharray = undefined;
}
// Resolve url(#id) gradient references to CSS gradient strings
let backgroundImage: string | undefined;
if (fill && fill.startsWith("url(")) {
const resolved = resolveGradient(fill, el);
if (resolved) {
backgroundImage = resolved.cssGradient;
fill = resolved.fallbackColor;
} else {
fill = resolveGradientColor(fill, el) ?? fill;
}
}
// Preserve gradient strokes for capable writers and keep a concrete
// fallback color for formats that only accept simple stroke colors.
if (stroke && stroke.startsWith("url(")) {
const resolved = resolveGradient(stroke, el);
if (resolved) {
strokeImage = resolved.cssGradient;
stroke = resolved.fallbackColor;
} else {
stroke = resolveGradientColor(stroke, el) ?? stroke;
}
}
// Scale fontSize by the CTM so it matches the screen-coordinate quad.
// Same principle as strokeWidth: CSS fontSize is in local SVG coordinates,
// but extracted text quads are in screen coordinates after CTM transformation.
let { fontSize } = base;
if (fontSize) {
const fs = parseFloat(fontSize);
if (!isNaN(fs) && fs > 0) {
const sx = Math.sqrt(ctm.a * ctm.a + ctm.b * ctm.b);
const sy = Math.sqrt(ctm.c * ctm.c + ctm.d * ctm.d);
const scale = Math.sqrt(sx * sy);
fontSize = `${fs * scale}px`;
}
}
// In SVG, fill determines text color — override CSS color with fill
const svgColor = (fill && fill !== "none" && !fill.startsWith("url(")) ? fill : undefined;
return {
...base,
fill: fill !== "none" ? fill : undefined,
fillRule: fillRule === "evenodd" ? "evenodd" : fillRule === "nonzero" ? "nonzero" : undefined,
stroke: stroke !== "none" ? stroke : undefined,
strokeImage,
strokeWidth,
strokeDasharray,
fontSize,
backgroundImage: backgroundImage ?? base.backgroundImage,
...(svgColor ? { color: svgColor } : {}),
};
}
/** Resolve a url(#id) gradient reference to its first stop color. */
function resolveGradientColor(urlRef: string, el: SVGGraphicsElement): string | undefined {
const match = urlRef.match(/url\(["']?#([^"')]+)["']?\)/);
if (!match) return undefined;
const id = match[1];
const ownerSvg = el.ownerSVGElement;
if (!ownerSvg) return undefined;
const gradEl = ownerSvg.querySelector(`#${id}`);
if (!gradEl) return undefined;
// Get stop colors from the gradient
const stops = gradEl.querySelectorAll("stop");
if (stops.length === 0) return undefined;
// Use the first stop's color as a representative solid color
const stopStyle = getComputedStyle(stops[0]);
const stopColor = stopStyle.getPropertyValue("stop-color")
|| stopStyle.stopColor
|| (stops[0] as SVGStopElement).getAttribute("stop-color")
|| undefined;
return stopColor || undefined;
}
/** Resolve a url(#id) gradient reference to a CSS gradient string for the PNG writer. */
function resolveGradient(urlRef: string, el: SVGGraphicsElement): { cssGradient: string; fallbackColor: string } | undefined {
const match = urlRef.match(/url\(["']?#([^"')]+)["']?\)/);
if (!match) return undefined;
const id = match[1];
const ownerSvg = el.ownerSVGElement;
if (!ownerSvg) return undefined;
const gradEl = ownerSvg.querySelector(`#${id}`);
if (!gradEl) return undefined;
const stops = gradEl.querySelectorAll("stop");
if (stops.length === 0) return undefined;
// Extract stop colors and offsets
const colorStops: string[] = [];
let fallbackColor = "";
for (let i = 0; i < stops.length; i++) {
const stop = stops[i] as SVGStopElement;
const stopStyle = getComputedStyle(stop);
const color = stopStyle.getPropertyValue("stop-color")
|| stopStyle.stopColor
|| stop.getAttribute("stop-color")
|| "";
let offset = stop.getAttribute("offset") ?? "0%";
// Normalize SVG fraction offset (0..1) to CSS percentage
if (!offset.endsWith("%")) {
const val = parseFloat(offset);
if (!isNaN(val)) offset = `${val * 100}%`;
}
if (i === 0) fallbackColor = color;
colorStops.push(`${color} ${offset}`);
}
const tag = gradEl.tagName.toLowerCase();
if (tag === "lineargradient") {
const lg = gradEl as SVGLinearGradientElement;
const x1 = parseFloat(lg.getAttribute("x1") ?? "0");
const y1 = parseFloat(lg.getAttribute("y1") ?? "0");
const x2 = parseFloat(lg.getAttribute("x2") ?? "100");
const y2 = parseFloat(lg.getAttribute("y2") ?? "0");
// Convert SVG gradient vector to CSS angle
const dx = x2 - x1;
const dy = y2 - y1;
const angleDeg = Math.round(Math.atan2(dx, -dy) * (180 / Math.PI));
const cssGradient = `linear-gradient(${angleDeg}deg, ${colorStops.join(", ")})`;
return { cssGradient, fallbackColor };
}
if (tag === "radialgradient") {
const cssGradient = `radial-gradient(circle, ${colorStops.join(", ")})`;
return { cssGradient, fallbackColor };
}
return undefined;
}
/** Apply the CTM (current transformation matrix) to a point. */
function applyCtm(point: Point, ctm: DOMMatrix): Point {
return {
x: ctm.a * point.x + ctm.c * point.y + ctm.e,
y: ctm.b * point.x + ctm.d * point.y + ctm.f,
};
}
/** Get the screen CTM for an SVG element, adjusted to align with getBoxQuads. */
function getCtm(el: SVGGraphicsElement): DOMMatrix {
return getSvgScreenCtm(el);
}
/** Transform an array of points using a pre-computed or freshly-obtained CTM. */
function transformPoints(points: Point[], el: SVGGraphicsElement, preCtm?: DOMMatrix): Point[] {
const ctm = preCtm ?? getCtm(el);
return points.map((p) => applyCtm(p, ctm));
}
/** Convert 4 corner points to a Quad. */
function rectToQuad(x: number, y: number, w: number, h: number): Quad {
return [
{ x, y },
{ x: x + w, y },
{ x: x + w, y: y + h },
{ x, y: y + h },
];
}
function extractRect(el: SVGRectElement, style: Style, zIndex: number, ctm: DOMMatrix): IRNode[] {
let x = el.x.baseVal.value;
let y = el.y.baseVal.value;
let w = el.width.baseVal.value;
let h = el.height.baseVal.value;
// Fallback to getBBox() when SVG attributes are missing but CSS defines geometry (SVG2)
if (w === 0 || h === 0) {
try {
const bbox = el.getBBox();
if (bbox.width > 0 || bbox.height > 0) {
x = bbox.x;
y = bbox.y;
w = bbox.width;
h = bbox.height;
}
} catch { /* getBBox may throw if element is not rendered */ }
}
if (w === 0 || h === 0) return [];
// Handle rx/ry rounded corners (e.g. pill shapes)
let rx = el.rx.baseVal.value;
let ry = el.ry.baseVal.value;
if (rx && !ry) ry = rx;
if (ry && !rx) rx = ry;
if (rx > 0 || ry > 0) {
const sx = Math.sqrt(ctm.a * ctm.a + ctm.b * ctm.b);
const sy = Math.sqrt(ctm.c * ctm.c + ctm.d * ctm.d);
const scaledR = Math.min(rx * sx, ry * sy);
style = { ...style, borderRadius: `${scaledR}px` };
}
const rawQuad = rectToQuad(x, y, w, h);
const transformed = transformPoints(rawQuad, el, ctm) as Quad;
return [{ type: "polygon", points: transformed, style, zIndex }];
}
function extractCircle(el: SVGCircleElement, style: Style, zIndex: number, ctm: DOMMatrix): IRNode[] {
const cx = el.cx.baseVal.value;
const cy = el.cy.baseVal.value;
const r = el.r.baseVal.value;
if (r === 0) return [];
const points: Point[] = [];
for (let i = 0; i < CIRCLE_SEGMENTS; i++) {
const angle = (2 * Math.PI * i) / CIRCLE_SEGMENTS;
points.push({ x: cx + r * Math.cos(angle), y: cy + r * Math.sin(angle) });
}
const transformed = transformPoints(points, el, ctm);
return [{ type: "polyline", points: transformed, closed: true, style, zIndex }];
}
function extractEllipse(el: SVGEllipseElement, style: Style, zIndex: number, ctm: DOMMatrix): IRNode[] {
const cx = el.cx.baseVal.value;
const cy = el.cy.baseVal.value;
const rx = el.rx.baseVal.value;
const ry = el.ry.baseVal.value;
if (rx === 0 || ry === 0) return [];
const points: Point[] = [];
for (let i = 0; i < CIRCLE_SEGMENTS; i++) {
const angle = (2 * Math.PI * i) / CIRCLE_SEGMENTS;
points.push({ x: cx + rx * Math.cos(angle), y: cy + ry * Math.sin(angle) });
}
const transformed = transformPoints(points, el, ctm);
return [{ type: "polyline", points: transformed, closed: true, style, zIndex }];
}
function extractLine(el: SVGLineElement, style: Style, zIndex: number, ctm: DOMMatrix): IRNode[] {
const p1: Point = { x: el.x1.baseVal.value, y: el.y1.baseVal.value };
const p2: Point = { x: el.x2.baseVal.value, y: el.y2.baseVal.value };
const transformed = transformPoints([p1, p2], el, ctm);
const results: IRNode[] = [{ type: "polyline", points: transformed, closed: false, style, zIndex }];
results.push(...extractMarkers(el, transformed, style, zIndex, false));
return results;
}
function extractPolyline(
el: SVGPolylineElement | SVGPolygonElement,
style: Style,
zIndex: number,
closed: boolean,
ctm: DOMMatrix
): IRNode[] {
const points: Point[] = [];
const numPoints = el.points.numberOfItems;
for (let i = 0; i < numPoints; i++) {
const pt = el.points.getItem(i);
points.push({ x: pt.x, y: pt.y });
}
if (points.length === 0) return [];
const transformed = transformPoints(points, el, ctm);
const results: IRNode[] = [{ type: "polyline", points: transformed, closed, style, zIndex }];
results.push(...extractMarkers(el, transformed, style, zIndex, closed));
return results;
}
function extractPath(el: SVGPathElement, style: Style, zIndex: number, ctm: DOMMatrix): IRNode[] {
const subpaths = splitPathSubpaths(el);
if (subpaths.length > 1) {
const sampled = extractCompoundPathBySampling(el, subpaths, style, zIndex, ctm);
if (sampled.length > 0) return sampled;
}
// Try getPathData if available (modern API)
if (typeof (el as any).getPathData === "function") {
return extractPathFromPathData(el, style, zIndex, ctm);
}
// Fallback: sample via getPointAtLength
return extractPathBySampling(el, style, zIndex, ctm);
}
type PathDataSegmentLike = {
type: string;
values: number[];
};
function splitPathSubpaths(el: SVGPathElement): string[] {
if (typeof (el as any).getPathData === "function") {
try {
const rawSegments = (el as any).getPathData({ normalize: true }) as PathDataSegmentLike[];
const subpaths = splitNormalizedPathData(rawSegments);
if (subpaths.length > 1) {
return subpaths.map(serializePathDataSegments);
}
} catch {
// Fall through to string-based splitting for older/partial implementations.
}
}
return splitPathSubpathsFromString(el.getAttribute("d") ?? "");
}
function splitNormalizedPathData(segments: PathDataSegmentLike[]): PathDataSegmentLike[][] {
const subpaths: PathDataSegmentLike[][] = [];
let current: PathDataSegmentLike[] = [];
for (const segment of segments) {
if (segment.type.toUpperCase() === "M" && current.length > 0) {
subpaths.push(current);
current = [];
}
current.push({
type: segment.type.toUpperCase(),
values: [...segment.values],
});
}
if (current.length > 0) subpaths.push(current);
return subpaths;
}
function serializePathDataSegments(segments: PathDataSegmentLike[]): string {
return segments.map((segment) => {
if (segment.values.length === 0) return segment.type;
return `${segment.type}${segment.values.map((value) => {
const rounded = Math.round(value * 1000) / 1000;
return Number.isInteger(rounded) ? rounded.toString() : rounded.toString();
}).join(" ")}`;
}).join(" ");
}
const PATH_COMMAND_ARITY: Record<string, number> = {
A: 7,
C: 6,
H: 1,
L: 2,
M: 2,
Q: 4,
S: 4,
T: 2,
V: 1,
Z: 0,
};
function isPathCommandToken(token: string): boolean {
return /^[AaCcHhLlMmQqSsTtVvZz]$/.test(token);
}
function parsePathDataCommands(pathData: string): PathDataSegmentLike[] | null {
const commands: PathDataSegmentLike[] = [];
let index = 0;
let currentCommand = "";
function skipSeparators(): void {
while (index < pathData.length && /[\s,]/.test(pathData[index])) {
index += 1;
}
}
function readNumberValue(): number | null {
skipSeparators();
const match = /^[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?/.exec(pathData.slice(index));
if (!match) return null;
const value = Number(match[0]);
if (!Number.isFinite(value)) return null;
index += match[0].length;
return value;
}
function readArcFlagValue(): number | null {
skipSeparators();
const flag = pathData[index];
if (flag !== "0" && flag !== "1") return null;
index += 1;
return Number(flag);
}
function readSegmentValues(command: string): number[] | null {
const upperCommand = command.toUpperCase();
const arity = PATH_COMMAND_ARITY[upperCommand];
if (arity === undefined || arity === 0) return [];
const values: number[] = [];
for (let valueIndex = 0; valueIndex < arity; valueIndex += 1) {
const value = upperCommand === "A" && (valueIndex === 3 || valueIndex === 4)
? readArcFlagValue()
: readNumberValue();
if (value === null) return null;
values.push(value);
}
return values;
}
while (true) {
skipSeparators();
if (index >= pathData.length) break;
if (isPathCommandToken(pathData[index])) {
currentCommand = pathData[index];
index += 1;
} else if (!currentCommand) {
return null;
}
const upperCommand = currentCommand.toUpperCase();
const arity = PATH_COMMAND_ARITY[upperCommand];
if (arity === undefined) return null;
if (arity === 0) {
commands.push({ type: currentCommand, values: [] });
currentCommand = "";
continue;
}
if (upperCommand === "M") {
const moveValues = readSegmentValues(currentCommand);
if (!moveValues) return null;
commands.push({ type: currentCommand, values: moveValues });
const lineCommand = currentCommand === "m" ? "l" : "L";
skipSeparators();
while (index < pathData.length && !isPathCommandToken(pathData[index])) {
const lineValues = readSegmentValues(lineCommand);
if (!lineValues) return null;
commands.push({
type: lineCommand,
values: lineValues,
});
skipSeparators();
}
continue;
}
while (true) {
const values = readSegmentValues(currentCommand);
if (!values) return null;
commands.push({
type: currentCommand,
values,
});
skipSeparators();
if (index >= pathData.length || isPathCommandToken(pathData[index])) break;
}
}
return commands;
}
function advancePathCurrentPoint(
segment: PathDataSegmentLike,
currentPoint: Point,
subpathStart: Point,
): Point {
const type = segment.type;
const values = segment.values;
const relative = type === type.toLowerCase();
switch (type.toUpperCase()) {
case "Z":
return { ...subpathStart };
case "H": {
const x = values[values.length - 1];
return {
x: relative ? currentPoint.x + x : x,
y: currentPoint.y,
};
}
case "V": {
const y = values[values.length - 1];
return {
x: currentPoint.x,
y: relative ? currentPoint.y + y : y,
};
}
case "A":
case "C":
case "L":
case "M":
case "Q":
case "S":
case "T": {
const x = values[values.length - 2];
const y = values[values.length - 1];
return {
x: relative ? currentPoint.x + x : x,
y: relative ? currentPoint.y + y : y,
};
}
default:
return currentPoint;
}
}
function splitParsedPathDataCommands(segments: PathDataSegmentLike[]): string[] {
const subpaths: PathDataSegmentLike[][] = [];
let currentSubpath: PathDataSegmentLike[] = [];
let currentPoint: Point = { x: 0, y: 0 };
let subpathStart: Point = { x: 0, y: 0 };
for (const segment of segments) {
if (segment.type.toUpperCase() === "M") {
if (currentSubpath.length > 0) {
subpaths.push(currentSubpath);
}
currentPoint = advancePathCurrentPoint(segment, currentPoint, subpathStart);
subpathStart = { ...currentPoint };
currentSubpath = [{ type: "M", values: [currentPoint.x, currentPoint.y] }];
continue;
}
if (currentSubpath.length === 0) {
return [];
}
currentSubpath.push({
type: segment.type.toUpperCase() === "Z" ? "Z" : segment.type,
values: [...segment.values],
});
currentPoint = advancePathCurrentPoint(segment, currentPoint, subpathStart);
}
if (currentSubpath.length > 0) {
subpaths.push(currentSubpath);
}
return subpaths.map(serializePathDataSegments);
}
function splitPathSubpathsFromString(pathData: string): string[] {
const trimmed = pathData.trim();
if (!trimmed) return [];
const parsed = parsePathDataCommands(trimmed);
if (!parsed) return [trimmed];
const moveCommands = parsed.filter((segment) => segment.type.toUpperCase() === "M");
if (moveCommands.length <= 1) return [trimmed];
const subpaths = splitParsedPathDataCommands(parsed);
return subpaths.length > 1 ? subpaths : [trimmed];
}
function extractCompoundPathBySampling(
el: SVGPathElement,
subpaths: string[],
style: Style,
zIndex: number,
ctm: DOMMatrix
): IRNode[] {
const ownerSvg = el.ownerSVGElement;
if (!ownerSvg) return [];
const pathSubpaths: NonNullable<Style["pathSubpaths"]> = [];
for (const subpath of subpaths) {
const tempPath = document.createElementNS("http://www.w3.org/2000/svg", "path");
tempPath.setAttribute("d", subpath);
tempPath.setAttribute("visibility", "hidden");
ownerSvg.appendChild(tempPath);
try {
const sampled = samplePathGeometry(tempPath, el, ctm);
if (sampled) pathSubpaths.push(sampled);
} finally {
tempPath.remove();
}
}
if (pathSubpaths.length === 0) return [];
return [{
type: "polyline",
points: pathSubpaths.flatMap((subpath) => subpath.points),
closed: pathSubpaths.every((subpath) => subpath.closed),
style: {
...style,
pathSubpaths,
},
zIndex,
}];
}
function extractPathFromPathData(
el: SVGPathElement,
style: Style,
zIndex: number,
ctm: DOMMatrix
): IRNode[] {
// getPathData returns normalized path segments
// Still sample for consistent output
return extractPathBySampling(el, style, zIndex, ctm);
}
function extractPathBySampling(
el: SVGPathElement,
style: Style,
zIndex: number,
ctm: DOMMatrix
): IRNode[] {
const sampled = samplePathGeometry(el, el, ctm);
if (!sampled) return [];
const results: IRNode[] = [{
type: "polyline",
points: sampled.points,
closed: sampled.closed,
style,
zIndex,
}];
results.push(...extractMarkers(el, sampled.points, style, zIndex, sampled.closed));
return results;
}
function samplePathGeometry(
pathEl: SVGPathElement,
transformEl: SVGGraphicsElement,
ctm: DOMMatrix
): NonNullable<Style["pathSubpaths"]>[number] | null {
const pathData = pathEl.getAttribute("d") ?? "";
let sampled = pathData ? sampledPathGeometryCache.get(pathData) : undefined;
if (sampled === undefined) {
let totalLength: number;
try {
totalLength = pathEl.getTotalLength();
} catch {
sampled = null;
if (pathData) sampledPathGeometryCache.set(pathData, sampled);
return null;
}
if (totalLength === 0) {
sampled = null;
if (pathData) sampledPathGeometryCache.set(pathData, sampled);
return null;
}
const closed = /[Zz]\s*$/.test(pathData.trim()) || /[Zz]/.test(pathData);
const points: Point[] = [];
const sampleCount = Math.max(PATH_SAMPLE_COUNT, Math.ceil(totalLength / 2));
for (let i = 0; i <= sampleCount; i++) {
const len = (totalLength * i) / sampleCount;
const pt = pathEl.getPointAtLength(len);
points.push({ x: pt.x, y: pt.y });
}
sampled = { points, closed };
if (pathData) sampledPathGeometryCache.set(pathData, sampled);
}
if (!sampled) return null;
const transformed = transformPoints(sampled.points, transformEl, ctm);
return { points: transformed, closed: sampled.closed };
}
/**
* Extract SVG marker geometry and place it at the appropriate position/rotation.
* Handles marker-start, marker-mid, and marker-end.
*/
function extractMarkers(
el: SVGGraphicsElement,
points: Point[],
style: Style,
zIndex: number,
closed = false
): IRNode[] {
if (points.length < 2) return [];
const cs = getComputedStyle(el);
const markerStart = cs.getPropertyValue("marker-start").trim() || el.getAttribute("marker-start") || "";
const markerMid = cs.getPropertyValue("marker-mid").trim() || el.getAttribute("marker-mid") || "";
const markerEnd = cs.getPropertyValue("marker-end").trim() || el.getAttribute("marker-end") || "";
const results: IRNode[] = [];
const ownerSvg = (el as any).ownerSVGElement as SVGSVGElement | null;
if (!ownerSvg) return [];
// Compute CTM scale factor — marker shapes are defined in local SVG units
// but points[] are already in screen coordinates after CTM transformation.
// Without this, markers are too large when viewBox > viewport (CTM < 1)
// and too small when viewBox < viewport (CTM > 1).
const ctm = getCtm(el);
const ctmSx = Math.sqrt(ctm.a * ctm.a + ctm.b * ctm.b);
const ctmSy = Math.sqrt(ctm.c * ctm.c + ctm.d * ctm.d);
const ctmScale = Math.sqrt(ctmSx * ctmSy);
function resolveMarker(ref: string): SVGMarkerElement | null {
if (!ref || ref === "none") return null;
const m = ref.match(/url\(["']?#([^"')]+)["']?\)/);
if (!m) return null;
return ownerSvg!.querySelector(`#${m[1]}`) as SVGMarkerElement | null;
}
function placeMarker(marker: SVGMarkerElement, pos: Point, angle: number): void {
// Parse marker attributes
const vb = marker.viewBox.baseVal;
const mw = marker.markerWidth.baseVal.value || 3;
const mh = marker.markerHeight.baseVal.value || 3;
const refX = marker.refX.baseVal.value;
const refY = marker.refY.baseVal.value;
// Compute scale from viewBox to marker size
const vbW = vb?.width || mw;
const vbH = vb?.height || mh;
const scaleX = mw / vbW;
const scaleY = mh / vbH;
// Determine scale multiplier based on markerUnits attribute.
// "strokeWidth" (default): marker is scaled by the referencing element's stroke width.
// "userSpaceOnUse": marker uses the referencing element's user coordinate system directly.
// In both cases, multiply by ctmScale to convert from SVG user units to screen pixels.
const markerUnitsAttr = marker.getAttribute("markerUnits");
const sw = markerUnitsAttr === "userSpaceOnUse"
? 1
: (parseFloat(cs.strokeWidth) || 1);
const cosA = Math.cos(angle);
const sinA = Math.sin(angle);
const s = sw * ctmScale;
// Extract shapes from marker children
for (const child of Array.from(marker.children)) {
if (child instanceof SVGPathElement) {
let totalLength: number;
try { totalLength = child.getTotalLength(); } catch { continue; }
if (totalLength === 0) continue;
const rawPts: Point[] = [];
const sampleCount = Math.max(32, Math.ceil(totalLength / 2));
for (let i = 0; i <= sampleCount; i++) {
const pt = child.getPointAtLength((totalLength * i) / sampleCount);
rawPts.push({ x: pt.x, y: pt.y });
}
// Transform: shift by -refX/-refY, scale, rotate, translate to position
const transformed = rawPts.map(p => {
const lx = (p.x - refX) * scaleX * s;
const ly = (p.y - refY) * scaleY * s;
return {
x: pos.x + lx * cosA - ly * sinA,
y: pos.y + lx * sinA + ly * cosA,
};
});
// Get marker shape's fill
const childCs = getComputedStyle(child);
const childFill = childCs.fill || child.getAttribute("fill") || undefined;
const childStroke = childCs.stroke || child.getAttribute("stroke") || undefined;
const markerStyle: Style = {
...style,
fill: childFill !== "none" ? childFill : undefined,
stroke: childStroke !== "none" ? childStroke : undefined,
};
results.push({ type: "polyline", points: transformed, closed: true, style: markerStyle, zIndex });
} else if (child instanceof SVGPolygonElement || child instanceof SVGPolylineElement) {
const rawPts: Point[] = [];
for (let i = 0; i < child.points.numberOfItems; i++) {
const pt = child.points.getItem(i);
rawPts.push({ x: pt.x, y: pt.y });
}
const transformed = rawPts.map(p => {
const lx = (p.x - refX) * scaleX * s;
const ly = (p.y - refY) * scaleY * s;
return {
x: pos.x + lx * cosA - ly * sinA,
y: pos.y + lx * sinA + ly * cosA,
};
});
const childCs = getComputedStyle(child);
const childFill = childCs.fill || child.getAttribute("fill") || undefined;
const markerStyle: Style = { ...style, fill: childFill !== "none" ? childFill : undefined };
results.push({ type: "polyline", points: transformed, closed: child instanceof SVGPolygonElement, style: markerStyle, zIndex });
} else if (child instanceof SVGCircleElement || child instanceof SVGEllipseElement) {
const cx0 = child instanceof SVGCircleElement ? child.cx.baseVal.value : (child as SVGEllipseElement).cx.baseVal.value;
const cy0 = child instanceof SVGCircleElement ? child.cy.baseVal.value : (child as SVGEllipseElement).cy.baseVal.value;
const rx0 = child instanceof SVGCircleElement ? child.r.baseVal.value : (child as SVGEllipseElement).rx.baseVal.value;
const ry0 = child instanceof SVGCircleElement ? child.r.baseVal.value : (child as SVGEllipseElement).ry.baseVal.value;
const circPts: Point[] = [];
for (let ci = 0; ci < CIRCLE_SEGMENTS; ci++) {
const a = (2 * Math.PI * ci) / CIRCLE_SEGMENTS;
circPts.push({ x: cx0 + rx0 * Math.cos(a), y: cy0 + ry0 * Math.sin(a) });
}
const transformed = circPts.map(p => {
const lx = (p.x - refX) * scaleX * s;
const ly = (p.y - refY) * scaleY * s;
return {
x: pos.x + lx * cosA - ly * sinA,
y: pos.y + lx * sinA + ly * cosA,
};
});
const childCs = getComputedStyle(child);
const childFill = childCs.fill || child.getAttribute("fill") || undefined;
const markerStyle: Style = { ...style, fill: childFill !== "none" ? childFill : undefined };
results.push({ type: "polyline", points: transformed, closed: true, style: markerStyle, zIndex });
} else if (child instanceof SVGRectElement) {
const rx = child.x.baseVal.value;
const ry = child.y.baseVal.value;
const rw = child.width.baseVal.value;
const rh = child.height.baseVal.value;
const rawPts: Point[] = [
{ x: rx, y: ry }, { x: rx + rw, y: ry },
{ x: rx + rw, y: ry + rh }, { x: rx, y: ry + rh },
];
const transformed = rawPts.map(p => {
const lx = (p.x - refX) * scaleX * s;
const ly = (p.y - refY) * scaleY * s;
return {