postcss-calc
Version:
PostCSS plugin to reduce calc()
125 lines (114 loc) • 4.14 kB
JavaScript
// Spec: https://www.w3.org/TR/css-values-4/#serialize-a-calculation-tree
// Outer calc() is added when the top-level result contains an arithmetic
// operator, or when a finite scalar needs context-sensitive CSS semantics.
import { checkCalculationDepth } from './limits.js';
import { isCalculationFunction, lookupMathFunction } from './functions.js';
import { isScalar } from './serialize/precision.js';
import { TextSink } from './serialize/sink.js';
import {
emitCall,
emitOpaqueCall,
emitMathResult,
emitWrappedRoot,
} from './serialize/expression.js';
/**
* @typedef {import('./node.js').Node} Node
* @typedef {import('./node.js').Sum} Sum
* @typedef {import('./node.js').Product} Product
* @typedef {import('./node.js').ProductFactor} ProductFactor
* @typedef {object} SerializeOptions
* @property {number | false} [precision] Decimal places for numbers. `false` disables rounding. Default 5.
* @property {string} [calcName] Wrapper name to use when `calc()` is needed. Default `'calc'`.
* @property {boolean} [unwrapSingleNegativeNumber] Deprecated alias for `unwrapSingleValue`.
* @property {boolean} [unwrapSingleValue] Serialize fully resolved finite scalar results without calculation syntax.
*/
/** @param {SerializeOptions} opts @return {'standard' | 'unwrap-all'} */
function normalizeScalarPolicy(opts) {
return opts.unwrapSingleValue || opts.unwrapSingleNegativeNumber
? 'unwrap-all'
: 'standard';
}
/**
* @param {SerializeOptions} opts
* @param {import('./serialize/sink.js').Sink} out
* @return {import('./serialize/precision.js').SerializeSession}
*/
function makeSession(opts, out) {
return {
out,
precision: opts.precision ?? 5,
scalarPolicy: normalizeScalarPolicy(opts),
};
}
/**
* @param {Node} node
* @param {SerializeOptions} [opts]
* @return {string}
*/
function serialize(node, opts = {}) {
checkCalculationDepth(node);
const out = new TextSink();
emitMathResult(node, makeSession(opts, out), opts.calcName ?? 'calc');
return out.join();
}
/**
* Print a result into `out`. An unresolved root that is not a calculation and
* does not match its own name prints nothing.
*
* @param {{tree: Node, status: 'resolved' | 'unresolved', rootName: string, rootSpelling: string, calculation?: boolean}} result
* @param {SerializeOptions} opts
* @param {import('./serialize/sink.js').Sink} out
* @return {boolean} Whether anything was printed.
*/
function printResult(result, opts, out) {
const node = result.tree;
checkCalculationDepth(node);
const isCalc = result.calculation ?? isCalculationFunction(result.rootName);
const session = makeSession(opts, out);
if (!isCalc && result.status === 'unresolved') {
const rootName =
result.calculation === undefined
? result.rootName.toLowerCase()
: result.rootName;
if (
(node.type === 'Call' || node.type === 'OpaqueCall') &&
node.name.toLowerCase() === rootName
) {
if (node.type === 'Call') emitCall(node, session, result.rootSpelling);
else emitOpaqueCall(node, session, result.rootSpelling);
return true;
}
return false;
}
const wrapper = isCalc
? result.rootSpelling || opts.calcName || 'calc'
: 'calc';
// A bare Ident/Call result still needs calc() under every policy, unless
// it is a math function (min(), clamp(), ...) that is valid on its own.
if (
!isScalar(node) &&
!(
!isCalc &&
node.type === 'Call' &&
lookupMathFunction(node.name) !== undefined
)
) {
emitWrappedRoot(node, session, wrapper);
} else {
emitMathResult(node, session, wrapper);
}
return true;
}
/**
* Returns `undefined` for an unresolved root that is not a calculation and
* does not match its own name: the caller keeps the source text as it is.
*
* @param {Parameters<typeof printResult>[0]} result
* @param {SerializeOptions} [opts]
* @return {string | undefined}
*/
function serializeResult(result, opts = {}) {
const out = new TextSink();
return printResult(result, opts, out) ? out.join() : undefined;
}
export { printResult, serialize, serializeResult };