style-dictionary-utils
Version:
Utilities to use in your style dictionary config
53 lines (52 loc) • 2.29 kB
JavaScript
import { isDimensionFilter } from '../filter/isDimension.js';
import { getValue } from '../utilities/getValue.js';
export const dimensionValueTransformer = (dimensionTokenValue, platform) => {
// If already a string, return as-is
if (typeof dimensionTokenValue === 'string') {
return dimensionTokenValue;
}
if (dimensionTokenValue === undefined || dimensionTokenValue === null) {
throw `Invalid dimension value: 'undefined'\n`;
}
// handle object format
const { value, unit } = dimensionTokenValue;
const appendUnit = (platform === null || platform === void 0 ? void 0 : platform.appendUnit) === false ? false : true;
const outputUnit = (platform === null || platform === void 0 ? void 0 : platform.outputUnit) || unit || 'px';
const supportedUnits = ['px', 'rem'];
if (isNaN(value)) {
throw `Invalid Number: '${value}' is not a valid number\n`;
}
if (!supportedUnits.includes(unit)) {
throw `Invalid Unit: '${unit}' is not a valid unit\n`;
}
if (unit !== outputUnit && unit === 'px' && outputUnit === 'rem') {
const baseFont = (platform === null || platform === void 0 ? void 0 : platform.basePxFontSize) || 16;
return `${value / baseFont}${appendUnit ? outputUnit : ''}`;
}
if (unit !== outputUnit && unit === 'rem' && outputUnit === 'px') {
const baseFont = (platform === null || platform === void 0 ? void 0 : platform.basePxFontSize) || 16;
return `${baseFont * value}${appendUnit ? outputUnit : ''}`;
}
return `${value}${appendUnit ? outputUnit : ''}`;
};
/**
* dimension
* @description convert all dimensions that use pixel value to rem, uses `platform.options.basePxFontSize`
* as the base font, or `16` if not provided
*/
export const dimensionCss = {
name: 'dimension/css',
type: `value`,
transitive: true,
filter: (token) => isDimensionFilter(token),
transform: (token, platform) => {
try {
const tokenValue = getValue(token);
return dimensionValueTransformer(tokenValue, platform);
// catch errors and rethrow with token name
}
catch (error) {
throw new Error(`Error transforming dimension token '${token.name}': ${error}`);
}
},
};