source: frontend/node_modules/postcss-calc/src/lib/stringifier.js

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 13 days ago

Fix frontend appearance

  • Property mode set to 100644
File size: 2.3 KB
Line 
1'use strict';
2const order = {
3 '*': 0,
4 '/': 0,
5 '+': 1,
6 '-': 1,
7};
8
9/**
10 * @param {number} value
11 * @param {number | false} prec
12 */
13function round(value, prec) {
14 if (prec !== false) {
15 const precision = Math.pow(10, prec);
16 return Math.round(value * precision) / precision;
17 }
18 return value;
19}
20
21/**
22 * @param {number | false} prec
23 * @param {import('../parser').CalcNode} node
24 *
25 * @return {string}
26 */
27function stringify(node, prec) {
28 switch (node.type) {
29 case 'MathExpression': {
30 const { left, right, operator: op } = node;
31 let str = '';
32 if (left.type === 'MathExpression' && order[op] < order[left.operator]) {
33 str += `(${stringify(left, prec)})`;
34 } else {
35 str += stringify(left, prec);
36 }
37
38 str += order[op] ? ` ${node.operator} ` : node.operator;
39
40 if (
41 right.type === 'MathExpression' &&
42 order[op] < order[right.operator]
43 ) {
44 str += `(${stringify(right, prec)})`;
45 } else {
46 str += stringify(right, prec);
47 }
48
49 return str;
50 }
51 case 'Number':
52 return round(node.value, prec).toString();
53 case 'Function':
54 return node.value.toString();
55 case 'ParenthesizedExpression':
56 return `(${stringify(node.content, prec)})`;
57 default:
58 return round(node.value, prec) + node.unit;
59 }
60}
61
62/**
63 * @param {string} calc
64 * @param {import('../parser').CalcNode} node
65 * @param {string} originalValue
66 * @param {{precision: number | false, warnWhenCannotResolve: boolean}} options
67 * @param {import("postcss").Result} result
68 * @param {import("postcss").ChildNode} item
69 *
70 * @returns {string}
71 */
72module.exports = function (calc, node, originalValue, options, result, item) {
73 let str = stringify(node, options.precision);
74
75 const shouldPrintCalc =
76 node.type === 'MathExpression' || node.type === 'Function';
77
78 if (shouldPrintCalc) {
79 // if calc expression couldn't be resolved to a single value, re-wrap it as
80 // a calc()
81 str = `${calc}(${str})`;
82
83 // if the warnWhenCannotResolve option is on, inform the user that the calc
84 // expression could not be resolved to a single value
85 if (options.warnWhenCannotResolve) {
86 result.warn('Could not reduce expression: ' + originalValue, {
87 plugin: 'postcss-calc',
88 node: item,
89 });
90 }
91 }
92 return str;
93};
Note: See TracBrowser for help on using the repository browser.