-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsvg-writer.ts
More file actions
1241 lines (1093 loc) · 51.4 KB
/
svg-writer.ts
File metadata and controls
1241 lines (1093 loc) · 51.4 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 Writer.
* Maps IR nodes to SVG elements and produces a standalone SVG document string.
*/
import type { FontAssetCollection, FontAssetMode } from "../font-assets.js";
import type { ClipQuad, PathSubpath, Point, Quad, SourceMetadata, Style, Writer } from "../types.js";
import { roundedQuadPath } from "../geometry.js";
import { normalizeWhitespaceAwareText, preservesWhitespace } from "../shared/text-whitespace.js";
import { getVisibleCssColorString, parseCssColor, type ParsedCssColor } from "./shared/css-color.js";
import { getPointBounds, getQuadBounds, parseClipPathShape, type ClipPathBounds, type ClipPathShape } from "./shared/clip-path.js";
import { buildEmbeddedFontDataUrl, buildFontFaceCss, choosePreferredWebFontSource, normalizeFontBasePath } from "./shared/font-assets.js";
import {
expandRepeatingGradientStops,
extractAllGradients,
normalizeGradientStopOffsets,
parseGradientAst,
type GradientStopAst,
type ParsedGradientAst,
} from "./shared/gradient-utils.js";
import { getSvgBlendModeStyle } from "./shared/filter-effects.js";
import { formatWriterNumber as n, getVisibleStroke, isAxisAlignedRect, parseMinDimensionBorderRadius as parseBorderRadius } from "./shared/writer-utils.js";
// ── Color helpers ───────────────────────────────────────────────────
/** Escape text for use inside XML/SVG elements.
* Encodes XML special characters and non-BMP Unicode characters as numeric
* character references so the output is safe for any XML parser.
*/
function escXml(s: string): string {
let out = "";
for (const ch of s) {
const code = ch.codePointAt(0)!;
switch (ch) {
case "&": out += "&"; break;
case "<": out += "<"; break;
case ">": out += ">"; break;
case '"': out += """; break;
case "'": out += "'"; break;
default:
if (code < 0x20 && code !== 0x9 && code !== 0xA && code !== 0xD) {
// Invalid XML control character — skip
} else if (code > 0x7E) {
// Non-ASCII — encode as numeric reference for encoding safety
out += `&#x${code.toString(16).toUpperCase()};`;
} else {
out += ch;
}
break;
}
}
return out;
}
function buildSourceDataAttributes(source: SourceMetadata | undefined): string[] {
if (!source) return [];
const attrs = [
`data-source-xpath="${escXml(source.xpath)}"`,
`data-source-original-type="${escXml(source.originalType)}"`,
];
if (source.id) {
attrs.push(`data-source-id="${escXml(source.id)}"`);
}
return attrs;
}
function injectOpeningTagAttributes(xml: string, attributes: string[]): string {
if (attributes.length === 0) return xml;
return xml.replace(/^<([^\s>/]+)([^>]*?)(\s*\/?)>/, (_match, tagName: string, rest: string, closing: string) => {
const trimmedRest = rest.trimEnd();
return `<${tagName}${trimmedRest ? ` ${trimmedRest}` : ""} ${attributes.join(" ")}${closing}>`;
});
}
function getSvgEffectStyle(style: Style): string | undefined {
const declarations: string[] = [];
if (style.filter && style.filter !== "none") {
declarations.push(`filter:${style.filter}`);
}
const blendMode = getSvgBlendModeStyle(style.mixBlendMode);
if (blendMode) {
declarations.push(`mix-blend-mode:${blendMode}`);
}
return declarations.length > 0 ? declarations.join(";") : undefined;
}
function pointsToPath(points: Point[], closed: boolean): string {
return points.map((point, index) => `${index === 0 ? "M" : "L"}${n(point.x)},${n(point.y)}`).join(" ") + (closed ? " Z" : "");
}
function subpathsToPath(subpaths: PathSubpath[]): string {
return subpaths
.filter((subpath) => subpath.points.length > 0)
.map((subpath) => pointsToPath(subpath.points, subpath.closed))
.join(" ");
}
function normalizeFontFamily(fontFamily: string | undefined, fallback: string): string {
const normalized = fontFamily?.trim();
return normalized && normalized.length > 0 ? normalized : fallback;
}
type RenderedOutline = {
color: string;
width: number;
style: string;
offset: number;
};
type QuadTransform = {
width: number;
height: number;
a: number;
b: number;
c: number;
d: number;
e: number;
f: number;
};
function getQuadTransform(points: Quad): QuadTransform | null {
const dx = points[1].x - points[0].x;
const dy = points[1].y - points[0].y;
const ldx = points[3].x - points[0].x;
const ldy = points[3].y - points[0].y;
const width = Math.hypot(dx, dy);
const height = Math.hypot(ldx, ldy);
if (width <= 0 || height <= 0) return null;
return {
width,
height,
a: dx / width,
b: dy / width,
c: ldx / height,
d: ldy / height,
e: points[0].x,
f: points[0].y,
};
}
function getVisibleOutline(style: Style): RenderedOutline | null {
if (!style.outlineWidth) return null;
const width = parseFloat(style.outlineWidth);
if (!Number.isFinite(width) || width <= 0) return null;
const outlineStyle = style.outlineStyle === "auto" ? "solid" : style.outlineStyle;
if (!outlineStyle || outlineStyle === "none") return null;
const color = getVisibleCssColorString(style.outlineColor ?? style.color ?? style.stroke ?? style.fill);
if (!color) return null;
const offsetValue = style.outlineOffset ? parseFloat(style.outlineOffset) : 0;
return {
color,
width,
style: outlineStyle,
offset: Number.isFinite(offsetValue) ? offsetValue : 0,
};
}
function getOutlineDasharray(outline: RenderedOutline): string | undefined {
switch (outline.style) {
case "dashed": {
const dash = Math.max(outline.width * 3, 1);
return `${n(dash)} ${n(dash)}`;
}
case "dotted": {
const gap = Math.max(outline.width * 1.5, 1);
return `${n(outline.width)} ${n(gap)}`;
}
default:
return undefined;
}
}
function roundedQuadToPath(points: Quad, radius: number, cornerShapes?: [number, number, number, number]): string {
const segments = roundedQuadPath(points, radius, cornerShapes);
return segments.map((segment) => {
switch (segment.type) {
case "M": return `M${n(segment.x)},${n(segment.y)}`;
case "L": return `L${n(segment.x)},${n(segment.y)}`;
case "Q": return `Q${n(segment.cx)},${n(segment.cy)} ${n(segment.x)},${n(segment.y)}`;
}
}).join(" ") + " Z";
}
function roundedRectPathData(x: number, y: number, w: number, h: number, r: number): string {
const radius = Math.min(Math.max(r, 0), w / 2, h / 2);
if (radius <= 0) {
return `M${n(x)},${n(y)} H${n(x + w)} V${n(y + h)} H${n(x)} Z`;
}
return [
`M${n(x + radius)},${n(y)}`,
`H${n(x + w - radius)}`,
`A${n(radius)},${n(radius)} 0 0 1 ${n(x + w)},${n(y + radius)}`,
`V${n(y + h - radius)}`,
`A${n(radius)},${n(radius)} 0 0 1 ${n(x + w - radius)},${n(y + h)}`,
`H${n(x + radius)}`,
`A${n(radius)},${n(radius)} 0 0 1 ${n(x)},${n(y + h - radius)}`,
`V${n(y + radius)}`,
`A${n(radius)},${n(radius)} 0 0 1 ${n(x + radius)},${n(y)}`,
"Z",
].join(" ");
}
// ── Gradient parsing (subset of png-writer logic) ───────────────────
interface GradientStop { offset: number; color: string; }
interface LinearGradient { type: "linear"; angleDeg: number; stops: GradientStop[]; repeating: boolean; }
interface RadialGradient { type: "radial"; stops: GradientStop[]; repeating: boolean; }
interface ConicGradient { type: "conic"; fromAngleDeg: number; stops: GradientStop[]; repeating: boolean; }
type ParsedGradient = LinearGradient | RadialGradient | ConicGradient;
const CONIC_GRADIENT_SEGMENTS = 120;
function formatCssColor(color: ParsedCssColor): string {
if (color.a >= 0.999) return `rgb(${color.r}, ${color.g}, ${color.b})`;
return `rgba(${color.r}, ${color.g}, ${color.b}, ${Number(color.a.toFixed(3))})`;
}
function interpolateConicColor(t: number, stops: GradientStop[], repeating = false): string {
if (stops.length === 0) return "transparent";
const parsedStops = stops
.map((stop) => ({ ...stop, parsed: parseCssColor(stop.color) }))
.filter((stop): stop is GradientStop & { parsed: ParsedCssColor } => !!stop.parsed)
.sort((left, right) => left.offset - right.offset);
if (parsedStops.length === 0) return stops[0].color;
const maxOffset = parsedStops[parsedStops.length - 1].offset;
if (repeating && maxOffset > 0 && maxOffset < 0.999999) {
t = ((t % maxOffset) + maxOffset) % maxOffset;
}
if (parsedStops.length === 1) return formatCssColor(parsedStops[0].parsed);
if (t <= parsedStops[0].offset) return formatCssColor(parsedStops[0].parsed);
if (t >= parsedStops[parsedStops.length - 1].offset) return formatCssColor(parsedStops[parsedStops.length - 1].parsed);
for (let i = 0; i < parsedStops.length - 1; i++) {
const start = parsedStops[i];
const end = parsedStops[i + 1];
if (t < start.offset || t > end.offset) continue;
const range = end.offset - start.offset;
const fraction = range > 0 ? (t - start.offset) / range : 0;
return formatCssColor({
r: Math.round(start.parsed.r + (end.parsed.r - start.parsed.r) * fraction),
g: Math.round(start.parsed.g + (end.parsed.g - start.parsed.g) * fraction),
b: Math.round(start.parsed.b + (end.parsed.b - start.parsed.b) * fraction),
a: start.parsed.a + (end.parsed.a - start.parsed.a) * fraction,
});
}
return formatCssColor(parsedStops[parsedStops.length - 1].parsed);
}
function resolveGradientStops(stopsAst: GradientStopAst<string>[]): GradientStop[] {
const stops = stopsAst.map((stop) => ({
color: stop.color,
offset: stop.unit === "auto" ? -1 : stop.offset,
}));
if (stops.length === 0) return stops;
if (stopsAst.some((stop) => stop.unit === "px")) {
if (stops[0].offset < 0) stops[0].offset = 0;
return stops;
}
return normalizeGradientStopOffsets(stops);
}
function toSvgGradient(gradient: ParsedGradientAst<string>): ParsedGradient {
const stops = resolveGradientStops(gradient.stops);
if (gradient.type === "linear") return { ...gradient, stops };
if (gradient.type === "radial") return { ...gradient, stops };
return { ...gradient, stops };
}
// ── Box Shadow parsing ──────────────────────────────────────────────
interface ParsedBoxShadow {
inset: boolean;
offsetX: number;
offsetY: number;
blur: number;
spread: number;
color: string;
}
function parseBoxShadow(boxShadow: string | undefined): ParsedBoxShadow[] {
if (!boxShadow || boxShadow === "none") return [];
const shadows: ParsedBoxShadow[] = [];
const parts: string[] = [];
let depth = 0, current = "";
for (const ch of boxShadow) {
if (ch === "(") depth++; else if (ch === ")") depth--;
else if (ch === "," && depth === 0) { parts.push(current.trim()); current = ""; continue; }
current += ch;
}
if (current.trim()) parts.push(current.trim());
for (const part of parts) {
const inset = /\binset\b/i.test(part);
const cleaned = part.replace(/\binset\b/gi, "").trim();
let color = "rgba(0,0,0,0.5)";
let numericPart = cleaned;
const rgbaMatch = cleaned.match(/rgba?\([^)]+\)/);
if (rgbaMatch) { color = rgbaMatch[0]; numericPart = cleaned.replace(rgbaMatch[0], "").trim(); }
else {
const hexMatch = cleaned.match(/#[0-9a-fA-F]{3,8}/);
if (hexMatch) { color = hexMatch[0]; numericPart = cleaned.replace(hexMatch[0], "").trim(); }
}
const nums = numericPart.match(/-?[\d.]+px/g)?.map(s => parseFloat(s)) ?? [];
if (nums.length >= 2) {
shadows.push({ inset, offsetX: nums[0], offsetY: nums[1], blur: nums[2] ?? 0, spread: nums[3] ?? 0, color });
}
}
return shadows;
}
// ── SVG Writer ──────────────────────────────────────────────────────
/** Options for the SVG writer. */
export type SVGWriterOptions = {
/** Viewport width in pixels. */
width: number;
/** Viewport height in pixels. */
height: number;
/** Downloaded @font-face assets used by extracted text. */
fontAssets?: FontAssetCollection;
/** How downloadable fonts are emitted in the SVG output. */
fontMode?: FontAssetMode;
/** Scale factor applied to width and height. */
zoom?: number;
};
export class SVGWriter implements Writer<string> {
private width: number;
private height: number;
private fontAssets?: FontAssetCollection;
private fontMode: FontAssetMode;
private fontCounter = 0;
private elements: string[] = [];
private defs: string[] = [];
private defIdCounter = 0;
private clipCache = new Map<string, string>(); // clipKey → clip-path id
private imageCache = new Map<string, string>(); // dataUrl → symbol def id
/**
* Font files referenced by the SVG output.
* Maps relative file paths to raw font bytes.
* Only populated when `fontMode` is `{ type: "external" }`.
*/
fontFiles = new Map<string, Uint8Array>();
/**
* @param optionsOrWidth Options object, or viewport width in pixels (positional form).
* @param height Viewport height in pixels (positional form).
* @param zoom Scale factor applied to width and height (positional form).
*/
constructor(optionsOrWidth: SVGWriterOptions | number, height?: number, zoom?: number) {
if (typeof optionsOrWidth === "object") {
const z = optionsOrWidth.zoom ?? 1;
this.width = optionsOrWidth.width * z;
this.height = optionsOrWidth.height * z;
this.fontAssets = optionsOrWidth.fontAssets;
this.fontMode = optionsOrWidth.fontMode ?? { type: "none" };
} else {
const z = zoom ?? 1;
this.width = optionsOrWidth * z;
this.height = (height ?? 0) * z;
this.fontMode = { type: "none" };
}
}
async begin(): Promise<void> {
this.elements = [];
this.defs = [];
this.fontCounter = 0;
this.defIdCounter = 0;
this.clipCache.clear();
this.imageCache.clear();
this.fontFiles.clear();
}
private getFontFilename(source: NonNullable<ReturnType<typeof choosePreferredWebFontSource>>): string {
const idx = ++this.fontCounter;
const fileName = `font${idx}.${source.format}`;
const basePath = this.fontMode.type === "external" ? normalizeFontBasePath(this.fontMode.basePath) : "";
const relativePath = basePath ? `${basePath}/${fileName}` : fileName;
this.fontFiles.set(relativePath, source.data);
return relativePath;
}
private buildFontCss(): string {
if (!this.fontAssets || this.fontAssets.faces.length === 0 || this.fontMode.type === "none") {
return "";
}
const rules: string[] = [];
for (const face of this.fontAssets.faces) {
const source = choosePreferredWebFontSource(face);
if (!source) continue;
const sourceUrl = this.fontMode.type === "inline"
? buildEmbeddedFontDataUrl(source)
: this.getFontFilename(source);
rules.push(buildFontFaceCss(face, sourceUrl, source.format));
}
return rules.join("\n");
}
private getCachedClipId(key: string, buildDef: (id: string) => string): string {
const cached = this.clipCache.get(key);
if (cached) return cached;
const id = `clip${++this.defIdCounter}`;
this.defs.push(buildDef(id));
this.clipCache.set(key, id);
return id;
}
/** Create a clipPath def for clipBounds and return its id, reusing identical clip paths. */
private getRectClipId(style: Style): string | null {
const clip = style.clipBounds;
if (!clip) return null;
const r = clip.radius > 0 ? Math.min(clip.radius, clip.w / 2, clip.h / 2) : 0;
const key = `rect:${n(clip.x)},${n(clip.y)},${n(clip.w)},${n(clip.h)},${n(r)}`;
return this.getCachedClipId(key, (id) => {
if (r > 0) {
return `<clipPath id="${id}" clipPathUnits="userSpaceOnUse"><rect x="${n(clip.x)}" y="${n(clip.y)}" width="${n(clip.w)}" height="${n(clip.h)}" rx="${n(r)}" ry="${n(r)}"/></clipPath>`;
}
return `<clipPath id="${id}" clipPathUnits="userSpaceOnUse"><rect x="${n(clip.x)}" y="${n(clip.y)}" width="${n(clip.w)}" height="${n(clip.h)}"/></clipPath>`;
});
}
private buildClipShapeElement(shape: ClipPathShape): string {
switch (shape.kind) {
case "inset": {
const radiusAttrs = shape.rx > 0 || shape.ry > 0
? ` rx="${n(shape.rx)}" ry="${n(shape.ry)}"`
: "";
return `<rect x="${n(shape.x)}" y="${n(shape.y)}" width="${n(shape.w)}" height="${n(shape.h)}"${radiusAttrs}/>`;
}
case "ellipse":
if (Math.abs(shape.rx - shape.ry) < 0.0001) {
return `<circle cx="${n(shape.cx)}" cy="${n(shape.cy)}" r="${n(shape.rx)}"/>`;
}
return `<ellipse cx="${n(shape.cx)}" cy="${n(shape.cy)}" rx="${n(shape.rx)}" ry="${n(shape.ry)}"/>`;
case "polygon": {
const d = shape.points.map((point, index) => `${index === 0 ? "M" : "L"}${n(point.x)},${n(point.y)}`).join(" ") + " Z";
const clipRule = shape.fillRule === "evenodd" ? ' clip-rule="evenodd"' : "";
return `<path d="${d}"${clipRule}/>`;
}
case "path": {
const clipRule = shape.fillRule === "evenodd" ? ' clip-rule="evenodd"' : "";
return `<path d="${subpathsToPath(shape.subpaths)}"${clipRule}/>`;
}
}
}
private getShapeClipId(style: Style, bounds?: ClipPathBounds): string | null {
if (!bounds) return null;
const shape = parseClipPathShape(style.clipPath, bounds);
if (!shape) return null;
const key = `shape:${style.clipPath}|${n(bounds.x)},${n(bounds.y)},${n(bounds.w)},${n(bounds.h)}`;
return this.getCachedClipId(key, (id) => `<clipPath id="${id}" clipPathUnits="userSpaceOnUse">${this.buildClipShapeElement(shape)}</clipPath>`);
}
private buildClipQuadElement(clipQuad: ClipQuad): string {
if (clipQuad.radius > 0) {
return `<path d="${roundedQuadToPath(clipQuad.points, clipQuad.radius)}"/>`;
}
const path = clipQuad.points.map((point, index) => `${index === 0 ? "M" : "L"}${n(point.x)},${n(point.y)}`).join(" ") + " Z";
return `<path d="${path}"/>`;
}
private getQuadClipIds(style: Style): string[] {
const clipQuads = style.clipQuads;
if (!clipQuads?.length) return [];
return clipQuads.map((clipQuad) => {
const key = `quad:${n(clipQuad.radius)}:${clipQuad.points.map((point) => `${n(point.x)},${n(point.y)}`).join("|")}`;
return this.getCachedClipId(
key,
(id) => `<clipPath id="${id}" clipPathUnits="userSpaceOnUse">${this.buildClipQuadElement(clipQuad)}</clipPath>`,
);
});
}
private getBorderRadiusClipId(points: Quad, style: Style): string | null {
const topEdge = Math.hypot(points[1].x - points[0].x, points[1].y - points[0].y);
const leftEdge = Math.hypot(points[3].x - points[0].x, points[3].y - points[0].y);
const radius = parseBorderRadius(style.borderRadius, topEdge, leftEdge);
if (radius <= 0) return null;
const clipQuad: ClipQuad = {
points,
radius: Math.min(radius, topEdge / 2, leftEdge / 2),
};
const key = `radius:${n(clipQuad.radius)}:${clipQuad.points.map((point) => `${n(point.x)},${n(point.y)}`).join("|")}`;
return this.getCachedClipId(
key,
(id) => `<clipPath id="${id}" clipPathUnits="userSpaceOnUse">${this.buildClipQuadElement(clipQuad)}</clipPath>`,
);
}
private buildOutlineElement(points: Quad, style: Style, outline: RenderedOutline, opacity: number | undefined): string {
const dasharray = getOutlineDasharray(outline);
const attrs = [
` fill="none"`,
` stroke="${escXml(outline.color)}"`,
` stroke-width="${n(outline.width)}"`,
];
if (dasharray) attrs.push(` stroke-dasharray="${dasharray}"`);
if (outline.style === "dotted") attrs.push(` stroke-linecap="round"`);
if (opacity !== undefined) attrs.push(` opacity="${n(opacity)}"`);
if (isAxisAlignedRect(points) && !style.cornerShapes) {
const x = Math.min(points[0].x, points[1].x, points[2].x, points[3].x);
const y = Math.min(points[0].y, points[1].y, points[2].y, points[3].y);
const width = Math.max(points[0].x, points[1].x, points[2].x, points[3].x) - x;
const height = Math.max(points[0].y, points[1].y, points[2].y, points[3].y) - y;
const padding = outline.offset + outline.width / 2;
const radius = parseBorderRadius(style.borderRadius, width, height);
const outlineRadius = Math.min(Math.max(radius + padding, 0), (width + padding * 2) / 2, (height + padding * 2) / 2);
return `<rect x="${n(x - padding)}" y="${n(y - padding)}" width="${n(width + padding * 2)}" height="${n(height + padding * 2)}" rx="${n(outlineRadius)}" ry="${n(outlineRadius)}"${attrs.join("")}/>`;
}
const topEdge = Math.hypot(points[1].x - points[0].x, points[1].y - points[0].y);
const leftEdge = Math.hypot(points[3].x - points[0].x, points[3].y - points[0].y);
const radius = parseBorderRadius(style.borderRadius, topEdge, leftEdge);
const path = radius > 0 && (!isAxisAlignedRect(points) || style.cornerShapes)
? roundedQuadToPath(points, radius, style.cornerShapes)
: `${points.map((point, index) => `${index === 0 ? "M" : "L"}${n(point.x)},${n(point.y)}`).join(" ")} Z`;
return `<path d="${path}"${attrs.join("")}/>`;
}
/** Push an element, wrapping it in clip groups when clipBounds or clip-path are set. */
private pushElement(element: string, style: Style, bounds?: ClipPathBounds, source?: SourceMetadata): void {
let wrapped = injectOpeningTagAttributes(element, buildSourceDataAttributes(source));
const effectStyle = getSvgEffectStyle(style);
if (effectStyle) {
wrapped = `<g style="${escXml(effectStyle)}">${wrapped}</g>`;
}
for (const quadClipId of this.getQuadClipIds(style)) {
wrapped = `<g clip-path="url(#${quadClipId})">${wrapped}</g>`;
}
const shapeClipId = this.getShapeClipId(style, bounds);
if (shapeClipId) {
wrapped = `<g clip-path="url(#${shapeClipId})">${wrapped}</g>`;
}
const rectClipId = this.getRectClipId(style);
if (rectClipId) {
wrapped = `<g clip-path="url(#${rectClipId})">${wrapped}</g>`;
}
this.elements.push(wrapped);
}
/** Check if borders have different colors/widths/styles per side (skip if borderRadius). */
private hasMixedBorders(style: Style): boolean {
if (style.borderRadius && style.borderRadius !== "0px" && style.borderRadius !== "0%") return false;
const sides = [
{ c: style.borderTopColor, w: style.borderTopWidth, s: style.borderTopStyle },
{ c: style.borderRightColor, w: style.borderRightWidth, s: style.borderRightStyle },
{ c: style.borderBottomColor, w: style.borderBottomWidth, s: style.borderBottomStyle },
{ c: style.borderLeftColor, w: style.borderLeftWidth, s: style.borderLeftStyle },
];
if (!sides[0].s) return false;
if (sides.some(s => s.s === "double")) return true;
const ref = sides[0];
return sides.some(s => s.c !== ref.c || s.w !== ref.w || s.s !== ref.s);
}
/** Draw each border side independently as an SVG line. */
private drawPerSideBorders(points: Quad, style: Style): void {
const sides: Array<{
from: Point; to: Point;
color?: string; width?: string; borderStyle?: string;
}> = [
{ from: points[0], to: points[1], color: style.borderTopColor, width: style.borderTopWidth, borderStyle: style.borderTopStyle },
{ from: points[1], to: points[2], color: style.borderRightColor, width: style.borderRightWidth, borderStyle: style.borderRightStyle },
{ from: points[2], to: points[3], color: style.borderBottomColor, width: style.borderBottomWidth, borderStyle: style.borderBottomStyle },
{ from: points[3], to: points[0], color: style.borderLeftColor, width: style.borderLeftWidth, borderStyle: style.borderLeftStyle },
];
for (const side of sides) {
const color = getVisibleCssColorString(side.color);
const w = side.width ? parseFloat(side.width) : 0;
if (!color || w <= 0 || !side.borderStyle || side.borderStyle === "none" || side.borderStyle === "hidden") continue;
const x1 = n(side.from.x), y1 = n(side.from.y);
const x2 = n(side.to.x), y2 = n(side.to.y);
if (side.borderStyle === "double" && w >= 3) {
const lineW = Math.max(1, w / 3);
const dx = side.to.x - side.from.x;
const dy = side.to.y - side.from.y;
const len = Math.sqrt(dx * dx + dy * dy);
if (len <= 0) continue;
const nx = -dy / len;
const ny = dx / len;
const off = w / 3;
// Outer line
this.elements.push(`<line x1="${n(side.from.x - nx * off)}" y1="${n(side.from.y - ny * off)}" x2="${n(side.to.x - nx * off)}" y2="${n(side.to.y - ny * off)}" stroke="${escXml(color)}" stroke-width="${n(lineW)}"/>`);
// Inner line
this.elements.push(`<line x1="${n(side.from.x + nx * off)}" y1="${n(side.from.y + ny * off)}" x2="${n(side.to.x + nx * off)}" y2="${n(side.to.y + ny * off)}" stroke="${escXml(color)}" stroke-width="${n(lineW)}"/>`);
} else {
const attrs: string[] = [
`x1="${x1}"`, `y1="${y1}"`, `x2="${x2}"`, `y2="${y2}"`,
`stroke="${escXml(color)}"`, `stroke-width="${n(w)}"`,
];
if (side.borderStyle === "dashed") {
attrs.push(`stroke-dasharray="${n(w * 3)} ${n(w * 3)}"`);
} else if (side.borderStyle === "dotted") {
attrs.push(`stroke-dasharray="${n(w)} ${n(w)}"`, `stroke-linecap="round"`);
}
this.elements.push(`<line ${attrs.join(" ")}/>`);
}
}
}
async drawPolygon(points: Quad, style: Style, source?: SourceMetadata): Promise<void> {
const fill = getVisibleCssColorString(style.fill);
const stroke = getVisibleStroke(style, getVisibleCssColorString);
const outline = getVisibleOutline(style);
const mixedBorders = this.hasMixedBorders(style);
if (!fill && !stroke && !outline && !style.boxShadow && !mixedBorders) return;
const w = Math.abs(points[1].x - points[0].x);
const h = Math.abs(points[3].y - points[0].y);
const radius = parseBorderRadius(style.borderRadius, w, h);
// Outer box shadows (drop shadows via SVG filter)
const shadows = parseBoxShadow(style.boxShadow);
const outerShadows = shadows.filter(s => !s.inset);
let filterId: string | undefined;
if (outerShadows.length > 0) {
filterId = this.addDropShadowFilter(outerShadows);
}
const opacity = (style.opacity !== undefined && style.opacity < 1) ? style.opacity : undefined;
if (isAxisAlignedRect(points) && !style.cornerShapes) {
const x = Math.min(points[0].x, points[1].x, points[2].x, points[3].x);
const y = Math.min(points[0].y, points[1].y, points[2].y, points[3].y);
const r = radius > 0 ? Math.min(radius, w / 2, h / 2) : 0;
const gradientIds = this.addGradientDefs(style.backgroundImage, x, y, w, h);
const strokeGradientId = this.addGradientDef(style.strokeImage, x, y, w, h);
const baseElement = this.buildLayeredShape(
(attrs) => `<rect x="${n(x)}" y="${n(y)}" width="${n(w)}" height="${n(h)}" rx="${n(r)}" ry="${n(r)}"${attrs}/>` ,
fill,
mixedBorders ? null : stroke,
style,
gradientIds,
strokeGradientId,
undefined,
undefined,
);
const layers = [baseElement];
if (outline) {
layers.push(this.buildOutlineElement(points, style, outline, undefined));
}
const groupAttrs: string[] = [];
if (filterId) groupAttrs.push(`filter="url(#${filterId})"`);
if (opacity !== undefined) groupAttrs.push(`opacity="${n(opacity)}"`);
const element = layers.length === 1 && groupAttrs.length === 0
? layers[0]
: `<g${groupAttrs.length > 0 ? ` ${groupAttrs.join(" ")}` : ""}>${layers.join("")}</g>`;
this.pushElement(element, style, getQuadBounds(points), source);
if (mixedBorders) this.drawPerSideBorders(points, style);
// Inset shadows as clipped overlays
this.addInsetShadows(shadows.filter(s => s.inset), x, y, w, h, r);
return;
}
const d = points.map((p, i) => `${i === 0 ? "M" : "L"}${n(p.x)},${n(p.y)}`).join(" ") + " Z";
const x = Math.min(...points.map(p => p.x));
const y = Math.min(...points.map(p => p.y));
// For non-axis-aligned quads with border-radius, use rounded path
const edgeW = Math.sqrt((points[1].x - points[0].x) ** 2 + (points[1].y - points[0].y) ** 2);
const edgeH = Math.sqrt((points[3].x - points[0].x) ** 2 + (points[3].y - points[0].y) ** 2);
const nonAlignedRadius = parseBorderRadius(style.borderRadius, edgeW, edgeH);
let pathD: string;
if (nonAlignedRadius > 0 && (!isAxisAlignedRect(points) || style.cornerShapes)) {
const segs = roundedQuadPath(points, nonAlignedRadius, style.cornerShapes);
pathD = roundedQuadToPath(points, nonAlignedRadius, style.cornerShapes);
} else {
pathD = d;
}
const gradientIds = this.addGradientDefs(style.backgroundImage, x, y, w || 1, h || 1);
const strokeGradientId = this.addGradientDef(style.strokeImage, x, y, w || 1, h || 1);
const baseElement = this.buildLayeredShape(
(attrs) => `<path d="${pathD}"${attrs}/>` ,
fill,
mixedBorders ? null : stroke,
style,
gradientIds,
strokeGradientId,
undefined,
undefined,
);
const layers = [baseElement];
if (outline) {
layers.push(this.buildOutlineElement(points, style, outline, undefined));
}
const groupAttrs: string[] = [];
if (filterId) groupAttrs.push(`filter="url(#${filterId})"`);
if (opacity !== undefined) groupAttrs.push(`opacity="${n(opacity)}"`);
const element = layers.length === 1 && groupAttrs.length === 0
? layers[0]
: `<g${groupAttrs.length > 0 ? ` ${groupAttrs.join(" ")}` : ""}>${layers.join("")}</g>`;
this.pushElement(element, style, getQuadBounds(points), source);
if (mixedBorders) this.drawPerSideBorders(points, style);
if (isAxisAlignedRect(points)) {
this.addInsetShadows(shadows.filter(s => s.inset), x, y, w, h, 0);
}
}
async drawPolyline(points: Point[], closed: boolean, style: Style, source?: SourceMetadata): Promise<void> {
if (points.length < 2) return;
const fill = getVisibleCssColorString(style.fill);
const stroke = getVisibleStroke(style, getVisibleCssColorString);
if (!fill && !stroke) return;
const opacity = (style.opacity !== undefined && style.opacity < 1) ? style.opacity : undefined;
// Compute bounding box for gradient
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
for (const p of points) {
if (p.x < minX) minX = p.x;
if (p.y < minY) minY = p.y;
if (p.x > maxX) maxX = p.x;
if (p.y > maxY) maxY = p.y;
}
const d = style.pathSubpaths?.length ? subpathsToPath(style.pathSubpaths) : pointsToPath(points, closed);
const gradientIds = this.addGradientDefs(style.backgroundImage, minX, minY, maxX - minX || 1, maxY - minY || 1);
const strokeGradientId = this.addGradientDef(style.strokeImage, minX, minY, maxX - minX || 1, maxY - minY || 1);
const canFillPath = closed || !!style.pathSubpaths?.length;
const element = this.buildLayeredShape(
(attrs) => `<path d="${d}"${style.fillRule === "evenodd" ? ' fill-rule="evenodd"' : ""}${attrs}/>` ,
canFillPath ? fill : null,
stroke,
style,
gradientIds,
strokeGradientId,
undefined,
opacity,
);
this.pushElement(element, style, getPointBounds(points), source);
}
async drawText(quad: Quad, text: string, style: Style, source?: SourceMetadata): Promise<void> {
const preserveWhitespace = preservesWhitespace(style);
const sanitized = normalizeWhitespaceAwareText(text, style);
if (sanitized.length === 0) return;
const opacity = (style.opacity !== undefined && style.opacity < 1) ? style.opacity : undefined;
const transform = getQuadTransform(quad);
if (!transform) return;
const transformed = !isAxisAlignedRect(quad);
const usesVerticalWriting = !!style.writingMode && style.writingMode !== "horizontal-tb";
// Compute font metrics
const quadHeight = Math.sqrt((quad[3].x - quad[0].x) ** 2 + (quad[3].y - quad[0].y) ** 2);
const styleFontSize = style.fontSize ? parseFloat(style.fontSize) : 12;
const fontSize = quadHeight > 0 ? Math.min(styleFontSize, quadHeight) : styleFontSize;
const fontWeight = style.fontWeight ?? "normal";
const fontStyle = style.fontStyle ?? "normal";
const fontFamily = normalizeFontFamily(style.fontFamily, "sans-serif");
const textColor = getVisibleCssColorString(style.color) ?? getVisibleCssColorString(style.fill) ?? "#000000";
const halfLeading = Math.max(0, (quadHeight - fontSize) / 2);
const x = transformed ? 0 : quad[0].x;
const y = transformed
? (usesVerticalWriting ? 0 : halfLeading)
: quad[0].y + (quadHeight > 0 ? (quad[3].y - quad[0].y) * (halfLeading / quadHeight) : 0);
const attrs: string[] = [];
attrs.push(`x="${n(x)}" y="${n(y)}"`);
attrs.push(`fill="${escXml(textColor)}"`);
attrs.push(`dominant-baseline="text-before-edge"`);
const fontParts: string[] = [];
if (fontStyle !== "normal") fontParts.push(`font-style="${fontStyle}"`);
if (fontWeight !== "normal" && fontWeight !== "400") fontParts.push(`font-weight="${fontWeight}"`);
fontParts.push(`font-size="${n(fontSize)}px"`);
fontParts.push(`font-family="${escXml(fontFamily)}"`);
attrs.push(...fontParts);
if (style.letterSpacing && style.letterSpacing !== "normal") {
attrs.push(`letter-spacing="${escXml(style.letterSpacing)}"`);
}
if (style.wordSpacing && style.wordSpacing !== "normal" && style.wordSpacing !== "0px") {
attrs.push(`word-spacing="${escXml(style.wordSpacing)}"`);
}
if (transformed) {
attrs.push(`transform="matrix(${n(transform.a)},${n(transform.b)},${n(transform.c)},${n(transform.d)},${n(transform.e)},${n(transform.f)})"`);
}
if (opacity !== undefined) {
attrs.push(`opacity="${n(opacity)}"`);
}
if (preserveWhitespace) {
attrs.push(`xml:space="preserve"`);
}
if (style.direction && style.direction !== "ltr") {
attrs.push(`direction="${escXml(style.direction)}"`);
attrs.push(`unicode-bidi="embed"`);
}
if (style.writingMode && style.writingMode !== "horizontal-tb") {
attrs.push(`writing-mode="${escXml(style.writingMode)}"`);
}
// Text shadow
let shadowFilterId: string | undefined;
if (style.textShadow && style.textShadow !== "none") {
shadowFilterId = this.addTextShadowFilter(style.textShadow);
if (shadowFilterId) attrs.push(`filter="url(#${shadowFilterId})"`);
}
// Text decoration
let decoration: string | undefined;
if (style.textDecoration) {
if (style.textDecoration.includes("underline")) decoration = "underline";
else if (style.textDecoration.includes("line-through")) decoration = "line-through";
else if (style.textDecoration.includes("overline")) decoration = "overline";
if (decoration) attrs.push(`text-decoration="${decoration}"`);
}
// Justified text: use textLength to stretch text to match the original quad width
if (style.textAlign === "justify") {
const quadWidth = transform.width;
if (quadWidth > 0) {
attrs.push(`textLength="${n(quadWidth)}" lengthAdjust="spacing"`);
}
}
this.pushElement(`<text ${attrs.join(" ")}>${escXml(sanitized)}</text>`, style, getQuadBounds(quad), source);
}
async drawImage(quad: Quad, dataUrl: string, width: number, height: number, style: Style, _rgbData?: number[], source?: SourceMetadata): Promise<void> {
const dx = quad[1].x - quad[0].x;
const dy = quad[1].y - quad[0].y;
const topEdge = Math.sqrt(dx * dx + dy * dy);
const ldx = quad[3].x - quad[0].x;
const ldy = quad[3].y - quad[0].y;
const leftEdge = Math.sqrt(ldx * ldx + ldy * ldy);
if (topEdge <= 0 || leftEdge <= 0) return;
const angle = Math.atan2(dy, dx);
const angleDeg = angle * (180 / Math.PI);
const opacity = (style.opacity !== undefined && style.opacity < 1) ? style.opacity : undefined;
// Check if this image data has been seen before (dedup via <symbol> + <use>)
let symbolId = this.imageCache.get(dataUrl);
if (!symbolId) {
symbolId = this.nextId("imgSym");
this.imageCache.set(dataUrl, symbolId);
this.defs.push(`<symbol id="${symbolId}" viewBox="0 0 1 1" preserveAspectRatio="none"><image href="${escXml(dataUrl)}" width="1" height="1" preserveAspectRatio="none"/></symbol>`);
}
const attrs: string[] = [];
if (Math.abs(angleDeg) > 0.5) {
attrs.push(`transform="translate(${n(quad[0].x)},${n(quad[0].y)}) rotate(${n(angleDeg)})"`);
attrs.push(`x="0" y="0"`);
} else {
attrs.push(`x="${n(quad[0].x)}" y="${n(quad[0].y)}"`);
}
attrs.push(`width="${n(topEdge)}" height="${n(leftEdge)}"`);
if (opacity !== undefined) attrs.push(`opacity="${n(opacity)}"`);
const ir = style.imageRendering;
if (ir === "pixelated" || ir === "crisp-edges" || ir === "-moz-crisp-edges") {
attrs.push(`image-rendering="pixelated"`);
}
let imageElement = `<use href="#${symbolId}" ${attrs.join(" ")}/>`;
const borderRadiusClipId = this.getBorderRadiusClipId(quad, style);
if (borderRadiusClipId) {
imageElement = `<g clip-path="url(#${borderRadiusClipId})">${imageElement}</g>`;
}
const outline = getVisibleOutline(style);
const layers = [imageElement];
if (outline) {
layers.push(this.buildOutlineElement(quad, style, outline, undefined));
}
const element = layers.length === 1 && opacity === undefined
? layers[0]
: `<g${opacity !== undefined ? ` opacity="${n(opacity)}"` : ""}>${layers.join("")}</g>`;
this.pushElement(element, style, getQuadBounds(quad), source);
}
async end(): Promise<string> {
const fontCss = this.buildFontCss();
const styleBlock = fontCss ? `<style>${escXml(fontCss)}</style>\n` : "";
const defsBlock = this.defs.length > 0 ? `<defs>\n${this.defs.join("\n")}\n</defs>\n` : "";
return `<?xml version="1.0" encoding="UTF-8"?>\n<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${n(this.width)}" height="${n(this.height)}" viewBox="0 0 ${n(this.width)} ${n(this.height)}">\n${styleBlock}${defsBlock}${this.elements.join("\n")}\n</svg>`;
}
// ── Private helpers ─────────────────────────────────────────────
private nextId(prefix: string): string {
return `${prefix}${++this.defIdCounter}`;
}
private buildShapeAttrs(
fill: string | null,
stroke: { color: string; width: number } | null,
style: Style,
gradId: string | undefined,
filterId: string | undefined,
opacity: number | undefined,
): string {
const parts: string[] = [];
if (gradId) {
parts.push(` fill="url(#${gradId})"`);
} else if (fill) {
parts.push(` fill="${escXml(fill)}"`);
} else {
parts.push(` fill="none"`);
}
if (stroke) {
parts.push(` stroke="${escXml(stroke.color)}" stroke-width="${n(stroke.width)}"`);
}
if (style.strokeDasharray && style.strokeDasharray !== "none") {
parts.push(` stroke-dasharray="${escXml(style.strokeDasharray)}"`);
}
if (filterId) parts.push(` filter="url(#${filterId})"`);
if (opacity !== undefined) parts.push(` opacity="${n(opacity)}"`);
return parts.join("");
}
private buildPolylineAttrs(
fill: string | null,
stroke: { color: string; width: number } | null,
style: Style,
gradId: string | undefined,
opacity: number | undefined,
closed: boolean,
): string {
const parts: string[] = [];
if (fill && closed) {
if (gradId) {
parts.push(` fill="url(#${gradId})"`);
} else {
parts.push(` fill="${escXml(fill)}"`);
}
} else if (fill && !closed) {
// SVG fills open paths from first to last point
if (gradId) {
parts.push(` fill="url(#${gradId})"`);
} else {
parts.push(` fill="${escXml(fill)}"`);
}
} else {
parts.push(` fill="none"`);
}
if (stroke) {
parts.push(` stroke="${escXml(stroke.color)}" stroke-width="${n(stroke.width)}"`);
} else if (!fill) {
// Neither fill nor stroke visible — shouldn't reach here, but safety
parts.push(` stroke="none"`);
}
if (style.strokeDasharray && style.strokeDasharray !== "none") {
parts.push(` stroke-dasharray="${escXml(style.strokeDasharray)}"`);
}
if (opacity !== undefined) parts.push(` opacity="${n(opacity)}"`);
return parts.join("");
}
private addGradientDefs(
backgroundImage: string | undefined,
x: number,
y: number,
w: number,
h: number,