@eturnity/dom_to_svg 8.22.0 → 8.34.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.
package/lib/css.js CHANGED
@@ -1,96 +1,108 @@
1
- export const isCSSFontFaceRule = (rule) => rule.type === CSSRule.FONT_FACE_RULE;
2
- export const isInline = (styles) => styles.displayOutside === 'inline' || styles.display.startsWith('inline-');
3
- export const isPositioned = (styles) => styles.position !== 'static';
4
- export const isInFlow = (styles) => styles.float !== 'none' && styles.position !== 'absolute' && styles.position !== 'fixed';
5
- export const isTransparent = (color) => color === 'transparent' || color === 'rgba(0, 0, 0, 0)';
6
- export const hasUniformBorder = (styles) => parseFloat(styles.borderTopWidth) !== 0 &&
7
- styles.borderTopStyle !== 'none' &&
8
- styles.borderTopStyle !== 'inset' &&
9
- styles.borderTopStyle !== 'outset' &&
10
- !isTransparent(styles.borderTopColor) &&
11
- // Cannot use border property directly as in Firefox those are empty strings.
12
- // Need to get the specific border properties from the specific sides.
13
- // https://stackoverflow.com/questions/41696063/getcomputedstyle-returns-empty-strings-on-ff-when-instead-crome-returns-a-comp
14
- styles.borderTopWidth === styles.borderLeftWidth &&
15
- styles.borderTopWidth === styles.borderRightWidth &&
16
- styles.borderTopWidth === styles.borderBottomWidth &&
17
- styles.borderTopColor === styles.borderLeftColor &&
18
- styles.borderTopColor === styles.borderRightColor &&
19
- styles.borderTopColor === styles.borderBottomColor &&
20
- styles.borderTopStyle === styles.borderLeftStyle &&
21
- styles.borderTopStyle === styles.borderRightStyle &&
22
- styles.borderTopStyle === styles.borderBottomStyle;
1
+ export const isCSSFontFaceRule = rule => rule.type === CSSRule.FONT_FACE_RULE
2
+ export const isInline = styles => styles.displayOutside === 'inline' || styles.display.startsWith('inline-')
3
+ export const isPositioned = styles => styles.position !== 'static'
4
+ export const isInFlow = styles =>
5
+ styles.float !== 'none' && styles.position !== 'absolute' && styles.position !== 'fixed'
6
+ export const isTransparent = color => color === 'transparent' || color === 'rgba(0, 0, 0, 0)'
7
+ export const hasUniformBorder = styles =>
8
+ parseFloat(styles.borderTopWidth) !== 0 &&
9
+ styles.borderTopStyle !== 'none' &&
10
+ styles.borderTopStyle !== 'inset' &&
11
+ styles.borderTopStyle !== 'outset' &&
12
+ !isTransparent(styles.borderTopColor) &&
13
+ // Cannot use border property directly as in Firefox those are empty strings.
14
+ // Need to get the specific border properties from the specific sides.
15
+ // https://stackoverflow.com/questions/41696063/getcomputedstyle-returns-empty-strings-on-ff-when-instead-crome-returns-a-comp
16
+ styles.borderTopWidth === styles.borderLeftWidth &&
17
+ styles.borderTopWidth === styles.borderRightWidth &&
18
+ styles.borderTopWidth === styles.borderBottomWidth &&
19
+ styles.borderTopColor === styles.borderLeftColor &&
20
+ styles.borderTopColor === styles.borderRightColor &&
21
+ styles.borderTopColor === styles.borderBottomColor &&
22
+ styles.borderTopStyle === styles.borderLeftStyle &&
23
+ styles.borderTopStyle === styles.borderRightStyle &&
24
+ styles.borderTopStyle === styles.borderBottomStyle
23
25
  /** The 4 sides of a box. */
24
- const SIDES = ['top', 'bottom', 'right', 'left'];
26
+ const SIDES = ['top', 'bottom', 'right', 'left']
25
27
  /** Whether the given side is a horizontal side. */
26
- export const isHorizontal = (side) => side === 'bottom' || side === 'top';
28
+ export const isHorizontal = side => side === 'bottom' || side === 'top'
27
29
  /**
28
30
  * The two corners for each side, in order of lower coordinate to higher coordinate.
29
31
  */
30
32
  const CORNERS = {
31
- top: ['left', 'right'],
32
- bottom: ['left', 'right'],
33
- left: ['top', 'bottom'],
34
- right: ['top', 'bottom'],
35
- };
33
+ top: ['left', 'right'],
34
+ bottom: ['left', 'right'],
35
+ left: ['top', 'bottom'],
36
+ right: ['top', 'bottom'],
37
+ }
36
38
  /**
37
39
  * Returns the (elliptic) border radii for a given side.
38
40
  * For example, for the top side it will return the horizontal top-left and the horizontal top-right border radii.
39
41
  */
40
- export function getBorderRadiiForSide(side, styles, bounds) {
41
- var _a, _b, _c, _d;
42
- const [horizontalStyle1, verticalStyle1] = styles
43
- .getPropertyValue(isHorizontal(side)
44
- ? `border-${side}-${CORNERS[side][0]}-radius`
45
- : `border-${CORNERS[side][0]}-${side}-radius`)
46
- .split(' ');
47
- const [horizontalStyle2, verticalStyle2] = styles
48
- .getPropertyValue(isHorizontal(side)
49
- ? `border-${side}-${CORNERS[side][1]}-radius`
50
- : `border-${CORNERS[side][1]}-${side}-radius`)
51
- .split(' ');
52
- if (isHorizontal(side)) {
53
- return [
54
- (_a = parseCSSLength(horizontalStyle1 || '0px', bounds.width)) !== null && _a !== void 0 ? _a : 0,
55
- (_b = parseCSSLength(horizontalStyle2 || '0px', bounds.width)) !== null && _b !== void 0 ? _b : 0,
56
- ];
57
- }
42
+ export function getBorderRadiiForSide(side, styles, bounds, zoom) {
43
+ var _a, _b, _c, _d
44
+ const [horizontalStyle1, verticalStyle1] = styles
45
+ .getPropertyValue(
46
+ isHorizontal(side) ? `border-${side}-${CORNERS[side][0]}-radius` : `border-${CORNERS[side][0]}-${side}-radius`
47
+ )
48
+ .split(' ')
49
+ const [horizontalStyle2, verticalStyle2] = styles
50
+ .getPropertyValue(
51
+ isHorizontal(side) ? `border-${side}-${CORNERS[side][1]}-radius` : `border-${CORNERS[side][1]}-${side}-radius`
52
+ )
53
+ .split(' ')
54
+ if (isHorizontal(side)) {
58
55
  return [
59
- (_c = parseCSSLength(verticalStyle1 || horizontalStyle1 || '0px', bounds.height)) !== null && _c !== void 0 ? _c : 0,
60
- (_d = parseCSSLength(verticalStyle2 || horizontalStyle2 || '0px', bounds.height)) !== null && _d !== void 0 ? _d : 0,
61
- ];
56
+ (_a = parseCSSLength(horizontalStyle1 || '0px', bounds.width, zoom)) !== null && _a !== void 0 ? _a : 0,
57
+ (_b = parseCSSLength(horizontalStyle2 || '0px', bounds.width, zoom)) !== null && _b !== void 0 ? _b : 0,
58
+ ]
59
+ }
60
+ return [
61
+ (_c = parseCSSLength(verticalStyle1 || horizontalStyle1 || '0px', bounds.height, zoom)) !== null && _c !== void 0
62
+ ? _c
63
+ : 0,
64
+ (_d = parseCSSLength(verticalStyle2 || horizontalStyle2 || '0px', bounds.height, zoom)) !== null && _d !== void 0
65
+ ? _d
66
+ : 0,
67
+ ]
62
68
  }
63
69
  /**
64
70
  * Returns the factor by which all border radii have to be scaled to fit correctly.
65
71
  *
66
72
  * @see https://drafts.csswg.org/css-backgrounds-3/#corner-overlap
67
73
  */
68
- export const calculateOverlappingCurvesFactor = (styles, bounds) => Math.min(...SIDES.map(side => {
69
- const length = isHorizontal(side) ? bounds.width : bounds.height;
70
- const radiiSum = getBorderRadiiForSide(side, styles, bounds).reduce((sum, radius) => sum + radius, 0);
71
- return length / radiiSum;
72
- }), 1);
73
- export const isVisible = (styles) => styles.displayOutside !== 'none' &&
74
- styles.display !== 'none' &&
75
- styles.visibility !== 'hidden' &&
76
- styles.opacity !== '0';
77
- export function parseCSSLength(length, containerLength) {
78
- if (length.endsWith('px')) {
79
- return parseFloat(length);
80
- }
81
- if (length.endsWith('%')) {
82
- return (parseFloat(length) / 100) * containerLength;
83
- }
84
- return undefined;
74
+ export const calculateOverlappingCurvesFactor = (styles, bounds) =>
75
+ Math.min(
76
+ ...SIDES.map(side => {
77
+ const length = isHorizontal(side) ? bounds.width : bounds.height
78
+ const radiiSum = getBorderRadiiForSide(side, styles, bounds).reduce((sum, radius) => sum + radius, 0)
79
+ return length / radiiSum
80
+ }),
81
+ 1
82
+ )
83
+ export const isVisible = styles =>
84
+ styles.displayOutside !== 'none' &&
85
+ styles.display !== 'none' &&
86
+ styles.visibility !== 'hidden' &&
87
+ styles.opacity !== '0'
88
+ export function parseCSSLength(length, containerLength, zoom = 1) {
89
+ if (length.endsWith('px')) {
90
+ return parseFloat(length) * zoom
91
+ }
92
+ if (length.endsWith('%')) {
93
+ return (parseFloat(length) / 100) * containerLength
94
+ }
95
+ return undefined
85
96
  }
86
- export const unescapeStringValue = (value) => value
97
+ export const unescapeStringValue = value =>
98
+ value
87
99
  // Replace hex escape sequences
88
100
  .replace(/\\([\da-f]{1,2})/gi, (substring, codePoint) => String.fromCodePoint(parseInt(codePoint, 16)))
89
101
  // Replace all other escapes (quotes, backslash, etc)
90
- .replace(/\\(.)/g, '$1');
102
+ .replace(/\\(.)/g, '$1')
91
103
  export function copyCssStyles(from, to) {
92
- for (const property of from) {
93
- to.setProperty(property, from.getPropertyValue(property), from.getPropertyPriority(property));
94
- }
104
+ for (const property of from) {
105
+ to.setProperty(property, from.getPropertyValue(property), from.getPropertyPriority(property))
106
+ }
95
107
  }
96
- //# sourceMappingURL=css.js.map
108
+ //# sourceMappingURL=css.js.map
package/lib/element.js CHANGED
@@ -373,19 +373,20 @@ function createBackgroundAndBorderBox(bounds, styles, context) {
373
373
  // Need to get the border property from some specific side (they are all the same in this condition).
374
374
  // https://stackoverflow.com/questions/41696063/getcomputedstyle-returns-empty-strings-on-ff-when-instead-crome-returns-a-comp
375
375
  background.setAttribute('stroke', styles.borderTopColor)
376
- background.setAttribute('stroke-width', adjustSizeWithZoom(styles.borderTopWidth, context.zoom))
377
- if (styles.borderTopStyle === 'dashed') {
376
+ background.setAttribute('stroke-width', adjustSizeWithZoom(styles.borderBottomWidth, context.zoom))
377
+ if (styles.borderBottomStyle === 'dashed') {
378
378
  // > Displays a series of short square-ended dashes or line segments.
379
379
  // > The exact size and length of the segments are not defined by the specification and are implementation-specific.
380
- background.setAttribute('stroke-dasharray', '1')
380
+ background.setAttribute('stroke-dasharray', '4')
381
381
  }
382
382
  }
383
383
  // Set border radius
384
384
  // Approximation, always assumes uniform border-radius by using the top-left horizontal radius and the top-left vertical radius for all corners.
385
385
  // TODO support irregular border radii on all corners by drawing border as a <path>.
386
386
  const overlappingCurvesFactor = calculateOverlappingCurvesFactor(styles, bounds)
387
- const radiusX = getBorderRadiiForSide('top', styles, bounds)[0] * overlappingCurvesFactor * context.zoom
388
- const radiusY = getBorderRadiiForSide('left', styles, bounds)[0] * overlappingCurvesFactor * context.zoom
387
+
388
+ const radiusX = getBorderRadiiForSide('top', styles, bounds, context.zoom)[0] * overlappingCurvesFactor
389
+ const radiusY = getBorderRadiiForSide('left', styles, bounds, context.zoom)[0] * overlappingCurvesFactor
389
390
  if (radiusX !== 0) {
390
391
  background.setAttribute('rx', radiusX.toString())
391
392
  }
@@ -414,7 +415,13 @@ function createBorder(styles, bounds, side, context) {
414
415
  border.setAttribute('stroke-linecap', 'square')
415
416
  const color = styles.getPropertyValue(`border-${side}-color`)
416
417
  border.setAttribute('stroke', color)
417
- border.setAttribute('stroke-width', styles.getPropertyValue(`border-${side}-width`))
418
+ border.setAttribute('fill', 'transparent')
419
+ border.setAttribute('stroke-width', adjustSizeWithZoom(styles.getPropertyValue(`border-${side}-width`), context.zoom))
420
+
421
+ const borderSideStyle = styles.getPropertyValue(`border-${side}-style`)
422
+ if (borderSideStyle === 'dashed') {
423
+ border.setAttribute('stroke-dasharray', 4 * context.zoom)
424
+ }
418
425
  // Handle inset/outset borders
419
426
  const borderStyle = styles.getPropertyValue(`border-${side}-style`)
420
427
  if (
package/lib/svg.js CHANGED
@@ -1,245 +1,255 @@
1
- import cssValueParser from 'postcss-value-parser';
2
- import { parseCSSLength } from './css.js';
3
- import { isElement, isSVGAnchorElement, isSVGElement, isSVGGraphicsElement, isSVGSVGElement, isSVGTextContentElement, isTextNode, svgNamespace, } from './dom.js';
4
- import { copyTextStyles } from './text.js';
5
- import { assert, diagonale } from './util.js';
1
+ import cssValueParser from 'postcss-value-parser'
2
+ import { parseCSSLength } from './css.js'
3
+ import {
4
+ isElement,
5
+ isSVGAnchorElement,
6
+ isSVGElement,
7
+ isSVGGraphicsElement,
8
+ isSVGSVGElement,
9
+ isSVGTextContentElement,
10
+ isTextNode,
11
+ svgNamespace,
12
+ } from './dom.js'
13
+ import { copyTextStyles } from './text.js'
14
+ import { assert, diagonale } from './util.js'
6
15
  /**
7
16
  * Recursively clone an `<svg>` element, inlining it into the output SVG document with the necessary transforms.
8
17
  */
9
18
  export function handleSvgNode(node, context) {
10
- if (isElement(node)) {
11
- if (!isSVGElement(node)) {
12
- return;
13
- }
14
- handleSvgElement(node, context);
15
- }
16
- else if (isTextNode(node)) {
17
- const clonedTextNode = node.cloneNode(true);
18
- context.currentSvgParent.append(clonedTextNode);
19
+ if (isElement(node)) {
20
+ if (!isSVGElement(node)) {
21
+ return
19
22
  }
23
+ handleSvgElement(node, context)
24
+ } else if (isTextNode(node)) {
25
+ const clonedTextNode = node.cloneNode(true)
26
+ context.currentSvgParent.append(clonedTextNode)
27
+ }
20
28
  }
21
- const ignoredElements = new Set(['script', 'style', 'foreignElement']);
22
- const URL_ID_REFERENCE_REGEX = /\burl\(["']?#/;
29
+ const ignoredElements = new Set(['script', 'style', 'foreignElement'])
30
+ const URL_ID_REFERENCE_REGEX = /\burl\(["']?#/
23
31
  export function handleSvgElement(element, context) {
24
- var _a, _b, _c, _d;
25
- if (ignoredElements.has(element.tagName)) {
26
- return;
32
+ var _a, _b, _c, _d
33
+ if (ignoredElements.has(element.tagName)) {
34
+ return
35
+ }
36
+ let elementToAppend
37
+ if (isSVGSVGElement(element)) {
38
+ const contentContainer = context.svgDocument.createElementNS(svgNamespace, 'g')
39
+ elementToAppend = contentContainer
40
+ contentContainer.classList.add('svg-content', ...element.classList)
41
+ contentContainer.dataset.viewBox = (_a = element.getAttribute('viewBox')) !== null && _a !== void 0 ? _a : ''
42
+ contentContainer.dataset.width = (_b = element.getAttribute('width')) !== null && _b !== void 0 ? _b : ''
43
+ contentContainer.dataset.height = (_c = element.getAttribute('height')) !== null && _c !== void 0 ? _c : ''
44
+ // Since the SVG is getting inlined into the output SVG, we need to transform its contents according to its
45
+ // viewBox, width, height and preserveAspectRatio. We can use getScreenCTM() for this on one of its
46
+ // SVGGraphicsElement children (in Chrome calling it on the <svg> works too, but not in Firefox:
47
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=873106).
48
+ for (const child of element.children) {
49
+ if (!isSVGGraphicsElement(child)) {
50
+ continue
51
+ }
52
+ let viewBoxTransformMatrix =
53
+ // When this function is called on an inline <svg> element in the original DOM, we want
54
+ // getScreenCTM() to map it to the DOM coordinate system. When this function is called from
55
+ // inlineResources() the <svg> is already embedded into the output <svg>. In that case the output
56
+ // SVG already has a viewBox, and the coordinate system of the SVG is not equal to the coordinate
57
+ // system of the screen, therefor we need to use getCTM() to map it into the output SVG's
58
+ // coordinate system.
59
+ child.ownerDocument !== context.svgDocument &&
60
+ // When we inline an SVG, we put a transform on it for the getScreenCTM(). When that SVG also
61
+ // contains another SVG, the inner SVG should just get transformed relative to the outer SVG, not
62
+ // relative to the screen, because the transforms will stack in the output SVG.
63
+ !((_d = element.parentElement) === null || _d === void 0 ? void 0 : _d.closest('svg'))
64
+ ? child.getScreenCTM()
65
+ : child.getCTM()
66
+ // This should only be null if the <svg> is `display: none`
67
+ if (!viewBoxTransformMatrix) {
68
+ break
69
+ }
70
+ // Make sure to handle a child that already has a transform. That transform should only apply to the
71
+ // child, not to the entire SVG contents, so we need to calculate it out.
72
+ if (child.transform.baseVal.numberOfItems > 0) {
73
+ child.transform.baseVal.consolidate()
74
+ const existingTransform = child.transform.baseVal.getItem(0).matrix
75
+ viewBoxTransformMatrix = viewBoxTransformMatrix.multiply(existingTransform.inverse())
76
+ }
77
+ contentContainer.transform.baseVal.appendItem(
78
+ contentContainer.transform.baseVal.createSVGTransformFromMatrix(viewBoxTransformMatrix)
79
+ )
80
+ break
27
81
  }
28
- let elementToAppend;
29
- if (isSVGSVGElement(element)) {
30
- const contentContainer = context.svgDocument.createElementNS(svgNamespace, 'g');
31
- elementToAppend = contentContainer;
32
- contentContainer.classList.add('svg-content', ...element.classList);
33
- contentContainer.dataset.viewBox = (_a = element.getAttribute('viewBox')) !== null && _a !== void 0 ? _a : '';
34
- contentContainer.dataset.width = (_b = element.getAttribute('width')) !== null && _b !== void 0 ? _b : '';
35
- contentContainer.dataset.height = (_c = element.getAttribute('height')) !== null && _c !== void 0 ? _c : '';
36
- // Since the SVG is getting inlined into the output SVG, we need to transform its contents according to its
37
- // viewBox, width, height and preserveAspectRatio. We can use getScreenCTM() for this on one of its
38
- // SVGGraphicsElement children (in Chrome calling it on the <svg> works too, but not in Firefox:
39
- // https://bugzilla.mozilla.org/show_bug.cgi?id=873106).
40
- for (const child of element.children) {
41
- if (!isSVGGraphicsElement(child)) {
42
- continue;
43
- }
44
- let viewBoxTransformMatrix =
45
- // When this function is called on an inline <svg> element in the original DOM, we want
46
- // getScreenCTM() to map it to the DOM coordinate system. When this function is called from
47
- // inlineResources() the <svg> is already embedded into the output <svg>. In that case the output
48
- // SVG already has a viewBox, and the coordinate system of the SVG is not equal to the coordinate
49
- // system of the screen, therefor we need to use getCTM() to map it into the output SVG's
50
- // coordinate system.
51
- child.ownerDocument !== context.svgDocument &&
52
- // When we inline an SVG, we put a transform on it for the getScreenCTM(). When that SVG also
53
- // contains another SVG, the inner SVG should just get transformed relative to the outer SVG, not
54
- // relative to the screen, because the transforms will stack in the output SVG.
55
- !((_d = element.parentElement) === null || _d === void 0 ? void 0 : _d.closest('svg'))
56
- ? child.getScreenCTM()
57
- : child.getCTM();
58
- // This should only be null if the <svg> is `display: none`
59
- if (!viewBoxTransformMatrix) {
60
- break;
61
- }
62
- // Make sure to handle a child that already has a transform. That transform should only apply to the
63
- // child, not to the entire SVG contents, so we need to calculate it out.
64
- if (child.transform.baseVal.numberOfItems > 0) {
65
- child.transform.baseVal.consolidate();
66
- const existingTransform = child.transform.baseVal.getItem(0).matrix;
67
- viewBoxTransformMatrix = viewBoxTransformMatrix.multiply(existingTransform.inverse());
68
- }
69
- contentContainer.transform.baseVal.appendItem(contentContainer.transform.baseVal.createSVGTransformFromMatrix(viewBoxTransformMatrix));
70
- break;
71
- }
82
+ } else {
83
+ // Clone element
84
+ if (isSVGAnchorElement(element) && !context.options.keepLinks) {
85
+ elementToAppend = context.svgDocument.createElementNS(svgNamespace, 'g')
86
+ } else {
87
+ elementToAppend = element.cloneNode(false)
72
88
  }
73
- else {
74
- // Clone element
75
- if (isSVGAnchorElement(element) && !context.options.keepLinks) {
76
- elementToAppend = context.svgDocument.createElementNS(svgNamespace, 'g');
77
- }
78
- else {
79
- elementToAppend = element.cloneNode(false);
80
- }
81
- // Remove event handlers
82
- for (const attribute of elementToAppend.attributes) {
83
- if (attribute.localName.startsWith('on')) {
84
- elementToAppend.attributes.removeNamedItemNS(attribute.namespaceURI, attribute.localName);
85
- }
86
- else if (attribute.localName === 'href' && attribute.value.startsWith('javascript:')) {
87
- elementToAppend.attributes.removeNamedItemNS(attribute.namespaceURI, attribute.localName);
88
- }
89
- }
90
- const window = element.ownerDocument.defaultView;
91
- assert(window, "Element's ownerDocument has no defaultView");
92
- const svgViewportElement = element.ownerSVGElement;
93
- assert(svgViewportElement, 'Expected element to have ownerSVGElement');
94
- const styles = window.getComputedStyle(element);
95
- if (isSVGGraphicsElement(element)) {
96
- copyGraphicalPresentationAttributes(styles, elementToAppend, svgViewportElement.viewBox.animVal);
97
- if (isSVGTextContentElement(element)) {
98
- copyTextStyles(styles, elementToAppend);
99
- }
100
- }
101
- // Namespace ID references url(#...)
102
- for (const attribute of elementToAppend.attributes) {
103
- if (attribute.localName === 'href') {
104
- if (attribute.value.startsWith('#')) {
105
- attribute.value = attribute.value.replace('#', `#${context.idPrefix}`);
106
- }
107
- }
108
- else if (URL_ID_REFERENCE_REGEX.test(attribute.value)) {
109
- attribute.value = rewriteUrlIdReferences(attribute.value, context);
110
- }
111
- }
112
- for (const property of elementToAppend.style) {
113
- const value = elementToAppend.style.getPropertyValue(property);
114
- if (URL_ID_REFERENCE_REGEX.test(value)) {
115
- elementToAppend.style.setProperty(property, rewriteUrlIdReferences(value, context), elementToAppend.style.getPropertyPriority(property));
116
- }
117
- }
89
+ // Remove event handlers
90
+ for (const attribute of elementToAppend.attributes) {
91
+ if (attribute.localName.startsWith('on')) {
92
+ elementToAppend.attributes.removeNamedItemNS(attribute.namespaceURI, attribute.localName)
93
+ } else if (attribute.localName === 'href' && attribute.value.startsWith('javascript:')) {
94
+ elementToAppend.attributes.removeNamedItemNS(attribute.namespaceURI, attribute.localName)
95
+ }
118
96
  }
119
- // Make sure all IDs are unique
120
- if (elementToAppend.id) {
121
- elementToAppend.id = context.idPrefix + elementToAppend.id;
97
+ const window = element.ownerDocument.defaultView
98
+ assert(window, "Element's ownerDocument has no defaultView")
99
+ const svgViewportElement = element.ownerSVGElement
100
+ assert(svgViewportElement, 'Expected element to have ownerSVGElement')
101
+ const styles = window.getComputedStyle(element)
102
+ if (isSVGGraphicsElement(element)) {
103
+ copyGraphicalPresentationAttributes(styles, elementToAppend, svgViewportElement.viewBox.animVal)
104
+ if (isSVGTextContentElement(element)) {
105
+ copyTextStyles(styles, elementToAppend)
106
+ }
122
107
  }
123
- context.currentSvgParent.append(elementToAppend);
124
- for (const child of element.childNodes) {
125
- handleSvgNode(child, { ...context, currentSvgParent: elementToAppend });
108
+ // Namespace ID references url(#...)
109
+ for (const attribute of elementToAppend.attributes) {
110
+ if (attribute.localName === 'href') {
111
+ if (attribute.value.startsWith('#')) {
112
+ attribute.value = attribute.value.replace('#', `#${context.idPrefix}`)
113
+ }
114
+ } else if (URL_ID_REFERENCE_REGEX.test(attribute.value)) {
115
+ attribute.value = rewriteUrlIdReferences(attribute.value, context)
116
+ }
117
+ }
118
+ for (const property of elementToAppend.style) {
119
+ const value = elementToAppend.style.getPropertyValue(property)
120
+ if (URL_ID_REFERENCE_REGEX.test(value)) {
121
+ elementToAppend.style.setProperty(
122
+ property,
123
+ rewriteUrlIdReferences(value, context),
124
+ elementToAppend.style.getPropertyPriority(property)
125
+ )
126
+ }
126
127
  }
128
+ }
129
+ // Make sure all IDs are unique
130
+ if (elementToAppend.id) {
131
+ elementToAppend.id = context.idPrefix + elementToAppend.id
132
+ }
133
+ context.currentSvgParent.append(elementToAppend)
134
+ for (const child of element.childNodes) {
135
+ handleSvgNode(child, { ...context, currentSvgParent: elementToAppend })
136
+ }
127
137
  }
128
138
  const graphicalPresentationAttributes = [
129
- 'alignment-baseline',
130
- 'baseline-shift',
131
- // 'clip',
132
- 'clip-path',
133
- 'clip-rule',
134
- 'color',
135
- 'color-interpolation',
136
- 'color-interpolation-filters',
137
- // 'color-profile',
138
- 'color-rendering',
139
- // 'cursor',
140
- 'direction',
141
- // 'display',
142
- // 'enable-background',
143
- 'fill',
144
- 'fill-opacity',
145
- 'fill-rule',
146
- 'filter',
147
- 'flood-color',
148
- 'flood-opacity',
149
- 'image-rendering',
150
- 'lighting-color',
151
- 'marker-end',
152
- 'marker-mid',
153
- 'marker-start',
154
- 'mask',
155
- 'opacity',
156
- // 'overflow',
157
- 'pointer-events',
158
- 'shape-rendering',
159
- // 'solid-color',
160
- // 'solid-opacity',
161
- 'stop-color',
162
- 'stop-opacity',
163
- 'stroke',
164
- 'stroke-dasharray',
165
- 'stroke-dashoffset',
166
- 'stroke-linecap',
167
- 'stroke-linejoin',
168
- 'stroke-miterlimit',
169
- 'stroke-opacity',
170
- 'stroke-width',
171
- 'transform',
172
- 'vector-effect',
173
- 'visibility',
174
- ];
139
+ 'alignment-baseline',
140
+ 'baseline-shift',
141
+ // 'clip',
142
+ 'clip-path',
143
+ 'clip-rule',
144
+ 'color',
145
+ 'color-interpolation',
146
+ 'color-interpolation-filters',
147
+ // 'color-profile',
148
+ 'color-rendering',
149
+ // 'cursor',
150
+ 'direction',
151
+ // 'display',
152
+ // 'enable-background',
153
+ 'fill',
154
+ 'fill-opacity',
155
+ 'fill-rule',
156
+ 'filter',
157
+ 'flood-color',
158
+ 'flood-opacity',
159
+ 'image-rendering',
160
+ 'lighting-color',
161
+ 'marker-end',
162
+ 'marker-mid',
163
+ 'marker-start',
164
+ 'mask',
165
+ 'opacity',
166
+ // 'overflow',
167
+ 'pointer-events',
168
+ 'shape-rendering',
169
+ // 'solid-color',
170
+ // 'solid-opacity',
171
+ 'stop-color',
172
+ 'stop-opacity',
173
+ 'stroke',
174
+ 'stroke-dasharray',
175
+ 'stroke-dashoffset',
176
+ 'stroke-linecap',
177
+ 'stroke-linejoin',
178
+ 'stroke-miterlimit',
179
+ 'stroke-opacity',
180
+ 'stroke-width',
181
+ 'transform',
182
+ 'vector-effect',
183
+ 'visibility',
184
+ ]
175
185
  const defaults = {
176
- 'alignment-baseline': 'auto',
177
- 'baseline-shift': '0px',
178
- 'clip-path': 'none',
179
- 'clip-rule': 'nonzero',
180
- 'color-interpolation-filters': 'linearrgb',
181
- 'color-interpolation': 'srgb',
182
- 'color-rendering': 'auto',
183
- 'fill-opacity': '1',
184
- 'fill-rule': 'nonzero',
185
- 'flood-color': 'rgb(0, 0, 0)',
186
- 'flood-opacity': '1',
187
- 'image-rendering': 'auto',
188
- 'lighting-color': 'rgb(255, 255, 255)',
189
- 'marker-end': 'none',
190
- 'marker-mid': 'none',
191
- 'marker-start': 'none',
192
- 'pointer-events': 'auto',
193
- 'shape-rendering': 'auto',
194
- 'stop-color': 'rgb(0, 0, 0)',
195
- 'stop-opacity': '1',
196
- 'stroke-dasharray': 'none',
197
- 'stroke-dashoffset': '0px',
198
- 'stroke-linecap': 'butt',
199
- 'stroke-linejoin': 'miter',
200
- 'stroke-miterlimit': '4',
201
- 'stroke-opacity': '1',
202
- 'stroke-width': '1px',
203
- 'vector-effect': 'none',
204
- color: '',
205
- direction: 'ltr',
206
- fill: '',
207
- filter: 'none',
208
- mask: 'none',
209
- opacity: '1',
210
- stroke: '',
211
- transform: 'none',
212
- visibility: 'visible',
213
- };
186
+ 'alignment-baseline': 'auto',
187
+ 'baseline-shift': '0px',
188
+ 'clip-path': 'none',
189
+ 'clip-rule': 'nonzero',
190
+ 'color-interpolation-filters': 'linearrgb',
191
+ 'color-interpolation': 'srgb',
192
+ 'color-rendering': 'auto',
193
+ 'fill-opacity': '1',
194
+ 'fill-rule': 'nonzero',
195
+ 'flood-color': 'rgb(0, 0, 0)',
196
+ 'flood-opacity': '1',
197
+ 'image-rendering': 'auto',
198
+ 'lighting-color': 'rgb(255, 255, 255)',
199
+ 'marker-end': 'none',
200
+ 'marker-mid': 'none',
201
+ 'marker-start': 'none',
202
+ 'pointer-events': 'auto',
203
+ 'shape-rendering': 'auto',
204
+ 'stop-color': 'rgb(0, 0, 0)',
205
+ 'stop-opacity': '1',
206
+ 'stroke-dasharray': 'none',
207
+ 'stroke-dashoffset': '0px',
208
+ 'stroke-linecap': 'butt',
209
+ 'stroke-linejoin': 'miter',
210
+ 'stroke-miterlimit': '4',
211
+ 'stroke-opacity': '1',
212
+ 'stroke-width': '1px',
213
+ 'vector-effect': 'none',
214
+ color: '',
215
+ direction: 'ltr',
216
+ fill: '',
217
+ filter: 'none',
218
+ mask: 'none',
219
+ opacity: '1',
220
+ stroke: '',
221
+ transform: 'none',
222
+ visibility: 'visible',
223
+ }
214
224
  /**
215
225
  * Prefixes all ID references of the form `url(#id)` in the given string.
216
226
  */
217
227
  function rewriteUrlIdReferences(value, { idPrefix }) {
218
- const parsedValue = cssValueParser(value);
219
- parsedValue.walk(node => {
220
- if (node.type !== 'function' || node.value !== 'url') {
221
- return;
222
- }
223
- const urlArgument = node.nodes[0];
224
- if (!urlArgument) {
225
- return;
226
- }
227
- urlArgument.value = urlArgument.value.replace('#', `#${idPrefix}`);
228
- });
229
- return cssValueParser.stringify(parsedValue.nodes);
228
+ const parsedValue = cssValueParser(value)
229
+ parsedValue.walk(node => {
230
+ if (node.type !== 'function' || node.value !== 'url') {
231
+ return
232
+ }
233
+ const urlArgument = node.nodes[0]
234
+ if (!urlArgument) {
235
+ return
236
+ }
237
+ urlArgument.value = urlArgument.value.replace('#', `#${idPrefix}`)
238
+ })
239
+ return cssValueParser.stringify(parsedValue.nodes)
230
240
  }
231
241
  function copyGraphicalPresentationAttributes(styles, target, viewBox) {
232
- var _a;
233
- for (const attribute of graphicalPresentationAttributes) {
234
- let value = styles.getPropertyValue(attribute);
235
- if (value && value !== defaults[attribute]) {
236
- if (value.endsWith('%')) {
237
- // E.g. https://svgwg.org/svg2-draft/painting.html#StrokeWidth
238
- // Percentages: refer to the normalized diagonal of the current SVG viewport (see Units)
239
- value = (_a = parseCSSLength(value, diagonale(viewBox))) !== null && _a !== void 0 ? _a : 0;
240
- }
241
- target.setAttribute(attribute, value.toString());
242
- }
242
+ var _a
243
+ for (const attribute of graphicalPresentationAttributes) {
244
+ let value = styles.getPropertyValue(attribute)
245
+ if (value && value !== defaults[attribute]) {
246
+ if (value.endsWith('%')) {
247
+ // E.g. https://svgwg.org/svg2-draft/painting.html#StrokeWidth
248
+ // Percentages: refer to the normalized diagonal of the current SVG viewport (see Units)
249
+ value = (_a = parseCSSLength(value, diagonale(viewBox))) !== null && _a !== void 0 ? _a : 0
250
+ }
251
+ target.setAttribute(attribute, value.toString())
243
252
  }
253
+ }
244
254
  }
245
- //# sourceMappingURL=svg.js.map
255
+ //# sourceMappingURL=svg.js.map
package/lib/text.js CHANGED
@@ -1,4 +1,4 @@
1
- import { isVisible } from './css.js'
1
+ import { isVisible, parseCSSLength } from './css.js'
2
2
  import { svgNamespace } from './dom.js'
3
3
  import { doRectanglesIntersect, assert } from './util.js'
4
4
  export function handleTextNode(textNode, context) {
@@ -57,7 +57,8 @@ export function handleTextNode(textNode, context) {
57
57
  selection.removeAllRanges()
58
58
  }
59
59
  textSpan.setAttribute('x', lineRectangle.x.toString())
60
- textSpan.setAttribute('y', lineRectangle.bottom.toString()) // intentionally bottom because of dominant-baseline setting
60
+ const bottomRectangle = lineRectangle.bottom - 1 * context.zoom
61
+ textSpan.setAttribute('y', bottomRectangle.toString()) // intentionally bottom because of dominant-baseline setting
61
62
  const textContent = textSpan.textContent || ''
62
63
  const textLength = textContent.length
63
64
  if (textLength > 0) {
@@ -68,8 +69,7 @@ export function handleTextNode(textNode, context) {
68
69
  }
69
70
  // textSpan.setAttribute('textLength', lineRectangle.width.toString())
70
71
  // textSpan.setAttribute('lengthAdjust', 'spacingAndGlyphs')
71
- const calculatedFontSize = parseInt(parseInt(styles.fontSize) * context.zoom * 0.8) + 'px'
72
- const originalFontSize = styles.fontSize
72
+ const calculatedFontSize = parseCSSLength(styles.fontSize, lineRectangle, context.zoom) + 'px'
73
73
  // textSpan.setAttribute('data-original-font-size', originalFontSize)
74
74
  textSpan.setAttribute('font-size', calculatedFontSize)
75
75
  svgTextElement.append(textSpan)
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@eturnity/dom_to_svg",
3
3
  "author": "Eturnity Team",
4
- "version": "8.22.0",
4
+ "version": "8.34.0",
5
5
  "description": "Take SVG screenshots of DOM elements",
6
6
  "main": "lib/index.js",
7
7
  "sideEffects": false,