Skip to content

Commit

Permalink
feat: add config option to transform
Browse files Browse the repository at this point in the history
  • Loading branch information
Razinsky committed Jul 3, 2024
1 parent b454787 commit 0686e9d
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 5 deletions.
12 changes: 8 additions & 4 deletions src/checkAndEvaluateMath.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { DesignToken } from 'style-dictionary/types';
import { Parser } from 'expr-eval-fork';
import { parse, reduceExpression } from '@bundled-es-modules/postcss-calc-ast-parser';

const defaultFractionDigits = 4;
const mathChars = ['+', '-', '*', '/'];

const parser = new Parser();
Expand Down Expand Up @@ -74,7 +75,7 @@ function splitMultiIntoSingleValues(expr: string): string[] {
return [expr];
}

function parseAndReduce(expr: string): string | number {
function parseAndReduce(expr: string, fractionDigits = defaultFractionDigits): string | number {
let result: string | number = expr;

let evaluated;
Expand Down Expand Up @@ -127,12 +128,15 @@ function parseAndReduce(expr: string): string | number {
}

// the outer Number() gets rid of insignificant trailing zeros of decimal numbers
const reducedTo3Fixed = Number(Number.parseFloat(`${result}`).toFixed(3));
const reducedTo3Fixed = Number(Number.parseFloat(`${result}`).toFixed(fractionDigits));
result = resultUnit ? `${reducedTo3Fixed}${resultUnit}` : reducedTo3Fixed;
return result;
}

export function checkAndEvaluateMath(token: DesignToken): DesignToken['value'] {
export function checkAndEvaluateMath(
token: DesignToken,
fractionDigits?: number,
): DesignToken['value'] {
const expr = token.$value ?? token.value;
const type = token.$type ?? token.type;

Expand All @@ -145,7 +149,7 @@ export function checkAndEvaluateMath(token: DesignToken): DesignToken['value'] {
return expr;
}
const exprs = splitMultiIntoSingleValues(expr);
const reducedExprs = exprs.map(_expr => parseAndReduce(_expr));
const reducedExprs = exprs.map(_expr => parseAndReduce(_expr, fractionDigits));
if (reducedExprs.length === 1) {
return reducedExprs[0];
}
Expand Down
2 changes: 1 addition & 1 deletion src/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ export async function register(sd: typeof StyleDictionary, transformOpts?: Trans
type: 'value',
transitive: true,
filter: token => ['string', 'object'].includes(typeof (token.$value ?? token.value)),
transform: token => checkAndEvaluateMath(token),
transform: (token, config) => checkAndEvaluateMath(token, config.options?.mathFractionDigits),
});

sd.registerTransform({
Expand Down

0 comments on commit 0686e9d

Please sign in to comment.