stringifier.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = _default;
  6. var order = {
  7. "*": 0,
  8. "/": 0,
  9. "+": 1,
  10. "-": 1
  11. };
  12. function round(value, prec) {
  13. if (prec !== false) {
  14. var precision = Math.pow(10, prec);
  15. return Math.round(value * precision) / precision;
  16. }
  17. return value;
  18. }
  19. function stringify(node, prec) {
  20. switch (node.type) {
  21. case "MathExpression":
  22. {
  23. var left = node.left,
  24. right = node.right,
  25. op = node.operator;
  26. var str = "";
  27. if (left.type === 'MathExpression' && order[op] < order[left.operator]) {
  28. str += `(${stringify(left, prec)})`;
  29. } else {
  30. str += stringify(left, prec);
  31. }
  32. str += order[op] ? ` ${node.operator} ` : node.operator;
  33. if (right.type === 'MathExpression' && order[op] < order[right.operator]) {
  34. str += `(${stringify(right, prec)})`;
  35. } else {
  36. str += stringify(right, prec);
  37. }
  38. return str;
  39. }
  40. case 'Number':
  41. return round(node.value, prec);
  42. case 'Function':
  43. return node.value;
  44. default:
  45. return round(node.value, prec) + node.unit;
  46. }
  47. }
  48. function _default(calc, node, originalValue, options, result, item) {
  49. var str = stringify(node, options.precision);
  50. var shouldPrintCalc = node.type === "MathExpression" || node.type === "Function";
  51. if (shouldPrintCalc) {
  52. // if calc expression couldn't be resolved to a single value, re-wrap it as
  53. // a calc()
  54. str = `${calc}(${str})`; // if the warnWhenCannotResolve option is on, inform the user that the calc
  55. // expression could not be resolved to a single value
  56. if (options.warnWhenCannotResolve) {
  57. result.warn("Could not reduce expression: " + originalValue, {
  58. plugin: 'postcss-calc',
  59. node: item
  60. });
  61. }
  62. }
  63. return str;
  64. }
  65. module.exports = exports.default;