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.

95 lines
2.9 KiB

4 years ago
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. var _postcss = require("postcss");
  6. var _postcssValueParser = require("postcss-value-parser");
  7. var _postcssValueParser2 = _interopRequireDefault(_postcssValueParser);
  8. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  9. const atrule = "atrule";
  10. const decl = "decl";
  11. const rule = "rule";
  12. function reduceCalcWhitespaces(node) {
  13. if (node.type === "space") {
  14. node.value = " ";
  15. } else if (node.type === "function") {
  16. node.before = node.after = "";
  17. }
  18. }
  19. function reduceWhitespaces(node) {
  20. if (node.type === "space") {
  21. node.value = " ";
  22. } else if (node.type === "div") {
  23. node.before = node.after = "";
  24. } else if (node.type === "function") {
  25. node.before = node.after = "";
  26. if (node.value.toLowerCase() === "calc") {
  27. _postcssValueParser2.default.walk(node.nodes, reduceCalcWhitespaces);
  28. return false;
  29. }
  30. }
  31. }
  32. exports.default = (0, _postcss.plugin)("postcss-normalize-whitespace", () => {
  33. return css => {
  34. const cache = {};
  35. css.walk(node => {
  36. const { type } = node;
  37. if (~[decl, rule, atrule].indexOf(type) && node.raws.before) {
  38. node.raws.before = node.raws.before.replace(/\s/g, "");
  39. }
  40. if (type === decl) {
  41. // Ensure that !important values do not have any excess whitespace
  42. if (node.important) {
  43. node.raws.important = "!important";
  44. }
  45. // Remove whitespaces around ie 9 hack
  46. node.value = node.value.replace(/\s*(\\9)\s*/, "$1");
  47. const value = node.value;
  48. if (cache[value]) {
  49. node.value = cache[value];
  50. } else {
  51. const parsed = (0, _postcssValueParser2.default)(node.value);
  52. const result = parsed.walk(reduceWhitespaces).toString();
  53. // Trim whitespace inside functions & dividers
  54. node.value = result;
  55. cache[value] = result;
  56. }
  57. // Remove extra semicolons and whitespace before the declaration
  58. if (node.raws.before) {
  59. const prev = node.prev();
  60. if (prev && prev.type !== rule) {
  61. node.raws.before = node.raws.before.replace(/;/g, "");
  62. }
  63. }
  64. node.raws.between = ":";
  65. node.raws.semicolon = false;
  66. } else if (type === rule || type === atrule) {
  67. node.raws.between = node.raws.after = "";
  68. node.raws.semicolon = false;
  69. }
  70. });
  71. // Remove final newline
  72. css.raws.after = "";
  73. };
  74. });
  75. module.exports = exports["default"];