You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

cleanupNumericValues.js 2.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. 'use strict';
  2. exports.type = 'perItem';
  3. exports.active = true;
  4. exports.description = 'rounds numeric values to the fixed precision, removes default ‘px’ units';
  5. exports.params = {
  6. floatPrecision: 3,
  7. leadingZero: true,
  8. defaultPx: true,
  9. convertToPx: true
  10. };
  11. var regNumericValues = /^([\-+]?\d*\.?\d+([eE][\-+]?\d+)?)(px|pt|pc|mm|cm|m|in|ft|em|ex|%)?$/,
  12. removeLeadingZero = require('../lib/svgo/tools').removeLeadingZero,
  13. absoluteLengths = { // relative to px
  14. cm: 96/2.54,
  15. mm: 96/25.4,
  16. in: 96,
  17. pt: 4/3,
  18. pc: 16
  19. };
  20. /**
  21. * Round numeric values to the fixed precision,
  22. * remove default 'px' units.
  23. *
  24. * @param {Object} item current iteration item
  25. * @param {Object} params plugin params
  26. * @return {Boolean} if false, item will be filtered out
  27. *
  28. * @author Kir Belevich
  29. */
  30. exports.fn = function(item, params) {
  31. if (item.isElem()) {
  32. var floatPrecision = params.floatPrecision;
  33. if (item.hasAttr('viewBox')) {
  34. var nums = item.attr('viewBox').value.split(/\s,?\s*|,\s*/g);
  35. item.attr('viewBox').value = nums.map(function(value) {
  36. var num = +value;
  37. return isNaN(num) ? value : +num.toFixed(floatPrecision);
  38. }).join(' ');
  39. }
  40. item.eachAttr(function(attr) {
  41. // The `version` attribute is a text string and cannot be rounded
  42. if (attr.name === 'version') { return }
  43. var match = attr.value.match(regNumericValues);
  44. // if attribute value matches regNumericValues
  45. if (match) {
  46. // round it to the fixed precision
  47. var num = +(+match[1]).toFixed(floatPrecision),
  48. units = match[3] || '';
  49. // convert absolute values to pixels
  50. if (params.convertToPx && units && (units in absoluteLengths)) {
  51. var pxNum = +(absoluteLengths[units] * match[1]).toFixed(floatPrecision);
  52. if (String(pxNum).length < match[0].length) {
  53. num = pxNum;
  54. units = 'px';
  55. }
  56. }
  57. // and remove leading zero
  58. if (params.leadingZero) {
  59. num = removeLeadingZero(num);
  60. }
  61. // remove default 'px' units
  62. if (params.defaultPx && units === 'px') {
  63. units = '';
  64. }
  65. attr.value = num + units;
  66. }
  67. });
  68. }
  69. };