source: trip-planner-front/node_modules/svgo/plugins/cleanupNumericValues.js@ 76712b2

Last change on this file since 76712b2 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 2.9 KB
RevLine 
[6a3a178]1'use strict';
2
3const { removeLeadingZero } = require('../lib/svgo/tools');
4
5exports.name = 'cleanupNumericValues';
6exports.type = 'visitor';
7exports.active = true;
8exports.description =
9 'rounds numeric values to the fixed precision, removes default ‘px’ units';
10
11const regNumericValues =
12 /^([-+]?\d*\.?\d+([eE][-+]?\d+)?)(px|pt|pc|mm|cm|m|in|ft|em|ex|%)?$/;
13
14const absoluteLengths = {
15 // relative to px
16 cm: 96 / 2.54,
17 mm: 96 / 25.4,
18 in: 96,
19 pt: 4 / 3,
20 pc: 16,
21 px: 1,
22};
23
24/**
25 * Round numeric values to the fixed precision,
26 * remove default 'px' units.
27 *
28 * @author Kir Belevich
29 *
30 * @type {import('../lib/types').Plugin<{
31 * floatPrecision?: number,
32 * leadingZero?: boolean,
33 * defaultPx?: boolean,
34 * convertToPx?: boolean
35 * }>}
36 */
37exports.fn = (_root, params) => {
38 const {
39 floatPrecision = 3,
40 leadingZero = true,
41 defaultPx = true,
42 convertToPx = true,
43 } = params;
44
45 return {
46 element: {
47 enter: (node) => {
48 if (node.attributes.viewBox != null) {
49 const nums = node.attributes.viewBox.split(/\s,?\s*|,\s*/g);
50 node.attributes.viewBox = nums
51 .map((value) => {
52 const num = Number(value);
53 return Number.isNaN(num)
54 ? value
55 : Number(num.toFixed(floatPrecision));
56 })
57 .join(' ');
58 }
59
60 for (const [name, value] of Object.entries(node.attributes)) {
61 // The `version` attribute is a text string and cannot be rounded
62 if (name === 'version') {
63 continue;
64 }
65
66 const match = value.match(regNumericValues);
67
68 // if attribute value matches regNumericValues
69 if (match) {
70 // round it to the fixed precision
71 let num = Number(Number(match[1]).toFixed(floatPrecision));
72 /**
73 * @type {any}
74 */
75 let matchedUnit = match[3] || '';
76 /**
77 * @type{'' | keyof typeof absoluteLengths}
78 */
79 let units = matchedUnit;
80
81 // convert absolute values to pixels
82 if (convertToPx && units !== '' && units in absoluteLengths) {
83 const pxNum = Number(
84 (absoluteLengths[units] * Number(match[1])).toFixed(
85 floatPrecision
86 )
87 );
88 if (pxNum.toString().length < match[0].length) {
89 num = pxNum;
90 units = 'px';
91 }
92 }
93
94 // and remove leading zero
95 let str;
96 if (leadingZero) {
97 str = removeLeadingZero(num);
98 } else {
99 str = num.toString();
100 }
101
102 // remove default 'px' units
103 if (defaultPx && units === 'px') {
104 units = '';
105 }
106
107 node.attributes[name] = str + units;
108 }
109 }
110 },
111 },
112 };
113};
Note: See TracBrowser for help on using the repository browser.