1 | 'use strict';
|
2 |
|
3 | exports.type = 'perItem';
|
4 |
|
5 | exports.active = true;
|
6 |
|
7 | exports.description = 'rounds numeric values to the fixed precision, removes default ‘px’ units';
|
8 |
|
9 | exports.params = {
|
10 | floatPrecision: 3,
|
11 | leadingZero: true,
|
12 | defaultPx: true,
|
13 | convertToPx: true
|
14 | };
|
15 |
|
16 | var regNumericValues = /^([\-+]?\d*\.?\d+([eE][\-+]?\d+)?)(px|pt|pc|mm|cm|m|in|ft|em|ex|%)?$/,
|
17 | removeLeadingZero = require('../lib/svgo/tools').removeLeadingZero,
|
18 | absoluteLengths = {
|
19 | cm: 96/2.54,
|
20 | mm: 96/25.4,
|
21 | in: 96,
|
22 | pt: 4/3,
|
23 | pc: 16
|
24 | };
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 | exports.fn = function(item, params) {
|
37 |
|
38 | if (item.isElem()) {
|
39 |
|
40 | var floatPrecision = params.floatPrecision;
|
41 |
|
42 | if (item.hasAttr('viewBox')) {
|
43 | var nums = item.attr('viewBox').value.split(/\s,?\s*|,\s*/g);
|
44 | item.attr('viewBox').value = nums.map(function(value) {
|
45 | var num = +value;
|
46 | return isNaN(num) ? value : +num.toFixed(floatPrecision);
|
47 | }).join(' ');
|
48 | }
|
49 |
|
50 | item.eachAttr(function(attr) {
|
51 |
|
52 | if (attr.name === 'version') { return }
|
53 |
|
54 | var match = attr.value.match(regNumericValues);
|
55 |
|
56 |
|
57 | if (match) {
|
58 |
|
59 | var num = +(+match[1]).toFixed(floatPrecision),
|
60 | units = match[3] || '';
|
61 |
|
62 |
|
63 | if (params.convertToPx && units && (units in absoluteLengths)) {
|
64 | var pxNum = +(absoluteLengths[units] * match[1]).toFixed(floatPrecision);
|
65 |
|
66 | if (String(pxNum).length < match[0].length) {
|
67 | num = pxNum;
|
68 | units = 'px';
|
69 | }
|
70 | }
|
71 |
|
72 |
|
73 | if (params.leadingZero) {
|
74 | num = removeLeadingZero(num);
|
75 | }
|
76 |
|
77 |
|
78 | if (params.defaultPx && units === 'px') {
|
79 | units = '';
|
80 | }
|
81 |
|
82 | attr.value = num + units;
|
83 | }
|
84 | });
|
85 |
|
86 | }
|
87 |
|
88 | };
|