imagescript 3.8.1 → 3.10.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,43 @@ 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
+ const OFFSETS = Float64Array.from({ length: SAMPLES }, (_, s) => (s + 0.5) / SAMPLES);
53
+ export function render(source, mode, size, images = new Map(), fonts = []) {
35
54
  if (typeof source !== 'string')
36
55
  source = decodeUTF8(source);
37
56
  const root = parseXML(source).children.find(node => node.name === 'svg' && node.svg);
@@ -39,6 +58,7 @@ export function render(source, mode, size, images = new Map()) {
39
58
  throw new Error('SVG: no <svg> element');
40
59
  const doc = new Document(root);
41
60
  doc.images = images;
61
+ doc.given = fonts.map(data => fontFace(data)).filter(face => face !== null);
42
62
  const { width, height } = documentSize(root);
43
63
  if (!(width > 0) || !(height > 0))
44
64
  throw new Error('SVG: invalid dimensions');
@@ -72,6 +92,15 @@ function documentSize(root) {
72
92
  };
73
93
  return { width: lengthOf(root.attrs.width, viewBox ? viewBox[2] : 100), height: lengthOf(root.attrs.height, viewBox ? viewBox[3] : 100) };
74
94
  }
95
+ const glyphDocuments = new WeakMap();
96
+ function drawRaster(layer, image, matrix, filter) {
97
+ const inverse = invert(matrix);
98
+ const coverage = inverse && rasterize([transformPoints([0, 0, image.width, 0, image.width, image.height, 0, image.height], matrix)], false, layer.width, layer.height);
99
+ if (!coverage)
100
+ return;
101
+ const translated = Math.abs(matrix[0] - 1) < 1e-6 && Math.abs(matrix[3] - 1) < 1e-6 && matrix[1] === 0 && matrix[2] === 0;
102
+ layer.fill(coverage, sampler(premultiplied(image), image.width, image.height, inverse, false, translated ? 0 : filter, 1));
103
+ }
75
104
  function premultiplied(image) {
76
105
  if (image.premultiplied)
77
106
  return image.premultiplied;
@@ -157,6 +186,7 @@ export function embeddedImages(source) {
157
186
  }
158
187
  const SVG_NS = 'http://www.w3.org/2000/svg';
159
188
  function parseXML(text) {
189
+ text = text.replace(/\r\n?/g, '\n');
160
190
  const root = { name: '#root', attrs: {}, children: [], text: '', svg: false };
161
191
  const stack = [root];
162
192
  const namespaces = [{ '': SVG_NS }];
@@ -186,11 +216,17 @@ function parseXML(text) {
186
216
  return String.fromCodePoint(name[1] === 'x' || name[1] === 'X' ? parseInt(name.slice(2), 16) : parseInt(name.slice(1), 10));
187
217
  return name in entities ? entities[name] : match;
188
218
  });
219
+ const addText = (value) => {
220
+ const node = stack[stack.length - 1];
221
+ node.text += value;
222
+ if (node.content)
223
+ node.content.push(value);
224
+ };
189
225
  let i = 0;
190
226
  while (i < text.length) {
191
227
  if (text[i] !== '<') {
192
228
  const end = text.indexOf('<', i);
193
- stack[stack.length - 1].text += decode(text.slice(i, end === -1 ? text.length : end));
229
+ addText(decode(text.slice(i, end === -1 ? text.length : end)));
194
230
  i = end === -1 ? text.length : end;
195
231
  continue;
196
232
  }
@@ -200,7 +236,7 @@ function parseXML(text) {
200
236
  }
201
237
  else if (text.startsWith('<![CDATA[', i)) {
202
238
  const end = text.indexOf(']]>', i);
203
- stack[stack.length - 1].text += text.slice(i + 9, end === -1 ? text.length : end);
239
+ addText(text.slice(i + 9, end === -1 ? text.length : end));
204
240
  i = end === -1 ? text.length : end + 3;
205
241
  }
206
242
  else if (text.startsWith('<!', i)) {
@@ -262,7 +298,12 @@ function parseXML(text) {
262
298
  close.lastIndex = i;
263
299
  const end = close.exec(text);
264
300
  i = end ? close.lastIndex : text.length;
265
- stack[stack.length - 1].children.push(node);
301
+ const parent = stack[stack.length - 1];
302
+ parent.children.push(node);
303
+ if (parent.content)
304
+ parent.content.push(node);
305
+ if (parent.content || (node.name === 'text' && node.svg))
306
+ node.content = [];
266
307
  if (!end || !end[1]) {
267
308
  stack.push(node);
268
309
  namespaces.push(scope);
@@ -438,7 +479,27 @@ function parseSelector(selector) {
438
479
  function parseDeclarations(text) {
439
480
  const declarations = { normal: {}, important: {} };
440
481
  text = stripComments(text);
441
- for (const part of text.split(';')) {
482
+ const parts = [];
483
+ let depth = 0, quote = '', start = 0;
484
+ for (let i = 0; i < text.length; i++) {
485
+ const c = text[i];
486
+ if (quote) {
487
+ if (c === quote)
488
+ quote = '';
489
+ }
490
+ else if (c === '"' || c === '\'')
491
+ quote = c;
492
+ else if (c === '(')
493
+ depth++;
494
+ else if (c === ')')
495
+ depth = Math.max(0, depth - 1);
496
+ else if (c === ';' && !depth) {
497
+ parts.push(text.slice(start, i));
498
+ start = i + 1;
499
+ }
500
+ }
501
+ parts.push(text.slice(start));
502
+ for (const part of parts) {
442
503
  const colon = part.indexOf(':');
443
504
  if (colon === -1)
444
505
  continue;
@@ -483,6 +544,10 @@ class Document {
483
544
  rules;
484
545
  images = new Map();
485
546
  nested = new Map();
547
+ embedded;
548
+ given = [];
549
+ outputScale = 1;
550
+ texts = new WeakMap();
486
551
  constructor(root) {
487
552
  this.ids = new Map();
488
553
  this.active = new Set();
@@ -501,6 +566,7 @@ class Document {
501
566
  }
502
567
  this.root = root;
503
568
  this.rules = parseStyleSheet(styles.join('\n'));
569
+ this.embedded = embeddedFonts(styles.join('\n'));
504
570
  for (const name of ['fill', 'stroke'])
505
571
  this.breakPatternCycles(name);
506
572
  this.breakImageCycles();
@@ -573,13 +639,15 @@ class Document {
573
639
  if (name === 'marker')
574
640
  for (const kind of ['marker-start', 'marker-mid', 'marker-end'])
575
641
  own[kind] = declarations[name];
642
+ else if (name === 'font')
643
+ Object.assign(own, fontShorthand(declarations[name]) ?? {});
576
644
  else if (validProperty(name, declarations[name]))
577
645
  own[name] = declarations[name];
578
646
  }
579
647
  };
580
648
  const presentation = {};
581
649
  for (const name in node.attrs)
582
- if (PROPERTIES.has(name))
650
+ if (PROPERTIES.has(name) && !CSS_ONLY.has(name))
583
651
  presentation[name] = node.attrs[name].trim();
584
652
  apply(presentation);
585
653
  const rules = this.rules.filter(rule => rule.match(node));
@@ -594,7 +662,7 @@ class Document {
594
662
  apply(inline.important);
595
663
  const style = {};
596
664
  for (const name of PROPERTIES) {
597
- if (name === 'transform')
665
+ if (name === 'transform' || name === 'transform-origin')
598
666
  continue;
599
667
  let value = own[name];
600
668
  if (value === 'inherit' || (value === undefined && INHERITED.has(name)))
@@ -603,8 +671,19 @@ class Document {
603
671
  value = DEFAULTS[name];
604
672
  style[name] = value === undefined ? undefined : String(value).trim();
605
673
  }
674
+ const parentSize = parent ? parseFloat(parent['font-size']) : 16;
675
+ style['font-size'] = String(own['font-size'] !== undefined && own['font-size'] !== 'inherit' ? fontSize(own['font-size'], parentSize) : parentSize);
676
+ const parentWeight = parent ? Number(parent['font-weight']) : 400, weight = own['font-weight'];
677
+ style['font-weight'] = String(weight === undefined || weight === 'inherit' ? parentWeight : weight === 'normal' ? 400 : weight === 'bold' ? 700
678
+ : weight === 'bolder' ? Math.min(900, parentWeight + (parentWeight === 400 ? 300 : 100))
679
+ : weight === 'lighter' ? Math.max(100, parentWeight - (parentWeight === 400 ? 200 : 100))
680
+ : /^[1-9]00$/.test(weight) ? Number(weight) : parentWeight);
606
681
  style['mask-type'] = own['mask-type'] || node.attrs['mask-type'];
682
+ style['mix-blend-mode'] = own['mix-blend-mode'];
683
+ style.isolation = own.isolation;
684
+ style['background-color'] = own['background-color'];
607
685
  style.transform = own.transform;
686
+ style['transform-origin'] = own['transform-origin'];
608
687
  node.computed = style;
609
688
  node.computedParent = parent;
610
689
  return style;
@@ -637,7 +716,7 @@ class Document {
637
716
  return;
638
717
  let matrix = context.matrix;
639
718
  if (style.transform && !root)
640
- matrix = multiply(matrix, parseTransform(style.transform));
719
+ matrix = multiply(matrix, transformOf(style, context.viewport));
641
720
  const opacity = clamp01(parseNumber(style.opacity, 1));
642
721
  if (opacity <= 0)
643
722
  return;
@@ -664,18 +743,18 @@ class Document {
664
743
  }
665
744
  case 'use': return this.renderUse(node, ctx);
666
745
  case 'image': return this.renderImage(node, ctx);
746
+ case 'text': return this.renderText(node, ctx);
667
747
  default: {
668
748
  const path = shapePath(node, ctx.viewport, parseNumber(style['font-size'], 16));
669
749
  if (!path)
670
750
  return;
671
751
  this.paintPath(path, node, ctx);
672
- if (style.visibility === 'visible')
673
- this.renderMarkers(path, node, ctx);
674
752
  }
675
753
  }
676
754
  };
677
755
  const draw = filters && filters.length ? (layer) => this.filtered(filters, matrix, layer, drawContent) : (layer) => drawContent(layer);
678
- if (opacity >= 1 && !clipping && !masking)
756
+ const blend = style['mix-blend-mode'] && BLEND_MODES.has(style['mix-blend-mode']) ? style['mix-blend-mode'] : 'normal';
757
+ if (opacity >= 1 && !clipping && !masking && blend === 'normal' && style.isolation !== 'isolate')
679
758
  return draw(context.layer);
680
759
  const layer = new Layer(context.layer.width, context.layer.height);
681
760
  draw(layer);
@@ -690,7 +769,7 @@ class Document {
690
769
  else
691
770
  alpha = values;
692
771
  }
693
- context.layer.composite(layer, opacity, alpha);
772
+ context.layer.composite(layer, opacity, alpha, blend);
694
773
  }
695
774
  clipped(ctx, x, y, width, height, draw) {
696
775
  const layer = new Layer(ctx.layer.width, ctx.layer.height);
@@ -717,7 +796,7 @@ class Document {
717
796
  if (viewBox)
718
797
  matrix = multiply(matrix, viewBoxTransform(viewBox, width, height, node.attrs.preserveAspectRatio));
719
798
  const inner = { ...ctx, matrix, viewport: viewBox ? { width: viewBox[2], height: viewBox[3] } : { width, height } };
720
- if (/^(visible|auto)$/.test(node.attrs.overflow || ''))
799
+ if (overflowVisible(node))
721
800
  return this.renderChildren(node, inner);
722
801
  this.clipped(ctx, x, y, width, height, layer => this.renderChildren(node, { ...inner, layer }));
723
802
  }
@@ -731,6 +810,8 @@ class Document {
731
810
  const x = parseLength(node.attrs.x, ctx.viewport, 16, 'x');
732
811
  const y = parseLength(node.attrs.y, ctx.viewport, 16, 'y');
733
812
  const matrix = multiply(ctx.matrix, [1, 0, 0, 1, x, y]);
813
+ let content = target.attrs.transform ? originTransform(target.attrs.transform, target.attrs['transform-origin'], ctx.viewport) : [1, 0, 0, 1, 0, 0];
814
+ const contextElement = { style: ctx.style, matrix, viewport: ctx.viewport, bbox: () => this.groupBoundingBox(target, ctx.viewport, content), outer: ctx.contextElement };
734
815
  if (target.name === 'symbol' || target.name === 'svg') {
735
816
  const style = this.computeStyle(target, ctx.style);
736
817
  if (style.display === 'none')
@@ -746,9 +827,12 @@ class Document {
746
827
  if (target.name === 'svg')
747
828
  outer = multiply(outer, [1, 0, 0, 1, parseLength(target.attrs.x, ctx.viewport, 16, 'x'), parseLength(target.attrs.y, ctx.viewport, 16, 'y')]);
748
829
  const inner = viewBox ? multiply(outer, viewBoxTransform(viewBox, width, height, target.attrs.preserveAspectRatio)) : outer;
830
+ const inverse = invert(matrix);
831
+ if (inverse)
832
+ content = multiply(inverse, inner);
749
833
  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 || '')
834
+ const innerContext = { ...ctx, matrix: inner, style, viewport: viewBox ? { width: viewBox[2], height: viewBox[3] } : { width, height }, instanced: true, contextElement };
835
+ const draw = (layer) => overflowVisible(target)
752
836
  ? this.renderChildren(target, { ...innerContext, layer })
753
837
  : this.clipped({ ...ctx, matrix: outer, layer }, 0, 0, width, height, inner => this.renderChildren(target, { ...innerContext, layer: inner }));
754
838
  if (opacity >= 1)
@@ -760,10 +844,396 @@ class Document {
760
844
  }
761
845
  const computed = target.computed, computedParent = target.computedParent;
762
846
  target.computed = null;
763
- this.renderNode(target, { ...ctx, matrix, instanced: true });
847
+ this.renderNode(target, { ...ctx, matrix, instanced: true, contextElement });
764
848
  target.computed = computed;
765
849
  target.computedParent = computedParent;
766
850
  }
851
+ get fonts() {
852
+ return this.embedded.length ? [...this.embedded, ...this.given] : this.given;
853
+ }
854
+ textOf(node, style, viewport, scale = 1) {
855
+ const cached = this.texts.get(node);
856
+ if (cached && cached.style === style && cached.width === viewport.width && cached.height === viewport.height && cached.scale === scale)
857
+ return cached.layout;
858
+ let layout = null;
859
+ const fonts = this.fonts;
860
+ if (fonts.length) {
861
+ try {
862
+ layout = layOutText(this.textInput(node, style, viewport, scale), fonts);
863
+ }
864
+ catch (err) {
865
+ if (!(err instanceof RangeError))
866
+ throw err;
867
+ }
868
+ }
869
+ this.texts.set(node, { style, width: viewport.width, height: viewport.height, scale, layout });
870
+ return layout;
871
+ }
872
+ textInput(text, textStyle, viewport, scale) {
873
+ const leaves = [];
874
+ const preserveOf = (node, inherited) => node.attrs['xml:space'] === undefined ? inherited : node.attrs['xml:space'] === 'preserve';
875
+ const trim = (value, preserve) => {
876
+ value = value.replace(/[\r\n\t]/g, ' ');
877
+ return preserve ? value : value.replace(/ {2,}/g, ' ');
878
+ };
879
+ const allText = (node) => node.content ? node.content.map(c => typeof c === 'string' ? c : allText(c)).join('')
880
+ : node.text + node.children.map(allText).join('');
881
+ let preserve = false;
882
+ for (let p = text; p; p = p.parent)
883
+ if (p.attrs['xml:space'] !== undefined) {
884
+ preserve = p.attrs['xml:space'] === 'preserve';
885
+ break;
886
+ }
887
+ const build = (node, style, parent, preserve, depth) => {
888
+ const item = { node, style, parent, children: [] };
889
+ for (const child of node.content ?? []) {
890
+ if (typeof child === 'string') {
891
+ const leaf = { text: trim(child, preserve), item, preserve, depth };
892
+ item.children.push(leaf);
893
+ leaves.push(leaf);
894
+ continue;
895
+ }
896
+ const name = child.name === 'a' ? 'tspan' : child.name;
897
+ if (!child.svg || !['tspan', 'tref', 'textPath'].includes(name) || (name === 'textPath' && node !== text))
898
+ continue;
899
+ const childPreserve = preserveOf(child, preserve);
900
+ const childItem = name === 'tref' ? { node: child, style: this.computeStyle(child, style), parent: item, children: [] }
901
+ : build(child, this.computeStyle(child, style), item, childPreserve, depth + 1);
902
+ if (name === 'tref') {
903
+ const target = this.reference(this.href(child));
904
+ const value = target && target.svg && SVG_ELEMENTS.has(target.name) ? allText(target) : '';
905
+ if (value) {
906
+ const leaf = { text: trim(value, childPreserve), item: childItem, preserve: childPreserve, depth: depth + 1 };
907
+ childItem.children.push(leaf);
908
+ leaves.push(leaf);
909
+ }
910
+ }
911
+ item.children.push(childItem);
912
+ }
913
+ return item;
914
+ };
915
+ const root = build(text, textStyle, null, preserve, 0);
916
+ const dropFirst = (leaf) => { if (leaf.text[0] === ' ')
917
+ leaf.text = leaf.text.slice(1); };
918
+ const dropLast = (leaf) => { if (leaf.text.endsWith(' '))
919
+ leaf.text = leaf.text.slice(0, -1); };
920
+ if (leaves.length === 1) {
921
+ const leaf = leaves[0];
922
+ if (!leaf.preserve) {
923
+ if (leaf.text === ' ')
924
+ leaf.text = '';
925
+ else {
926
+ dropFirst(leaf);
927
+ dropLast(leaf);
928
+ }
929
+ }
930
+ }
931
+ else {
932
+ let lastNonEmpty = null;
933
+ for (let i = 0; i < leaves.length - 1; i++) {
934
+ let a = leaves[i];
935
+ const b = leaves[i + 1], depthA = leaves[i].depth, depthB = b.depth;
936
+ if (!a.text && lastNonEmpty)
937
+ a = lastNonEmpty;
938
+ const c1 = a.text[0], c2 = a.text[a.text.length - 1], c3 = b.text[0], c4 = b.text[b.text.length - 1];
939
+ if (depthA < depthB) {
940
+ if (c3 === ' ' && !b.preserve)
941
+ dropFirst(b);
942
+ }
943
+ else if (c2 === ' ' && c2 === c3) {
944
+ if (!a.preserve && !b.preserve)
945
+ dropLast(a);
946
+ else if (a.preserve && !b.preserve)
947
+ dropFirst(b);
948
+ }
949
+ const first = i === 0, last = i === leaves.length - 2;
950
+ if (first && c1 === ' ' && !a.preserve && a.text)
951
+ dropFirst(a);
952
+ else if (last && c4 === ' ' && b.text && !b.preserve)
953
+ dropLast(b);
954
+ if (last && c2 === ' ' && a.text && !b.text)
955
+ dropLast(a);
956
+ if (a.text.trim())
957
+ lastNonEmpty = a;
958
+ }
959
+ }
960
+ const codepoints = new Map();
961
+ for (const leaf of leaves)
962
+ codepoints.set(leaf, Array.from(leaf.text, c => c.codePointAt(0)));
963
+ const count = (item) => item.children.reduce((n, c) => n + ('text' in c ? codepoints.get(c).length : count(c)), 0);
964
+ const total = count(root);
965
+ const fontSizeOf = (item) => parseFloat(item.style['font-size']);
966
+ const xs = new Array(total).fill(null), ys = new Array(total).fill(null);
967
+ const dx = new Array(total).fill(0), dy = new Array(total).fill(0), rotations = new Array(total).fill(0);
968
+ const lengths = (value, axis, item) => value === undefined ? null : value.split(/[\s,]+/).filter(Boolean).map(v => parseLength(v, viewport, fontSizeOf(item), axis));
969
+ let offset = 0, lastAngle = 0;
970
+ const positions = (item) => {
971
+ const chars = count(item), name = item.node.name;
972
+ if (name === 'text' || name === 'tspan' || name === 'tref' || name === 'a') {
973
+ 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']]) {
974
+ const parsed = lengths(value, axis, item);
975
+ if (parsed)
976
+ for (let i = 0; i < Math.min(parsed.length, chars); i++)
977
+ list[offset + i] = parsed[i];
978
+ }
979
+ }
980
+ const rotate = item.node.attrs.rotate?.trim();
981
+ if (rotate !== undefined && rotate.split(/[\s,]+/).filter(Boolean).every(v => NUMBER_OR_PERCENTAGE.test(v) && !v.endsWith('%'))) {
982
+ const angles = parseNumberList(rotate);
983
+ for (let i = 0; i < chars; i++) {
984
+ if (i < angles.length)
985
+ lastAngle = angles[i];
986
+ rotations[offset + i] = lastAngle;
987
+ }
988
+ }
989
+ for (const child of item.children) {
990
+ if ('text' in child)
991
+ offset += codepoints.get(child).length;
992
+ else
993
+ positions(child);
994
+ }
995
+ };
996
+ positions(root);
997
+ const chunks = [];
998
+ let chars = 0, split = false, flow = null;
999
+ const visible = (item) => item.style.display !== 'none' && this.passesConditions(item.node);
1000
+ const decoration = (item, kind) => {
1001
+ const has = (style) => (style['text-decoration'] ?? '').split(/\s+/).includes(kind);
1002
+ let found = false;
1003
+ for (let p = item; p; p = p.parent)
1004
+ if (has(p.style))
1005
+ found = true;
1006
+ for (let n = text.parent; !found && n && n.name !== '#root'; n = n.parent)
1007
+ if (has(this.styleOf(n)))
1008
+ found = true;
1009
+ if (!found)
1010
+ return null;
1011
+ for (let p = item; p; p = p.parent)
1012
+ if (has(p.style) || p.node === text)
1013
+ return p.style;
1014
+ return textStyle;
1015
+ };
1016
+ const span = (item, start, end) => {
1017
+ const style = item.style, fontSize = fontSizeOf(item);
1018
+ const shifts = [];
1019
+ for (let p = item; p && p.node !== text; p = p.parent) {
1020
+ const value = p.style['baseline-shift']?.trim();
1021
+ if (value === undefined)
1022
+ continue;
1023
+ if (value === 'sub' || value === 'super')
1024
+ shifts.push(value);
1025
+ else if (/%$/.test(value))
1026
+ shifts.push(fontSizeOf(p) * parseFloat(value) / 100);
1027
+ else if (LENGTH.test(value))
1028
+ shifts.push(parseLength(value, viewport, fontSizeOf(p), 'y'));
1029
+ else
1030
+ shifts.push(0);
1031
+ }
1032
+ let dominant = style['dominant-baseline'];
1033
+ if (dominant === 'no-change')
1034
+ dominant = (item.parent ? item.parent.style['dominant-baseline'] : 'auto');
1035
+ const textLength = item.node.attrs.textLength !== undefined && LENGTH.test(item.node.attrs.textLength.trim())
1036
+ ? parseLength(item.node.attrs.textLength, viewport, fontSize, 'x') : null;
1037
+ const spacing = (value) => !value || value === 'normal' ? 0 : parseLength(value, viewport, fontSize, 'x');
1038
+ const stretch = { 'ultra-condensed': 1, 'extra-condensed': 2, condensed: 3, narrower: 3, 'semi-condensed': 4, 'semi-expanded': 6, expanded: 7,
1039
+ wider: 7, 'extra-expanded': 8, 'ultra-expanded': 9 }[style['font-stretch']] ?? 5;
1040
+ const fontStyle = style['font-style'] === 'italic' || style['font-style'] === 'oblique' ? style['font-style'] : 'normal';
1041
+ return {
1042
+ start, end, paint: style, visible: style.visibility === 'visible',
1043
+ font: { families: parseFontFamilies(style['font-family'] ?? ''), weight: Number(style['font-weight']), style: fontStyle, stretch },
1044
+ fontSize, smallCaps: style['font-variant'] === 'small-caps',
1045
+ kerning: !(style.kerning !== undefined && style.kerning !== 'auto' && parseLength(style.kerning, viewport, fontSize, 'x') === 0) && style['font-kerning'] !== 'none',
1046
+ letterSpacing: spacing(style['letter-spacing']), wordSpacing: spacing(style['word-spacing']),
1047
+ textLength: textLength !== null && textLength >= 0 ? textLength : null, spacingAndGlyphs: item.node.attrs.lengthAdjust === 'spacingAndGlyphs',
1048
+ dominantBaseline: dominant, alignmentBaseline: (style['alignment-baseline'] ?? 'auto'),
1049
+ baselineShift: shifts.every(v => v === 0) ? [] : shifts,
1050
+ underline: decoration(item, 'underline'), overline: decoration(item, 'overline'), lineThrough: decoration(item, 'line-through'),
1051
+ };
1052
+ };
1053
+ const collect = (item) => {
1054
+ for (const child of item.children) {
1055
+ if (!('text' in child)) {
1056
+ if (child.node.name === 'textPath') {
1057
+ const resolved = this.textPathOf(child.node, viewport, fontSizeOf(child));
1058
+ if (!resolved) {
1059
+ chars += count(child);
1060
+ continue;
1061
+ }
1062
+ flow = resolved;
1063
+ split = true;
1064
+ }
1065
+ collect(child);
1066
+ flow = null;
1067
+ if (child.node.name === 'textPath')
1068
+ split = true;
1069
+ continue;
1070
+ }
1071
+ const cps = codepoints.get(child);
1072
+ if (!visible(item) || !(fontSizeOf(item) > 0)) {
1073
+ chars += cps.length;
1074
+ continue;
1075
+ }
1076
+ let current = null;
1077
+ for (const cp of cps) {
1078
+ let chunk = chunks[chunks.length - 1];
1079
+ if (xs[chars] !== null || ys[chars] !== null || split || !chunk) {
1080
+ chunk = { x: xs[chars], y: ys[chars], anchor: (item.style['text-anchor'] ?? 'start'), codepoints: [], offset: chars, spans: [], path: flow };
1081
+ chunks.push(chunk);
1082
+ current = null;
1083
+ }
1084
+ split = false;
1085
+ if (!current)
1086
+ chunk.spans.push(current = span(item, chunk.codepoints.length, chunk.codepoints.length));
1087
+ chunk.codepoints.push(cp);
1088
+ current.end++;
1089
+ chars++;
1090
+ }
1091
+ }
1092
+ };
1093
+ collect(root);
1094
+ const mode = textStyle['writing-mode'];
1095
+ return { chunks, dx, dy, rotate: rotations, vertical: mode === 'tb' || mode === 'tb-rl' || mode === 'vertical-rl' || mode === 'vertical-lr', scale };
1096
+ }
1097
+ textPathOf(node, viewport, fontSize) {
1098
+ const target = this.reference(this.href(node));
1099
+ const raw = target ? shapePath(target, viewport, fontSize) : null;
1100
+ if (!target || !raw || !raw.length)
1101
+ return null;
1102
+ const m = target.attrs.transform ? originTransform(target.attrs.transform, target.attrs['transform-origin'], viewport) : null;
1103
+ const path = m ? raw.map(c => [c[0], ...transformPoints(c.slice(1), m)]) : raw;
1104
+ const offset = (node.attrs.startOffset ?? '').trim();
1105
+ const startOffset = /%$/.test(offset) ? pathLength(path) * parseFloat(offset) / 100 : parseLength(offset || '0', viewport, fontSize, 'x');
1106
+ return { path, startOffset: Number.isFinite(startOffset) ? startOffset : 0 };
1107
+ }
1108
+ renderText(node, ctx) {
1109
+ 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);
1110
+ if (!layout)
1111
+ return;
1112
+ const crisp = ctx.style['text-rendering'] === 'optimizeSpeed';
1113
+ const paint = (path, style, order) => {
1114
+ 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' };
1115
+ this.paintPath(path, node, { ...ctx, style: textStyle }, layout.bbox);
1116
+ };
1117
+ for (const span of layout.spans) {
1118
+ if (!span.visible)
1119
+ continue;
1120
+ for (const d of span.before)
1121
+ paint(d.path, d.paint, 'normal');
1122
+ if (span.glyphs.length)
1123
+ paint(span.glyphs, span.paint, span.paint['paint-order']);
1124
+ for (const glyph of span.colors)
1125
+ this.renderColorGlyph(glyph, span.paint, node, ctx, paint);
1126
+ for (const d of span.after)
1127
+ paint(d.path, d.paint, 'normal');
1128
+ }
1129
+ }
1130
+ renderColorGlyph(g, style, node, ctx, paint) {
1131
+ const font = g.face.font, tables = colorTablesOf(font);
1132
+ const m = multiply(ctx.matrix, g.matrix);
1133
+ const fill = parseColor(style.fill === 'currentColor' ? style.color : style.fill) ?? [0, 0, 0, 1];
1134
+ 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;
1135
+ const hex = (color) => '#' + color.toString(16).padStart(8, '0');
1136
+ const image = (raster, matrix) => drawRaster(ctx.layer, raster, matrix, 2);
1137
+ if (g.kind === 'layers') {
1138
+ for (const layer of tables.layers?.(g.glyph) ?? []) {
1139
+ const path = [];
1140
+ placeOutline(path, font.outline(layer.glyph), g.matrix);
1141
+ paint(path, { ...style, fill: hex(layer.color ?? foreground), 'fill-opacity': '1', stroke: 'none' }, 'normal');
1142
+ }
1143
+ }
1144
+ else if (g.kind === 'paint' && tables.paints) {
1145
+ const s = Math.sqrt(Math.abs(m[0] * m[3] - m[1] * m[2]));
1146
+ if (!(s > 0))
1147
+ return;
1148
+ const bitmap = renderPaintGlyph(font, tables.paints, g.glyph, s, 0, foreground, glyph => font.outline(glyph), (path, clip) => rasterizeGlyph(path, 1, 0, clip));
1149
+ if (!bitmap)
1150
+ return;
1151
+ const premultiplied = new Float32Array(bitmap.data.length);
1152
+ for (let i = 0; i < premultiplied.length; i++)
1153
+ premultiplied[i] = bitmap.data[i] / 255;
1154
+ 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]));
1155
+ }
1156
+ else if (g.kind === 'bitmap') {
1157
+ const s = Math.sqrt(Math.abs(m[0] * m[3] - m[1] * m[2]));
1158
+ const bitmap = tables.bitmaps(Math.round(s * font.unitsPerEm))?.(g.glyph) ?? tables.bitmaps(g.fontSize)?.(g.glyph);
1159
+ if (!bitmap)
1160
+ return;
1161
+ let decoded;
1162
+ try {
1163
+ decoded = decodePNG(bitmap.png);
1164
+ }
1165
+ catch {
1166
+ return;
1167
+ }
1168
+ const k = font.unitsPerEm / bitmap.ppem;
1169
+ let left = bitmap.left * k, top = bitmap.top * k;
1170
+ if (font.tables.sbix && !font.tables.CBDT) {
1171
+ let xMin = Infinity, yMin = Infinity;
1172
+ for (const c of font.outline(g.glyph))
1173
+ for (let i = 1; i + 1 < c.length; i += 2) {
1174
+ xMin = Math.min(xMin, c[i]);
1175
+ yMin = Math.min(yMin, c[i + 1]);
1176
+ }
1177
+ if (!Number.isFinite(xMin))
1178
+ xMin = yMin = 0;
1179
+ left -= xMin;
1180
+ top += Math.abs(yMin) < 1e-3 ? -0.128 * font.unitsPerEm : yMin;
1181
+ }
1182
+ image(decoded, multiply(m, [k, 0, 0, -k, left, top]));
1183
+ }
1184
+ else if (g.kind === 'svg') {
1185
+ const doc = this.glyphDocument(font, tables.svg?.(g.glyph) ?? null);
1186
+ 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 });
1187
+ }
1188
+ }
1189
+ glyphDocument(font, data) {
1190
+ if (!data)
1191
+ return null;
1192
+ let documents = glyphDocuments.get(font);
1193
+ if (!documents)
1194
+ glyphDocuments.set(font, documents = new Map());
1195
+ if (!documents.has(data.byteOffset)) {
1196
+ let doc = null;
1197
+ try {
1198
+ const root = parseXML(svgText(data)).children.find(n => n.name === 'svg' && n.svg);
1199
+ if (root)
1200
+ doc = new Document(root);
1201
+ }
1202
+ catch {
1203
+ doc = null;
1204
+ }
1205
+ documents.set(data.byteOffset, doc);
1206
+ }
1207
+ const doc = documents.get(data.byteOffset) ?? null;
1208
+ if (doc) {
1209
+ doc.images = this.images;
1210
+ doc.budget = this.budget;
1211
+ }
1212
+ return doc;
1213
+ }
1214
+ renderElement(id, matrix, layer, depth, contextElement) {
1215
+ const node = this.ids.get(id);
1216
+ if (!node || depth > 32)
1217
+ return;
1218
+ const style = node.parent && node.parent.name !== '#root' ? this.styleOf(node.parent) : null;
1219
+ const { width, height } = documentSize(this.root);
1220
+ const ctx = { matrix, style, viewport: { width, height }, layer, depth, instanced: true, contextElement };
1221
+ if (node.name === 'svg')
1222
+ this.renderChildren(node, { ...ctx, style: this.computeStyle(node, style) });
1223
+ else
1224
+ this.renderNode(node, ctx);
1225
+ }
1226
+ textOutlines(node, style, viewport) {
1227
+ const layout = this.textOf(node, style, viewport);
1228
+ if (!layout)
1229
+ return null;
1230
+ const path = [];
1231
+ for (const span of layout.spans)
1232
+ if (span.visible)
1233
+ for (const part of [...span.before, { path: span.glyphs }, ...span.after])
1234
+ path.push(...part.path);
1235
+ return path.length ? path : null;
1236
+ }
767
1237
  renderImage(node, ctx) {
768
1238
  const style = ctx.style;
769
1239
  const image = this.imageOf(node, ctx.viewport);
@@ -776,18 +1246,12 @@ class Document {
776
1246
  if (nested) {
777
1247
  nested.document.images = this.images;
778
1248
  nested.document.budget = this.budget;
1249
+ nested.document.given = this.given;
779
1250
  nested.document.renderRoot(matrix, layer, ctx.depth + 1, true);
780
1251
  return;
781
1252
  }
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
1253
  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));
1254
+ drawRaster(layer, raster, matrix, /^(optimizeSpeed|crisp-edges|pixelated)$/i.test(rendering || '') ? 0 : rendering === 'smooth' ? 1 : 2);
791
1255
  };
792
1256
  if (/\bslice\s*$/.test(aspect))
793
1257
  this.clipped(ctx, x, y, width, height, draw);
@@ -822,48 +1286,72 @@ class Document {
822
1286
  }
823
1287
  renderRoot(matrix, layer, depth, instanced = false) {
824
1288
  const { root } = this;
1289
+ this.outputScale = Math.sqrt(Math.hypot(matrix[0], matrix[1]) * Math.hypot(matrix[2], matrix[3])) || 1;
825
1290
  const viewBox = parseViewBox(root.attrs.viewBox);
826
1291
  const { width, height } = documentSize(root);
827
1292
  let matrix0 = matrix;
828
1293
  const rootStyle = this.computeStyle(root, null);
829
1294
  if (rootStyle.transform)
830
- matrix0 = multiply(matrix0, parseTransform(rootStyle.transform));
1295
+ matrix0 = multiply(matrix0, transformOf(rootStyle, { width, height }, '50% 50%'));
831
1296
  if (viewBox)
832
1297
  matrix0 = multiply(matrix0, viewBoxTransform(viewBox, width, height, root.attrs.preserveAspectRatio));
833
1298
  const viewport = viewBox ? { width: viewBox[2], height: viewBox[3] } : { width, height };
1299
+ const background = parseColor(rootStyle['background-color']);
1300
+ if (background && background[3] > 0) {
1301
+ const [x, y, w, h] = viewBox || [0, 0, width, height];
1302
+ const coverage = rasterize([transformPoints([x, y, x + w, y, x + w, y + h, x, y + h], matrix0)], false, layer.width, layer.height);
1303
+ if (coverage)
1304
+ layer.fill(coverage, solidPaint(background));
1305
+ }
834
1306
  this.renderNode(root, { matrix: matrix0, style: null, viewport, layer, depth, instanced }, true);
835
1307
  }
836
- paintPath(path, node, ctx) {
837
- const { matrix, layer } = ctx;
1308
+ paintPath(path, node, ctx, box) {
1309
+ const { matrix } = ctx;
838
1310
  const style = ctx.style;
839
1311
  if (style.visibility === 'hidden' || style.visibility === 'collapse')
840
1312
  return;
841
1313
  const scale = Math.sqrt(Math.abs(matrix[0] * matrix[3] - matrix[1] * matrix[2])) || 1e-9;
842
1314
  const tolerance = 0.1 / scale;
843
1315
  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);
1316
+ const bbox = box === undefined ? boundingBox(subpaths) : box;
1317
+ for (const part of paintOrder(style['paint-order'])) {
1318
+ if (part === 'fill')
1319
+ this.paintFill(subpaths, bbox, node, ctx);
1320
+ else if (part === 'stroke')
1321
+ this.paintStroke(subpaths, bbox, tolerance, ctx);
1322
+ else if (style.visibility === 'visible')
1323
+ this.renderMarkers(path, bbox, node, ctx);
851
1324
  }
1325
+ }
1326
+ paintFill(subpaths, bbox, node, ctx) {
1327
+ const { matrix, layer } = ctx;
1328
+ const style = ctx.style;
1329
+ const fill = node.name === 'line' ? null : this.paint(style.fill, style, bbox, matrix, style['fill-opacity'], ctx);
1330
+ if (!fill)
1331
+ return;
1332
+ const polygons = subpaths.map(points => transformPoints(points.points, matrix));
1333
+ const coverage = rasterize(polygons, style['fill-rule'] === 'evenodd', layer.width, layer.height);
1334
+ if (coverage)
1335
+ layer.fill(crisp(coverage, style), fill);
1336
+ }
1337
+ paintStroke(subpaths, bbox, tolerance, ctx) {
1338
+ const { matrix, layer } = ctx;
1339
+ const style = ctx.style;
852
1340
  const stroke = this.paint(style.stroke, style, bbox, matrix, style['stroke-opacity'], ctx);
853
1341
  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
- }
1342
+ if (!stroke || !(strokeWidth > 0))
1343
+ return;
1344
+ let lines = subpaths;
1345
+ const fontSize = parseNumber(style['font-size'], 16);
1346
+ const dashes = parseDashArray(style['stroke-dasharray'], ctx.viewport, fontSize);
1347
+ if (dashes)
1348
+ lines = dash(subpaths, dashes, parseLength(style['stroke-dashoffset'], ctx.viewport, fontSize, 'diagonal'));
1349
+ 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));
1350
+ const coverage = rasterize(polygons, false, layer.width, layer.height);
1351
+ if (coverage)
1352
+ layer.fill(crisp(coverage, style), stroke);
865
1353
  }
866
- renderMarkers(path, node, ctx) {
1354
+ renderMarkers(path, bbox, node, ctx) {
867
1355
  const style = ctx.style;
868
1356
  for (let p = node.parent; p; p = p.parent)
869
1357
  if (p.name === 'clipPath')
@@ -892,11 +1380,12 @@ class Document {
892
1380
  const inverse = invert(viewBoxMatrix);
893
1381
  if (!inverse)
894
1382
  continue;
895
- const clip = /^(visible|auto)$/.test(marker.attrs.overflow?.trim() || '') ? null
1383
+ const clip = overflowVisible(marker) ? null
896
1384
  : transformPoints([0, 0, width, height], inverse);
897
1385
  const orient = (marker.attrs.orient || '').trim();
898
1386
  const fixed = orient === 'auto' || orient === 'auto-start-reverse' ? null : parseAngle(orient);
899
1387
  const markerStyle = this.styleOf(marker);
1388
+ const contextElement = { style, matrix: ctx.matrix, viewport: ctx.viewport, bbox: () => bbox, outer: ctx.contextElement };
900
1389
  const draw = (x, y, index) => {
901
1390
  let angle = fixed ?? vertexAngle(segments, index);
902
1391
  if (orient === 'auto-start-reverse' && index === 0)
@@ -907,7 +1396,7 @@ class Document {
907
1396
  matrix = multiply(matrix, [cos, sin, -sin, cos, 0, 0]);
908
1397
  }
909
1398
  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 };
1399
+ const inner = { ...ctx, matrix, style: markerStyle, depth: ctx.depth + 1, viewport: viewBox ? { width: viewBox[2], height: viewBox[3] } : ctx.viewport, contextElement };
911
1400
  this.active.add(marker);
912
1401
  if (!clip)
913
1402
  this.renderChildren(marker, inner);
@@ -938,6 +1427,12 @@ class Document {
938
1427
  paint(value, style, bbox, matrix, opacityValue, ctx) {
939
1428
  if (!value || value === 'none')
940
1429
  return null;
1430
+ if (value === 'context-fill' || value === 'context-stroke') {
1431
+ const element = ctx.contextElement;
1432
+ if (!element)
1433
+ return null;
1434
+ return this.paint(element.style[value === 'context-fill' ? 'fill' : 'stroke'], element.style, element.bbox(), element.matrix, opacityValue, { ...ctx, viewport: element.viewport, contextElement: element.outer });
1435
+ }
941
1436
  const opacity = clamp01(parseNumber(opacityValue, 1));
942
1437
  let color = value;
943
1438
  if (/^url\(/.test(value)) {
@@ -973,6 +1468,8 @@ class Document {
973
1468
  for (const name of names)
974
1469
  if (attrs[name] === undefined && current.attrs[name] !== undefined)
975
1470
  attrs[name] = current.attrs[name];
1471
+ if (attrs.gradientTransform === current.attrs.gradientTransform && attrs['transform-origin'] === undefined)
1472
+ attrs['transform-origin'] = this.styleOf(current)['transform-origin'] ?? '';
976
1473
  if (!stops) {
977
1474
  const own = current.children.filter(child => child.name === 'stop');
978
1475
  if (own.length)
@@ -997,8 +1494,8 @@ class Document {
997
1494
  return c[3] * opacity > 0 ? solidPaint([c[0], c[1], c[2], c[3] * opacity]) : null;
998
1495
  }
999
1496
  const objectBox = attrs.gradientUnits !== 'userSpaceOnUse';
1000
- if (objectBox && (!bbox || bbox.width <= 0 || bbox.height <= 0))
1001
- return null;
1497
+ if (objectBox && noArea(bbox))
1498
+ return undefined;
1002
1499
  const coordinate = (value, fallback, axis) => {
1003
1500
  if (value === undefined)
1004
1501
  return fallback;
@@ -1010,7 +1507,7 @@ class Document {
1010
1507
  if (objectBox && bbox)
1011
1508
  gradientMatrix = multiply(gradientMatrix, [bbox.width, 0, 0, bbox.height, bbox.x, bbox.y]);
1012
1509
  if (attrs.gradientTransform)
1013
- gradientMatrix = multiply(gradientMatrix, parseTransform(attrs.gradientTransform));
1510
+ gradientMatrix = multiply(gradientMatrix, originTransform(attrs.gradientTransform, attrs['transform-origin'], ctx.viewport));
1014
1511
  const inverse = invert(gradientMatrix);
1015
1512
  if (!inverse)
1016
1513
  return null;
@@ -1088,6 +1585,8 @@ class Document {
1088
1585
  for (const name of names)
1089
1586
  if (attrs[name] === undefined && current.attrs[name] !== undefined)
1090
1587
  attrs[name] = current.attrs[name];
1588
+ if (attrs.patternTransform === current.attrs.patternTransform && attrs['transform-origin'] === undefined)
1589
+ attrs['transform-origin'] = this.styleOf(current)['transform-origin'] ?? '';
1091
1590
  if (!content && current.children.some(child => child.svg))
1092
1591
  content = current;
1093
1592
  }
@@ -1100,7 +1599,10 @@ class Document {
1100
1599
  const objectBox = attrs.patternUnits !== 'userSpaceOnUse';
1101
1600
  const contentBox = attrs.patternContentUnits === 'objectBoundingBox';
1102
1601
  const viewBox = parseViewBox(attrs.viewBox);
1103
- if ((objectBox || (contentBox && !viewBox)) && (!bbox || bbox.width <= 0 || bbox.height <= 0))
1602
+ const noBox = noArea(bbox);
1603
+ if (objectBox && noBox)
1604
+ return undefined;
1605
+ if (contentBox && !viewBox && noBox)
1104
1606
  return null;
1105
1607
  const box = bbox || { x: 0, y: 0, width: 0, height: 0 };
1106
1608
  const coordinate = (name, axis) => {
@@ -1116,7 +1618,7 @@ class Document {
1116
1618
  return null;
1117
1619
  let patternMatrix = matrix, rotated = matrix[1] !== 0 || matrix[2] !== 0;
1118
1620
  if (attrs.patternTransform) {
1119
- const transform = parseTransform(attrs.patternTransform), transformed = multiply(patternMatrix, transform);
1621
+ const transform = originTransform(attrs.patternTransform, attrs['transform-origin'], ctx.viewport), transformed = multiply(patternMatrix, transform);
1120
1622
  if (invert(transformed)) {
1121
1623
  patternMatrix = transformed;
1122
1624
  rotated ||= transform[1] !== 0 || transform[2] !== 0;
@@ -1372,8 +1874,7 @@ class Document {
1372
1874
  }
1373
1875
  case 'feBlend': {
1374
1876
  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') };
1877
+ return { type: 'blend', mode: BLEND_MODES.has(mode) && mode !== 'plus-lighter' ? mode : 'normal', input: input('in'), input2: input('in2') };
1377
1878
  }
1378
1879
  case 'feMorphology': {
1379
1880
  let rx = scale[0], ry = scale[1];
@@ -1581,11 +2082,11 @@ class Document {
1581
2082
  this.active.add(clip);
1582
2083
  let clipMatrix = matrix;
1583
2084
  if (style.transform)
1584
- clipMatrix = multiply(clipMatrix, parseTransform(style.transform));
2085
+ clipMatrix = multiply(clipMatrix, transformOf(style, context.viewport));
1585
2086
  if (clip.attrs.clipPathUnits === 'objectBoundingBox') {
1586
2087
  const path = shapePath(node, context.viewport, 16);
1587
2088
  const bbox = path ? boundingBox(flatten(path, 0.1)) : this.groupBoundingBox(node, context.viewport);
1588
- if (!bbox || bbox.width <= 0 || bbox.height <= 0)
2089
+ if (!bbox || noArea(bbox))
1589
2090
  return alpha;
1590
2091
  clipMatrix = multiply(clipMatrix, [bbox.width, 0, 0, bbox.height, bbox.x, bbox.y]);
1591
2092
  }
@@ -1597,7 +2098,7 @@ class Document {
1597
2098
  continue;
1598
2099
  let childMatrix = clipMatrix;
1599
2100
  if (childStyle.transform)
1600
- childMatrix = multiply(childMatrix, parseTransform(childStyle.transform));
2101
+ childMatrix = multiply(childMatrix, transformOf(childStyle, context.viewport));
1601
2102
  let shape = child;
1602
2103
  if (child.name === 'use') {
1603
2104
  const target = this.reference(this.href(child));
@@ -1606,15 +2107,16 @@ class Document {
1606
2107
  childMatrix = multiply(childMatrix, [1, 0, 0, 1, parseLength(child.attrs.x, context.viewport, 16, 'x'), parseLength(child.attrs.y, context.viewport, 16, 'y')]);
1607
2108
  const targetStyle = this.computeStyle(target, childStyle);
1608
2109
  if (targetStyle.transform)
1609
- childMatrix = multiply(childMatrix, parseTransform(targetStyle.transform));
2110
+ childMatrix = multiply(childMatrix, transformOf(targetStyle, context.viewport));
1610
2111
  shape = target;
1611
2112
  }
1612
- const path = shapePath(shape, context.viewport, 16);
2113
+ const text = shape.name === 'text';
2114
+ const path = text ? this.textOutlines(shape, childStyle, context.viewport) : shapePath(shape, context.viewport, 16);
1613
2115
  if (!path)
1614
2116
  continue;
1615
2117
  const scale = Math.sqrt(Math.abs(childMatrix[0] * childMatrix[3] - childMatrix[1] * childMatrix[2])) || 1e-9;
1616
2118
  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);
2119
+ const coverage = rasterize(polygons, !text && this.computeStyle(shape, childStyle)['clip-rule'] === 'evenodd', width, height);
1618
2120
  if (!coverage)
1619
2121
  continue;
1620
2122
  const own = this.reference(childStyle['clip-path']);
@@ -1638,12 +2140,19 @@ class Document {
1638
2140
  this.active.delete(clip);
1639
2141
  return alpha;
1640
2142
  }
1641
- groupBoundingBox(node, viewport) {
2143
+ textBox(node, viewport) {
2144
+ const layout = this.textOf(node, this.styleOf(node), viewport);
2145
+ if (!layout)
2146
+ return null;
2147
+ const { x, y, width, height } = layout.bbox;
2148
+ return [['M', x, y], ['L', x + width, y], ['L', x + width, y + height], ['L', x, y + height], ['Z']];
2149
+ }
2150
+ groupBoundingBox(node, viewport, matrix = [1, 0, 0, 1, 0, 0]) {
1642
2151
  let box = null;
1643
2152
  const visit = (n, matrix) => {
1644
2153
  const image = n.name === 'image' ? this.imageOf(n, viewport) : null;
1645
2154
  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);
2155
+ ['L', image.x, image.y + image.height], ['Z']] : n.name === 'text' ? this.textBox(n, viewport) : shapePath(n, viewport, 16);
1647
2156
  if (path) {
1648
2157
  const points = flatten(path, 0.1).map(p => transformPoints(p.points, matrix));
1649
2158
  const b = boundingBox(points.map(p => ({ points: p })));
@@ -1651,9 +2160,10 @@ class Document {
1651
2160
  box = box ? union(box, b) : b;
1652
2161
  }
1653
2162
  for (const child of n.children)
1654
- visit(child, child.attrs.transform ? multiply(matrix, parseTransform(child.attrs.transform)) : matrix);
2163
+ if (child.svg && this.styleOf(child).display !== 'none')
2164
+ visit(child, child.attrs.transform ? multiply(matrix, originTransform(child.attrs.transform, child.attrs['transform-origin'], viewport)) : matrix);
1655
2165
  };
1656
- visit(node, [1, 0, 0, 1, 0, 0]);
2166
+ visit(node, matrix);
1657
2167
  return box;
1658
2168
  }
1659
2169
  maskValues(mask, node, matrix, context) {
@@ -1663,7 +2173,7 @@ class Document {
1663
2173
  const bbox = path ? boundingBox(flatten(path, 0.1)) : this.groupBoundingBox(node, context.viewport);
1664
2174
  const userSpace = mask.attrs.maskUnits === 'userSpaceOnUse';
1665
2175
  const contentBox = mask.attrs.maskContentUnits === 'objectBoundingBox';
1666
- if ((!userSpace || contentBox) && (!bbox || bbox.width <= 0 || bbox.height <= 0))
2176
+ if ((!userSpace || contentBox) && noArea(bbox))
1667
2177
  return values;
1668
2178
  const box = bbox || { x: 0, y: 0, width: 0, height: 0 };
1669
2179
  const fraction = (name, fallback) => {
@@ -2101,11 +2611,24 @@ class Layer {
2101
2611
  d[i + 3] = a + d[i + 3] * inv;
2102
2612
  }
2103
2613
  }
2104
- composite(layer, opacity, mask) {
2614
+ composite(layer, opacity, mask, blend = 'normal') {
2105
2615
  if (layer.x1 <= layer.x0)
2106
2616
  return;
2107
2617
  this.extend(layer.x0, layer.y0, layer.x1, layer.y1);
2108
2618
  const s = layer.data, d = this.data;
2619
+ if (blend !== 'normal') {
2620
+ for (let y = layer.y0; y < layer.y1; y++) {
2621
+ for (let p = y * this.width + layer.x0, end = y * this.width + layer.x1, i = p * 4; p < end; p++, i += 4) {
2622
+ const f = mask ? opacity * mask[p] : opacity;
2623
+ if (s[i + 3] <= 0 || f <= 0)
2624
+ continue;
2625
+ blendPixel(blend, s[i] * f, s[i + 1] * f, s[i + 2] * f, s[i + 3] * f, d, i);
2626
+ for (let k = i; k < i + 4; k++)
2627
+ d[k] = Math.min(Math.max(d[k], 0), 1);
2628
+ }
2629
+ }
2630
+ return;
2631
+ }
2109
2632
  for (let y = layer.y0; y < layer.y1; y++) {
2110
2633
  for (let p = y * this.width + layer.x0, end = y * this.width + layer.x1, i = p * 4; p < end; p++, i += 4) {
2111
2634
  if (s[i + 3] <= 0)
@@ -2140,9 +2663,30 @@ class Layer {
2140
2663
  return new Uint8Array(out.buffer);
2141
2664
  }
2142
2665
  }
2666
+ const scratch = (() => {
2667
+ const arrays = { f64: [], f32: [], i32: [] };
2668
+ const get = (kind, Type) => (slot, n) => {
2669
+ const list = arrays[kind];
2670
+ if (!list[slot] || list[slot].length < n)
2671
+ list[slot] = new Type(Math.max(n, 2 * (list[slot]?.length ?? 0), 64));
2672
+ return list[slot];
2673
+ };
2674
+ return { f64: get('f64', Float64Array), f32: get('f32', Float32Array), i32: get('i32', Int32Array) };
2675
+ })();
2676
+ function crisp(coverage, style) {
2677
+ if (style['shape-rendering'] !== 'crispEdges' && style['shape-rendering'] !== 'optimizeSpeed')
2678
+ return coverage;
2679
+ const { data } = coverage;
2680
+ for (let i = 0; i < data.length; i++)
2681
+ data[i] = data[i] >= 0.5 ? 1 : 0;
2682
+ return coverage;
2683
+ }
2143
2684
  function rasterize(polygons, evenOdd, width, height) {
2144
- const edges = [];
2145
- let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
2685
+ let numPoints = 0;
2686
+ for (const points of polygons)
2687
+ numPoints += points.length >> 1;
2688
+ const tops = scratch.f64(0, numPoints), bottoms = scratch.f64(1, numPoints), xs = scratch.f64(2, numPoints), slopes = scratch.f64(3, numPoints), dirs = scratch.i32(0, numPoints);
2689
+ let numEdges = 0, minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
2146
2690
  for (const points of polygons) {
2147
2691
  const n = points.length >> 1;
2148
2692
  if (n < 2)
@@ -2155,15 +2699,18 @@ function rasterize(polygons, evenOdd, width, height) {
2155
2699
  continue;
2156
2700
  const down = ay < by;
2157
2701
  const top = down ? ay : by, bottom = down ? by : ay;
2158
- const topX = down ? ax : bx;
2159
- edges.push({ top, bottom, x: topX, slope: (down ? bx - ax : ax - bx) / (bottom - top), dir: down ? 1 : -1 });
2702
+ tops[numEdges] = top;
2703
+ bottoms[numEdges] = bottom;
2704
+ xs[numEdges] = down ? ax : bx;
2705
+ slopes[numEdges] = (down ? bx - ax : ax - bx) / (bottom - top);
2706
+ dirs[numEdges++] = down ? 1 : -1;
2160
2707
  minY = Math.min(minY, top);
2161
2708
  maxY = Math.max(maxY, bottom);
2162
2709
  minX = Math.min(minX, ax, bx);
2163
2710
  maxX = Math.max(maxX, ax, bx);
2164
2711
  }
2165
2712
  }
2166
- if (!edges.length)
2713
+ if (!numEdges)
2167
2714
  return null;
2168
2715
  const x0 = Math.max(0, Math.floor(minX)), x1 = Math.min(width, Math.ceil(maxX));
2169
2716
  const y0 = Math.max(0, Math.floor(minY)), y1 = Math.min(height, Math.ceil(maxY));
@@ -2171,13 +2718,24 @@ function rasterize(polygons, evenOdd, width, height) {
2171
2718
  return null;
2172
2719
  const w = x1 - x0, h = y1 - y0;
2173
2720
  const data = new Float32Array(w * h);
2174
- const row = new Float32Array(w + 2);
2175
- const steps = new Float32Array(w + 2);
2721
+ const row = scratch.f32(0, w + 2);
2722
+ const steps = scratch.f32(1, w + 2);
2176
2723
  const weight = 1 / SAMPLES;
2177
- edges.sort((a, b) => a.top - b.top);
2178
- let next = 0;
2179
- let active = [];
2180
- const crossings = [];
2724
+ const rowStarts = scratch.i32(1, h + 1).fill(0, 0, h + 1), order = scratch.i32(2, numEdges);
2725
+ const startRow = (e) => Math.max(0, Math.floor(tops[e]) - y0);
2726
+ for (let e = 0; e < numEdges; e++)
2727
+ if (startRow(e) < h)
2728
+ rowStarts[startRow(e) + 1]++;
2729
+ for (let r = 0; r < h; r++)
2730
+ rowStarts[r + 1] += rowStarts[r];
2731
+ const placed = scratch.i32(3, h);
2732
+ placed.set(rowStarts.subarray(0, h));
2733
+ for (let e = 0; e < numEdges; e++)
2734
+ if (startRow(e) < h)
2735
+ order[placed[startRow(e)]++] = e;
2736
+ let numActive = 0;
2737
+ const active = scratch.i32(4, numEdges), keys = scratch.f64(4, numEdges), firsts = scratch.i32(5, numEdges), lasts = scratch.i32(6, numEdges);
2738
+ const counts = new Int32Array(SAMPLES), starts = new Int32Array(SAMPLES), ends = new Int32Array(SAMPLES);
2181
2739
  const span = (a, b) => {
2182
2740
  a = Math.max(a, x0) - x0;
2183
2741
  b = Math.min(b, x1) - x0;
@@ -2194,23 +2752,69 @@ function rasterize(polygons, evenOdd, width, height) {
2194
2752
  }
2195
2753
  };
2196
2754
  for (let py = y0; py < y1; py++) {
2197
- row.fill(0);
2198
- steps.fill(0);
2199
- while (next < edges.length && edges[next].top < py + 1)
2200
- active.push(edges[next++]);
2201
- active = active.filter(edge => edge.bottom > py);
2755
+ row.fill(0, 0, w + 2);
2756
+ steps.fill(0, 0, w + 2);
2757
+ let kept = 0;
2758
+ for (let k = 0; k < numActive; k++)
2759
+ if (bottoms[active[k]] > py)
2760
+ active[kept++] = active[k];
2761
+ numActive = kept;
2762
+ for (let k = rowStarts[py - y0]; k < rowStarts[py - y0 + 1]; k++)
2763
+ active[numActive++] = order[k];
2764
+ const mid = py + 0.5;
2765
+ for (let k = 0; k < numActive; k++) {
2766
+ const e = active[k], key = xs[e] + (Math.min(Math.max(mid, tops[e]), bottoms[e]) - tops[e]) * slopes[e];
2767
+ let j = k - 1;
2768
+ for (; j >= 0 && keys[j] > key; j--) {
2769
+ keys[j + 1] = keys[j];
2770
+ active[j + 1] = active[j];
2771
+ }
2772
+ keys[j + 1] = key;
2773
+ active[j + 1] = e;
2774
+ }
2775
+ counts.fill(0);
2776
+ let total = 0;
2777
+ for (let k = 0; k < numActive; k++) {
2778
+ const e = active[k], top = tops[e], bottom = bottoms[e];
2779
+ let s0 = Math.max(0, Math.ceil((top - py) * SAMPLES - 0.5)), s1 = Math.min(SAMPLES - 1, Math.ceil((bottom - py) * SAMPLES - 0.5) - 1);
2780
+ while (s0 > 0 && py + OFFSETS[s0 - 1] >= top)
2781
+ s0--;
2782
+ while (s0 < SAMPLES && !(py + OFFSETS[s0] >= top))
2783
+ s0++;
2784
+ while (s1 < SAMPLES - 1 && py + OFFSETS[s1 + 1] < bottom)
2785
+ s1++;
2786
+ while (s1 >= 0 && !(py + OFFSETS[s1] < bottom))
2787
+ s1--;
2788
+ firsts[k] = s0;
2789
+ lasts[k] = s1;
2790
+ for (let s = s0; s <= s1; s++)
2791
+ counts[s]++;
2792
+ if (s1 >= s0)
2793
+ total += s1 - s0 + 1;
2794
+ }
2795
+ const crossings = scratch.f64(5, 2 * total);
2796
+ for (let s = 0, at = 0; s < SAMPLES; s++) {
2797
+ starts[s] = at;
2798
+ at += 2 * counts[s];
2799
+ }
2800
+ for (let s = 0; s < SAMPLES; s++)
2801
+ ends[s] = starts[s];
2802
+ for (let k = 0; k < numActive; k++) {
2803
+ const e = active[k];
2804
+ for (let s = firsts[k]; s <= lasts[k]; s++) {
2805
+ const sy = py + OFFSETS[s];
2806
+ crossings[ends[s]++] = xs[e] + (sy - tops[e]) * slopes[e];
2807
+ crossings[ends[s]++] = dirs[e];
2808
+ }
2809
+ }
2202
2810
  for (let s = 0; s < SAMPLES; s++) {
2203
- const sy = py + (s + 0.5) / SAMPLES;
2204
- crossings.length = 0;
2205
- for (const edge of active)
2206
- if (sy >= edge.top && sy < edge.bottom)
2207
- crossings.push(edge.x + (sy - edge.top) * edge.slope, edge.dir);
2208
- if (crossings.length < 4)
2811
+ const base = starts[s], end = ends[s];
2812
+ if (end - base < 4)
2209
2813
  continue;
2210
- for (let i = 2; i < crossings.length; i += 2) {
2814
+ for (let i = base + 2; i < end; i += 2) {
2211
2815
  const x = crossings[i], dir = crossings[i + 1];
2212
2816
  let j = i - 2;
2213
- for (; j >= 0 && crossings[j] > x; j -= 2) {
2817
+ for (; j >= base && crossings[j] > x; j -= 2) {
2214
2818
  crossings[j + 2] = crossings[j];
2215
2819
  crossings[j + 3] = crossings[j + 1];
2216
2820
  }
@@ -2218,7 +2822,7 @@ function rasterize(polygons, evenOdd, width, height) {
2218
2822
  crossings[j + 3] = dir;
2219
2823
  }
2220
2824
  let winding = 0;
2221
- for (let i = 0; i < crossings.length - 2; i += 2) {
2825
+ for (let i = base; i < end - 2; i += 2) {
2222
2826
  winding += crossings[i + 1];
2223
2827
  if (evenOdd ? winding & 1 : winding !== 0)
2224
2828
  span(crossings[i], crossings[i + 2]);
@@ -2313,8 +2917,13 @@ function shapePath(node, viewport, fontSize) {
2313
2917
  function parsePath(d) {
2314
2918
  const path = [];
2315
2919
  const items = [];
2316
- for (const m of d.matchAll(PATH_TOKENS))
2920
+ let end = 0;
2921
+ for (const m of d.matchAll(PATH_TOKENS)) {
2922
+ if (m.index !== end && !/^[\s,]*$/.test(d.slice(end, m.index)))
2923
+ break;
2924
+ end = m.index + m[0].length;
2317
2925
  items.push(m[1] ? { command: m[1] } : m[2]);
2926
+ }
2318
2927
  let i = 0;
2319
2928
  let command = null;
2320
2929
  let x = 0, y = 0, sx = 0, sy = 0;
@@ -2541,6 +3150,12 @@ function flatten(path, tolerance) {
2541
3150
  }
2542
3151
  return subpaths;
2543
3152
  }
3153
+ function noArea(bbox) {
3154
+ if (!bbox)
3155
+ return true;
3156
+ const epsilon = 1e-9 * Math.max(1, Math.abs(bbox.x), Math.abs(bbox.y));
3157
+ return !(bbox.width > epsilon) || !(bbox.height > epsilon);
3158
+ }
2544
3159
  function boundingBox(subpaths) {
2545
3160
  let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
2546
3161
  for (const { points } of subpaths)
@@ -2580,7 +3195,7 @@ function dash(subpaths, pattern, offset) {
2580
3195
  const pts = closed ? [...points, points[0], points[1]] : points;
2581
3196
  let index = 0;
2582
3197
  let remaining = ((offset % total) + total) % total;
2583
- while (remaining >= pattern[index]) {
3198
+ while (remaining > pattern[index] || (remaining === pattern[index] && remaining > 0)) {
2584
3199
  remaining -= pattern[index];
2585
3200
  index = (index + 1) % pattern.length;
2586
3201
  }
@@ -2604,7 +3219,7 @@ function dash(subpaths, pattern, offset) {
2604
3219
  if (on) {
2605
3220
  if (current) {
2606
3221
  current.push(mx, my);
2607
- result.push({ points: current, closed: false });
3222
+ result.push({ points: current, closed: false, direction: [(bx - ax) / length, (by - ay) / length] });
2608
3223
  }
2609
3224
  current = null;
2610
3225
  }
@@ -2649,7 +3264,7 @@ function strokePolygons(subpaths, halfWidth, cap, join, miterLimit, tolerance) {
2649
3264
  }
2650
3265
  add(polygon);
2651
3266
  };
2652
- for (const { points: raw, closed } of subpaths) {
3267
+ for (const { points: raw, closed, direction } of subpaths) {
2653
3268
  const points = [raw[0], raw[1]];
2654
3269
  for (let i = 2; i < raw.length; i += 2)
2655
3270
  if (Math.abs(raw[i] - points[points.length - 2]) > 1e-9 || Math.abs(raw[i + 1] - points[points.length - 1]) > 1e-9)
@@ -2659,10 +3274,11 @@ function strokePolygons(subpaths, halfWidth, cap, join, miterLimit, tolerance) {
2659
3274
  const n = points.length >> 1;
2660
3275
  if (n === 1) {
2661
3276
  const [x, y] = points;
3277
+ const [dx, dy] = direction ? [direction[0] * halfWidth, direction[1] * halfWidth] : [halfWidth, 0];
2662
3278
  if (cap === 'round')
2663
3279
  circle(x, y);
2664
3280
  else if (cap === 'square')
2665
- add([x - halfWidth, y - halfWidth, x + halfWidth, y - halfWidth, x + halfWidth, y + halfWidth, x - halfWidth, y + halfWidth]);
3281
+ 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
3282
  continue;
2667
3283
  }
2668
3284
  const segmentCount = closed ? n : n - 1;
@@ -2767,6 +3383,154 @@ function parseTransform(value) {
2767
3383
  }
2768
3384
  return matrix;
2769
3385
  }
3386
+ function fontShorthand(value) {
3387
+ const out = { 'font-style': 'normal', 'font-variant': 'normal', 'font-weight': 'normal', 'font-stretch': 'normal', 'font-kerning': 'auto' };
3388
+ const tokens = value.trim().split(/\s+/);
3389
+ let i = 0;
3390
+ for (; i < tokens.length; i++) {
3391
+ const t = tokens[i];
3392
+ if (t === 'normal')
3393
+ continue;
3394
+ if (t === 'italic' || t === 'oblique')
3395
+ out['font-style'] = t;
3396
+ else if (t === 'small-caps')
3397
+ out['font-variant'] = t;
3398
+ else if (/^(bold|bolder|lighter|[1-9]00)$/.test(t))
3399
+ out['font-weight'] = t;
3400
+ else if (/^(ultra|extra|semi)?-?(condensed|expanded)$/.test(t))
3401
+ out['font-stretch'] = t;
3402
+ else
3403
+ break;
3404
+ }
3405
+ const size = tokens[i]?.split('/')[0];
3406
+ const family = tokens.slice(i + 1).join(' ');
3407
+ if (!size || !family || !(LENGTH.test(size) || /^(xx-small|x-small|small|medium|large|x-large|xx-large|smaller|larger)$/.test(size)))
3408
+ return null;
3409
+ out['font-size'] = size;
3410
+ out['font-family'] = family;
3411
+ return out;
3412
+ }
3413
+ function fontSize(value, parent) {
3414
+ const v = value.trim();
3415
+ const steps = { 'xx-small': -3, 'x-small': -2, small: -1, medium: 0, large: 1, 'x-large': 2, 'xx-large': 3 };
3416
+ if (v in steps)
3417
+ return 16 * 1.2 ** steps[v];
3418
+ if (v === 'smaller')
3419
+ return parent / 1.2;
3420
+ if (v === 'larger')
3421
+ return parent * 1.2;
3422
+ const match = LENGTH.exec(v);
3423
+ if (!match)
3424
+ return parent;
3425
+ const n = parseFloat(match[1]);
3426
+ return match[2] === '%' ? n * parent / 100 : match[2] === 'em' ? n * parent : match[2] === 'ex' ? n * parent / 2 : parseLength(v, null, parent);
3427
+ }
3428
+ function embeddedFonts(css) {
3429
+ const faces = [];
3430
+ css = stripComments(css);
3431
+ for (let at = css.search(/@font-face\s*\{/i); at >= 0;) {
3432
+ const open = css.indexOf('{', at), end = blockEnd(css, open);
3433
+ const declarations = parseDeclarations(css.slice(open + 1, end));
3434
+ const d = { ...declarations.normal, ...declarations.important };
3435
+ const family = parseFontFamilies(d['font-family'] ?? '')[0];
3436
+ const weight = d['font-weight'] === 'bold' ? 700 : /^\d+$/.test(d['font-weight'] ?? '') ? Number(d['font-weight']) : 400;
3437
+ const style = d['font-style'] === 'italic' || d['font-style'] === 'oblique' ? d['font-style'] : 'normal';
3438
+ if (family)
3439
+ for (const [, , url] of (d.src ?? '').matchAll(/url\(\s*(['"]?)([^'")]*)\1\s*\)/g)) {
3440
+ const uri = dataURI(url);
3441
+ if (!uri)
3442
+ continue;
3443
+ let data = uri.data;
3444
+ try {
3445
+ if (data[0] === 0x77 && data[1] === 0x4f && data[2] === 0x46 && data[3] === 0x46)
3446
+ data = fromWOFF(data);
3447
+ }
3448
+ catch {
3449
+ data = null;
3450
+ }
3451
+ const face = data && fontFace(data, { family, weight, style });
3452
+ if (face) {
3453
+ faces.push(face);
3454
+ break;
3455
+ }
3456
+ }
3457
+ const next = css.slice(end + 1).search(/@font-face\s*\{/i);
3458
+ at = next < 0 ? -1 : end + 1 + next;
3459
+ }
3460
+ return faces;
3461
+ }
3462
+ function fromWOFF(data) {
3463
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
3464
+ const count = view.getUint16(12);
3465
+ const tables = [];
3466
+ for (let i = 0; i < count; i++) {
3467
+ const e = 44 + i * 20, offset = view.getUint32(e + 4), compressed = view.getUint32(e + 8), length = view.getUint32(e + 12);
3468
+ const raw = data.subarray(offset, offset + compressed);
3469
+ tables.push({ tag: view.getUint32(e), checksum: view.getUint32(e + 16), data: compressed < length ? decompress(raw, length).subarray(0, length) : raw });
3470
+ }
3471
+ const header = 12 + count * 16;
3472
+ let size = header;
3473
+ for (const t of tables)
3474
+ size += t.data.length + 3 & ~3;
3475
+ const out = new Uint8Array(size), o = new DataView(out.buffer);
3476
+ o.setUint32(0, view.getUint32(4));
3477
+ o.setUint16(4, count);
3478
+ let position = header;
3479
+ tables.forEach((t, i) => {
3480
+ o.setUint32(12 + i * 16, t.tag);
3481
+ o.setUint32(16 + i * 16, t.checksum);
3482
+ o.setUint32(20 + i * 16, position);
3483
+ o.setUint32(24 + i * 16, t.data.length);
3484
+ out.set(t.data, position);
3485
+ position += t.data.length + 3 & ~3;
3486
+ });
3487
+ return out;
3488
+ }
3489
+ function transformOf(style, viewport, fallback) {
3490
+ return originTransform(style.transform, style['transform-origin'] ?? fallback, viewport, parseNumber(style['font-size'], 16));
3491
+ }
3492
+ function originTransform(transform, origin, viewport, fontSize = 16) {
3493
+ const matrix = parseTransform(transform);
3494
+ const at = origin ? parseOrigin(origin, viewport, fontSize) : null;
3495
+ return at ? multiply(multiply([1, 0, 0, 1, at[0], at[1]], matrix), [1, 0, 0, 1, -at[0], -at[1]]) : matrix;
3496
+ }
3497
+ const ORIGIN_KEYWORDS = { left: ['x', '0%'], right: ['x', '100%'], top: ['y', '0%'], bottom: ['y', '100%'], center: [null, '50%'] };
3498
+ function parseOrigin(value, viewport, fontSize) {
3499
+ const parts = value.trim().split(/\s+/);
3500
+ if (parts.length > 3 || (parts.length === 3 && !LENGTH.test(parts[2])))
3501
+ return null;
3502
+ const terms = parts.slice(0, 2).map(part => {
3503
+ const keyword = ORIGIN_KEYWORDS[part];
3504
+ return keyword ? { axis: keyword[0], value: keyword[1] } : LENGTH.test(part) ? { axis: null, value: part } : null;
3505
+ });
3506
+ if (terms.some(term => !term))
3507
+ return null;
3508
+ const center = { axis: null, value: '50%' };
3509
+ let [x, y] = terms;
3510
+ if (!y)
3511
+ [x, y] = x.axis === 'y' ? [center, x] : [x, center];
3512
+ else if (x.axis === 'y' || y.axis === 'x')
3513
+ [x, y] = [y, x];
3514
+ if (x.axis === 'y' || y.axis === 'x')
3515
+ return null;
3516
+ return [parseLength(x.value, viewport, fontSize, 'x'), parseLength(y.value, viewport, fontSize, 'y')];
3517
+ }
3518
+ function paintOrder(value) {
3519
+ const normal = ['fill', 'stroke', 'markers'];
3520
+ const given = value && value !== 'normal' ? value.trim().split(/\s+/) : [];
3521
+ if (given.some((part, i) => !normal.includes(part) || given.indexOf(part) !== i))
3522
+ return [...normal];
3523
+ return [...given, ...normal.filter(part => !given.includes(part))];
3524
+ }
3525
+ function overflowVisible(node) {
3526
+ let value = node.attrs.overflow?.trim();
3527
+ for (let p = node.parent; value === 'inherit'; p = p.parent) {
3528
+ if (!p || p.name === '#root')
3529
+ return true;
3530
+ value = p.attrs.overflow?.trim() ?? (/^(svg|symbol|marker|pattern)$/.test(p.name) && p.parent && p.parent.name !== '#root' ? 'hidden' : 'visible');
3531
+ }
3532
+ return value === 'visible' || value === 'auto';
3533
+ }
2770
3534
  function parseViewBox(value) {
2771
3535
  if (!value)
2772
3536
  return null;