Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
"@bundled-es-modules/deepmerge": "^4.3.1",
"@bundled-es-modules/postcss-calc-ast-parser": "^0.1.6",
"@tokens-studio/types": "^0.5.1",
"@tokens-studio/unit-calculator": "^0.0.1",
"colorjs.io": "^0.5.2",
"expr-eval-fork": "^2.0.2",
"is-mergeable-object": "^1.1.1"
Expand Down
54 changes: 9 additions & 45 deletions src/checkAndEvaluateMath.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ import { DesignToken } from 'style-dictionary/types';
import { Parser } from 'expr-eval-fork';
import { parse, reduceExpression } from '@bundled-es-modules/postcss-calc-ast-parser';
import { defaultFractionDigits } from './utils/constants.js';
import { reduceToFixed } from './utils/reduceToFixed.js';
import { strictCheckAndEvaluateMath, MathOptions } from './strictCheckAndEvaluateMath.js';
import { transformByTokenType } from './utils/transformByTokenType.js';

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

Expand Down Expand Up @@ -148,16 +151,18 @@ export function parseAndReduce(
return result;
}

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

export function checkAndEvaluateMath(
token: DesignToken,
fractionDigits?: number,
strictOptions?: Partial<MathOptions>,
): DesignToken['value'] {
if (strictOptions) return strictCheckAndEvaluateMath(token, { fractionDigits, ...strictOptions });

const expr = token.$value ?? token.value;
const type = token.$type ?? token.type;

Expand All @@ -177,48 +182,7 @@ export function checkAndEvaluateMath(
return reducedExprs.join(' ');
};

const transformProp = (val: Record<string, number | string>, prop: string) => {
if (typeof val === 'object' && val[prop] !== undefined) {
val[prop] = resolveMath(val[prop]);
}
return val;
};

let transformed = expr;
switch (type) {
case 'typography':
case 'border': {
transformed = transformed as Record<string, number | string>;
// double check that expr is still an object and not already shorthand transformed to a string
if (typeof expr === 'object') {
Object.keys(transformed).forEach(prop => {
transformed = transformProp(transformed, prop);
});
}
break;
}
case 'shadow': {
transformed = transformed as
| Record<string, number | string>
| Record<string, number | string>[];
const transformShadow = (shadowVal: Record<string, number | string>) => {
// double check that expr is still an object and not already shorthand transformed to a string
if (typeof expr === 'object') {
Object.keys(shadowVal).forEach(prop => {
shadowVal = transformProp(shadowVal, prop);
});
}
return shadowVal;
};
if (Array.isArray(transformed)) {
transformed = transformed.map(transformShadow);
}
transformed = transformShadow(transformed);
break;
}
default:
transformed = resolveMath(transformed);
}
const transformed = transformByTokenType(expr, type, resolveMath);

return transformed;
}
9 changes: 8 additions & 1 deletion src/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,14 @@ 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, platformCfg) => checkAndEvaluateMath(token, platformCfg.mathFractionDigits),
transform: (token, platformCfg) =>
checkAndEvaluateMath(
token,
// backwards compability prop
platformCfg.mathFractionDigits,
// strict math mode options
platformCfg.mathOptions,
),
});

sd.registerTransform({
Expand Down
70 changes: 70 additions & 0 deletions src/strictCheckAndEvaluateMath.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { run, config as calcConfig } from '@tokens-studio/unit-calculator';
import type { IUnitValue } from '@tokens-studio/unit-calculator';
import { Parser } from 'expr-eval-fork';
import { DesignToken } from 'style-dictionary/types';
import { defaultFractionDigits } from './utils/constants.js';
import { MathExprEvalError } from './utils/errors.js';
import { reduceToFixed } from './utils/reduceToFixed.js';
import { transformByTokenType } from './utils/transformByTokenType.js';

const { roundTo } = new Parser().functions;

export const defaultCalcConfig = {
...calcConfig.defaultConfig,
mathFunctions: {
...calcConfig.defaultMathFunctions,
roundTo: (a: IUnitValue, b: IUnitValue) => {
const value = roundTo(a.value, b.value);
return { value, unit: a.unit };
},
},
};

export interface MathOptions {
fractionDigits: number;
calcConfig?: calcConfig.CalcConfig;
}

export function evaluateMathExpr(
expr: string,
{ fractionDigits, calcConfig }: MathOptions,
): string | number {
try {
const parsed = run(expr, calcConfig);
const values = parsed.exec().map(function (result) {
const { value, unit } = result;
const fixedValue = typeof value === 'number' ? reduceToFixed(value, fractionDigits) : value;
return unit ? `${fixedValue}${unit}` : fixedValue;
});
return values.length > 1 ? values.join(' ') : values[0];
} catch (exception) {
throw new MathExprEvalError({
value: expr,
exception: exception instanceof Error ? exception : undefined,
});
}
}

export function strictCheckAndEvaluateMath(
token: DesignToken,
options: Partial<MathOptions> = {},
): DesignToken['value'] {
const opts: MathOptions = {
fractionDigits: options.fractionDigits ?? defaultFractionDigits,
calcConfig: options.calcConfig ?? defaultCalcConfig,
};

const expr = token.$value ?? token.value;
const type = token.$type ?? token.type;

if (!['string', 'object'].includes(typeof expr)) {
return expr;
}

const resolveMath = (expr: DesignToken['value']) => {
if (typeof expr !== 'string') return expr;
return evaluateMathExpr(expr, opts);
};

return transformByTokenType(expr, type, resolveMath);
}
11 changes: 11 additions & 0 deletions src/utils/errors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export class MathExprEvalError extends Error {
value: string;
exception?: Error;

constructor({ value, exception }: { value: string; exception?: Error }) {
super('Could not evaluate expression');
this.name = 'MathExprEvalError';
this.value = value;
this.exception = exception;
}
}
6 changes: 0 additions & 6 deletions src/utils/is-nothing.ts

This file was deleted.

4 changes: 4 additions & 0 deletions src/utils/reduceToFixed.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export function reduceToFixed(val: number, fractionDigits?: number): number {
// the outer Number() gets rid of insignificant trailing zeros of decimal numbers
return Number(Number.parseFloat(val.toString()).toFixed(fractionDigits));
}
51 changes: 51 additions & 0 deletions src/utils/transformByTokenType.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import type { DesignToken } from 'style-dictionary/types';

export function transformByTokenType(
expr: DesignToken['value'],
type: string | undefined,
resolveMath: (expr: number | string) => number | string,
): DesignToken['value'] {
const transformProp = (val: Record<string, number | string>, prop: string) => {
if (typeof val === 'object' && val[prop] !== undefined) {
val[prop] = resolveMath(val[prop]);
}
return val;
};

let transformed = expr;
switch (type) {
case 'typography':
case 'border': {
transformed = transformed as Record<string, number | string>;
// double check that expr is still an object and not already shorthand transformed to a string
if (typeof expr === 'object') {
Object.keys(transformed).forEach(prop => {
transformed = transformProp(transformed, prop);
});
}
break;
}
case 'shadow': {
transformed = transformed as
| Record<string, number | string>
| Record<string, number | string>[];
const transformShadow = (shadowVal: Record<string, number | string>) => {
// double check that expr is still an object and not already shorthand transformed to a string
if (typeof expr === 'object') {
Object.keys(shadowVal).forEach(prop => {
shadowVal = transformProp(shadowVal, prop);
});
}
return shadowVal;
};
if (Array.isArray(transformed)) {
transformed = transformed.map(transformShadow);
}
transformed = transformShadow(transformed);
break;
}
default:
transformed = resolveMath(transformed);
}
return transformed;
}
Loading
Loading