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