UNPKG

@tokens-studio/sd-transforms

Version:

Custom transforms for Style-Dictionary, to work with Design Tokens that are exported from Tokens Studio

83 lines (82 loc) 2.69 kB
import { typeDtcgDelegate } from 'style-dictionary/utils'; const typesMap = { fontFamilies: 'fontFamily', fontWeights: 'fontWeight', fontSizes: 'fontSize', lineHeights: 'lineHeight', boxShadow: 'shadow', spacing: 'dimension', sizing: 'dimension', borderRadius: 'dimension', borderWidth: 'dimension', letterSpacing: 'dimension', paragraphSpacing: 'dimension', paragraphIndent: 'dimension', text: 'content', }; const propsMap = { shadow: { x: 'offsetX', y: 'offsetY', }, }; function recurse(slice) { const isToken = (Object.hasOwn(slice, '$type') && Object.hasOwn(slice, '$value')) || (Object.hasOwn(slice, 'type') && Object.hasOwn(slice, 'value')); if (isToken) { const { $value, value, type, $type } = slice; const usesDTCG = Object.hasOwn(slice, '$value'); const t = (usesDTCG ? $type : type); const v = usesDTCG ? $value : value; const tProp = `${usesDTCG ? '$' : ''}type`; const newT = (typesMap[t] ?? t); const k = 'studio.tokens'; if (newT !== t) { // replace the type with new type slice[tProp] = newT; // store the original type as metadata slice.$extensions = { ...slice.$extensions, [k]: { ...(slice.$extensions?.[k] ?? {}), originalType: t, }, }; } // now also check propsMap if we need to map some props if (typeof v === 'object') { const pMap = propsMap[newT]; if (pMap) { const convertProps = (obj) => { Object.entries(pMap).forEach(([key, propValue]) => { if (obj[key] !== undefined) { obj[propValue] = obj[key]; delete obj[key]; } }); }; const newV = v; if (Array.isArray(newV)) { newV.forEach(convertProps); } else { convertProps(newV); } slice[`${usesDTCG ? '$' : ''}value`] = newV; } } } else { Object.values(slice).forEach(val => { if (typeof val === 'object') { recurse(val); } }); } } export function alignTypes(dictionary) { // pre-emptively type dtcg delegate because otherwise we cannot align types properly here const copy = typeDtcgDelegate(structuredClone(dictionary)); recurse(copy); return copy; }