import { existsSync, mkdirSync } from 'node:fs'; import { appendFile, readFile, writeFile } from 'node:fs/promises'; import { posix } from 'node:path'; import StyleDictionary from 'style-dictionary'; import { fixCSSFile } from './src/transforms/css/cssFixers.mts'; import { registerTokenStudioTransformGroup } from './src/transforms/styleDictonary/styleDictionaryTransforms.mts'; // Will take the theme name and remove all spaces and make it lowercase const normalizeThemeName = (name: string): string => { return name.toLowerCase().replaceAll(/\s+/g, ''); }; const removeUnitlessLineHeightTransform = () => { // During update to W3C DTCG format, we found that the tokens-studio transformGroup // includes the transform "ts/size/lineheight" which transforms line-height token values declared with % into a unitless value. // This caused minor UI changes in many of our components. We decided that this is not something we want to have happen automatically. // Therefore we remove this specific transform from the transformGroup before building. const indexOfLineHeightTransform = StyleDictionary.hooks.transformGroups['tokens-studio'].indexOf('ts/size/lineheight'); if (indexOfLineHeightTransform !== -1) { StyleDictionary.hooks.transformGroups['tokens-studio'].splice(indexOfLineHeightTransform, 1); } }; StyleDictionary.registerAction({ name: 'fixCSSTokens', do: async function (_dictionary, config) { const buildPath = config.buildPath || 'dist/'; const files = config.files || []; // TS allows roundTo(), exponentiation (^) and basic calculations (without `calc()`) in their values, but these are not valid CSS. for (const file of files) { if (!file.destination) { throw new Error(`Expected a destination for build file in "${buildPath}".`); } const filePath = posix.join(buildPath, file.destination); console.log('🔧 fixing css:', filePath); await fixCSSFile(filePath); } }, // No undo action available - files are deleted during cleanup. undo: function () {}, }); // Custom header to add generation date StyleDictionary.registerFileHeader({ name: 'nlds-rhc-header', fileHeader: function (defaultMessage = []) { return [...defaultMessage, `Generated on ${new Date().toUTCString()}`]; }, }); const excludes = [ 'components/avatar', 'components/form-field-option-label', 'components/modal-dialog', 'components/pagination/todo', 'components/status-badge', 'components/summary-list', 'components/task-list', 'components/toolbar-button', ]; // register token-studio transforms registerTokenStudioTransformGroup(StyleDictionary); // Get the platforms config const getPlatformsConfig = (buildPath: string, themeName: string) => { return { javascript: { transformGroup: 'tokens-studio', transforms: ['name/camel'], buildPath, excludes, options: { fileHeader: 'nlds-rhc-header', }, files: [ { format: 'typescript/es6-declarations', destination: 'index.d.ts', }, { format: 'typescript/module-declarations', destination: 'tokens.d.ts', }, { destination: 'index.js', format: 'javascript/es6', }, { destination: 'tokens.js', format: 'javascript/module', }, { destination: 'index.tokens.json', format: 'json/nested', }, { destination: 'index.json', format: 'json/flat', }, ], }, web: { transformGroup: 'tokens-studio', transforms: ['name/kebab'], buildPath, excludes, actions: ['fixCSSTokens'], options: { fileHeader: 'nlds-rhc-header', outputReferences: true, }, files: [ { destination: 'root.css', format: 'css/variables', }, { destination: 'index.css', format: 'css/variables', options: { selector: `.${themeName}`, }, }, { destination: '_variables.scss', format: 'scss/variables', }, ], }, }; }; const darkModeCSS = await readFile('./src/dark-mode.css', 'utf8'); const fluidCSS = await readFile('./src/fluid.css', 'utf8'); // This will build the base theme lintblauw async function buildBaseTokens() { const config = getPlatformsConfig('dist/', 'rhc-theme'); const StyleDictionaryBase = new StyleDictionary({ log: { verbosity: 'verbose' }, source: ['./src/**/base.tokens.json'], preprocessors: ['tokens-studio'], platforms: { ...config, }, }); await StyleDictionaryBase.hasInitialized; await StyleDictionaryBase.cleanAllPlatforms(); await StyleDictionaryBase.buildAllPlatforms(); await appendFile(`dist/index.css`, darkModeCSS); await appendFile(`dist/index.css`, fluidCSS); } // This will build the themes async function buildThemes() { const themesJson = await readFile('./src/generated/themes.json', 'utf-8'); const themes: Record = JSON.parse(themesJson); // Process each theme separately for (const [theme, themeData] of Object.entries(themes)) { const themeName = normalizeThemeName(theme); const themesDir = `./src/generated/${themeName}`; // Create the theme directory if it doesn't exist if (!existsSync(themesDir)) { mkdirSync(themesDir, { recursive: true }); } // Write individual theme tokens await writeFile(posix.join(themesDir, `tokens.json`), JSON.stringify(themeData.tokens, null, 2)); const config = getPlatformsConfig(`dist/${themeName}/`, themeName); // Create a separate Style Dictionary instance for each theme const StyleDictionaryTheme = new StyleDictionary({ log: { verbosity: 'verbose' }, source: [`./src/generated/${themeName}/tokens.json`], preprocessors: ['tokens-studio'], platforms: { ...config, }, }); await StyleDictionaryTheme.hasInitialized; // Build this specific theme await StyleDictionaryTheme.cleanAllPlatforms(); await StyleDictionaryTheme.buildAllPlatforms(); // Append the fluid and dark mode CSS, with the appropriate class name await appendFile( `dist/${themeName}/index.css`, `${darkModeCSS}\n${fluidCSS}`.replaceAll('.rhc-theme', `.${themeName}`), ); } } async function build() { removeUnitlessLineHeightTransform(); // This needs to happen before building anything await buildBaseTokens(); await buildThemes(); } await build().catch((error) => { console.error(error); process.exitCode = 1; });