UNPKG

2.56 kBJavaScriptView Raw
1'use strict';
2
3exports.type = 'perItem';
4
5exports.active = true;
6
7exports.description = 'rounds numeric values to the fixed precision, removes default ‘px’ units';
8
9exports.params = {
10 floatPrecision: 3,
11 leadingZero: true,
12 defaultPx: true,
13 convertToPx: true
14};
15
16var regNumericValues = /^([\-+]?\d*\.?\d+([eE][\-+]?\d+)?)(px|pt|pc|mm|cm|m|in|ft|em|ex|%)?$/,
17 removeLeadingZero = require('../lib/svgo/tools').removeLeadingZero,
18 absoluteLengths = { // relative to px
19 cm: 96/2.54,
20 mm: 96/25.4,
21 in: 96,
22 pt: 4/3,
23 pc: 16
24 };
25
26/**
27 * Round numeric values to the fixed precision,
28 * remove default 'px' units.
29 *
30 * @param {Object} item current iteration item
31 * @param {Object} params plugin params
32 * @return {Boolean} if false, item will be filtered out
33 *
34 * @author Kir Belevich
35 */
36exports.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 // The `version` attribute is a text string and cannot be rounded
52 if (attr.name === 'version') { return }
53
54 var match = attr.value.match(regNumericValues);
55
56 // if attribute value matches regNumericValues
57 if (match) {
58 // round it to the fixed precision
59 var num = +(+match[1]).toFixed(floatPrecision),
60 units = match[3] || '';
61
62 // convert absolute values to pixels
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 // and remove leading zero
73 if (params.leadingZero) {
74 num = removeLeadingZero(num);
75 }
76
77 // remove default 'px' units
78 if (params.defaultPx && units === 'px') {
79 units = '';
80 }
81
82 attr.value = num + units;
83 }
84 });
85
86 }
87
88};