@ggraphic/editor 0.1.0-alpha.5 → 0.1.0-alpha.6

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 (125) hide show
  1. package/dist/CanvasEditorProvider.d.ts +6 -1
  2. package/dist/components/CanvasEditor/CanvasEditorShell.js +139 -36
  3. package/dist/components/CanvasEditor/editorShell.d.ts +6 -0
  4. package/dist/components/CanvasEditor/types.d.ts +28 -0
  5. package/dist/components/GenericCanvas.d.ts +19 -2
  6. package/dist/components/GenericCanvas.js +28 -3
  7. package/dist/components/PagePreview.d.ts +8 -1
  8. package/dist/components/PagePreview.js +4 -1
  9. package/dist/components/TopBar/DownloadSection.d.ts +24 -3
  10. package/dist/components/TopBar/DownloadSection.js +45 -7
  11. package/dist/components/TopBar/ShareDropdown.d.ts +4 -2
  12. package/dist/components/TopBar/ShareDropdown.js +2 -2
  13. package/dist/entries/export.d.ts +14 -1
  14. package/dist/entries/export.js +14 -1
  15. package/dist/entries/services.d.ts +1 -1
  16. package/dist/export/fonts/fontFiles.d.ts +100 -0
  17. package/dist/export/fonts/fontFiles.js +333 -0
  18. package/dist/export/fonts/glyphs.d.ts +113 -0
  19. package/dist/export/fonts/glyphs.js +120 -0
  20. package/dist/export/fonts/variation.d.ts +23 -0
  21. package/dist/export/fonts/variation.js +43 -0
  22. package/dist/export/pdf/pdfContent.d.ts +108 -0
  23. package/dist/export/pdf/pdfContent.js +566 -0
  24. package/dist/export/pdf/pdfFontkit.d.ts +54 -0
  25. package/dist/export/pdf/pdfFontkit.js +159 -0
  26. package/dist/export/pdf/pdfGeometry.d.ts +54 -0
  27. package/dist/export/pdf/pdfGeometry.js +228 -0
  28. package/dist/export/pdf/pdfResources.d.ts +109 -0
  29. package/dist/export/pdf/pdfResources.js +314 -0
  30. package/dist/export/pdf/writePdf.d.ts +34 -0
  31. package/dist/export/pdf/writePdf.js +165 -0
  32. package/dist/export/pptx/exportPptxDeck.d.ts +10 -2
  33. package/dist/export/pptx/exportPptxDeck.js +5 -2
  34. package/dist/export/pptx/svgPicture.d.ts +19 -0
  35. package/dist/export/pptx/svgPicture.js +64 -0
  36. package/dist/export/pptx/vectorizeElement.d.ts +9 -0
  37. package/dist/export/pptx/vectorizeElement.js +118 -0
  38. package/dist/export/pptx/writePptx.d.ts +13 -0
  39. package/dist/export/pptx/writePptx.js +17 -0
  40. package/dist/export/printPdf.d.ts +1 -0
  41. package/dist/export/printPdf.js +1 -1
  42. package/dist/export/scene/browserDeps.d.ts +32 -0
  43. package/dist/export/scene/browserDeps.js +174 -0
  44. package/dist/export/scene/imageBytes.d.ts +79 -0
  45. package/dist/export/scene/imageBytes.js +330 -0
  46. package/dist/export/scene/itemBounds.d.ts +9 -0
  47. package/dist/export/scene/itemBounds.js +40 -0
  48. package/dist/export/scene/matrix.d.ts +13 -0
  49. package/dist/export/scene/matrix.js +32 -0
  50. package/dist/export/scene/rasterLimit.d.ts +13 -0
  51. package/dist/export/scene/rasterLimit.js +24 -0
  52. package/dist/export/scene/rebaseOps.d.ts +8 -0
  53. package/dist/export/scene/rebaseOps.js +51 -0
  54. package/dist/export/scene/recordPageScene.d.ts +28 -0
  55. package/dist/export/scene/recordPageScene.js +224 -0
  56. package/dist/export/scene/recordingCanvas.d.ts +55 -0
  57. package/dist/export/scene/recordingCanvas.js +71 -0
  58. package/dist/export/scene/recordingContext.d.ts +162 -0
  59. package/dist/export/scene/recordingContext.js +1031 -0
  60. package/dist/export/scene/replayScene.d.ts +31 -0
  61. package/dist/export/scene/replayScene.js +213 -0
  62. package/dist/export/scene/resolveScene.d.ts +48 -0
  63. package/dist/export/scene/resolveScene.js +236 -0
  64. package/dist/export/scene/trustedSvgImages.d.ts +3 -0
  65. package/dist/export/scene/trustedSvgImages.js +21 -0
  66. package/dist/export/scene/types.d.ts +241 -0
  67. package/dist/export/scene/types.js +38 -0
  68. package/dist/export/slidesPdf.d.ts +10 -2
  69. package/dist/export/slidesPdf.js +8 -4
  70. package/dist/export/svg/__fixtures__/barChart.svg +1 -0
  71. package/dist/export/svg/__golden__/fixture-editable.svg +87 -0
  72. package/dist/export/svg/__golden__/fixture-outlines.svg +88 -0
  73. package/dist/export/svg/inlineSvg.d.ts +10 -0
  74. package/dist/export/svg/inlineSvg.js +119 -0
  75. package/dist/export/svg/scopeCss.d.ts +45 -0
  76. package/dist/export/svg/scopeCss.js +214 -0
  77. package/dist/export/svg/svgColor.d.ts +8 -0
  78. package/dist/export/svg/svgColor.js +46 -0
  79. package/dist/export/svg/svgImageScene.d.ts +41 -0
  80. package/dist/export/svg/svgImageScene.js +128 -0
  81. package/dist/export/svg/svgPathData.d.ts +31 -0
  82. package/dist/export/svg/svgPathData.js +466 -0
  83. package/dist/export/svg/svgToScene.d.ts +19 -0
  84. package/dist/export/svg/svgToScene.js +1183 -0
  85. package/dist/export/svg/writeSvg.d.ts +33 -0
  86. package/dist/export/svg/writeSvg.js +594 -0
  87. package/dist/export/svg/xml.d.ts +23 -0
  88. package/dist/export/svg/xml.js +49 -0
  89. package/dist/export/vectorDeps.d.ts +27 -0
  90. package/dist/export/vectorDeps.js +37 -0
  91. package/dist/export/vectorExport.d.ts +85 -0
  92. package/dist/export/vectorExport.js +287 -0
  93. package/dist/hostServices.d.ts +15 -0
  94. package/dist/i18n/de.d.ts +26 -9
  95. package/dist/i18n/de.js +26 -10
  96. package/dist/i18n/en.js +24 -0
  97. package/dist/primitives/AssetPrimitive.js +7 -2
  98. package/dist/primitives/CanvasIcons.js +6 -0
  99. package/dist/primitives/CanvasStage.js +2 -2
  100. package/dist/primitives/ChartPrimitive.d.ts +11 -1
  101. package/dist/primitives/ChartPrimitive.js +73 -19
  102. package/dist/primitives/IconPrimitive.js +3 -0
  103. package/dist/primitives/IllustrationPrimitive.js +14 -1
  104. package/dist/primitives/chartFont.d.ts +30 -0
  105. package/dist/primitives/chartFont.js +127 -0
  106. package/dist/sidebar/sections/ImageAdjustSection.js +5 -4
  107. package/dist/sidebar/sections/assets/ElementsPanel.js +4 -2
  108. package/dist/sidebar/sections/assets/assetAudience.d.ts +12 -0
  109. package/dist/sidebar/sections/assets/assetAudience.js +18 -0
  110. package/dist/sidebar/sections/assets/useElementCatalog.js +3 -2
  111. package/dist/styles/compiled.css +1 -1
  112. package/dist/utils/canvasAssets.d.ts +11 -1
  113. package/dist/utils/canvasAssets.js +8 -0
  114. package/dist/utils/canvasIcons.js +5 -3
  115. package/dist/utils/captureStage.d.ts +19 -0
  116. package/dist/utils/captureStage.js +14 -1
  117. package/dist/utils/externalIcons.d.ts +7 -0
  118. package/dist/utils/externalIcons.js +70 -3
  119. package/dist/utils/illustrations/svgCache.js +6 -1
  120. package/dist/utils/imageFilters.d.ts +13 -0
  121. package/dist/utils/imageFilters.js +11 -0
  122. package/dist/utils/zipPageImages.d.ts +8 -0
  123. package/dist/utils/zipPageImages.js +16 -4
  124. package/package.json +6 -2
  125. package/skills/ggraphic-embed/SKILL.md +33 -1
@@ -0,0 +1,1183 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ /**
3
+ * Converts the markup of an SVG image into scene ops (`../scene/types.ts`): the same path, text
4
+ * and group ops the recorder makes from a canvas, with absolute matrices, paints and clips. A
5
+ * writer that cannot embed SVG (the PDF writer) draws icons, illustrations and charts with them.
6
+ *
7
+ * What it reads: shapes, `g`/`a`/`use`/`symbol`/nested `svg`, `transform`, `viewBox` and
8
+ * `preserveAspectRatio`, presentation attributes, `style` and `<style>` rules (selectors are
9
+ * matched by the DOM), inheritance, solid colours, linear and radial gradients, `clipPath` in
10
+ * user space, and text with `tspan`, per-glyph positions and `text-anchor`.
11
+ *
12
+ * What it does not read is NOT dropped quietly. Every construct it skips or cannot reproduce adds
13
+ * a name to `unsupported` (an element, a property or a feature), once; the caller rasters the
14
+ * image when the list is not empty. The ops it returns are best effort in that case.
15
+ *
16
+ * Conventions of the result:
17
+ * - `box.matrix` maps the box (`0..width` by `0..height`) to the page; the SVG viewport is fitted
18
+ * into the box by `viewBox` and `preserveAspectRatio`. The box is the image at its natural size
19
+ * (what a canvas draws before it crops and stretches, as `writeSvg` does for its nested `<svg>`);
20
+ * a stretch to the destination rect is part of `box.matrix`, a crop is a clip on the caller's
21
+ * side. Every op carries its full matrix, and its commands are in the user space of that matrix,
22
+ * as the recorder leaves them.
23
+ * - `opacity` on one op is its `alpha`; on several it is a `group` with identity matrix, whose
24
+ * ops keep their own matrices and clips, as in a replayed page.
25
+ * - A radial gradient in a box that is not square is an ellipse. The IR has circles only, so such
26
+ * a fill is emitted in the space of the gradient (matrix and commands both adjusted).
27
+ * - Text is one op per run of equal style and baseline, with one x per code point. Glyph advances
28
+ * come from `defaults.measure`; without it a glyph is 0.6 em wide. The PDF writer lays text out
29
+ * again from the font file, the advances here only place the run (`text-anchor`, `tspan` flow).
30
+ */
31
+ import { IDENTITY, apply, invert, multiply } from '../scene/matrix.js';
32
+ import { fontFamilies } from '../scene/recordingContext.js';
33
+ import { parseSvgColor } from './svgColor.js';
34
+ import { commandBounds, ellipseCommands, parseNumberList, parsePathData, parseTransform, pointsCommands, rectCommands, transformCommands, } from './svgPathData.js';
35
+ export function svgToScene(markup, box, defaults) {
36
+ return new Converter(box, defaults).run(markup);
37
+ }
38
+ // ---------------------------------------------------------------------------------------------
39
+ // Vocabulary
40
+ const SVG_NS = 'http://www.w3.org/2000/svg';
41
+ const SHAPES = new Set(['path', 'rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon']);
42
+ /** Elements that draw, or hold what draws. */
43
+ const DRAWN = new Set([...SHAPES, 'svg', 'g', 'a', 'use', 'text']);
44
+ /** Everything else this converter knows. Any other element is unsupported wherever it stands. */
45
+ const KNOWN = new Set([
46
+ ...DRAWN,
47
+ ...['defs', 'symbol', 'clipPath', 'linearGradient', 'radialGradient', 'stop', 'tspan'],
48
+ ...['style', 'title', 'desc', 'metadata'],
49
+ ]);
50
+ /** Properties that inherit; kept as specified and read where they are used. */
51
+ const INHERITED = [
52
+ ...['fill', 'fill-opacity', 'fill-rule', 'stroke', 'stroke-opacity', 'stroke-width'],
53
+ ...['stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-dasharray'],
54
+ ...['stroke-dashoffset', 'paint-order', 'clip-rule', 'visibility', 'color'],
55
+ ...['font-family', 'font-style', 'text-anchor', 'dominant-baseline', 'text-decoration'],
56
+ ...['letter-spacing', 'word-spacing', 'writing-mode', 'white-space'],
57
+ ...['marker-start', 'marker-mid', 'marker-end'],
58
+ ];
59
+ /** Every presentation attribute that is read; the inherited ones, font size and weight, and: */
60
+ const PRESENTATION = [
61
+ ...INHERITED,
62
+ ...['font-size', 'font-weight', 'opacity', 'display', 'clip-path', 'overflow'],
63
+ ...['stop-color', 'stop-opacity', 'filter', 'mask', 'vector-effect', 'mix-blend-mode'],
64
+ ];
65
+ /** CSS properties that are not read at all (a shorthand, a different transform syntax). */
66
+ const CSS_NOT_READ = new Set(['font', 'transform']);
67
+ const GENERIC_FAMILIES = new Set([
68
+ ...['serif', 'sans-serif', 'monospace', 'cursive', 'fantasy', 'system-ui', 'math', 'emoji'],
69
+ ...['ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded', 'fangsong'],
70
+ ...['-apple-system', 'blinkmacsystemfont'],
71
+ ]);
72
+ /**
73
+ * Where `dominant-baseline` puts the alphabetic baseline below `y`, in em. Approximations: the
74
+ * metrics of the font are not at hand here, and the PDF writer re-lays text from the file.
75
+ */
76
+ const BASELINE_SHIFT = {
77
+ auto: 0,
78
+ alphabetic: 0,
79
+ 'use-script': 0,
80
+ 'no-change': 0,
81
+ 'reset-size': 0,
82
+ central: 0.35,
83
+ middle: 0.3,
84
+ hanging: 0.8,
85
+ 'text-before-edge': 0.9,
86
+ 'text-top': 0.9,
87
+ };
88
+ /** More elements than this are a bomb (`use` chains that double), not a drawing. */
89
+ const MAX_ELEMENTS = 20_000;
90
+ const GLYPH_WIDTH_EM = 0.6;
91
+ // ---------------------------------------------------------------------------------------------
92
+ // Small parsers
93
+ const LENGTH = /^([+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?)(px|pt|pc|mm|cm|in|em|ex|rem|%)?$/;
94
+ const FRACTION = /^\s*([+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?)(%?)\s*$/;
95
+ /** `0.5` and `50%` are both 0.5; `null` for anything else. */
96
+ function fraction(value) {
97
+ if (value == null)
98
+ return null;
99
+ const match = FRACTION.exec(value);
100
+ if (!match)
101
+ return null;
102
+ const n = Number(match[1]);
103
+ return Number.isFinite(n) ? (match[2] ? n / 100 : n) : null;
104
+ }
105
+ const clamp01 = (n) => Math.min(1, Math.max(0, n));
106
+ const unitNumber = (value, fallback) => clamp01(fraction(value) ?? fallback);
107
+ /** `-0` becomes `0`: the same matrix must compare equal however it was composed. */
108
+ const tidy = (m) => [m[0] + 0, m[1] + 0, m[2] + 0, m[3] + 0, m[4] + 0, m[5] + 0];
109
+ const translation = (x, y) => [1, 0, 0, 1, x, y];
110
+ /** The id in `url(#id)`; `null` for `none`, an external reference or anything else. */
111
+ function referencedId(value) {
112
+ return value ? (/^url\(\s*(['"]?)#([^'")\s]+)\1\s*\)/.exec(value.trim())?.[2] ?? null) : null;
113
+ }
114
+ /** Splits at `separator` outside parentheses and quotes. */
115
+ function splitTop(text, separator) {
116
+ const parts = [];
117
+ let depth = 0;
118
+ let quote = '';
119
+ let from = 0;
120
+ for (let i = 0; i < text.length; i++) {
121
+ const c = text[i];
122
+ if (quote) {
123
+ if (c === quote)
124
+ quote = '';
125
+ }
126
+ else if (c === '"' || c === "'")
127
+ quote = c;
128
+ else if (c === '(')
129
+ depth++;
130
+ else if (c === ')')
131
+ depth = Math.max(0, depth - 1);
132
+ else if (c === separator && depth === 0) {
133
+ parts.push(text.slice(from, i));
134
+ from = i + 1;
135
+ }
136
+ }
137
+ parts.push(text.slice(from));
138
+ return parts;
139
+ }
140
+ function parseDeclarations(text) {
141
+ const out = [];
142
+ for (const part of splitTop(text, ';')) {
143
+ const colon = part.indexOf(':');
144
+ if (colon < 0)
145
+ continue;
146
+ const name = part.slice(0, colon).trim().toLowerCase();
147
+ const value = part
148
+ .slice(colon + 1)
149
+ .replace(/!\s*important\s*$/i, '')
150
+ .trim();
151
+ if (name && value)
152
+ out.push([name, value]);
153
+ }
154
+ return out;
155
+ }
156
+ function specificity(selector) {
157
+ const flat = selector.replace(/\[[^\]]*\]/g, '[]');
158
+ const ids = flat.match(/#[\w-]+/g)?.length ?? 0;
159
+ const classes = flat.match(/\.[\w-]+|\[\]|:(?!:)[\w-]+/g)?.length ?? 0;
160
+ const types = flat.match(/(?:^|[\s>+~(])[a-zA-Z][\w-]*/g)?.length ?? 0;
161
+ return ids * 10_000 + classes * 100 + types;
162
+ }
163
+ /** The index of the `}` that closes the `{` at `open`, or the end of the text. */
164
+ function closingBrace(text, open) {
165
+ let depth = 0;
166
+ for (let i = open; i < text.length; i++) {
167
+ if (text[i] === '{')
168
+ depth++;
169
+ else if (text[i] === '}' && --depth === 0)
170
+ return i;
171
+ }
172
+ return text.length;
173
+ }
174
+ /**
175
+ * Style rules in source order. `@font-face` is read as nothing (the fonts are the writer's
176
+ * business); any other at-rule is unsupported by name, and its rules are not applied.
177
+ */
178
+ function parseStyleSheet(css, unsupported, firstOrder) {
179
+ const text = css.replace(/\/\*[\s\S]*?\*\//g, '');
180
+ const rules = [];
181
+ let i = 0;
182
+ while (i < text.length) {
183
+ while (i < text.length && /\s/.test(text[i]))
184
+ i++;
185
+ if (i >= text.length)
186
+ break;
187
+ if (text[i] === '@') {
188
+ const name = /^@[\w-]+/.exec(text.slice(i))?.[0].toLowerCase() ?? '@';
189
+ if (name !== '@font-face')
190
+ unsupported.add(name);
191
+ const semicolon = text.indexOf(';', i);
192
+ const open = text.indexOf('{', i);
193
+ i =
194
+ open >= 0 && (semicolon < 0 || open < semicolon)
195
+ ? closingBrace(text, open) + 1
196
+ : semicolon < 0
197
+ ? text.length
198
+ : semicolon + 1;
199
+ continue;
200
+ }
201
+ const open = text.indexOf('{', i);
202
+ if (open < 0)
203
+ break;
204
+ const close = closingBrace(text, open);
205
+ const declarations = parseDeclarations(text.slice(open + 1, close));
206
+ for (const selector of splitTop(text.slice(i, open), ',')) {
207
+ const trimmed = selector.trim();
208
+ if (trimmed) {
209
+ rules.push({
210
+ selector: trimmed,
211
+ specificity: specificity(trimmed),
212
+ order: firstOrder + rules.length,
213
+ declarations,
214
+ });
215
+ }
216
+ }
217
+ i = close + 1;
218
+ }
219
+ return rules;
220
+ }
221
+ /** `viewBox` as `[x, y, width, height]`; `null` when absent or unusable (which turns it off). */
222
+ function parseViewBox(value) {
223
+ const numbers = value ? parseNumberList(value) : null;
224
+ if (!numbers || numbers.length !== 4 || !(numbers[2] > 0) || !(numbers[3] > 0))
225
+ return null;
226
+ return [numbers[0], numbers[1], numbers[2], numbers[3]];
227
+ }
228
+ /** `viewBox` into a `width` by `height` viewport, per `preserveAspectRatio`. */
229
+ function fitViewBox(viewBox, aspect, width, height, intrinsic) {
230
+ if (!viewBox) {
231
+ // No viewBox: the width and height attributes are the size of the image, stretched to fit.
232
+ const sx = intrinsic?.width ? width / intrinsic.width : 1;
233
+ const sy = intrinsic?.height ? height / intrinsic.height : 1;
234
+ return { matrix: [sx, 0, 0, sy, 0, 0], slice: false };
235
+ }
236
+ const [vx, vy, vw, vh] = viewBox;
237
+ const words = (aspect ?? '').trim().split(/\s+/).filter(Boolean);
238
+ if (words[0] === 'defer')
239
+ words.shift();
240
+ const align = words[0] && words[0] !== 'meet' && words[0] !== 'slice' ? words[0] : 'xMidYMid';
241
+ const slice = words.includes('slice');
242
+ if (align === 'none') {
243
+ const [sx, sy] = [width / vw, height / vh];
244
+ return { matrix: [sx, 0, 0, sy, 0 - vx * sx, 0 - vy * sy], slice: false };
245
+ }
246
+ const scale = slice ? Math.max(width / vw, height / vh) : Math.min(width / vw, height / vh);
247
+ const alignX = align.startsWith('xMin') ? 0 : align.startsWith('xMax') ? 1 : 0.5;
248
+ const alignY = align.endsWith('YMin') ? 0 : align.endsWith('YMax') ? 1 : 0.5;
249
+ return {
250
+ matrix: [
251
+ scale,
252
+ 0,
253
+ 0,
254
+ scale,
255
+ (width - vw * scale) * alignX - vx * scale,
256
+ (height - vh * scale) * alignY - vy * scale,
257
+ ],
258
+ slice,
259
+ };
260
+ }
261
+ function fontWeightOf(value, parent) {
262
+ switch (value?.toLowerCase()) {
263
+ case undefined:
264
+ return parent;
265
+ case 'normal':
266
+ return 400;
267
+ case 'bold':
268
+ return 700;
269
+ case 'bolder':
270
+ return parent < 400 ? 400 : parent < 600 ? 700 : 900;
271
+ case 'lighter':
272
+ return parent < 600 ? 100 : parent < 800 ? 400 : 700;
273
+ default: {
274
+ const n = Number(value);
275
+ return Number.isFinite(n) && n >= 1 && n <= 1000 ? n : parent;
276
+ }
277
+ }
278
+ }
279
+ class Converter {
280
+ box;
281
+ defaults;
282
+ unsupported = new Set();
283
+ rules = [];
284
+ ids = new Map();
285
+ specifiedCache = new Map();
286
+ badSelectors = new Set();
287
+ /** The elements being drawn: an element that refers to itself is not drawn again. */
288
+ active = new Set();
289
+ count = 0;
290
+ root = null;
291
+ constructor(box, defaults) {
292
+ this.box = box;
293
+ this.defaults = defaults;
294
+ }
295
+ run(markup) {
296
+ const root = this.parse(markup);
297
+ if (!root)
298
+ return { ops: [], unsupported: ['document'] };
299
+ this.root = root;
300
+ this.index(root);
301
+ const ctx = {
302
+ matrix: this.box.matrix,
303
+ clips: [],
304
+ style: {},
305
+ fontSize: this.defaults.font.size,
306
+ fontWeight: this.defaults.font.weight,
307
+ viewport: { width: this.box.width, height: this.box.height },
308
+ };
309
+ const ops = [];
310
+ this.element(root, ctx, ops);
311
+ return { ops, unsupported: [...this.unsupported] };
312
+ }
313
+ // -- the document ------------------------------------------------------------------------
314
+ parse(markup) {
315
+ if (typeof DOMParser === 'undefined')
316
+ return null;
317
+ let document;
318
+ try {
319
+ document = new DOMParser().parseFromString(markup, 'image/svg+xml');
320
+ }
321
+ catch {
322
+ return null;
323
+ }
324
+ const root = document.documentElement;
325
+ if (!root ||
326
+ root.namespaceURI !== SVG_NS ||
327
+ root.localName !== 'svg' ||
328
+ document.getElementsByTagName('parsererror').length > 0) {
329
+ return null;
330
+ }
331
+ return root;
332
+ }
333
+ /** One pass: unknown elements, ids, style sheets. */
334
+ index(root) {
335
+ for (const el of [root, ...Array.from(root.querySelectorAll('*'))]) {
336
+ if (el.namespaceURI !== SVG_NS)
337
+ continue;
338
+ if (!KNOWN.has(el.localName))
339
+ this.unsupported.add(el.localName);
340
+ const id = el.getAttribute('id');
341
+ if (id && !this.ids.has(id))
342
+ this.ids.set(id, el);
343
+ if (el.localName === 'style') {
344
+ const type = el.getAttribute('type');
345
+ if (!type || type === 'text/css') {
346
+ this.rules.push(...parseStyleSheet(el.textContent ?? '', this.unsupported, this.rules.length));
347
+ }
348
+ }
349
+ }
350
+ this.rules.sort((a, b) => a.specificity - b.specificity || a.order - b.order);
351
+ }
352
+ matches(el, selector) {
353
+ if (this.badSelectors.has(selector))
354
+ return false;
355
+ try {
356
+ return el.matches(selector);
357
+ }
358
+ catch {
359
+ this.badSelectors.add(selector);
360
+ this.unsupported.add('css-selector');
361
+ return false;
362
+ }
363
+ }
364
+ /**
365
+ * The properties set on an element: presentation attributes, then the style sheet by
366
+ * specificity, then the `style` attribute.
367
+ */
368
+ specified(el) {
369
+ const cached = this.specifiedCache.get(el);
370
+ if (cached)
371
+ return cached;
372
+ const own = new Map();
373
+ for (const name of PRESENTATION) {
374
+ const value = el.getAttribute(name);
375
+ if (value !== null)
376
+ own.set(name, value.trim());
377
+ }
378
+ const declare = (name, value) => {
379
+ if (CSS_NOT_READ.has(name))
380
+ this.unsupported.add(name);
381
+ else if (/\bvar\(/i.test(value))
382
+ this.unsupported.add('css-variable');
383
+ else
384
+ own.set(name, value);
385
+ };
386
+ for (const rule of this.rules) {
387
+ if (!this.matches(el, rule.selector))
388
+ continue;
389
+ for (const [name, value] of rule.declarations)
390
+ declare(name, value);
391
+ }
392
+ for (const [name, value] of parseDeclarations(el.getAttribute('style') ?? '')) {
393
+ declare(name, value);
394
+ }
395
+ this.specifiedCache.set(el, own);
396
+ return own;
397
+ }
398
+ // -- context -----------------------------------------------------------------------------
399
+ /** Inheritance only; the transform and the clip come after. */
400
+ derive(own, parent) {
401
+ const style = { ...parent.style };
402
+ for (const name of INHERITED) {
403
+ const value = own.get(name);
404
+ if (value !== undefined && value !== 'inherit')
405
+ style[name] = value;
406
+ }
407
+ const size = own.get('font-size');
408
+ return {
409
+ ...parent,
410
+ style,
411
+ fontSize: size === undefined ? parent.fontSize : this.fontSizeOf(size, parent),
412
+ fontWeight: fontWeightOf(own.get('font-weight'), parent.fontWeight),
413
+ };
414
+ }
415
+ fontSizeOf(value, parent) {
416
+ const percent = /^([+-]?(?:\d+\.?\d*|\.\d+))%$/.exec(value);
417
+ const size = percent
418
+ ? (Number(percent[1]) / 100) * parent.fontSize
419
+ : this.length(value, 'x', parent);
420
+ if (size === null || !(size > 0)) {
421
+ this.unsupported.add('font-size');
422
+ return parent.fontSize;
423
+ }
424
+ return size;
425
+ }
426
+ /** A length in user units; percentages refer to the viewport. `null` if it is not a length. */
427
+ length(value, axis, ctx) {
428
+ if (value == null)
429
+ return null;
430
+ const match = LENGTH.exec(value.trim());
431
+ if (!match)
432
+ return null;
433
+ const n = Number(match[1]);
434
+ if (!Number.isFinite(n))
435
+ return null;
436
+ const { width, height } = ctx.viewport;
437
+ switch (match[2]) {
438
+ case undefined:
439
+ case 'px':
440
+ return n;
441
+ case 'pt':
442
+ return (n * 4) / 3;
443
+ case 'pc':
444
+ return n * 16;
445
+ case 'mm':
446
+ return (n * 96) / 25.4;
447
+ case 'cm':
448
+ return (n * 96) / 2.54;
449
+ case 'in':
450
+ return n * 96;
451
+ case 'em':
452
+ return n * ctx.fontSize;
453
+ case 'ex':
454
+ return (n * ctx.fontSize) / 2;
455
+ case 'rem':
456
+ return n * 16;
457
+ default:
458
+ return ((n / 100) *
459
+ (axis === 'x' ? width : axis === 'y' ? height : Math.hypot(width, height) / Math.SQRT2));
460
+ }
461
+ }
462
+ transform(el) {
463
+ const value = el.getAttribute('transform');
464
+ if (value === null)
465
+ return IDENTITY;
466
+ const matrix = parseTransform(value);
467
+ if (!matrix) {
468
+ this.unsupported.add('transform');
469
+ return IDENTITY;
470
+ }
471
+ return matrix;
472
+ }
473
+ /** Properties no op can express; named, the element is still drawn as well as it can be. */
474
+ flagProperties(own, ctx, name) {
475
+ const flag = (property, off) => {
476
+ const value = own.get(property);
477
+ if (value !== undefined && value !== off)
478
+ this.unsupported.add(property);
479
+ };
480
+ flag('filter', 'none');
481
+ flag('mask', 'none');
482
+ flag('mix-blend-mode', 'normal');
483
+ if (!SHAPES.has(name))
484
+ return;
485
+ flag('vector-effect', 'none');
486
+ if (name !== 'rect' && name !== 'circle' && name !== 'ellipse') {
487
+ for (const property of ['marker-start', 'marker-mid', 'marker-end']) {
488
+ const value = ctx.style[property];
489
+ if (value && value !== 'none')
490
+ this.unsupported.add('marker');
491
+ }
492
+ }
493
+ }
494
+ // -- elements ----------------------------------------------------------------------------
495
+ children(el, ctx, out) {
496
+ for (const child of Array.from(el.children))
497
+ this.element(child, ctx, out);
498
+ }
499
+ element(el, parent, out) {
500
+ if (el.namespaceURI !== SVG_NS || !DRAWN.has(el.localName) || this.active.has(el))
501
+ return;
502
+ if (++this.count > MAX_ELEMENTS) {
503
+ this.unsupported.add('size');
504
+ return;
505
+ }
506
+ const own = this.specified(el);
507
+ if (el !== this.root && own.get('display') === 'none')
508
+ return;
509
+ const opacity = unitNumber(own.get('opacity'), 1);
510
+ if (opacity <= 0)
511
+ return;
512
+ let ctx = this.derive(own, parent);
513
+ ctx = { ...ctx, matrix: tidy(multiply(ctx.matrix, this.transform(el))) };
514
+ this.flagProperties(own, ctx, el.localName);
515
+ const clip = this.clipPath(own.get('clip-path'), ctx);
516
+ if (clip)
517
+ ctx = { ...ctx, clips: [...ctx.clips, clip] };
518
+ const local = [];
519
+ this.active.add(el);
520
+ try {
521
+ switch (el.localName) {
522
+ case 'svg': {
523
+ const root = el === this.root;
524
+ const x = root ? 0 : (this.length(el.getAttribute('x'), 'x', ctx) ?? 0);
525
+ const y = root ? 0 : (this.length(el.getAttribute('y'), 'y', ctx) ?? 0);
526
+ const width = root
527
+ ? this.box.width
528
+ : this.length(el.getAttribute('width') ?? '100%', 'x', ctx);
529
+ const height = root
530
+ ? this.box.height
531
+ : this.length(el.getAttribute('height') ?? '100%', 'y', ctx);
532
+ const clipOverflow = !root && !this.overflows(own);
533
+ const inner = width === null || height === null
534
+ ? null
535
+ : this.viewport(el, ctx, x, y, width, height, clipOverflow, root);
536
+ if (inner)
537
+ this.children(el, inner, local);
538
+ break;
539
+ }
540
+ case 'g':
541
+ case 'a':
542
+ this.children(el, ctx, local);
543
+ break;
544
+ case 'use':
545
+ this.use(el, ctx, local);
546
+ break;
547
+ case 'text':
548
+ this.text(el, ctx, local);
549
+ break;
550
+ default:
551
+ this.shape(el, ctx, local);
552
+ }
553
+ }
554
+ finally {
555
+ this.active.delete(el);
556
+ }
557
+ out.push(...withOpacity(local, opacity));
558
+ }
559
+ overflows(own) {
560
+ const overflow = own.get('overflow');
561
+ return overflow === 'visible' || overflow === 'auto';
562
+ }
563
+ /**
564
+ * The context inside an `svg` or `symbol` viewport placed at `(x, y)` with the given size:
565
+ * the `viewBox` fitted in, and a clip to the viewport where content would overflow it.
566
+ * `null` for an empty viewport (nothing is drawn).
567
+ */
568
+ viewport(el, ctx, x, y, width, height, clipOverflow, isRoot) {
569
+ if (!(width > 0 && height > 0))
570
+ return null;
571
+ const viewBox = parseViewBox(el.getAttribute('viewBox'));
572
+ const intrinsic = isRoot
573
+ ? {
574
+ width: this.length(el.getAttribute('width'), 'x', ctx),
575
+ height: this.length(el.getAttribute('height'), 'y', ctx),
576
+ }
577
+ : null;
578
+ const fit = fitViewBox(viewBox, el.getAttribute('preserveAspectRatio'), width, height, intrinsic);
579
+ const placed = tidy(multiply(ctx.matrix, translation(x, y)));
580
+ const clips = clipOverflow || fit.slice
581
+ ? [
582
+ ...ctx.clips,
583
+ {
584
+ matrix: placed,
585
+ commands: rectCommands(0, 0, width, height),
586
+ rule: 'nonzero',
587
+ },
588
+ ]
589
+ : ctx.clips;
590
+ return {
591
+ ...ctx,
592
+ matrix: tidy(multiply(placed, fit.matrix)),
593
+ clips,
594
+ viewport: viewBox ? { width: viewBox[2], height: viewBox[3] } : { width, height },
595
+ };
596
+ }
597
+ reference(el) {
598
+ const href = el.getAttribute('href') ?? el.getAttribute('xlink:href');
599
+ if (!href)
600
+ return null;
601
+ if (!href.startsWith('#')) {
602
+ this.unsupported.add('external-reference');
603
+ return null;
604
+ }
605
+ return this.ids.get(href.slice(1)) ?? null;
606
+ }
607
+ use(el, ctx, out) {
608
+ const target = this.reference(el);
609
+ if (!target)
610
+ return;
611
+ const x = this.length(el.getAttribute('x'), 'x', ctx) ?? 0;
612
+ const y = this.length(el.getAttribute('y'), 'y', ctx) ?? 0;
613
+ const placed = { ...ctx, matrix: tidy(multiply(ctx.matrix, translation(x, y))) };
614
+ if (target.localName !== 'symbol') {
615
+ this.element(target, placed, out);
616
+ return;
617
+ }
618
+ if (this.active.has(target))
619
+ return;
620
+ const own = this.specified(target);
621
+ const width = this.length(el.getAttribute('width') ?? '100%', 'x', ctx);
622
+ const height = this.length(el.getAttribute('height') ?? '100%', 'y', ctx);
623
+ if (width === null || height === null)
624
+ return;
625
+ const inner = this.viewport(target, this.derive(own, placed), 0, 0, width, height, !this.overflows(own), false);
626
+ if (!inner)
627
+ return;
628
+ this.active.add(target);
629
+ try {
630
+ this.children(target, inner, out);
631
+ }
632
+ finally {
633
+ this.active.delete(target);
634
+ }
635
+ }
636
+ // -- shapes ------------------------------------------------------------------------------
637
+ geometry(el, name, ctx) {
638
+ const len = (attribute, axis) => this.length(el.getAttribute(attribute), axis, ctx) ?? 0;
639
+ switch (name) {
640
+ case 'rect': {
641
+ const [x, y, width, height] = [
642
+ len('x', 'x'),
643
+ len('y', 'y'),
644
+ len('width', 'x'),
645
+ len('height', 'y'),
646
+ ];
647
+ if (!(width > 0 && height > 0))
648
+ return [];
649
+ let rx = this.length(el.getAttribute('rx'), 'x', ctx);
650
+ let ry = this.length(el.getAttribute('ry'), 'y', ctx);
651
+ if (rx !== null && !(rx >= 0))
652
+ rx = null;
653
+ if (ry !== null && !(ry >= 0))
654
+ ry = null;
655
+ rx ??= ry ?? 0;
656
+ ry ??= rx;
657
+ return rectCommands(x, y, width, height, Math.min(rx, width / 2), Math.min(ry, height / 2));
658
+ }
659
+ case 'circle': {
660
+ const r = len('r', 'xy');
661
+ return r > 0 ? ellipseCommands(len('cx', 'x'), len('cy', 'y'), r, r) : [];
662
+ }
663
+ case 'ellipse': {
664
+ const [rx, ry] = [len('rx', 'x'), len('ry', 'y')];
665
+ return rx > 0 && ry > 0 ? ellipseCommands(len('cx', 'x'), len('cy', 'y'), rx, ry) : [];
666
+ }
667
+ case 'line':
668
+ return [
669
+ { op: 'M', x: len('x1', 'x'), y: len('y1', 'y') },
670
+ { op: 'L', x: len('x2', 'x'), y: len('y2', 'y') },
671
+ ];
672
+ case 'polyline':
673
+ case 'polygon':
674
+ return pointsCommands(el.getAttribute('points') ?? '', name === 'polygon');
675
+ default:
676
+ return parsePathData(el.getAttribute('d') ?? '');
677
+ }
678
+ }
679
+ shape(el, ctx, out) {
680
+ const name = el.localName;
681
+ const commands = this.geometry(el, name, ctx);
682
+ if (!commands.some((c) => c.op !== 'M' && c.op !== 'Z'))
683
+ return;
684
+ if (ctx.style.visibility === 'hidden' || ctx.style.visibility === 'collapse')
685
+ return;
686
+ const bounds = () => commandBounds(commands);
687
+ const rule = ctx.style['fill-rule'] === 'evenodd' ? 'evenodd' : 'nonzero';
688
+ const fill = name === 'line' ? null : this.resolvePaint('fill', ctx, bounds);
689
+ const fillOp = fill && this.pathOp('fill', commands, rule, fill, null, ctx);
690
+ const strokeStyle = this.strokeStyle(ctx);
691
+ const stroke = strokeStyle && this.resolvePaint('stroke', ctx, bounds);
692
+ const strokeOp = stroke && strokeStyle && this.pathOp('stroke', commands, 'nonzero', stroke, strokeStyle, ctx);
693
+ const strokeFirst = /^\s*stroke/.test(ctx.style['paint-order'] ?? '');
694
+ for (const op of strokeFirst ? [strokeOp, fillOp] : [fillOp, strokeOp])
695
+ if (op)
696
+ out.push(op);
697
+ }
698
+ pathOp(mode, commands, rule, { paint, fold }, stroke, ctx) {
699
+ return {
700
+ kind: 'path',
701
+ mode,
702
+ commands: fold ? transformCommands(commands, invert(fold)) : commands,
703
+ rule,
704
+ paint,
705
+ stroke,
706
+ matrix: fold ? tidy(multiply(ctx.matrix, fold)) : ctx.matrix,
707
+ alpha: 1,
708
+ clips: ctx.clips,
709
+ shadow: null,
710
+ };
711
+ }
712
+ strokeStyle(ctx) {
713
+ const width = this.length(ctx.style['stroke-width'] ?? '1', 'xy', ctx);
714
+ if (width === null || !(width > 0))
715
+ return null;
716
+ const { 'stroke-linecap': cap, 'stroke-linejoin': join } = ctx.style;
717
+ const limit = Number(ctx.style['stroke-miterlimit'] ?? 4);
718
+ return {
719
+ width,
720
+ cap: cap === 'round' || cap === 'square' ? cap : 'butt',
721
+ join: join === 'round' || join === 'bevel' ? join : 'miter',
722
+ miterLimit: limit >= 1 ? limit : 4,
723
+ dash: this.dashes(ctx),
724
+ dashOffset: this.length(ctx.style['stroke-dashoffset'] ?? '0', 'xy', ctx) ?? 0,
725
+ };
726
+ }
727
+ /** An even-length list (an odd one repeats), or none for `none`, a bad value or a zero sum. */
728
+ dashes(ctx) {
729
+ const value = ctx.style['stroke-dasharray'];
730
+ if (!value || value === 'none')
731
+ return [];
732
+ const lengths = value
733
+ .trim()
734
+ .split(/[\s,]+/)
735
+ .map((item) => this.length(item, 'xy', ctx));
736
+ if (lengths.some((n) => n === null || n < 0))
737
+ return [];
738
+ const dash = lengths;
739
+ if (dash.reduce((a, b) => a + b, 0) === 0)
740
+ return [];
741
+ return dash.length % 2 === 1 ? [...dash, ...dash] : dash;
742
+ }
743
+ // -- paint -------------------------------------------------------------------------------
744
+ /**
745
+ * The paint of `fill` or `stroke`, or `null` for none. `bounds` is the bounding box of the
746
+ * shape, for gradients in box units; `null` where there is no such box (text).
747
+ */
748
+ resolvePaint(kind, ctx, bounds) {
749
+ const raw = (ctx.style[kind] ?? (kind === 'fill' ? 'black' : 'none')).trim();
750
+ if (raw === 'none')
751
+ return null;
752
+ const opacity = unitNumber(ctx.style[`${kind}-opacity`], 1);
753
+ let colour = raw;
754
+ const reference = /^url\(\s*(['"]?)(.*?)\1\s*\)\s*(.*)$/s.exec(raw);
755
+ if (reference) {
756
+ const target = reference[2].startsWith('#')
757
+ ? this.ids.get(reference[2].slice(1))
758
+ : undefined;
759
+ if (reference[2] && !reference[2].startsWith('#'))
760
+ this.unsupported.add('external-reference');
761
+ if (target?.localName === 'linearGradient' || target?.localName === 'radialGradient') {
762
+ return this.gradient(target, kind, opacity, ctx, bounds);
763
+ }
764
+ // A pattern is reported with the elements; a missing target takes the fallback colour.
765
+ colour = target ? '' : reference[3];
766
+ if (!colour)
767
+ return null;
768
+ }
769
+ if (colour.toLowerCase() === 'currentcolor')
770
+ colour = ctx.style.color ?? 'black';
771
+ const parsed = parseSvgColor(colour);
772
+ if (!parsed) {
773
+ this.unsupported.add('color');
774
+ return null;
775
+ }
776
+ const alpha = parsed.alpha * opacity;
777
+ return alpha > 0 ? { paint: { type: 'solid', hex: parsed.hex, alpha }, fold: null } : null;
778
+ }
779
+ gradientChain(gradient) {
780
+ const chain = [];
781
+ let el = gradient;
782
+ while (el && !chain.includes(el)) {
783
+ chain.push(el);
784
+ const href = el.getAttribute('href') ?? el.getAttribute('xlink:href');
785
+ const next = href?.startsWith('#')
786
+ ? this.ids.get(href.slice(1))
787
+ : undefined;
788
+ el =
789
+ next && (next.localName === 'linearGradient' || next.localName === 'radialGradient')
790
+ ? next
791
+ : undefined;
792
+ }
793
+ return chain;
794
+ }
795
+ stops(chain, opacity) {
796
+ const holder = chain.find((g) => Array.from(g.children).some((c) => c.localName === 'stop'));
797
+ const stops = [];
798
+ let previous = 0;
799
+ for (const stop of Array.from(holder?.children ?? [])) {
800
+ if (stop.localName !== 'stop')
801
+ continue;
802
+ const own = this.specified(stop);
803
+ previous = Math.max(previous, clamp01(fraction(stop.getAttribute('offset')) ?? 0));
804
+ let colour = own.get('stop-color') ?? 'black';
805
+ if (colour.toLowerCase() === 'currentcolor')
806
+ colour = own.get('color') ?? 'black';
807
+ const parsed = parseSvgColor(colour);
808
+ if (!parsed) {
809
+ this.unsupported.add('color');
810
+ continue;
811
+ }
812
+ stops.push({
813
+ offset: previous,
814
+ hex: parsed.hex,
815
+ alpha: parsed.alpha * unitNumber(own.get('stop-opacity'), 1) * opacity,
816
+ });
817
+ }
818
+ return stops;
819
+ }
820
+ gradient(gradient, kind, opacity, ctx, bounds) {
821
+ const chain = this.gradientChain(gradient);
822
+ const attribute = (name) => chain.map((g) => g.getAttribute(name)).find((value) => value !== null) ?? null;
823
+ const spread = attribute('spreadMethod');
824
+ if (spread && spread !== 'pad')
825
+ this.unsupported.add('spreadMethod');
826
+ const stops = this.stops(chain, opacity);
827
+ if (stops.length === 0)
828
+ return null;
829
+ const last = stops[stops.length - 1];
830
+ const lastColour = {
831
+ paint: { type: 'solid', hex: last.hex, alpha: last.alpha },
832
+ fold: null,
833
+ };
834
+ if (stops.length === 1)
835
+ return lastColour;
836
+ // The gradient space: the user space, or the unit square of the shape's bounding box, and
837
+ // then the gradient's own transform.
838
+ const boxUnits = attribute('gradientUnits') !== 'userSpaceOnUse';
839
+ let unit = IDENTITY;
840
+ if (boxUnits) {
841
+ if (!bounds) {
842
+ this.unsupported.add('textGradient');
843
+ return null;
844
+ }
845
+ const box = bounds();
846
+ if (!box || !(box.width > 0) || !(box.height > 0))
847
+ return null;
848
+ unit = [box.width, 0, 0, box.height, box.x, box.y];
849
+ }
850
+ const own = attribute('gradientTransform');
851
+ let transform = IDENTITY;
852
+ if (own !== null) {
853
+ const parsed = parseTransform(own);
854
+ if (parsed)
855
+ transform = parsed;
856
+ else
857
+ this.unsupported.add('transform');
858
+ }
859
+ const m = tidy(multiply(unit, transform));
860
+ const [a, b, c, d] = m;
861
+ const det = a * d - b * c;
862
+ if (!Number.isFinite(det) || det === 0)
863
+ return null;
864
+ const coordinate = (name, fallback, axis) => {
865
+ const value = attribute(name) ?? fallback;
866
+ return (boxUnits ? fraction(value) : this.length(value, axis, ctx)) ?? 0;
867
+ };
868
+ if (gradient.localName === 'linearGradient') {
869
+ const [x1, y1] = [coordinate('x1', '0%', 'x'), coordinate('y1', '0%', 'y')];
870
+ const [vx, vy] = [coordinate('x2', '100%', 'x') - x1, coordinate('y2', '0%', 'y') - y1];
871
+ const length2 = vx * vx + vy * vy;
872
+ if (length2 === 0)
873
+ return lastColour;
874
+ // Isolines are perpendicular to the vector in gradient space, not in user space: the user
875
+ // space direction is the normal, M^-T v, scaled to the same parameter range.
876
+ const nx = (d * vx - b * vy) / det;
877
+ const ny = (a * vy - c * vx) / det;
878
+ const scale = length2 / (nx * nx + ny * ny);
879
+ const p0 = apply(m, x1, y1);
880
+ const paint = {
881
+ type: 'linear',
882
+ x0: p0.x,
883
+ y0: p0.y,
884
+ x1: p0.x + nx * scale,
885
+ y1: p0.y + ny * scale,
886
+ stops,
887
+ };
888
+ return { paint, fold: null };
889
+ }
890
+ const [cx, cy] = [coordinate('cx', '50%', 'x'), coordinate('cy', '50%', 'y')];
891
+ const r = coordinate('r', '50%', 'xy');
892
+ if (!(r > 0))
893
+ return lastColour;
894
+ const fx = attribute('fx') === null ? cx : coordinate('fx', '50%', 'x');
895
+ const fy = attribute('fy') === null ? cy : coordinate('fy', '50%', 'y');
896
+ const fr = coordinate('fr', '0%', 'xy');
897
+ const scale = Math.hypot(a, b);
898
+ const tolerance = 1e-9 * (a * a + b * b + c * c + d * d);
899
+ if (Math.abs(a * c + b * d) <= tolerance &&
900
+ Math.abs(a * a + b * b - c * c - d * d) <= tolerance) {
901
+ const focus = apply(m, fx, fy);
902
+ const centre = apply(m, cx, cy);
903
+ const paint = {
904
+ type: 'radial',
905
+ x0: focus.x,
906
+ y0: focus.y,
907
+ r0: fr * scale,
908
+ x1: centre.x,
909
+ y1: centre.y,
910
+ r1: r * scale,
911
+ stops,
912
+ };
913
+ return { paint, fold: null };
914
+ }
915
+ // An ellipse: the circle is only a circle in the gradient space, so the shape is drawn there.
916
+ // A stroke would be distorted with it, and text has no shape to move into that space.
917
+ if (kind === 'stroke' || bounds === null) {
918
+ this.unsupported.add('radialGradient');
919
+ return null;
920
+ }
921
+ return {
922
+ paint: { type: 'radial', x0: fx, y0: fy, r0: fr, x1: cx, y1: cy, r1: r, stops },
923
+ fold: m,
924
+ };
925
+ }
926
+ // -- clip paths --------------------------------------------------------------------------
927
+ /** The clip the `clip-path` property names, in the user space of the element it is on. */
928
+ clipPath(value, ctx) {
929
+ const id = referencedId(value);
930
+ const clip = id === null ? undefined : this.ids.get(id);
931
+ if (!clip || clip.localName !== 'clipPath')
932
+ return null;
933
+ const own = this.specified(clip);
934
+ if (clip.getAttribute('clipPathUnits') === 'objectBoundingBox') {
935
+ this.unsupported.add('clipPathUnits');
936
+ return null;
937
+ }
938
+ if (own.get('clip-path'))
939
+ this.unsupported.add('clipPath:clip-path');
940
+ const base = this.transform(clip);
941
+ const commands = [];
942
+ let rule = null;
943
+ for (const child of Array.from(clip.children)) {
944
+ const name = child.localName;
945
+ if (child.namespaceURI !== SVG_NS)
946
+ continue;
947
+ if (name === 'text' || name === 'use') {
948
+ this.unsupported.add(`clipPath:${name}`);
949
+ continue;
950
+ }
951
+ if (!SHAPES.has(name))
952
+ continue;
953
+ const shape = this.specified(child);
954
+ if (shape.get('display') === 'none' || shape.get('visibility') === 'hidden')
955
+ continue;
956
+ if (shape.get('clip-path'))
957
+ this.unsupported.add('clipPath:clip-path');
958
+ const geometry = this.geometry(child, name, this.derive(shape, ctx));
959
+ if (geometry.length === 0)
960
+ continue;
961
+ commands.push(...transformCommands(geometry, multiply(base, this.transform(child))));
962
+ rule ??=
963
+ (shape.get('clip-rule') ?? own.get('clip-rule')) === 'evenodd' ? 'evenodd' : 'nonzero';
964
+ }
965
+ return { matrix: ctx.matrix, commands, rule: rule ?? 'nonzero' };
966
+ }
967
+ // -- text --------------------------------------------------------------------------------
968
+ fontOf(ctx) {
969
+ const base = this.defaults.font;
970
+ const [first, ...rest] = ctx.style['font-family'] ? fontFamilies(ctx.style['font-family']) : [];
971
+ const declared = first !== undefined && !GENERIC_FAMILIES.has(first.toLowerCase());
972
+ const fallback = declared ? rest : base.fallback;
973
+ const style = ctx.style['font-style'];
974
+ return {
975
+ family: declared ? first : base.family,
976
+ ...(fallback && fallback.length > 0 && { fallback: [...fallback] }),
977
+ weight: ctx.fontWeight,
978
+ style: style === undefined
979
+ ? base.style
980
+ : style === 'italic' || style === 'oblique'
981
+ ? 'italic'
982
+ : 'normal',
983
+ size: ctx.fontSize,
984
+ };
985
+ }
986
+ advances(text, font) {
987
+ const measured = this.defaults.measure?.(text, font);
988
+ const count = Array.from(text).length;
989
+ if (measured && measured.length === count && measured.every(Number.isFinite))
990
+ return measured;
991
+ return Array.from({ length: count }, () => font.size * GLYPH_WIDTH_EM);
992
+ }
993
+ runOf(ctx) {
994
+ const font = this.fontOf(ctx);
995
+ const hidden = ctx.style.visibility === 'hidden' || ctx.style.visibility === 'collapse';
996
+ const fill = hidden ? null : this.resolvePaint('fill', ctx, null);
997
+ const strokeStyle = hidden ? null : this.strokeStyle(ctx);
998
+ const stroke = strokeStyle && this.resolvePaint('stroke', ctx, null);
999
+ const strokeFirst = /^\s*stroke/.test(ctx.style['paint-order'] ?? '');
1000
+ const anchor = ctx.style['text-anchor'] ?? 'start';
1001
+ const baseline = ctx.style['dominant-baseline'] ?? 'auto';
1002
+ if (!Object.hasOwn(BASELINE_SHIFT, baseline))
1003
+ this.unsupported.add('dominant-baseline');
1004
+ const shift = (BASELINE_SHIFT[baseline] ?? 0) * font.size;
1005
+ const key = JSON.stringify([font, fill, stroke, strokeStyle, strokeFirst, anchor, shift]);
1006
+ return {
1007
+ key,
1008
+ font,
1009
+ fill,
1010
+ stroke,
1011
+ strokeStyle: stroke ? strokeStyle : null,
1012
+ strokeFirst,
1013
+ anchor,
1014
+ shift,
1015
+ };
1016
+ }
1017
+ /** Properties and attributes of text that the ops cannot say. */
1018
+ flagText(el, ctx) {
1019
+ for (const attribute of ['rotate', 'textLength']) {
1020
+ if (el.hasAttribute(attribute))
1021
+ this.unsupported.add(attribute);
1022
+ }
1023
+ // White space is always collapsed here; a text that keeps its spaces would move.
1024
+ if (el.getAttribute('xml:space') === 'preserve' ||
1025
+ /^pre/.test(ctx.style['white-space'] ?? '')) {
1026
+ this.unsupported.add('xml:space');
1027
+ }
1028
+ for (const property of ['letter-spacing', 'word-spacing']) {
1029
+ const value = ctx.style[property];
1030
+ if (value && value !== 'normal' && parseFloat(value) !== 0)
1031
+ this.unsupported.add(property);
1032
+ }
1033
+ const decoration = ctx.style['text-decoration'];
1034
+ if (decoration && decoration !== 'none')
1035
+ this.unsupported.add('text-decoration');
1036
+ const mode = ctx.style['writing-mode'];
1037
+ if (mode && !['horizontal-tb', 'lr', 'lr-tb'].includes(mode))
1038
+ this.unsupported.add('writing-mode');
1039
+ }
1040
+ text(root, ctx, out) {
1041
+ const glyphs = [];
1042
+ // Positions by the index of the glyph they apply to: `x`, `y`, `dx` and `dy` are lists.
1043
+ const at = {
1044
+ x: new Map(),
1045
+ y: new Map(),
1046
+ dx: new Map(),
1047
+ dy: new Map(),
1048
+ };
1049
+ let penX = 0;
1050
+ let penY = 0;
1051
+ let chunk = -1;
1052
+ let afterSpace = true;
1053
+ const positions = (el, style) => {
1054
+ for (const [name, axis] of [
1055
+ ['x', 'x'],
1056
+ ['y', 'y'],
1057
+ ['dx', 'x'],
1058
+ ['dy', 'y'],
1059
+ ]) {
1060
+ const list = el
1061
+ .getAttribute(name)
1062
+ ?.trim()
1063
+ .split(/[\s,]+/)
1064
+ .filter(Boolean) ?? [];
1065
+ list.forEach((item, i) => {
1066
+ const value = this.length(item, axis, style);
1067
+ if (value !== null)
1068
+ at[name].set(glyphs.length + i, value);
1069
+ });
1070
+ }
1071
+ this.flagText(el, style);
1072
+ };
1073
+ const addText = (data, style) => {
1074
+ const run = this.runOf(style);
1075
+ const kept = [];
1076
+ for (const char of Array.from(data.replace(/[\t\r\n ]+/g, ' '))) {
1077
+ if (char === ' ' && afterSpace)
1078
+ continue;
1079
+ afterSpace = char === ' ';
1080
+ kept.push(char);
1081
+ }
1082
+ if (kept.length === 0)
1083
+ return;
1084
+ const advances = this.advances(kept.join(''), run.font);
1085
+ kept.forEach((char, i) => {
1086
+ const index = glyphs.length;
1087
+ let starts = index === 0;
1088
+ if (at.x.has(index)) {
1089
+ penX = at.x.get(index);
1090
+ starts = true;
1091
+ }
1092
+ if (at.y.has(index)) {
1093
+ penY = at.y.get(index);
1094
+ starts = true;
1095
+ }
1096
+ penX += at.dx.get(index) ?? 0;
1097
+ penY += at.dy.get(index) ?? 0;
1098
+ if (starts)
1099
+ chunk++;
1100
+ glyphs.push({ char, x: penX, y: penY, advance: advances[i], run, chunk });
1101
+ penX += advances[i];
1102
+ });
1103
+ };
1104
+ const visit = (el, style) => {
1105
+ positions(el, style);
1106
+ for (const node of Array.from(el.childNodes)) {
1107
+ if (node.nodeType === 3 || node.nodeType === 4) {
1108
+ addText(node.data, style);
1109
+ }
1110
+ else if (node.nodeType === 1) {
1111
+ const child = node;
1112
+ if (child.namespaceURI !== SVG_NS ||
1113
+ (child.localName !== 'tspan' && child.localName !== 'a'))
1114
+ continue;
1115
+ const own = this.specified(child);
1116
+ if (own.get('display') !== 'none')
1117
+ visit(child, this.derive(own, style));
1118
+ }
1119
+ }
1120
+ };
1121
+ visit(root, ctx);
1122
+ while (glyphs.at(-1)?.char === ' ')
1123
+ glyphs.pop();
1124
+ // A text chunk (it starts at an absolute position) is anchored as a whole.
1125
+ const chunks = new Map();
1126
+ for (const glyph of glyphs)
1127
+ chunks.set(glyph.chunk, [...(chunks.get(glyph.chunk) ?? []), glyph]);
1128
+ const shifts = new Map();
1129
+ for (const [index, members] of chunks) {
1130
+ const [first, last] = [members[0], members[members.length - 1]];
1131
+ const width = last.x + last.advance - first.x;
1132
+ shifts.set(index, first.run.anchor === 'middle' ? -width / 2 : first.run.anchor === 'end' ? -width : 0);
1133
+ }
1134
+ let group = [];
1135
+ const flush = () => {
1136
+ const first = group[0];
1137
+ if (!first)
1138
+ return;
1139
+ const { run } = first;
1140
+ const make = (mode) => {
1141
+ const resolved = mode === 'fill' ? run.fill : run.stroke;
1142
+ if (!resolved)
1143
+ return null;
1144
+ return {
1145
+ kind: 'text',
1146
+ mode,
1147
+ text: group.map((g) => g.char).join(''),
1148
+ xs: group.map((g) => g.x + (shifts.get(g.chunk) ?? 0)),
1149
+ y: first.y + run.shift,
1150
+ font: run.font,
1151
+ paint: resolved.paint,
1152
+ stroke: mode === 'stroke' ? run.strokeStyle : null,
1153
+ matrix: ctx.matrix,
1154
+ alpha: 1,
1155
+ clips: ctx.clips,
1156
+ shadow: null,
1157
+ };
1158
+ };
1159
+ const ops = run.strokeFirst ? [make('stroke'), make('fill')] : [make('fill'), make('stroke')];
1160
+ for (const op of ops)
1161
+ if (op)
1162
+ out.push(op);
1163
+ group = [];
1164
+ };
1165
+ for (const glyph of glyphs) {
1166
+ const previous = group.at(-1);
1167
+ if (previous && (previous.run.key !== glyph.run.key || previous.y !== glyph.y))
1168
+ flush();
1169
+ group.push(glyph);
1170
+ }
1171
+ flush();
1172
+ }
1173
+ }
1174
+ /**
1175
+ * Element opacity: on the one op it makes, its alpha; on several, a group composited as a whole.
1176
+ */
1177
+ function withOpacity(ops, opacity) {
1178
+ if (opacity >= 1 || ops.length === 0)
1179
+ return ops;
1180
+ if (ops.length === 1)
1181
+ return [{ ...ops[0], alpha: ops[0].alpha * opacity }];
1182
+ return [{ kind: 'group', matrix: IDENTITY, alpha: opacity, clips: [], shadow: null, ops }];
1183
+ }