imagescript 3.8.0 → 3.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -14,24 +14,42 @@ import { decode as decodeUTF8, encode as encodeUTF8 } from "../util/utf8.js";
14
14
  import { base64 } from "../util/bytes.js";
15
15
  import { gunzip } from "../codecs/zlib.js";
16
16
  import { applyFilter } from "./filter.js";
17
- const UNSUPPORTED = new Set(['text', 'filter', 'pattern', 'marker', 'foreignObject', 'script', 'style', 'title', 'desc', 'metadata',
17
+ import { BLEND_MODES, blendPixel } from "./blend.js";
18
+ import { fontFace, layOutText, parseFontFamilies, pathLength, placeOutline, colorTablesOf } from "./svg-text.js";
19
+ import { rasterizeGlyph } from "./text.js";
20
+ import { renderPaintGlyph } from "./colr.js";
21
+ import { decodeSync as decodePNG } from "../codecs/png.js";
22
+ import { decompress } from "../codecs/zlib.js";
23
+ const UNSUPPORTED = new Set(['filter', 'pattern', 'marker', 'foreignObject', 'script', 'style', 'title', 'desc', 'metadata',
18
24
  'defs', 'clipPath', 'mask', 'linearGradient', 'radialGradient', 'stop', 'symbol', 'font', 'font-face', 'animate', 'animateTransform', 'animateMotion', 'set']);
19
25
  const INHERITED = new Set(['fill', 'fill-opacity', 'fill-rule', 'stroke', 'stroke-width', 'stroke-opacity', 'stroke-linecap', 'stroke-linejoin',
20
26
  'stroke-miterlimit', 'stroke-dasharray', 'stroke-dashoffset', 'color', 'visibility', 'clip-rule', 'font-size', 'marker-start', 'marker-mid',
21
- 'marker-end', 'image-rendering', 'color-interpolation-filters']);
27
+ 'marker-end', 'image-rendering', 'color-interpolation-filters', 'paint-order', 'shape-rendering',
28
+ 'font-family', 'font-weight', 'font-style', 'font-stretch', 'font-variant', 'text-anchor', 'letter-spacing', 'word-spacing', 'dominant-baseline',
29
+ 'writing-mode', 'kerning', 'font-kerning', 'text-rendering']);
30
+ const CSS_ONLY = new Set(['font-kerning']);
31
+ const SVG_ELEMENTS = new Set(['a', 'altGlyph', 'altGlyphDef', 'altGlyphItem', 'animate', 'animateColor', 'animateMotion', 'animateTransform', 'circle',
32
+ 'clipPath', 'color-profile', 'cursor', 'defs', 'desc', 'ellipse', 'feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix',
33
+ 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur',
34
+ 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence',
35
+ 'filter', 'font', 'font-face', 'foreignObject', 'g', 'glyph', 'glyphRef', 'hkern', 'image', 'line', 'linearGradient', 'marker', 'mask', 'metadata',
36
+ 'missing-glyph', 'mpath', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'script', 'set', 'stop', 'style', 'svg', 'switch',
37
+ 'symbol', 'text', 'textPath', 'title', 'tref', 'tspan', 'use', 'view', 'vkern']);
22
38
  const SWITCHABLE = new Set(['svg', 'g', 'a', 'switch', 'use', 'path', 'rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon', 'text', 'image', 'foreignObject']);
23
- const PROPERTIES = new Set([...INHERITED, 'opacity', 'display', 'clip-path', 'mask', 'stop-color', 'stop-opacity', 'transform', 'filter', 'flood-color',
24
- 'flood-opacity', 'lighting-color']);
39
+ const PROPERTIES = new Set([...INHERITED, 'opacity', 'display', 'clip-path', 'mask', 'stop-color', 'stop-opacity', 'transform', 'transform-origin', 'filter', 'flood-color',
40
+ 'flood-opacity', 'lighting-color', 'text-decoration', 'baseline-shift', 'alignment-baseline']);
25
41
  const DEFAULTS = {
26
42
  'fill': 'black', 'fill-opacity': '1', 'fill-rule': 'nonzero', 'stroke': 'none', 'stroke-width': '1', 'stroke-opacity': '1',
27
43
  'stroke-linecap': 'butt', 'stroke-linejoin': 'miter', 'stroke-miterlimit': '4', 'stroke-dasharray': 'none', 'stroke-dashoffset': '0',
28
44
  'color': 'black', 'visibility': 'visible', 'clip-rule': 'nonzero', 'font-size': '16', 'opacity': '1', 'display': 'inline',
29
45
  'stop-color': 'black', 'stop-opacity': '1', 'marker-start': 'none', 'marker-mid': 'none', 'marker-end': 'none',
30
46
  'image-rendering': 'auto', 'filter': 'none', 'flood-color': 'black', 'flood-opacity': '1', 'color-interpolation-filters': 'linearRGB',
31
- 'lighting-color': 'white'
47
+ 'lighting-color': 'white', 'shape-rendering': 'auto', 'font-weight': '400', 'font-style': 'normal', 'font-stretch': 'normal',
48
+ 'font-variant': 'normal', 'text-anchor': 'start', 'letter-spacing': 'normal', 'word-spacing': 'normal', 'dominant-baseline': 'auto',
49
+ 'writing-mode': 'lr-tb', 'text-rendering': 'auto'
32
50
  };
33
51
  const SAMPLES = 16;
34
- export function render(source, mode, size, images = new Map()) {
52
+ export function render(source, mode, size, images = new Map(), fonts = []) {
35
53
  if (typeof source !== 'string')
36
54
  source = decodeUTF8(source);
37
55
  const root = parseXML(source).children.find(node => node.name === 'svg' && node.svg);
@@ -39,6 +57,7 @@ export function render(source, mode, size, images = new Map()) {
39
57
  throw new Error('SVG: no <svg> element');
40
58
  const doc = new Document(root);
41
59
  doc.images = images;
60
+ doc.given = fonts.map(data => fontFace(data)).filter(face => face !== null);
42
61
  const { width, height } = documentSize(root);
43
62
  if (!(width > 0) || !(height > 0))
44
63
  throw new Error('SVG: invalid dimensions');
@@ -72,6 +91,15 @@ function documentSize(root) {
72
91
  };
73
92
  return { width: lengthOf(root.attrs.width, viewBox ? viewBox[2] : 100), height: lengthOf(root.attrs.height, viewBox ? viewBox[3] : 100) };
74
93
  }
94
+ const glyphDocuments = new WeakMap();
95
+ function drawRaster(layer, image, matrix, filter) {
96
+ const inverse = invert(matrix);
97
+ const coverage = inverse && rasterize([transformPoints([0, 0, image.width, 0, image.width, image.height, 0, image.height], matrix)], false, layer.width, layer.height);
98
+ if (!coverage)
99
+ return;
100
+ const translated = Math.abs(matrix[0] - 1) < 1e-6 && Math.abs(matrix[3] - 1) < 1e-6 && matrix[1] === 0 && matrix[2] === 0;
101
+ layer.fill(coverage, sampler(premultiplied(image), image.width, image.height, inverse, false, translated ? 0 : filter, 1));
102
+ }
75
103
  function premultiplied(image) {
76
104
  if (image.premultiplied)
77
105
  return image.premultiplied;
@@ -157,6 +185,7 @@ export function embeddedImages(source) {
157
185
  }
158
186
  const SVG_NS = 'http://www.w3.org/2000/svg';
159
187
  function parseXML(text) {
188
+ text = text.replace(/\r\n?/g, '\n');
160
189
  const root = { name: '#root', attrs: {}, children: [], text: '', svg: false };
161
190
  const stack = [root];
162
191
  const namespaces = [{ '': SVG_NS }];
@@ -186,11 +215,17 @@ function parseXML(text) {
186
215
  return String.fromCodePoint(name[1] === 'x' || name[1] === 'X' ? parseInt(name.slice(2), 16) : parseInt(name.slice(1), 10));
187
216
  return name in entities ? entities[name] : match;
188
217
  });
218
+ const addText = (value) => {
219
+ const node = stack[stack.length - 1];
220
+ node.text += value;
221
+ if (node.content)
222
+ node.content.push(value);
223
+ };
189
224
  let i = 0;
190
225
  while (i < text.length) {
191
226
  if (text[i] !== '<') {
192
227
  const end = text.indexOf('<', i);
193
- stack[stack.length - 1].text += decode(text.slice(i, end === -1 ? text.length : end));
228
+ addText(decode(text.slice(i, end === -1 ? text.length : end)));
194
229
  i = end === -1 ? text.length : end;
195
230
  continue;
196
231
  }
@@ -200,7 +235,7 @@ function parseXML(text) {
200
235
  }
201
236
  else if (text.startsWith('<![CDATA[', i)) {
202
237
  const end = text.indexOf(']]>', i);
203
- stack[stack.length - 1].text += text.slice(i + 9, end === -1 ? text.length : end);
238
+ addText(text.slice(i + 9, end === -1 ? text.length : end));
204
239
  i = end === -1 ? text.length : end + 3;
205
240
  }
206
241
  else if (text.startsWith('<!', i)) {
@@ -262,7 +297,12 @@ function parseXML(text) {
262
297
  close.lastIndex = i;
263
298
  const end = close.exec(text);
264
299
  i = end ? close.lastIndex : text.length;
265
- stack[stack.length - 1].children.push(node);
300
+ const parent = stack[stack.length - 1];
301
+ parent.children.push(node);
302
+ if (parent.content)
303
+ parent.content.push(node);
304
+ if (parent.content || (node.name === 'text' && node.svg))
305
+ node.content = [];
266
306
  if (!end || !end[1]) {
267
307
  stack.push(node);
268
308
  namespaces.push(scope);
@@ -438,7 +478,27 @@ function parseSelector(selector) {
438
478
  function parseDeclarations(text) {
439
479
  const declarations = { normal: {}, important: {} };
440
480
  text = stripComments(text);
441
- for (const part of text.split(';')) {
481
+ const parts = [];
482
+ let depth = 0, quote = '', start = 0;
483
+ for (let i = 0; i < text.length; i++) {
484
+ const c = text[i];
485
+ if (quote) {
486
+ if (c === quote)
487
+ quote = '';
488
+ }
489
+ else if (c === '"' || c === '\'')
490
+ quote = c;
491
+ else if (c === '(')
492
+ depth++;
493
+ else if (c === ')')
494
+ depth = Math.max(0, depth - 1);
495
+ else if (c === ';' && !depth) {
496
+ parts.push(text.slice(start, i));
497
+ start = i + 1;
498
+ }
499
+ }
500
+ parts.push(text.slice(start));
501
+ for (const part of parts) {
442
502
  const colon = part.indexOf(':');
443
503
  if (colon === -1)
444
504
  continue;
@@ -483,6 +543,10 @@ class Document {
483
543
  rules;
484
544
  images = new Map();
485
545
  nested = new Map();
546
+ embedded;
547
+ given = [];
548
+ outputScale = 1;
549
+ texts = new WeakMap();
486
550
  constructor(root) {
487
551
  this.ids = new Map();
488
552
  this.active = new Set();
@@ -501,6 +565,7 @@ class Document {
501
565
  }
502
566
  this.root = root;
503
567
  this.rules = parseStyleSheet(styles.join('\n'));
568
+ this.embedded = embeddedFonts(styles.join('\n'));
504
569
  for (const name of ['fill', 'stroke'])
505
570
  this.breakPatternCycles(name);
506
571
  this.breakImageCycles();
@@ -573,13 +638,15 @@ class Document {
573
638
  if (name === 'marker')
574
639
  for (const kind of ['marker-start', 'marker-mid', 'marker-end'])
575
640
  own[kind] = declarations[name];
641
+ else if (name === 'font')
642
+ Object.assign(own, fontShorthand(declarations[name]) ?? {});
576
643
  else if (validProperty(name, declarations[name]))
577
644
  own[name] = declarations[name];
578
645
  }
579
646
  };
580
647
  const presentation = {};
581
648
  for (const name in node.attrs)
582
- if (PROPERTIES.has(name))
649
+ if (PROPERTIES.has(name) && !CSS_ONLY.has(name))
583
650
  presentation[name] = node.attrs[name].trim();
584
651
  apply(presentation);
585
652
  const rules = this.rules.filter(rule => rule.match(node));
@@ -594,7 +661,7 @@ class Document {
594
661
  apply(inline.important);
595
662
  const style = {};
596
663
  for (const name of PROPERTIES) {
597
- if (name === 'transform')
664
+ if (name === 'transform' || name === 'transform-origin')
598
665
  continue;
599
666
  let value = own[name];
600
667
  if (value === 'inherit' || (value === undefined && INHERITED.has(name)))
@@ -603,8 +670,19 @@ class Document {
603
670
  value = DEFAULTS[name];
604
671
  style[name] = value === undefined ? undefined : String(value).trim();
605
672
  }
673
+ const parentSize = parent ? parseFloat(parent['font-size']) : 16;
674
+ style['font-size'] = String(own['font-size'] !== undefined && own['font-size'] !== 'inherit' ? fontSize(own['font-size'], parentSize) : parentSize);
675
+ const parentWeight = parent ? Number(parent['font-weight']) : 400, weight = own['font-weight'];
676
+ style['font-weight'] = String(weight === undefined || weight === 'inherit' ? parentWeight : weight === 'normal' ? 400 : weight === 'bold' ? 700
677
+ : weight === 'bolder' ? Math.min(900, parentWeight + (parentWeight === 400 ? 300 : 100))
678
+ : weight === 'lighter' ? Math.max(100, parentWeight - (parentWeight === 400 ? 200 : 100))
679
+ : /^[1-9]00$/.test(weight) ? Number(weight) : parentWeight);
606
680
  style['mask-type'] = own['mask-type'] || node.attrs['mask-type'];
681
+ style['mix-blend-mode'] = own['mix-blend-mode'];
682
+ style.isolation = own.isolation;
683
+ style['background-color'] = own['background-color'];
607
684
  style.transform = own.transform;
685
+ style['transform-origin'] = own['transform-origin'];
608
686
  node.computed = style;
609
687
  node.computedParent = parent;
610
688
  return style;
@@ -637,7 +715,7 @@ class Document {
637
715
  return;
638
716
  let matrix = context.matrix;
639
717
  if (style.transform && !root)
640
- matrix = multiply(matrix, parseTransform(style.transform));
718
+ matrix = multiply(matrix, transformOf(style, context.viewport));
641
719
  const opacity = clamp01(parseNumber(style.opacity, 1));
642
720
  if (opacity <= 0)
643
721
  return;
@@ -664,18 +742,18 @@ class Document {
664
742
  }
665
743
  case 'use': return this.renderUse(node, ctx);
666
744
  case 'image': return this.renderImage(node, ctx);
745
+ case 'text': return this.renderText(node, ctx);
667
746
  default: {
668
747
  const path = shapePath(node, ctx.viewport, parseNumber(style['font-size'], 16));
669
748
  if (!path)
670
749
  return;
671
750
  this.paintPath(path, node, ctx);
672
- if (style.visibility === 'visible')
673
- this.renderMarkers(path, node, ctx);
674
751
  }
675
752
  }
676
753
  };
677
754
  const draw = filters && filters.length ? (layer) => this.filtered(filters, matrix, layer, drawContent) : (layer) => drawContent(layer);
678
- if (opacity >= 1 && !clipping && !masking)
755
+ const blend = style['mix-blend-mode'] && BLEND_MODES.has(style['mix-blend-mode']) ? style['mix-blend-mode'] : 'normal';
756
+ if (opacity >= 1 && !clipping && !masking && blend === 'normal' && style.isolation !== 'isolate')
679
757
  return draw(context.layer);
680
758
  const layer = new Layer(context.layer.width, context.layer.height);
681
759
  draw(layer);
@@ -690,7 +768,7 @@ class Document {
690
768
  else
691
769
  alpha = values;
692
770
  }
693
- context.layer.composite(layer, opacity, alpha);
771
+ context.layer.composite(layer, opacity, alpha, blend);
694
772
  }
695
773
  clipped(ctx, x, y, width, height, draw) {
696
774
  const layer = new Layer(ctx.layer.width, ctx.layer.height);
@@ -717,7 +795,7 @@ class Document {
717
795
  if (viewBox)
718
796
  matrix = multiply(matrix, viewBoxTransform(viewBox, width, height, node.attrs.preserveAspectRatio));
719
797
  const inner = { ...ctx, matrix, viewport: viewBox ? { width: viewBox[2], height: viewBox[3] } : { width, height } };
720
- if (/^(visible|auto)$/.test(node.attrs.overflow || ''))
798
+ if (overflowVisible(node))
721
799
  return this.renderChildren(node, inner);
722
800
  this.clipped(ctx, x, y, width, height, layer => this.renderChildren(node, { ...inner, layer }));
723
801
  }
@@ -731,6 +809,8 @@ class Document {
731
809
  const x = parseLength(node.attrs.x, ctx.viewport, 16, 'x');
732
810
  const y = parseLength(node.attrs.y, ctx.viewport, 16, 'y');
733
811
  const matrix = multiply(ctx.matrix, [1, 0, 0, 1, x, y]);
812
+ let content = target.attrs.transform ? originTransform(target.attrs.transform, target.attrs['transform-origin'], ctx.viewport) : [1, 0, 0, 1, 0, 0];
813
+ const contextElement = { style: ctx.style, matrix, viewport: ctx.viewport, bbox: () => this.groupBoundingBox(target, ctx.viewport, content), outer: ctx.contextElement };
734
814
  if (target.name === 'symbol' || target.name === 'svg') {
735
815
  const style = this.computeStyle(target, ctx.style);
736
816
  if (style.display === 'none')
@@ -746,9 +826,12 @@ class Document {
746
826
  if (target.name === 'svg')
747
827
  outer = multiply(outer, [1, 0, 0, 1, parseLength(target.attrs.x, ctx.viewport, 16, 'x'), parseLength(target.attrs.y, ctx.viewport, 16, 'y')]);
748
828
  const inner = viewBox ? multiply(outer, viewBoxTransform(viewBox, width, height, target.attrs.preserveAspectRatio)) : outer;
829
+ const inverse = invert(matrix);
830
+ if (inverse)
831
+ content = multiply(inverse, inner);
749
832
  const opacity = clamp01(parseNumber(style.opacity, 1));
750
- const innerContext = { ...ctx, matrix: inner, style, viewport: viewBox ? { width: viewBox[2], height: viewBox[3] } : { width, height }, instanced: true };
751
- const draw = (layer) => /^(visible|auto)$/.test(target.attrs.overflow || '')
833
+ const innerContext = { ...ctx, matrix: inner, style, viewport: viewBox ? { width: viewBox[2], height: viewBox[3] } : { width, height }, instanced: true, contextElement };
834
+ const draw = (layer) => overflowVisible(target)
752
835
  ? this.renderChildren(target, { ...innerContext, layer })
753
836
  : this.clipped({ ...ctx, matrix: outer, layer }, 0, 0, width, height, inner => this.renderChildren(target, { ...innerContext, layer: inner }));
754
837
  if (opacity >= 1)
@@ -760,10 +843,396 @@ class Document {
760
843
  }
761
844
  const computed = target.computed, computedParent = target.computedParent;
762
845
  target.computed = null;
763
- this.renderNode(target, { ...ctx, matrix, instanced: true });
846
+ this.renderNode(target, { ...ctx, matrix, instanced: true, contextElement });
764
847
  target.computed = computed;
765
848
  target.computedParent = computedParent;
766
849
  }
850
+ get fonts() {
851
+ return this.embedded.length ? [...this.embedded, ...this.given] : this.given;
852
+ }
853
+ textOf(node, style, viewport, scale = 1) {
854
+ const cached = this.texts.get(node);
855
+ if (cached && cached.style === style && cached.width === viewport.width && cached.height === viewport.height && cached.scale === scale)
856
+ return cached.layout;
857
+ let layout = null;
858
+ const fonts = this.fonts;
859
+ if (fonts.length) {
860
+ try {
861
+ layout = layOutText(this.textInput(node, style, viewport, scale), fonts);
862
+ }
863
+ catch (err) {
864
+ if (!(err instanceof RangeError))
865
+ throw err;
866
+ }
867
+ }
868
+ this.texts.set(node, { style, width: viewport.width, height: viewport.height, scale, layout });
869
+ return layout;
870
+ }
871
+ textInput(text, textStyle, viewport, scale) {
872
+ const leaves = [];
873
+ const preserveOf = (node, inherited) => node.attrs['xml:space'] === undefined ? inherited : node.attrs['xml:space'] === 'preserve';
874
+ const trim = (value, preserve) => {
875
+ value = value.replace(/[\r\n\t]/g, ' ');
876
+ return preserve ? value : value.replace(/ {2,}/g, ' ');
877
+ };
878
+ const allText = (node) => node.content ? node.content.map(c => typeof c === 'string' ? c : allText(c)).join('')
879
+ : node.text + node.children.map(allText).join('');
880
+ let preserve = false;
881
+ for (let p = text; p; p = p.parent)
882
+ if (p.attrs['xml:space'] !== undefined) {
883
+ preserve = p.attrs['xml:space'] === 'preserve';
884
+ break;
885
+ }
886
+ const build = (node, style, parent, preserve, depth) => {
887
+ const item = { node, style, parent, children: [] };
888
+ for (const child of node.content ?? []) {
889
+ if (typeof child === 'string') {
890
+ const leaf = { text: trim(child, preserve), item, preserve, depth };
891
+ item.children.push(leaf);
892
+ leaves.push(leaf);
893
+ continue;
894
+ }
895
+ const name = child.name === 'a' ? 'tspan' : child.name;
896
+ if (!child.svg || !['tspan', 'tref', 'textPath'].includes(name) || (name === 'textPath' && node !== text))
897
+ continue;
898
+ const childPreserve = preserveOf(child, preserve);
899
+ const childItem = name === 'tref' ? { node: child, style: this.computeStyle(child, style), parent: item, children: [] }
900
+ : build(child, this.computeStyle(child, style), item, childPreserve, depth + 1);
901
+ if (name === 'tref') {
902
+ const target = this.reference(this.href(child));
903
+ const value = target && target.svg && SVG_ELEMENTS.has(target.name) ? allText(target) : '';
904
+ if (value) {
905
+ const leaf = { text: trim(value, childPreserve), item: childItem, preserve: childPreserve, depth: depth + 1 };
906
+ childItem.children.push(leaf);
907
+ leaves.push(leaf);
908
+ }
909
+ }
910
+ item.children.push(childItem);
911
+ }
912
+ return item;
913
+ };
914
+ const root = build(text, textStyle, null, preserve, 0);
915
+ const dropFirst = (leaf) => { if (leaf.text[0] === ' ')
916
+ leaf.text = leaf.text.slice(1); };
917
+ const dropLast = (leaf) => { if (leaf.text.endsWith(' '))
918
+ leaf.text = leaf.text.slice(0, -1); };
919
+ if (leaves.length === 1) {
920
+ const leaf = leaves[0];
921
+ if (!leaf.preserve) {
922
+ if (leaf.text === ' ')
923
+ leaf.text = '';
924
+ else {
925
+ dropFirst(leaf);
926
+ dropLast(leaf);
927
+ }
928
+ }
929
+ }
930
+ else {
931
+ let lastNonEmpty = null;
932
+ for (let i = 0; i < leaves.length - 1; i++) {
933
+ let a = leaves[i];
934
+ const b = leaves[i + 1], depthA = leaves[i].depth, depthB = b.depth;
935
+ if (!a.text && lastNonEmpty)
936
+ a = lastNonEmpty;
937
+ const c1 = a.text[0], c2 = a.text[a.text.length - 1], c3 = b.text[0], c4 = b.text[b.text.length - 1];
938
+ if (depthA < depthB) {
939
+ if (c3 === ' ' && !b.preserve)
940
+ dropFirst(b);
941
+ }
942
+ else if (c2 === ' ' && c2 === c3) {
943
+ if (!a.preserve && !b.preserve)
944
+ dropLast(a);
945
+ else if (a.preserve && !b.preserve)
946
+ dropFirst(b);
947
+ }
948
+ const first = i === 0, last = i === leaves.length - 2;
949
+ if (first && c1 === ' ' && !a.preserve && a.text)
950
+ dropFirst(a);
951
+ else if (last && c4 === ' ' && b.text && !b.preserve)
952
+ dropLast(b);
953
+ if (last && c2 === ' ' && a.text && !b.text)
954
+ dropLast(a);
955
+ if (a.text.trim())
956
+ lastNonEmpty = a;
957
+ }
958
+ }
959
+ const codepoints = new Map();
960
+ for (const leaf of leaves)
961
+ codepoints.set(leaf, Array.from(leaf.text, c => c.codePointAt(0)));
962
+ const count = (item) => item.children.reduce((n, c) => n + ('text' in c ? codepoints.get(c).length : count(c)), 0);
963
+ const total = count(root);
964
+ const fontSizeOf = (item) => parseFloat(item.style['font-size']);
965
+ const xs = new Array(total).fill(null), ys = new Array(total).fill(null);
966
+ const dx = new Array(total).fill(0), dy = new Array(total).fill(0), rotations = new Array(total).fill(0);
967
+ const lengths = (value, axis, item) => value === undefined ? null : value.split(/[\s,]+/).filter(Boolean).map(v => parseLength(v, viewport, fontSizeOf(item), axis));
968
+ let offset = 0, lastAngle = 0;
969
+ const positions = (item) => {
970
+ const chars = count(item), name = item.node.name;
971
+ if (name === 'text' || name === 'tspan' || name === 'tref' || name === 'a') {
972
+ for (const [list, value, axis] of [[xs, item.node.attrs.x, 'x'], [ys, item.node.attrs.y, 'y'], [dx, item.node.attrs.dx, 'x'], [dy, item.node.attrs.dy, 'y']]) {
973
+ const parsed = lengths(value, axis, item);
974
+ if (parsed)
975
+ for (let i = 0; i < Math.min(parsed.length, chars); i++)
976
+ list[offset + i] = parsed[i];
977
+ }
978
+ }
979
+ const rotate = item.node.attrs.rotate?.trim();
980
+ if (rotate !== undefined && rotate.split(/[\s,]+/).filter(Boolean).every(v => NUMBER_OR_PERCENTAGE.test(v) && !v.endsWith('%'))) {
981
+ const angles = parseNumberList(rotate);
982
+ for (let i = 0; i < chars; i++) {
983
+ if (i < angles.length)
984
+ lastAngle = angles[i];
985
+ rotations[offset + i] = lastAngle;
986
+ }
987
+ }
988
+ for (const child of item.children) {
989
+ if ('text' in child)
990
+ offset += codepoints.get(child).length;
991
+ else
992
+ positions(child);
993
+ }
994
+ };
995
+ positions(root);
996
+ const chunks = [];
997
+ let chars = 0, split = false, flow = null;
998
+ const visible = (item) => item.style.display !== 'none' && this.passesConditions(item.node);
999
+ const decoration = (item, kind) => {
1000
+ const has = (style) => (style['text-decoration'] ?? '').split(/\s+/).includes(kind);
1001
+ let found = false;
1002
+ for (let p = item; p; p = p.parent)
1003
+ if (has(p.style))
1004
+ found = true;
1005
+ for (let n = text.parent; !found && n && n.name !== '#root'; n = n.parent)
1006
+ if (has(this.styleOf(n)))
1007
+ found = true;
1008
+ if (!found)
1009
+ return null;
1010
+ for (let p = item; p; p = p.parent)
1011
+ if (has(p.style) || p.node === text)
1012
+ return p.style;
1013
+ return textStyle;
1014
+ };
1015
+ const span = (item, start, end) => {
1016
+ const style = item.style, fontSize = fontSizeOf(item);
1017
+ const shifts = [];
1018
+ for (let p = item; p && p.node !== text; p = p.parent) {
1019
+ const value = p.style['baseline-shift']?.trim();
1020
+ if (value === undefined)
1021
+ continue;
1022
+ if (value === 'sub' || value === 'super')
1023
+ shifts.push(value);
1024
+ else if (/%$/.test(value))
1025
+ shifts.push(fontSizeOf(p) * parseFloat(value) / 100);
1026
+ else if (LENGTH.test(value))
1027
+ shifts.push(parseLength(value, viewport, fontSizeOf(p), 'y'));
1028
+ else
1029
+ shifts.push(0);
1030
+ }
1031
+ let dominant = style['dominant-baseline'];
1032
+ if (dominant === 'no-change')
1033
+ dominant = (item.parent ? item.parent.style['dominant-baseline'] : 'auto');
1034
+ const textLength = item.node.attrs.textLength !== undefined && LENGTH.test(item.node.attrs.textLength.trim())
1035
+ ? parseLength(item.node.attrs.textLength, viewport, fontSize, 'x') : null;
1036
+ const spacing = (value) => !value || value === 'normal' ? 0 : parseLength(value, viewport, fontSize, 'x');
1037
+ const stretch = { 'ultra-condensed': 1, 'extra-condensed': 2, condensed: 3, narrower: 3, 'semi-condensed': 4, 'semi-expanded': 6, expanded: 7,
1038
+ wider: 7, 'extra-expanded': 8, 'ultra-expanded': 9 }[style['font-stretch']] ?? 5;
1039
+ const fontStyle = style['font-style'] === 'italic' || style['font-style'] === 'oblique' ? style['font-style'] : 'normal';
1040
+ return {
1041
+ start, end, paint: style, visible: style.visibility === 'visible',
1042
+ font: { families: parseFontFamilies(style['font-family'] ?? ''), weight: Number(style['font-weight']), style: fontStyle, stretch },
1043
+ fontSize, smallCaps: style['font-variant'] === 'small-caps',
1044
+ kerning: !(style.kerning !== undefined && style.kerning !== 'auto' && parseLength(style.kerning, viewport, fontSize, 'x') === 0) && style['font-kerning'] !== 'none',
1045
+ letterSpacing: spacing(style['letter-spacing']), wordSpacing: spacing(style['word-spacing']),
1046
+ textLength: textLength !== null && textLength >= 0 ? textLength : null, spacingAndGlyphs: item.node.attrs.lengthAdjust === 'spacingAndGlyphs',
1047
+ dominantBaseline: dominant, alignmentBaseline: (style['alignment-baseline'] ?? 'auto'),
1048
+ baselineShift: shifts.every(v => v === 0) ? [] : shifts,
1049
+ underline: decoration(item, 'underline'), overline: decoration(item, 'overline'), lineThrough: decoration(item, 'line-through'),
1050
+ };
1051
+ };
1052
+ const collect = (item) => {
1053
+ for (const child of item.children) {
1054
+ if (!('text' in child)) {
1055
+ if (child.node.name === 'textPath') {
1056
+ const resolved = this.textPathOf(child.node, viewport, fontSizeOf(child));
1057
+ if (!resolved) {
1058
+ chars += count(child);
1059
+ continue;
1060
+ }
1061
+ flow = resolved;
1062
+ split = true;
1063
+ }
1064
+ collect(child);
1065
+ flow = null;
1066
+ if (child.node.name === 'textPath')
1067
+ split = true;
1068
+ continue;
1069
+ }
1070
+ const cps = codepoints.get(child);
1071
+ if (!visible(item) || !(fontSizeOf(item) > 0)) {
1072
+ chars += cps.length;
1073
+ continue;
1074
+ }
1075
+ let current = null;
1076
+ for (const cp of cps) {
1077
+ let chunk = chunks[chunks.length - 1];
1078
+ if (xs[chars] !== null || ys[chars] !== null || split || !chunk) {
1079
+ chunk = { x: xs[chars], y: ys[chars], anchor: (item.style['text-anchor'] ?? 'start'), codepoints: [], offset: chars, spans: [], path: flow };
1080
+ chunks.push(chunk);
1081
+ current = null;
1082
+ }
1083
+ split = false;
1084
+ if (!current)
1085
+ chunk.spans.push(current = span(item, chunk.codepoints.length, chunk.codepoints.length));
1086
+ chunk.codepoints.push(cp);
1087
+ current.end++;
1088
+ chars++;
1089
+ }
1090
+ }
1091
+ };
1092
+ collect(root);
1093
+ const mode = textStyle['writing-mode'];
1094
+ return { chunks, dx, dy, rotate: rotations, vertical: mode === 'tb' || mode === 'tb-rl' || mode === 'vertical-rl' || mode === 'vertical-lr', scale };
1095
+ }
1096
+ textPathOf(node, viewport, fontSize) {
1097
+ const target = this.reference(this.href(node));
1098
+ const raw = target ? shapePath(target, viewport, fontSize) : null;
1099
+ if (!target || !raw || !raw.length)
1100
+ return null;
1101
+ const m = target.attrs.transform ? originTransform(target.attrs.transform, target.attrs['transform-origin'], viewport) : null;
1102
+ const path = m ? raw.map(c => [c[0], ...transformPoints(c.slice(1), m)]) : raw;
1103
+ const offset = (node.attrs.startOffset ?? '').trim();
1104
+ const startOffset = /%$/.test(offset) ? pathLength(path) * parseFloat(offset) / 100 : parseLength(offset || '0', viewport, fontSize, 'x');
1105
+ return { path, startOffset: Number.isFinite(startOffset) ? startOffset : 0 };
1106
+ }
1107
+ renderText(node, ctx) {
1108
+ const m = ctx.matrix, layout = this.textOf(node, ctx.style, ctx.viewport, Math.sqrt(Math.hypot(m[0], m[1]) * Math.hypot(m[2], m[3])) / this.outputScale);
1109
+ if (!layout)
1110
+ return;
1111
+ const crisp = ctx.style['text-rendering'] === 'optimizeSpeed';
1112
+ const paint = (path, style, order) => {
1113
+ const textStyle = { ...style, 'fill-rule': 'nonzero', 'paint-order': order, 'marker-start': 'none', 'marker-mid': 'none', 'marker-end': 'none', 'shape-rendering': crisp ? 'crispEdges' : 'auto', visibility: 'visible' };
1114
+ this.paintPath(path, node, { ...ctx, style: textStyle }, layout.bbox);
1115
+ };
1116
+ for (const span of layout.spans) {
1117
+ if (!span.visible)
1118
+ continue;
1119
+ for (const d of span.before)
1120
+ paint(d.path, d.paint, 'normal');
1121
+ if (span.glyphs.length)
1122
+ paint(span.glyphs, span.paint, span.paint['paint-order']);
1123
+ for (const glyph of span.colors)
1124
+ this.renderColorGlyph(glyph, span.paint, node, ctx, paint);
1125
+ for (const d of span.after)
1126
+ paint(d.path, d.paint, 'normal');
1127
+ }
1128
+ }
1129
+ renderColorGlyph(g, style, node, ctx, paint) {
1130
+ const font = g.face.font, tables = colorTablesOf(font);
1131
+ const m = multiply(ctx.matrix, g.matrix);
1132
+ const fill = parseColor(style.fill === 'currentColor' ? style.color : style.fill) ?? [0, 0, 0, 1];
1133
+ const foreground = (Math.round(fill[0] * 255) << 24 | Math.round(fill[1] * 255) << 16 | Math.round(fill[2] * 255) << 8 | Math.round(fill[3] * 255)) >>> 0;
1134
+ const hex = (color) => '#' + color.toString(16).padStart(8, '0');
1135
+ const image = (raster, matrix) => drawRaster(ctx.layer, raster, matrix, 2);
1136
+ if (g.kind === 'layers') {
1137
+ for (const layer of tables.layers?.(g.glyph) ?? []) {
1138
+ const path = [];
1139
+ placeOutline(path, font.outline(layer.glyph), g.matrix);
1140
+ paint(path, { ...style, fill: hex(layer.color ?? foreground), 'fill-opacity': '1', stroke: 'none' }, 'normal');
1141
+ }
1142
+ }
1143
+ else if (g.kind === 'paint' && tables.paints) {
1144
+ const s = Math.sqrt(Math.abs(m[0] * m[3] - m[1] * m[2]));
1145
+ if (!(s > 0))
1146
+ return;
1147
+ const bitmap = renderPaintGlyph(font, tables.paints, g.glyph, s, 0, foreground, glyph => font.outline(glyph), (path, clip) => rasterizeGlyph(path, 1, 0, clip));
1148
+ if (!bitmap)
1149
+ return;
1150
+ const premultiplied = new Float32Array(bitmap.data.length);
1151
+ for (let i = 0; i < premultiplied.length; i++)
1152
+ premultiplied[i] = bitmap.data[i] / 255;
1153
+ image({ width: bitmap.width, height: bitmap.height, pixels: bitmap.data, premultiplied }, multiply(m, [1 / s, 0, 0, -1 / s, bitmap.left / s, bitmap.top / s]));
1154
+ }
1155
+ else if (g.kind === 'bitmap') {
1156
+ const s = Math.sqrt(Math.abs(m[0] * m[3] - m[1] * m[2]));
1157
+ const bitmap = tables.bitmaps(Math.round(s * font.unitsPerEm))?.(g.glyph) ?? tables.bitmaps(g.fontSize)?.(g.glyph);
1158
+ if (!bitmap)
1159
+ return;
1160
+ let decoded;
1161
+ try {
1162
+ decoded = decodePNG(bitmap.png);
1163
+ }
1164
+ catch {
1165
+ return;
1166
+ }
1167
+ const k = font.unitsPerEm / bitmap.ppem;
1168
+ let left = bitmap.left * k, top = bitmap.top * k;
1169
+ if (font.tables.sbix && !font.tables.CBDT) {
1170
+ let xMin = Infinity, yMin = Infinity;
1171
+ for (const c of font.outline(g.glyph))
1172
+ for (let i = 1; i + 1 < c.length; i += 2) {
1173
+ xMin = Math.min(xMin, c[i]);
1174
+ yMin = Math.min(yMin, c[i + 1]);
1175
+ }
1176
+ if (!Number.isFinite(xMin))
1177
+ xMin = yMin = 0;
1178
+ left -= xMin;
1179
+ top += Math.abs(yMin) < 1e-3 ? -0.128 * font.unitsPerEm : yMin;
1180
+ }
1181
+ image(decoded, multiply(m, [k, 0, 0, -k, left, top]));
1182
+ }
1183
+ else if (g.kind === 'svg') {
1184
+ const doc = this.glyphDocument(font, tables.svg?.(g.glyph) ?? null);
1185
+ doc?.renderElement(`glyph${g.glyph}`, multiply(m, [1, 0, 0, -1, 0, 0]), ctx.layer, ctx.depth + 1, { style, matrix: ctx.matrix, viewport: ctx.viewport, bbox: () => this.textOf(node, ctx.style, ctx.viewport)?.bbox ?? null });
1186
+ }
1187
+ }
1188
+ glyphDocument(font, data) {
1189
+ if (!data)
1190
+ return null;
1191
+ let documents = glyphDocuments.get(font);
1192
+ if (!documents)
1193
+ glyphDocuments.set(font, documents = new Map());
1194
+ if (!documents.has(data.byteOffset)) {
1195
+ let doc = null;
1196
+ try {
1197
+ const root = parseXML(svgText(data)).children.find(n => n.name === 'svg' && n.svg);
1198
+ if (root)
1199
+ doc = new Document(root);
1200
+ }
1201
+ catch {
1202
+ doc = null;
1203
+ }
1204
+ documents.set(data.byteOffset, doc);
1205
+ }
1206
+ const doc = documents.get(data.byteOffset) ?? null;
1207
+ if (doc) {
1208
+ doc.images = this.images;
1209
+ doc.budget = this.budget;
1210
+ }
1211
+ return doc;
1212
+ }
1213
+ renderElement(id, matrix, layer, depth, contextElement) {
1214
+ const node = this.ids.get(id);
1215
+ if (!node || depth > 32)
1216
+ return;
1217
+ const style = node.parent && node.parent.name !== '#root' ? this.styleOf(node.parent) : null;
1218
+ const { width, height } = documentSize(this.root);
1219
+ const ctx = { matrix, style, viewport: { width, height }, layer, depth, instanced: true, contextElement };
1220
+ if (node.name === 'svg')
1221
+ this.renderChildren(node, { ...ctx, style: this.computeStyle(node, style) });
1222
+ else
1223
+ this.renderNode(node, ctx);
1224
+ }
1225
+ textOutlines(node, style, viewport) {
1226
+ const layout = this.textOf(node, style, viewport);
1227
+ if (!layout)
1228
+ return null;
1229
+ const path = [];
1230
+ for (const span of layout.spans)
1231
+ if (span.visible)
1232
+ for (const part of [...span.before, { path: span.glyphs }, ...span.after])
1233
+ path.push(...part.path);
1234
+ return path.length ? path : null;
1235
+ }
767
1236
  renderImage(node, ctx) {
768
1237
  const style = ctx.style;
769
1238
  const image = this.imageOf(node, ctx.viewport);
@@ -776,18 +1245,12 @@ class Document {
776
1245
  if (nested) {
777
1246
  nested.document.images = this.images;
778
1247
  nested.document.budget = this.budget;
1248
+ nested.document.given = this.given;
779
1249
  nested.document.renderRoot(matrix, layer, ctx.depth + 1, true);
780
1250
  return;
781
1251
  }
782
- const pixels = raster;
783
- const inverse = invert(matrix);
784
- const coverage = inverse && rasterize([transformPoints([0, 0, pixels.width, 0, pixels.width, pixels.height, 0, pixels.height], matrix)], false, layer.width, layer.height);
785
- if (!coverage)
786
- return;
787
1252
  const rendering = style['image-rendering'];
788
- const translated = Math.abs(matrix[0] - 1) < 1e-6 && Math.abs(matrix[3] - 1) < 1e-6 && matrix[1] === 0 && matrix[2] === 0;
789
- const filter = translated || /^(optimizeSpeed|crisp-edges|pixelated)$/i.test(rendering || '') ? 0 : rendering === 'smooth' ? 1 : 2;
790
- layer.fill(coverage, sampler(premultiplied(pixels), pixels.width, pixels.height, inverse, false, filter, 1));
1253
+ drawRaster(layer, raster, matrix, /^(optimizeSpeed|crisp-edges|pixelated)$/i.test(rendering || '') ? 0 : rendering === 'smooth' ? 1 : 2);
791
1254
  };
792
1255
  if (/\bslice\s*$/.test(aspect))
793
1256
  this.clipped(ctx, x, y, width, height, draw);
@@ -822,48 +1285,72 @@ class Document {
822
1285
  }
823
1286
  renderRoot(matrix, layer, depth, instanced = false) {
824
1287
  const { root } = this;
1288
+ this.outputScale = Math.sqrt(Math.hypot(matrix[0], matrix[1]) * Math.hypot(matrix[2], matrix[3])) || 1;
825
1289
  const viewBox = parseViewBox(root.attrs.viewBox);
826
1290
  const { width, height } = documentSize(root);
827
1291
  let matrix0 = matrix;
828
1292
  const rootStyle = this.computeStyle(root, null);
829
1293
  if (rootStyle.transform)
830
- matrix0 = multiply(matrix0, parseTransform(rootStyle.transform));
1294
+ matrix0 = multiply(matrix0, transformOf(rootStyle, { width, height }, '50% 50%'));
831
1295
  if (viewBox)
832
1296
  matrix0 = multiply(matrix0, viewBoxTransform(viewBox, width, height, root.attrs.preserveAspectRatio));
833
1297
  const viewport = viewBox ? { width: viewBox[2], height: viewBox[3] } : { width, height };
1298
+ const background = parseColor(rootStyle['background-color']);
1299
+ if (background && background[3] > 0) {
1300
+ const [x, y, w, h] = viewBox || [0, 0, width, height];
1301
+ const coverage = rasterize([transformPoints([x, y, x + w, y, x + w, y + h, x, y + h], matrix0)], false, layer.width, layer.height);
1302
+ if (coverage)
1303
+ layer.fill(coverage, solidPaint(background));
1304
+ }
834
1305
  this.renderNode(root, { matrix: matrix0, style: null, viewport, layer, depth, instanced }, true);
835
1306
  }
836
- paintPath(path, node, ctx) {
837
- const { matrix, layer } = ctx;
1307
+ paintPath(path, node, ctx, box) {
1308
+ const { matrix } = ctx;
838
1309
  const style = ctx.style;
839
1310
  if (style.visibility === 'hidden' || style.visibility === 'collapse')
840
1311
  return;
841
1312
  const scale = Math.sqrt(Math.abs(matrix[0] * matrix[3] - matrix[1] * matrix[2])) || 1e-9;
842
1313
  const tolerance = 0.1 / scale;
843
1314
  const subpaths = flatten(path, tolerance);
844
- const bbox = boundingBox(subpaths);
845
- const fill = this.paint(style.fill, style, bbox, matrix, style['fill-opacity'], ctx);
846
- if (fill && node.name !== 'line') {
847
- const polygons = subpaths.map(points => transformPoints(points.points, matrix));
848
- const coverage = rasterize(polygons, style['fill-rule'] === 'evenodd', layer.width, layer.height);
849
- if (coverage)
850
- layer.fill(coverage, fill);
1315
+ const bbox = box === undefined ? boundingBox(subpaths) : box;
1316
+ for (const part of paintOrder(style['paint-order'])) {
1317
+ if (part === 'fill')
1318
+ this.paintFill(subpaths, bbox, node, ctx);
1319
+ else if (part === 'stroke')
1320
+ this.paintStroke(subpaths, bbox, tolerance, ctx);
1321
+ else if (style.visibility === 'visible')
1322
+ this.renderMarkers(path, bbox, node, ctx);
851
1323
  }
1324
+ }
1325
+ paintFill(subpaths, bbox, node, ctx) {
1326
+ const { matrix, layer } = ctx;
1327
+ const style = ctx.style;
1328
+ const fill = node.name === 'line' ? null : this.paint(style.fill, style, bbox, matrix, style['fill-opacity'], ctx);
1329
+ if (!fill)
1330
+ return;
1331
+ const polygons = subpaths.map(points => transformPoints(points.points, matrix));
1332
+ const coverage = rasterize(polygons, style['fill-rule'] === 'evenodd', layer.width, layer.height);
1333
+ if (coverage)
1334
+ layer.fill(crisp(coverage, style), fill);
1335
+ }
1336
+ paintStroke(subpaths, bbox, tolerance, ctx) {
1337
+ const { matrix, layer } = ctx;
1338
+ const style = ctx.style;
852
1339
  const stroke = this.paint(style.stroke, style, bbox, matrix, style['stroke-opacity'], ctx);
853
1340
  const strokeWidth = parseLength(style['stroke-width'], ctx.viewport, 16, 'diagonal');
854
- if (stroke && strokeWidth > 0) {
855
- let lines = subpaths;
856
- const fontSize = parseNumber(style['font-size'], 16);
857
- const dashes = parseDashArray(style['stroke-dasharray'], ctx.viewport, fontSize);
858
- if (dashes)
859
- lines = dash(subpaths, dashes, parseLength(style['stroke-dashoffset'], ctx.viewport, fontSize, 'diagonal'));
860
- const polygons = strokePolygons(lines, strokeWidth / 2, style['stroke-linecap'], style['stroke-linejoin'], Math.max(1, parseNumber(style['stroke-miterlimit'], 4)), tolerance).map(points => transformPoints(points, matrix));
861
- const coverage = rasterize(polygons, false, layer.width, layer.height);
862
- if (coverage)
863
- layer.fill(coverage, stroke);
864
- }
1341
+ if (!stroke || !(strokeWidth > 0))
1342
+ return;
1343
+ let lines = subpaths;
1344
+ const fontSize = parseNumber(style['font-size'], 16);
1345
+ const dashes = parseDashArray(style['stroke-dasharray'], ctx.viewport, fontSize);
1346
+ if (dashes)
1347
+ lines = dash(subpaths, dashes, parseLength(style['stroke-dashoffset'], ctx.viewport, fontSize, 'diagonal'));
1348
+ const polygons = strokePolygons(lines, strokeWidth / 2, style['stroke-linecap'], style['stroke-linejoin'], Math.max(1, parseNumber(style['stroke-miterlimit'], 4)), tolerance).map(points => transformPoints(points, matrix));
1349
+ const coverage = rasterize(polygons, false, layer.width, layer.height);
1350
+ if (coverage)
1351
+ layer.fill(crisp(coverage, style), stroke);
865
1352
  }
866
- renderMarkers(path, node, ctx) {
1353
+ renderMarkers(path, bbox, node, ctx) {
867
1354
  const style = ctx.style;
868
1355
  for (let p = node.parent; p; p = p.parent)
869
1356
  if (p.name === 'clipPath')
@@ -892,11 +1379,12 @@ class Document {
892
1379
  const inverse = invert(viewBoxMatrix);
893
1380
  if (!inverse)
894
1381
  continue;
895
- const clip = /^(visible|auto)$/.test(marker.attrs.overflow?.trim() || '') ? null
1382
+ const clip = overflowVisible(marker) ? null
896
1383
  : transformPoints([0, 0, width, height], inverse);
897
1384
  const orient = (marker.attrs.orient || '').trim();
898
1385
  const fixed = orient === 'auto' || orient === 'auto-start-reverse' ? null : parseAngle(orient);
899
1386
  const markerStyle = this.styleOf(marker);
1387
+ const contextElement = { style, matrix: ctx.matrix, viewport: ctx.viewport, bbox: () => bbox, outer: ctx.contextElement };
900
1388
  const draw = (x, y, index) => {
901
1389
  let angle = fixed ?? vertexAngle(segments, index);
902
1390
  if (orient === 'auto-start-reverse' && index === 0)
@@ -907,7 +1395,7 @@ class Document {
907
1395
  matrix = multiply(matrix, [cos, sin, -sin, cos, 0, 0]);
908
1396
  }
909
1397
  matrix = multiply(matrix, [sx * units, 0, 0, sy * units, -refX * sx * units, -refY * sy * units]);
910
- const inner = { ...ctx, matrix, style: markerStyle, depth: ctx.depth + 1, viewport: viewBox ? { width: viewBox[2], height: viewBox[3] } : ctx.viewport };
1398
+ const inner = { ...ctx, matrix, style: markerStyle, depth: ctx.depth + 1, viewport: viewBox ? { width: viewBox[2], height: viewBox[3] } : ctx.viewport, contextElement };
911
1399
  this.active.add(marker);
912
1400
  if (!clip)
913
1401
  this.renderChildren(marker, inner);
@@ -938,6 +1426,12 @@ class Document {
938
1426
  paint(value, style, bbox, matrix, opacityValue, ctx) {
939
1427
  if (!value || value === 'none')
940
1428
  return null;
1429
+ if (value === 'context-fill' || value === 'context-stroke') {
1430
+ const element = ctx.contextElement;
1431
+ if (!element)
1432
+ return null;
1433
+ return this.paint(element.style[value === 'context-fill' ? 'fill' : 'stroke'], element.style, element.bbox(), element.matrix, opacityValue, { ...ctx, viewport: element.viewport, contextElement: element.outer });
1434
+ }
941
1435
  const opacity = clamp01(parseNumber(opacityValue, 1));
942
1436
  let color = value;
943
1437
  if (/^url\(/.test(value)) {
@@ -973,6 +1467,8 @@ class Document {
973
1467
  for (const name of names)
974
1468
  if (attrs[name] === undefined && current.attrs[name] !== undefined)
975
1469
  attrs[name] = current.attrs[name];
1470
+ if (attrs.gradientTransform === current.attrs.gradientTransform && attrs['transform-origin'] === undefined)
1471
+ attrs['transform-origin'] = this.styleOf(current)['transform-origin'] ?? '';
976
1472
  if (!stops) {
977
1473
  const own = current.children.filter(child => child.name === 'stop');
978
1474
  if (own.length)
@@ -997,8 +1493,8 @@ class Document {
997
1493
  return c[3] * opacity > 0 ? solidPaint([c[0], c[1], c[2], c[3] * opacity]) : null;
998
1494
  }
999
1495
  const objectBox = attrs.gradientUnits !== 'userSpaceOnUse';
1000
- if (objectBox && (!bbox || bbox.width <= 0 || bbox.height <= 0))
1001
- return null;
1496
+ if (objectBox && noArea(bbox))
1497
+ return undefined;
1002
1498
  const coordinate = (value, fallback, axis) => {
1003
1499
  if (value === undefined)
1004
1500
  return fallback;
@@ -1010,7 +1506,7 @@ class Document {
1010
1506
  if (objectBox && bbox)
1011
1507
  gradientMatrix = multiply(gradientMatrix, [bbox.width, 0, 0, bbox.height, bbox.x, bbox.y]);
1012
1508
  if (attrs.gradientTransform)
1013
- gradientMatrix = multiply(gradientMatrix, parseTransform(attrs.gradientTransform));
1509
+ gradientMatrix = multiply(gradientMatrix, originTransform(attrs.gradientTransform, attrs['transform-origin'], ctx.viewport));
1014
1510
  const inverse = invert(gradientMatrix);
1015
1511
  if (!inverse)
1016
1512
  return null;
@@ -1088,6 +1584,8 @@ class Document {
1088
1584
  for (const name of names)
1089
1585
  if (attrs[name] === undefined && current.attrs[name] !== undefined)
1090
1586
  attrs[name] = current.attrs[name];
1587
+ if (attrs.patternTransform === current.attrs.patternTransform && attrs['transform-origin'] === undefined)
1588
+ attrs['transform-origin'] = this.styleOf(current)['transform-origin'] ?? '';
1091
1589
  if (!content && current.children.some(child => child.svg))
1092
1590
  content = current;
1093
1591
  }
@@ -1100,7 +1598,10 @@ class Document {
1100
1598
  const objectBox = attrs.patternUnits !== 'userSpaceOnUse';
1101
1599
  const contentBox = attrs.patternContentUnits === 'objectBoundingBox';
1102
1600
  const viewBox = parseViewBox(attrs.viewBox);
1103
- if ((objectBox || (contentBox && !viewBox)) && (!bbox || bbox.width <= 0 || bbox.height <= 0))
1601
+ const noBox = noArea(bbox);
1602
+ if (objectBox && noBox)
1603
+ return undefined;
1604
+ if (contentBox && !viewBox && noBox)
1104
1605
  return null;
1105
1606
  const box = bbox || { x: 0, y: 0, width: 0, height: 0 };
1106
1607
  const coordinate = (name, axis) => {
@@ -1116,7 +1617,7 @@ class Document {
1116
1617
  return null;
1117
1618
  let patternMatrix = matrix, rotated = matrix[1] !== 0 || matrix[2] !== 0;
1118
1619
  if (attrs.patternTransform) {
1119
- const transform = parseTransform(attrs.patternTransform), transformed = multiply(patternMatrix, transform);
1620
+ const transform = originTransform(attrs.patternTransform, attrs['transform-origin'], ctx.viewport), transformed = multiply(patternMatrix, transform);
1120
1621
  if (invert(transformed)) {
1121
1622
  patternMatrix = transformed;
1122
1623
  rotated ||= transform[1] !== 0 || transform[2] !== 0;
@@ -1372,8 +1873,7 @@ class Document {
1372
1873
  }
1373
1874
  case 'feBlend': {
1374
1875
  const mode = node.attrs.mode?.trim() || 'normal';
1375
- const modes = /^(normal|multiply|screen|overlay|darken|lighten|color-dodge|color-burn|hard-light|soft-light|difference|exclusion|hue|saturation|color|luminosity)$/;
1376
- return { type: 'blend', mode: modes.test(mode) ? mode : 'normal', input: input('in'), input2: input('in2') };
1876
+ return { type: 'blend', mode: BLEND_MODES.has(mode) && mode !== 'plus-lighter' ? mode : 'normal', input: input('in'), input2: input('in2') };
1377
1877
  }
1378
1878
  case 'feMorphology': {
1379
1879
  let rx = scale[0], ry = scale[1];
@@ -1581,11 +2081,11 @@ class Document {
1581
2081
  this.active.add(clip);
1582
2082
  let clipMatrix = matrix;
1583
2083
  if (style.transform)
1584
- clipMatrix = multiply(clipMatrix, parseTransform(style.transform));
2084
+ clipMatrix = multiply(clipMatrix, transformOf(style, context.viewport));
1585
2085
  if (clip.attrs.clipPathUnits === 'objectBoundingBox') {
1586
2086
  const path = shapePath(node, context.viewport, 16);
1587
2087
  const bbox = path ? boundingBox(flatten(path, 0.1)) : this.groupBoundingBox(node, context.viewport);
1588
- if (!bbox || bbox.width <= 0 || bbox.height <= 0)
2088
+ if (!bbox || noArea(bbox))
1589
2089
  return alpha;
1590
2090
  clipMatrix = multiply(clipMatrix, [bbox.width, 0, 0, bbox.height, bbox.x, bbox.y]);
1591
2091
  }
@@ -1597,7 +2097,7 @@ class Document {
1597
2097
  continue;
1598
2098
  let childMatrix = clipMatrix;
1599
2099
  if (childStyle.transform)
1600
- childMatrix = multiply(childMatrix, parseTransform(childStyle.transform));
2100
+ childMatrix = multiply(childMatrix, transformOf(childStyle, context.viewport));
1601
2101
  let shape = child;
1602
2102
  if (child.name === 'use') {
1603
2103
  const target = this.reference(this.href(child));
@@ -1606,15 +2106,16 @@ class Document {
1606
2106
  childMatrix = multiply(childMatrix, [1, 0, 0, 1, parseLength(child.attrs.x, context.viewport, 16, 'x'), parseLength(child.attrs.y, context.viewport, 16, 'y')]);
1607
2107
  const targetStyle = this.computeStyle(target, childStyle);
1608
2108
  if (targetStyle.transform)
1609
- childMatrix = multiply(childMatrix, parseTransform(targetStyle.transform));
2109
+ childMatrix = multiply(childMatrix, transformOf(targetStyle, context.viewport));
1610
2110
  shape = target;
1611
2111
  }
1612
- const path = shapePath(shape, context.viewport, 16);
2112
+ const text = shape.name === 'text';
2113
+ const path = text ? this.textOutlines(shape, childStyle, context.viewport) : shapePath(shape, context.viewport, 16);
1613
2114
  if (!path)
1614
2115
  continue;
1615
2116
  const scale = Math.sqrt(Math.abs(childMatrix[0] * childMatrix[3] - childMatrix[1] * childMatrix[2])) || 1e-9;
1616
2117
  const polygons = flatten(path, 0.1 / scale).map(points => transformPoints(points.points, childMatrix));
1617
- const coverage = rasterize(polygons, this.computeStyle(shape, childStyle)['clip-rule'] === 'evenodd', width, height);
2118
+ const coverage = rasterize(polygons, !text && this.computeStyle(shape, childStyle)['clip-rule'] === 'evenodd', width, height);
1618
2119
  if (!coverage)
1619
2120
  continue;
1620
2121
  const own = this.reference(childStyle['clip-path']);
@@ -1638,12 +2139,19 @@ class Document {
1638
2139
  this.active.delete(clip);
1639
2140
  return alpha;
1640
2141
  }
1641
- groupBoundingBox(node, viewport) {
2142
+ textBox(node, viewport) {
2143
+ const layout = this.textOf(node, this.styleOf(node), viewport);
2144
+ if (!layout)
2145
+ return null;
2146
+ const { x, y, width, height } = layout.bbox;
2147
+ return [['M', x, y], ['L', x + width, y], ['L', x + width, y + height], ['L', x, y + height], ['Z']];
2148
+ }
2149
+ groupBoundingBox(node, viewport, matrix = [1, 0, 0, 1, 0, 0]) {
1642
2150
  let box = null;
1643
2151
  const visit = (n, matrix) => {
1644
2152
  const image = n.name === 'image' ? this.imageOf(n, viewport) : null;
1645
2153
  const path = image ? [['M', image.x, image.y], ['L', image.x + image.width, image.y], ['L', image.x + image.width, image.y + image.height],
1646
- ['L', image.x, image.y + image.height], ['Z']] : shapePath(n, viewport, 16);
2154
+ ['L', image.x, image.y + image.height], ['Z']] : n.name === 'text' ? this.textBox(n, viewport) : shapePath(n, viewport, 16);
1647
2155
  if (path) {
1648
2156
  const points = flatten(path, 0.1).map(p => transformPoints(p.points, matrix));
1649
2157
  const b = boundingBox(points.map(p => ({ points: p })));
@@ -1651,9 +2159,10 @@ class Document {
1651
2159
  box = box ? union(box, b) : b;
1652
2160
  }
1653
2161
  for (const child of n.children)
1654
- visit(child, child.attrs.transform ? multiply(matrix, parseTransform(child.attrs.transform)) : matrix);
2162
+ if (child.svg && this.styleOf(child).display !== 'none')
2163
+ visit(child, child.attrs.transform ? multiply(matrix, originTransform(child.attrs.transform, child.attrs['transform-origin'], viewport)) : matrix);
1655
2164
  };
1656
- visit(node, [1, 0, 0, 1, 0, 0]);
2165
+ visit(node, matrix);
1657
2166
  return box;
1658
2167
  }
1659
2168
  maskValues(mask, node, matrix, context) {
@@ -1663,7 +2172,7 @@ class Document {
1663
2172
  const bbox = path ? boundingBox(flatten(path, 0.1)) : this.groupBoundingBox(node, context.viewport);
1664
2173
  const userSpace = mask.attrs.maskUnits === 'userSpaceOnUse';
1665
2174
  const contentBox = mask.attrs.maskContentUnits === 'objectBoundingBox';
1666
- if ((!userSpace || contentBox) && (!bbox || bbox.width <= 0 || bbox.height <= 0))
2175
+ if ((!userSpace || contentBox) && noArea(bbox))
1667
2176
  return values;
1668
2177
  const box = bbox || { x: 0, y: 0, width: 0, height: 0 };
1669
2178
  const fraction = (name, fallback) => {
@@ -2101,11 +2610,24 @@ class Layer {
2101
2610
  d[i + 3] = a + d[i + 3] * inv;
2102
2611
  }
2103
2612
  }
2104
- composite(layer, opacity, mask) {
2613
+ composite(layer, opacity, mask, blend = 'normal') {
2105
2614
  if (layer.x1 <= layer.x0)
2106
2615
  return;
2107
2616
  this.extend(layer.x0, layer.y0, layer.x1, layer.y1);
2108
2617
  const s = layer.data, d = this.data;
2618
+ if (blend !== 'normal') {
2619
+ for (let y = layer.y0; y < layer.y1; y++) {
2620
+ for (let p = y * this.width + layer.x0, end = y * this.width + layer.x1, i = p * 4; p < end; p++, i += 4) {
2621
+ const f = mask ? opacity * mask[p] : opacity;
2622
+ if (s[i + 3] <= 0 || f <= 0)
2623
+ continue;
2624
+ blendPixel(blend, s[i] * f, s[i + 1] * f, s[i + 2] * f, s[i + 3] * f, d, i);
2625
+ for (let k = i; k < i + 4; k++)
2626
+ d[k] = Math.min(Math.max(d[k], 0), 1);
2627
+ }
2628
+ }
2629
+ return;
2630
+ }
2109
2631
  for (let y = layer.y0; y < layer.y1; y++) {
2110
2632
  for (let p = y * this.width + layer.x0, end = y * this.width + layer.x1, i = p * 4; p < end; p++, i += 4) {
2111
2633
  if (s[i + 3] <= 0)
@@ -2140,6 +2662,14 @@ class Layer {
2140
2662
  return new Uint8Array(out.buffer);
2141
2663
  }
2142
2664
  }
2665
+ function crisp(coverage, style) {
2666
+ if (style['shape-rendering'] !== 'crispEdges' && style['shape-rendering'] !== 'optimizeSpeed')
2667
+ return coverage;
2668
+ const { data } = coverage;
2669
+ for (let i = 0; i < data.length; i++)
2670
+ data[i] = data[i] >= 0.5 ? 1 : 0;
2671
+ return coverage;
2672
+ }
2143
2673
  function rasterize(polygons, evenOdd, width, height) {
2144
2674
  const edges = [];
2145
2675
  let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
@@ -2313,8 +2843,13 @@ function shapePath(node, viewport, fontSize) {
2313
2843
  function parsePath(d) {
2314
2844
  const path = [];
2315
2845
  const items = [];
2316
- for (const m of d.matchAll(PATH_TOKENS))
2846
+ let end = 0;
2847
+ for (const m of d.matchAll(PATH_TOKENS)) {
2848
+ if (m.index !== end && !/^[\s,]*$/.test(d.slice(end, m.index)))
2849
+ break;
2850
+ end = m.index + m[0].length;
2317
2851
  items.push(m[1] ? { command: m[1] } : m[2]);
2852
+ }
2318
2853
  let i = 0;
2319
2854
  let command = null;
2320
2855
  let x = 0, y = 0, sx = 0, sy = 0;
@@ -2541,6 +3076,12 @@ function flatten(path, tolerance) {
2541
3076
  }
2542
3077
  return subpaths;
2543
3078
  }
3079
+ function noArea(bbox) {
3080
+ if (!bbox)
3081
+ return true;
3082
+ const epsilon = 1e-9 * Math.max(1, Math.abs(bbox.x), Math.abs(bbox.y));
3083
+ return !(bbox.width > epsilon) || !(bbox.height > epsilon);
3084
+ }
2544
3085
  function boundingBox(subpaths) {
2545
3086
  let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
2546
3087
  for (const { points } of subpaths)
@@ -2580,7 +3121,7 @@ function dash(subpaths, pattern, offset) {
2580
3121
  const pts = closed ? [...points, points[0], points[1]] : points;
2581
3122
  let index = 0;
2582
3123
  let remaining = ((offset % total) + total) % total;
2583
- while (remaining >= pattern[index]) {
3124
+ while (remaining > pattern[index] || (remaining === pattern[index] && remaining > 0)) {
2584
3125
  remaining -= pattern[index];
2585
3126
  index = (index + 1) % pattern.length;
2586
3127
  }
@@ -2604,7 +3145,7 @@ function dash(subpaths, pattern, offset) {
2604
3145
  if (on) {
2605
3146
  if (current) {
2606
3147
  current.push(mx, my);
2607
- result.push({ points: current, closed: false });
3148
+ result.push({ points: current, closed: false, direction: [(bx - ax) / length, (by - ay) / length] });
2608
3149
  }
2609
3150
  current = null;
2610
3151
  }
@@ -2649,7 +3190,7 @@ function strokePolygons(subpaths, halfWidth, cap, join, miterLimit, tolerance) {
2649
3190
  }
2650
3191
  add(polygon);
2651
3192
  };
2652
- for (const { points: raw, closed } of subpaths) {
3193
+ for (const { points: raw, closed, direction } of subpaths) {
2653
3194
  const points = [raw[0], raw[1]];
2654
3195
  for (let i = 2; i < raw.length; i += 2)
2655
3196
  if (Math.abs(raw[i] - points[points.length - 2]) > 1e-9 || Math.abs(raw[i + 1] - points[points.length - 1]) > 1e-9)
@@ -2659,10 +3200,11 @@ function strokePolygons(subpaths, halfWidth, cap, join, miterLimit, tolerance) {
2659
3200
  const n = points.length >> 1;
2660
3201
  if (n === 1) {
2661
3202
  const [x, y] = points;
3203
+ const [dx, dy] = direction ? [direction[0] * halfWidth, direction[1] * halfWidth] : [halfWidth, 0];
2662
3204
  if (cap === 'round')
2663
3205
  circle(x, y);
2664
3206
  else if (cap === 'square')
2665
- add([x - halfWidth, y - halfWidth, x + halfWidth, y - halfWidth, x + halfWidth, y + halfWidth, x - halfWidth, y + halfWidth]);
3207
+ add([x - dx + dy, y - dy - dx, x + dx + dy, y + dy - dx, x + dx - dy, y + dy + dx, x - dx - dy, y - dy + dx]);
2666
3208
  continue;
2667
3209
  }
2668
3210
  const segmentCount = closed ? n : n - 1;
@@ -2767,6 +3309,154 @@ function parseTransform(value) {
2767
3309
  }
2768
3310
  return matrix;
2769
3311
  }
3312
+ function fontShorthand(value) {
3313
+ const out = { 'font-style': 'normal', 'font-variant': 'normal', 'font-weight': 'normal', 'font-stretch': 'normal', 'font-kerning': 'auto' };
3314
+ const tokens = value.trim().split(/\s+/);
3315
+ let i = 0;
3316
+ for (; i < tokens.length; i++) {
3317
+ const t = tokens[i];
3318
+ if (t === 'normal')
3319
+ continue;
3320
+ if (t === 'italic' || t === 'oblique')
3321
+ out['font-style'] = t;
3322
+ else if (t === 'small-caps')
3323
+ out['font-variant'] = t;
3324
+ else if (/^(bold|bolder|lighter|[1-9]00)$/.test(t))
3325
+ out['font-weight'] = t;
3326
+ else if (/^(ultra|extra|semi)?-?(condensed|expanded)$/.test(t))
3327
+ out['font-stretch'] = t;
3328
+ else
3329
+ break;
3330
+ }
3331
+ const size = tokens[i]?.split('/')[0];
3332
+ const family = tokens.slice(i + 1).join(' ');
3333
+ if (!size || !family || !(LENGTH.test(size) || /^(xx-small|x-small|small|medium|large|x-large|xx-large|smaller|larger)$/.test(size)))
3334
+ return null;
3335
+ out['font-size'] = size;
3336
+ out['font-family'] = family;
3337
+ return out;
3338
+ }
3339
+ function fontSize(value, parent) {
3340
+ const v = value.trim();
3341
+ const steps = { 'xx-small': -3, 'x-small': -2, small: -1, medium: 0, large: 1, 'x-large': 2, 'xx-large': 3 };
3342
+ if (v in steps)
3343
+ return 16 * 1.2 ** steps[v];
3344
+ if (v === 'smaller')
3345
+ return parent / 1.2;
3346
+ if (v === 'larger')
3347
+ return parent * 1.2;
3348
+ const match = LENGTH.exec(v);
3349
+ if (!match)
3350
+ return parent;
3351
+ const n = parseFloat(match[1]);
3352
+ return match[2] === '%' ? n * parent / 100 : match[2] === 'em' ? n * parent : match[2] === 'ex' ? n * parent / 2 : parseLength(v, null, parent);
3353
+ }
3354
+ function embeddedFonts(css) {
3355
+ const faces = [];
3356
+ css = stripComments(css);
3357
+ for (let at = css.search(/@font-face\s*\{/i); at >= 0;) {
3358
+ const open = css.indexOf('{', at), end = blockEnd(css, open);
3359
+ const declarations = parseDeclarations(css.slice(open + 1, end));
3360
+ const d = { ...declarations.normal, ...declarations.important };
3361
+ const family = parseFontFamilies(d['font-family'] ?? '')[0];
3362
+ const weight = d['font-weight'] === 'bold' ? 700 : /^\d+$/.test(d['font-weight'] ?? '') ? Number(d['font-weight']) : 400;
3363
+ const style = d['font-style'] === 'italic' || d['font-style'] === 'oblique' ? d['font-style'] : 'normal';
3364
+ if (family)
3365
+ for (const [, , url] of (d.src ?? '').matchAll(/url\(\s*(['"]?)([^'")]*)\1\s*\)/g)) {
3366
+ const uri = dataURI(url);
3367
+ if (!uri)
3368
+ continue;
3369
+ let data = uri.data;
3370
+ try {
3371
+ if (data[0] === 0x77 && data[1] === 0x4f && data[2] === 0x46 && data[3] === 0x46)
3372
+ data = fromWOFF(data);
3373
+ }
3374
+ catch {
3375
+ data = null;
3376
+ }
3377
+ const face = data && fontFace(data, { family, weight, style });
3378
+ if (face) {
3379
+ faces.push(face);
3380
+ break;
3381
+ }
3382
+ }
3383
+ const next = css.slice(end + 1).search(/@font-face\s*\{/i);
3384
+ at = next < 0 ? -1 : end + 1 + next;
3385
+ }
3386
+ return faces;
3387
+ }
3388
+ function fromWOFF(data) {
3389
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
3390
+ const count = view.getUint16(12);
3391
+ const tables = [];
3392
+ for (let i = 0; i < count; i++) {
3393
+ const e = 44 + i * 20, offset = view.getUint32(e + 4), compressed = view.getUint32(e + 8), length = view.getUint32(e + 12);
3394
+ const raw = data.subarray(offset, offset + compressed);
3395
+ tables.push({ tag: view.getUint32(e), checksum: view.getUint32(e + 16), data: compressed < length ? decompress(raw, length).subarray(0, length) : raw });
3396
+ }
3397
+ const header = 12 + count * 16;
3398
+ let size = header;
3399
+ for (const t of tables)
3400
+ size += t.data.length + 3 & ~3;
3401
+ const out = new Uint8Array(size), o = new DataView(out.buffer);
3402
+ o.setUint32(0, view.getUint32(4));
3403
+ o.setUint16(4, count);
3404
+ let position = header;
3405
+ tables.forEach((t, i) => {
3406
+ o.setUint32(12 + i * 16, t.tag);
3407
+ o.setUint32(16 + i * 16, t.checksum);
3408
+ o.setUint32(20 + i * 16, position);
3409
+ o.setUint32(24 + i * 16, t.data.length);
3410
+ out.set(t.data, position);
3411
+ position += t.data.length + 3 & ~3;
3412
+ });
3413
+ return out;
3414
+ }
3415
+ function transformOf(style, viewport, fallback) {
3416
+ return originTransform(style.transform, style['transform-origin'] ?? fallback, viewport, parseNumber(style['font-size'], 16));
3417
+ }
3418
+ function originTransform(transform, origin, viewport, fontSize = 16) {
3419
+ const matrix = parseTransform(transform);
3420
+ const at = origin ? parseOrigin(origin, viewport, fontSize) : null;
3421
+ return at ? multiply(multiply([1, 0, 0, 1, at[0], at[1]], matrix), [1, 0, 0, 1, -at[0], -at[1]]) : matrix;
3422
+ }
3423
+ const ORIGIN_KEYWORDS = { left: ['x', '0%'], right: ['x', '100%'], top: ['y', '0%'], bottom: ['y', '100%'], center: [null, '50%'] };
3424
+ function parseOrigin(value, viewport, fontSize) {
3425
+ const parts = value.trim().split(/\s+/);
3426
+ if (parts.length > 3 || (parts.length === 3 && !LENGTH.test(parts[2])))
3427
+ return null;
3428
+ const terms = parts.slice(0, 2).map(part => {
3429
+ const keyword = ORIGIN_KEYWORDS[part];
3430
+ return keyword ? { axis: keyword[0], value: keyword[1] } : LENGTH.test(part) ? { axis: null, value: part } : null;
3431
+ });
3432
+ if (terms.some(term => !term))
3433
+ return null;
3434
+ const center = { axis: null, value: '50%' };
3435
+ let [x, y] = terms;
3436
+ if (!y)
3437
+ [x, y] = x.axis === 'y' ? [center, x] : [x, center];
3438
+ else if (x.axis === 'y' || y.axis === 'x')
3439
+ [x, y] = [y, x];
3440
+ if (x.axis === 'y' || y.axis === 'x')
3441
+ return null;
3442
+ return [parseLength(x.value, viewport, fontSize, 'x'), parseLength(y.value, viewport, fontSize, 'y')];
3443
+ }
3444
+ function paintOrder(value) {
3445
+ const normal = ['fill', 'stroke', 'markers'];
3446
+ const given = value && value !== 'normal' ? value.trim().split(/\s+/) : [];
3447
+ if (given.some((part, i) => !normal.includes(part) || given.indexOf(part) !== i))
3448
+ return [...normal];
3449
+ return [...given, ...normal.filter(part => !given.includes(part))];
3450
+ }
3451
+ function overflowVisible(node) {
3452
+ let value = node.attrs.overflow?.trim();
3453
+ for (let p = node.parent; value === 'inherit'; p = p.parent) {
3454
+ if (!p || p.name === '#root')
3455
+ return true;
3456
+ value = p.attrs.overflow?.trim() ?? (/^(svg|symbol|marker|pattern)$/.test(p.name) && p.parent && p.parent.name !== '#root' ? 'hidden' : 'visible');
3457
+ }
3458
+ return value === 'visible' || value === 'auto';
3459
+ }
2770
3460
  function parseViewBox(value) {
2771
3461
  if (!value)
2772
3462
  return null;