From 0686e9dc8153bcd8e1ae08395285fdd87019940e Mon Sep 17 00:00:00 2001 From: Simon Racine-Chevalier Date: Wed, 3 Jul 2024 12:15:14 -0600 Subject: [PATCH] feat: add config option to transform --- src/checkAndEvaluateMath.ts | 12 ++++++++---- src/register.ts | 2 +- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/src/checkAndEvaluateMath.ts b/src/checkAndEvaluateMath.ts index 324266b..fd70454 100644 --- a/src/checkAndEvaluateMath.ts +++ b/src/checkAndEvaluateMath.ts @@ -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(); @@ -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; @@ -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; @@ -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]; } diff --git a/src/register.ts b/src/register.ts index ec4e070..169812e 100644 --- a/src/register.ts +++ b/src/register.ts @@ -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({