Implementation Strategy:
a. Token Structure: We can use a JSON or JavaScript object to define our tokens. For example:
baseTokens = {
color: {
primary: '#000000',
secondary: '#ffffff',
},
spacing: {
small: '8px',
medium: '16px',
}
}
brandATokens = {
color: {
primary: '#ff0000', // overrides base
secondary: '#00ff00',
},
// ... must define all tokens in the base? Or can we inherit?
}
b. Inheritance vs Composition: We can have a base set and then each brand overrides only what it needs. But we must ensure that every token that the application uses is defined in the brand's set (either by overriding or inheriting). Alternatively, we can require that each brand defines every token (no inheritance) to be explicit.
c. Compile-Time Check: We can write a script (in Node.js, for example) that:
- Takes the base tokens and a list of brand tokens.
- Checks that each brand has the same structure (same keys) as the base tokens (or a subset? but then we must have a fallback to base for missing ones?).
- We can also check for deprecated tokens, etc.
d. CSS Generation: We can generate a CSS file for each brand that sets the CSS variables. We can do this at build time.
Example CSS:
:root {
--color-primary: #000000;
--color-secondary: #ffffff;
--spacing-small: 8px;
--spacing-medium: 16px;
}
[data-brand="brandA"] {
--color-primary: #ff0000;
--color-secondary: #00ff00;
}
But note: if brandA doesn't define spacing tokens, then we fall back to the :root (base) values. However, if we want to enforce that each brand defines every token, then we can generate the CSS without falling back to base? Or we can have a step that merges base and brand, and then generates the CSS for that brand as a complete set.
Alternatively, we can generate a separate CSS file for each brand that includes the base and then the overrides? But that would duplicate the base tokens in every brand's CSS. Instead, we can have:
base.css: defines all tokens in :root
brandA.css: only defines the overrides for brandA, and we rely on cascade.
But then if brandA doesn't override a token, it uses the base. That's acceptable if we allow partial overrides. However, if we want to enforce complete definitions, we can generate a CSS file for each brand that includes all tokens (by merging base and brand) and then we don't need the base.css? But then we have to load the brand-specific CSS and we lose the ability to have a default.
Alternatively, we can have:
:root { ...base... }
[data-brand="brandA"] { ...merged base+brandA... }
But then the brandA block would have to redeclare every token? That's redundant if we have many tokens.
e. Better Approach: Use CSS custom properties and cascade. We'll have:
:root {
/* base tokens */
}
[data-brand="brandA"] {
/* only the tokens that brandA overrides */
}
Then, in our components, we use the CSS variables. This way, we don't have to generate a full set for each brand. However, we must ensure that the brand-specific CSS includes at least the tokens that are different. But what if a brand wants to change every token? Then we have to list every token in the brand's CSS.
To avoid having to list every token in the brand's CSS, we can generate a CSS file for each brand that sets the variables on a parent element (like [data-brand="brandA"]) and we merge the base and the brand overrides. But then we have to generate the entire set of tokens for each brand? That might be acceptable if we have few brands and tokens.
Alternatively, we can have a build step that generates a CSS file for each brand that includes:
[data-brand="brandA"] {
--color-primary: ...;
--color-secondary: ...;
... all tokens ...
}
Then we don't need the base in :root? Or we can have base in :root and then the brand overrides only what's different? But then we have two sources of truth.
Let me propose:
We have a base set of tokens in :root. Then for each brand, we generate a CSS file that only includes the overrides. We then load the base CSS and the brand-specific CSS. The cascade will take care of the rest.
But then if a token is not overridden by the brand, it uses the base. This is acceptable if the base is a valid fallback for every brand? Not necessarily, because the base might be for a default brand and other brands might have different defaults for some tokens.
Alternatively, we can generate for each brand a complete set of tokens (by merging base and brand overrides) and then we set the brand's CSS on the [data-brand] selector. Then we don't need the base in :root? But then we have to set the base for the default brand? We can have:
:root {
/* base tokens, which are the same as the default brand? */
}
[data-brand="brandA"] {
/* all tokens for brandA, which may be completely different from base */
}
This way, the default brand uses the :root, and other brands use their own. But then we have to maintain two sets: the base (which is the default) and then the other brands. And we have to make sure that the base and the default brand are the same? Or we can have the base be the default brand? Then we don't need a separate default brand.
Let's define:
We have a set of brands, one of which is the default (maybe called "default" or "base"). We generate:
For the default brand, we don't need a [data-brand] selector because we use :root. But then if we have a non-default brand that doesn't override a token, it will fall back to the default (which is in :root). But what if the non-default brand wants a different value for a token that the default brand doesn't define? Then we have to define it in the non-default brand.
Alternatively, we can generate for every brand (including the default) a [data-brand] selector? Then we don't use :root for tokens? But then we have to set the brand on the html element and we lose the ability to have a default without setting a brand? We can set the default brand on the html element by default? Or we can have:
:root {
/* base tokens, which are the same as the default brand? */
}
[data-brand] {
/* for every brand, including default? But then we have duplication. */
}
Let me simplify:
We'll have a base token set (which is the default brand). Then for every other brand, we generate a CSS file that only overrides the tokens that are different.
In the HTML, we set the default brand by not setting any data-brand, and then the base tokens (in :root) are used. For other brands, we set data-brand="brandX" and then the overrides are applied.
But then the base tokens must be a complete set (all tokens defined) and every brand must have at least the same tokens? Actually, a brand might not need to override every token. So we can have:
baseTokens (complete set) -> :root
brandA overrides (partial set) -> [data-brand="brandA"]
Then, in the component, we use:
color: var(--color-primary);
If brandA doesn't override --color-primary, then it uses the base.
This is acceptable.
However, we must ensure that the brandA overrides are valid (i.e., they only override existing tokens). We can have a compile-time check that the brandA tokens are a subset of the base tokens? Or we can allow new tokens? But then we are extending the token set. We might want to allow that? Probably not, because then we break the consistency of the design system.
So, we enforce that every brand token must exist in the base token set.
f. Compile-Time Guardrails:
We'll have a script that:
1. Reads the base token file (e.g., `baseTokens.js` or `baseTokens.json`).
2. Reads all brand token files (e.g., `brandA.js`, `brandB.js`).
3. For each brand, check that every token in the brand's token object exists in the base token object (at the same path). Also, we can check that the types are the same? (e.g., if base token is a color in hex, then brand token must be a color in hex? Maybe not, but we can have type checking if we define types for tokens.)
4. We can also check for deprecations: if a token is removed from base, then we error if any brand still uses it.
5. We can also check that the base token set is complete (has all the required tokens for the application). But that's a separate concern.
g. Token Definition: We can define tokens in a structured way, for example:
baseTokens = {
color: {
primary: { value: '#000000', type: 'color' },
secondary: { value: '#ffffff', type: 'color' }
},
spacing: {
small: { value: '8px', type: 'spacing' }
}
}
Then in the brand, we can have:
brandA = {
color: {
primary: { value: '#ff0000' } // we don't need to repeat type
}
}
But then we have to merge the base and brand, and we keep the type from base. This way, we can validate that the brand's token value is of the correct type? We can have a type checker that, given the base token's type, checks that the brand token's value matches.
Alternatively, we can just have the value and then we don't have type information. Then we can only check the structure (the keys) and not the value type.
Let's assume we want type checking. We can define a schema for tokens? Or we can have a separate type definition.
Alternatively, we can have a flat structure? But then we lose grouping.
We can do:
baseTokens = {
'color.primary': { value: '#000000', type: 'color' },
'color.secondary': { value: '#ffffff', type: 'color' },
'spacing.small': { value: '8px', type: 'spacing' }
}
Then the brand can override:
brandA = {
'color.primary': { value: '#ff0000' }
}
Then we can check that the key exists in base, and then we can check the type? But we don't have the type in the brand token? We can skip type checking if we don't have the type in the brand. Or we can require that the brand token includes the type? But that's redundant.
Alternatively, we can have:
baseTokens = {
'color.primary': '#000000',
'color.secondary': '#ffffff',
'spacing.small': '8px'
}
Then the brand:
brandA = {
'color.primary': '#ff0000'
}
Then we can only check that the key exists in base. We cannot check the type.
If we want type checking, we need to have a separate type registry.
Let's keep it simple for now and just check the structure (the keys). We can add type checking later if needed.
h. Generation of CSS:
We'll generate a CSS file for the base (which goes into :root) and then for each brand, a CSS file that only contains the overrides.
Example:
base.css:
:root {
--color-primary: #000000;
--color-secondary: #ffffff;
--spacing-small: 8px;
}
brandA.css:
[data-brand="brandA"] {
--color-primary: #ff0000;
}
Then we include base.css and then the brand-specific CSS (if any) in the HTML.
But note: the brand-specific CSS must be loaded after the base.css so that the overrides take effect.
Alternatively, we can generate one CSS file per brand that includes the base and the overrides? Then we don't have to load two files? But then we duplicate the base tokens in every brand's CSS. That might be acceptable if the base tokens are small and we have few brands.
Let's assume we want to avoid duplication. So we'll have:
base.css (for base tokens)
brandA.css (only overrides)
Then in the HTML:
<link rel="stylesheet" href="base.css">
<link rel="stylesheet" href="brandA.css" data-brand="brandA">
But we don't want to load all brand CSS files for every page. We want to load only the brand that is active. We can set the data-brand on the html element and then load the corresponding brand CSS? Or we can have a build that inlines the brand CSS? Or we can have a server that serves the correct brand CSS.
Alternatively, we can generate a single CSS file that includes all brands? Then we load one file and switch by changing the data-brand attribute. But then we load all brands even if we only use one? That's not good for performance.
So, we want to load only the base and the active brand.
We can do:
<html data-brand="brandA">
<head>
<link rel="stylesheet" href="base.css">
<link rel="stylesheet" href="brandA.css">
</head>
Then in brandA.css, we have:
[data-brand="brandA"] {
... overrides ...
}
But note: the base.css sets the :root variables, and then the brandA.css overrides for the same variables when the data-brand is set.
However, if we have multiple brands, we would have to load the base and then the specific brand. We can have a server-side template that includes the correct brand CSS.
Alternatively, we can have a build step that generates a CSS file for each brand that includes the base and the overrides? Then we only load one file per brand? That would be:
base.css (for base tokens) -> we don't need this if we generate full sets for each brand?
brandA-full.css (includes base and overrides) -> then we don't need base.css?
But then we duplicate the base tokens in every brand's full CSS. That's more bytes but fewer requests.
Given that we are concerned about performance, we might want to avoid duplication and have:
base.css (common to all brands)
brandA.css (only overrides, small file)
Then we load two files, but the base is cached and the brand file is small.
Let's go with that.
i. Implementation Steps:
1. Define base tokens in a file (e.g., `tokens/base.js`).
2. Define brand tokens in separate files (e.g., `tokens/brandA.js`).
3. Write a Node.js script that:
a. Reads the base tokens and validates them (maybe ensure they have the required structure?).
b. For each brand token file:
- Validate that the brand token keys are a subset of the base token keys (at the same path). We can do a deep check.
- If there are any tokens in the brand that are not in the base, error.
- Also, we can check that the brand token file doesn't have extra top-level keys? Actually, we can have a structure that matches the base. So we require that the brand token object has the same top-level keys as the base? Not necessarily, because a brand might not override a whole category? Actually, we are allowing partial overrides, so a brand might not have the `spacing` key at all? Then we don't override any spacing.
But note: if the brand token object has a key that the base doesn't have, that's an error. And if the base has a key that the brand doesn't have, that's okay (we just don't override).
c. Generate base.css from base tokens.
d. For each brand, generate a CSS file that contains the overrides (only the tokens that are defined in the brand token object) in the form:
[data-brand="brandA"] {
--token-name: value;
}
How to convert the token object to CSS variable names? We can flatten the token object and use a delimiter (like dot) for nested keys.
Example:
baseTokens = {
color: {
primary: '#000'
}
}
We generate:
--color-primary: #000;
So we flatten the object.
4. We can also generate a TypeScript type definition file for the tokens? That would help in development.
j. Example Code:
Let's assume our tokens are defined in JavaScript files that export an object.
baseTokens.js:
module.exports = {
color: {
primary: '#000000',
secondary: '#ffffff'
},
spacing: {
small: '8px',
medium: '16px'
}
};
brandA.js:
module.exports = {
color: {
primary: '#ff0000'
}
};
Then our build script (buildTokens.js) might look like:
const fs = require('fs');
const path = require('path');
const baseTokens = require('./tokens/baseTokens');
const brandTokensDir = './tokens/brands';
// Function to flatten the token object
function flattenTokens(obj, prefix = '') {
return Object.keys(obj).reduce((acc, key) => {
const value = obj[key];
const newKey = prefix ? `${prefix}-${key}` : key;
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
return { ...acc, ...flattenTokens(value, newKey) };
} else {
return { ...acc, [newKey]: value };
}
}, {});
}
// Generate base.css
const baseFlat = flattenTokens(baseTokens);
let baseCSS = ':root {\n';
for (const [key, value] of Object.entries(baseFlat)) {
baseCSS += ` --${key}: ${value};\n`;
}
baseCSS += '}';
fs.writeFileSync('dist/base.css', baseCSS);
// Process each brand
const brandFiles = fs.readdirSync(brandTokensDir).filter(file => file.endsWith('.js'));
for (const file of brandFiles) {
const brandName = path.basename(file, '.js');
const brandTokens = require(path.join(brandTokensDir, file));
// Validate brand tokens against baseTokens (deep check)
// We'll write a function to check that every key in brandTokens exists in baseTokens at the same path.
function validateBrandTokens(brand, base, path = '') {
for (const key in brand) {
const fullPath = path ? `${path}.${key}` : key;
if (!(key in base)) {
throw new Error(`Brand ${brandName} has token ${fullPath} which is not in base tokens.`);
}
if (typeof brand[key] === 'object' && brand[key] !== null && !Array.isArray(brand[key])) {
if (typeof base[key] !== 'object' || base[key] === null || Array.isArray(base[key])) {
throw new Error(`Base token at ${fullPath} is not an object, but brand token is.`);
}
validateBrandTokens(brand[key], base[key], fullPath);
}
}
}
validateBrandTokens(brandTokens, baseTokens);
// Flatten the brand tokens (only the ones that are present)
const brandFlat = flattenTokens(brandTokens);
let brandCSS = `[data-brand="${brandName}"] {\n`;
for (const [key, value] of Object.entries(brandFlat)) {
brandCSS += ` --${key}: ${value};\n`;
}
brandCSS += '}';
fs.writeFileSync(`dist/brand-${brandName}.css`, brandCSS);
}
k. Usage in Components:
In your component CSS, you use the CSS variables:
.button {
background-color: var(--color-primary);
padding: var(--spacing-small);
}
Then, in your HTML, you set the data-brand attribute on the html element (or a parent) and load the base.css and the brand-specific CSS.
l. Guardrails at Compile Time:
The above script does:
- Validates that every brand token exists in the base.
- Generates the CSS.
We can extend this:
- We can also check that the brand token file doesn't have any extra top-level keys? Actually, the validation function already checks that every key in the brand exists in base, but it doesn't check that the brand doesn't have a top-level key that the base doesn't have? Actually, it does because we loop over the brand keys and check if they are in base. So if the brand has a top-level key that base doesn't have, it will error.
- We can also check for missing tokens? We don't require that the brand has every token, only that it doesn't have extra ones.
- We can also check that the base has all the required tokens for the application? That's a separate check: we can have a list of required tokens (from the components) and check that the base has them.
m. Extending to More Token Types:
The above flattening function will work for any nested object. But note: if we have a token that is an object (like a shadow or a gradient) then we cannot flatten it to a CSS variable because CSS variables are strings. We have to handle complex tokens differently.
We can have a convention: if a token's value is an object, then we don't try to flatten it? Or we stringify it? But then in CSS we cannot use an object.
Alternatively, we can have a different generation for complex tokens? Maybe we don't support nested objects for tokens that are intended to be used as a single CSS variable? We can have:
baseTokens = {
shadow: {
small: '0 2px 4px rgba(0,0,0,0.1)'
}
}
Then we flatten to `--shadow-small`.
But if we have:
baseTokens = {
button: {
background: {
color: '#000',
image: 'url(...)'
}
}
}
Then we cannot represent that as a single CSS variable? We would have to split it into two: `--button-background-color` and `--button-background-image`. So we should avoid nested objects for tokens that are meant to be separate CSS properties.
Therefore, we should design our token structure to be flat in terms of CSS properties. We can have:
baseTokens = {
color: {
buttonBackground: '#000',
buttonImage: 'url(...)'
}
}
So we avoid nested objects for tokens that are independent CSS properties.
Alternatively, we can have a token that is a complex object and then in the component we use multiple CSS variables? Then we would have to define multiple CSS variables for one token? That doesn't make sense.
So, we should design the token set to be a flat map of CSS variables? Or we can have a flat structure in the token definition.
Let's change the token definition to be a flat object? Then we don't need flattening.
Example:
baseTokens = {
'color.primary': '#000',
'color.secondary': '#fff',
'spacing.small': '8px'
}
Then the brand:
brandA = {
'color.primary': '#f00'
}
Then we generate:
:root {
--color-primary: #000;
--color.secondary: #fff; /* wait, we have a dot in the name? */
}
We don't want dots in the CSS variable name? We can use a different delimiter, like colon or dash? But then we have to be consistent.
Alternatively, we can use the dot in the CSS variable? That's allowed? Actually, CSS custom properties can contain a dash but not a dot? According to the spec, the name must start with two dashes and then any sequence of characters, but note that the identifier rules in CSS: https://www.w3.org/TR/css-syntax-3/#ident-token-diagram
It says: ident = [-+]? [a-zA-Z0-9_]|{unicode}|{escape} ...
So dot is not allowed? Actually, the spec says: "Otherwise, if the next character is a hyphen, ..." and then it continues. But the dot is not in the allowed set for an identifier? We can check:
In CSS, custom property names are case-sensitive and can contain any character except: they must start with two dashes and then a sequence of characters that are allowed in an identifier? Actually, the spec says: "The custom property name is an identifier, which means it must follow the same rules as CSS identifiers."
And CSS identifiers cannot start with a digit, cannot contain a dot? Actually, they can contain a dot? Let me check:
In CSS, identifiers (including element names, classes, and IDs) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, two hyphens, or a hyphen followed by a digit.
So dot is not allowed.
Therefore, we cannot use dot in the CSS variable name.
So we should use a different delimiter, like dash.
Example:
baseTokens = {
'color-primary': '#000',
'color-secondary': '#fff',
'spacing-small': '8px'
}
But then we lose the grouping? We can have:
baseTokens = {
color: {
primary: '#000',
secondary: '#fff'
}
}
And then flatten to:
--color-primary: #000;
--color-secondary: #fff;
So we use dash to separate the groups.
That's acceptable.
So our flatten function should use a dash.
Alternatively, we can let the token definition be nested and then we flatten with a dash. That's what we did above.
So we keep the nested structure in the token definition for organization, and then flatten with dash.
n. Summary:
We'll have:
tokens/
base.js
brands/
brandA.js
brandB.js
The token files export an object that can be nested.
We have a build script that:
1. Reads baseTokens.
2. Validates each brandTokens against baseTokens (only that the brand tokens are a subset of base, and that the structure matches for nested objects).
3. Generates base.css (with all base tokens as CSS variables in :root).
4. For each brand, generates a CSS file with only the overrides (the tokens that the brand defines) in a [data-brand="brandName"] block.
Then in the application, we set the data-brand attribute on the html element and include the base.css and the brand-specific CSS.
We can also have a default brand (the base) that doesn't require a data-brand attribute? Actually, the base is in :root, so if we don't set data-brand, we get the base. If we set data-brand to a brand, we get the overrides on top of base.
But what if a brand wants to completely change a token that the base doesn't have? Then we have to add it to the base? Because the validation will fail if the brand has a token that the base doesn't have.
So we must design the base token set to be complete for all brands? Or we can allow brands to extend the token set? But then we break the validation.
Alternatively, we can change the validation to allow brands to have tokens that are not in the base? But then we have to generate CSS variables for those tokens, and we don't have a base value. That's acceptable? Then the brand would define that token and the base wouldn't, so when we are in the base brand, that token is undefined? That might be acceptable if the component that uses that token is only used in that brand.
But we want to enforce that the design system is consistent and that we don't have missing tokens in the base for the components that are shared.
So, we have two options:
Option 1: The base token set must include all tokens that are used by any brand. Then every brand can override any token, and the base is the fallback.
Option 2: Each brand must define a complete set of tokens (no fallback to base). Then we generate a full CSS file for each brand (without base). Then we don't need the base.css? But then we have to load the brand-specific CSS only, and we don't have a base.
We can combine:
We have a base token set that is the default brand. Then for other brands, we can either:
a) Override only the differences (and rely on base for the rest) -> then the base must have all tokens.
b) Define a complete set (and then we don't need base.css for that brand) -> then we generate a full CSS file for that brand (without base) and we don't use the base.css for that brand? But then we have two ways of generating: one for base (which is a full set) and one for other brands (which can be partial or full). That's inconsistent.
Let's enforce:
The base token set must be a complete set (all tokens that the application uses). Then every brand can be a partial set (only overrides). Then we always load base.css and then the brand overrides.
This way, we have a single source of truth for the complete token set (the base) and brands only need to specify what's different.
But then if a brand wants to change a token that the base doesn't have, we have to add it to the base? That's acceptable because the base is the complete set.
So, we require that the base token set is complete (has all the tokens that any component might use). Then we validate that the brand tokens are a subset of the base.
How do we know what tokens are required by the components? We can have a separate step that extracts the token names from the component CSS? That's more complex.
Alternatively, we can have a list of required tokens in the build script? Or we can trust that the base token set is complete and then the brands are subsets.
For now, we'll assume that the base token set is complete.
o. Extending the Validation:
We can have a list of required tokens (from the design system) and check that the base token set includes them.
But that's a separate validation. We can do:
const requiredTokens = ['color-primary', 'spacing-small', ...];
Then check that baseFlat has all these keys.
But note: our tokens are nested, so the required tokens would be the flattened keys.
We can have a file that lists the required tokens (by their flattened name) and then check that the baseFlat has them.
p. Putting it all together:
We'll have:
tokens/
base.js
brands/
brandA.js
brandB.js
requiredTokens.json // list of required flattened token names
Then in the build script:
const requiredTokens = require('./tokens/requiredTokens');
// After flattening baseTokens, check that baseFlat has every token in requiredTokens.
This ensures that the base token set is complete.
q. TypeScript Support:
We can generate a TypeScript type for the tokens? We can generate a type that represents the base token structure? Then in our components, we can import the type and use it for CSS variable names? But CSS variable names are strings, so we might not need TypeScript for that.
Alternatively, we can generate a TypeScript module that exports the flattened token keys as constants? Then we can use them in our code to avoid typos.
Example:
export const tokens = {
colorPrimary: '--color-primary',
spacingSmall: '--spacing-small'
} as const;
Then in component:
style={{ backgroundColor: tokens.colorPrimary }}
But then we are using the CSS variable name as a string, and we have to set it in the style attribute? We might want to use CSS classes.
Alternatively, we can generate a CSS module? But then we are generating CSS, so we can import the CSS.
Given that we are generating CSS files, we can import the CSS in our JavaScript? Then we don't need to reference the variables in JavaScript.
So, for TypeScript, we might not need to generate anything. We can just use the CSS classes and CSS variables in our CSS files.
However, if we want to use the tokens in JavaScript (for inline styles, or for canvas, etc.) then we might want a JavaScript representation.
We can generate a tokens.js file that exports the base token values and the brand token values? Then we can use them in JavaScript.
But then we have two sources of truth: the CSS file and the JavaScript file. We want to avoid that.
Alternatively, we can generate the CSS from the same token source, and then in JavaScript we can read the computed style? That's runtime.
For now, let's focus on CSS.
r. Conclusion:
We'll implement:
1. Token definition in nested JavaScript objects.
2. Build script that:
a. Validates base token set against required tokens.
b. Validates each brand token set (must be a subset of base).
c. Generates base.css (all base tokens as CSS variables in :root).
d. Generates for each brand a CSS file with only the overrides (in [data-brand="brand"] block).
3. In the application, we load base.css and then the brand-specific CSS (if any) and set the data-brand attribute on the html element.
We can also generate a manifest file that lists the brands and their token files? Not necessary.
s. Edge Cases:
- What if a brand token is an object? We don't allow that because we flatten. So we must ensure that the token values are primitives (string, number). We can validate that in the base token set? Or we can just stringify objects? But then we cannot use them in CSS.
We should validate that the token value is a string (or number that can be converted to string). We can do:
In the flatten function, if we encounter an object (and it's not null and not an array) we flatten it. But if we encounter an array or an object at the leaf, we can stringify? But then we have a stringified object as a CSS variable? That might be acceptable for some cases (like a box-shadow string) but not for others.
Actually, we want the token value to be a valid CSS value. So we should not have objects as leaf values.
We can check in the base token set that every leaf is a string or number.
Then in the brand, we also check that the leaf is a string or number? Actually, we don't need to check the brand's leaf type because we are just copying the value. But we should check that the brand's leaf is a string or number? Yes, because we are going to output it as a CSS value.
So we can add a validation step that checks that every leaf in base and brand is a string or number.
t. Final Build Script Structure:
We'll have:
const baseTokens = require('./tokens/baseTokens');
const requiredTokens = require('./tokens/requiredTokens'); // array of flattened token names
function flattenTokens(obj, prefix = '') {
let result = {};
for (const key in obj) {
const value = obj[key];
const newKey = prefix ? `${prefix}-${key}` : key;
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
result = { ...result, ...flattenTokens(value, newKey) };
} else if (typeof value === 'string' || typeof value === 'number') {
result[newKey] = value;
} else {
throw new Error(`Invalid token value at ${newKey}: must be string or number, got ${typeof value}`);
}
}
return result;
}
// Validate base tokens have all required
const baseFlat = flattenTokens(baseTokens);
for (const token of requiredTokens) {
if (!(token in baseFlat)) {
throw new Error(`Base tokens missing required token: ${token}`);
}
}
// Generate base.css
let baseCSS = ':root {\n';
for (const [key, value] of Object.entries(baseFlat)) {
baseCSS += ` --${key}: ${value};\n`;
}
baseCSS += '}';
fs.writeFileSync('dist/base.css', baseCSS);
// Process brands
const brandFiles = fs.readdirSync(brandTokensDir).filter(file => file.endsWith('.js'));
for (const file of brandFiles) {
const brandName = path.basename(file, '.js');
const brandTokens = require(path.join(brandTokensDir, file));
// Validate brand tokens are a subset of base
function validateBrandTokens(brand, base, path = '') {
for (const key in brand) {
const fullPath = path ? `${path}-${key}` : key;
if (!(key in base)) {
throw new Error(`Brand ${brandName} has token ${fullPath} which is not in base tokens.`);
}
if (typeof brand[key] === 'object' && brand[key] !== null && !Array.isArray(brand[key])) {
if (typeof base[key] !== 'object' || base[key] === null || Array.isArray(base[key])) {
throw new Error(`Base token at ${fullPath} is not an object, but brand token is.`);
}
validateBrandTokens(brand[key], base[key], fullPath);
} else if (typeof brand[key] !== 'string' && typeof brand[key] !== 'number') {
throw new Error(`Brand token at ${fullPath} must be string or number, got ${typeof brand[key]}`);
}
}
}
validateBrandTokens(brandTokens, baseTokens);
// Flatten brand tokens
const brandFlat = flattenTokens(brandTokens);
let brandCSS = `[data-brand="${brandName}"] {\n`;
for (const [key, value] of Object.entries(brandFlat)) {
brandCSS += ` --${key}: ${value};\n`;
}
brandCSS += '}';
fs.writeFileSync(`dist/brand-${brandName}.css`, brandCSS);
}
u. Notes:
- We are using the same flattening function for base and brand, so we are consistent in the variable names.
- We are generating the base.css and then for each brand a CSS file with overrides.
- We are validating that the brand tokens are a subset of the base tokens (by key) and that the types (primitives) are correct.
- We are also validating that the base has all required tokens.
v. Potential Improvements:
- We can have a more sophisticated type system for tokens (like color, spacing, etc.) and validate that the values are in the correct format (e.g., color must be a hex string, spacing must be a string with units). But that might be overkill.
- We can generate TypeScript types for the tokens.
- We can generate a manifest file that maps brand names to their CSS file paths.
- We can have a watch mode for development.
w. Usage in Build Process:
We can run this script as part of our build process (e.g., in a npm script).
x. Example HTML:
<!DOCTYPE html>
<html data-brand="brandA">
<head>
<link rel="stylesheet" href="base.css">
<link rel="stylesheet" href="brand-brandA.css">
</head>
<body>
<button class="button">Click me</button>
</body>
</html>
y. Example Component CSS:
.button {
background-color: var(--color-primary);
padding: var(--spacing-small);
}
z. Handling Default Brand:
If we have a default brand (the base) then we don't set data-brand? But then we load base.css only.
Alternatively, we can set data-brand to "base" and then generate a brand-base.css that is empty? Or we can generate a brand-base.css that sets all base tokens? That would be redundant.
We can treat the base as the default when no data-brand is set. So we don't need a brand file for base.
But what if we want to have a brand that is exactly the base? Then we don't need a brand file for it. We just don't set data-brand.
So, we only generate brand CSS files for brands that are not the base.
However, if we want to have a brand that is the same as base but we still want to set data-brand for some reason? Then we don't need to generate a CSS file for it because it would be empty.
So, in our build script, we can skip generating a brand CSS file if the brand tokens are empty? Or we can generate an empty file? But then we have to load it? We can skip generating and then in the HTML, if the brand is the base, we don't load a brand CSS.
Alternatively, we can generate a brand CSS file for every brand, even if it's empty? Then we have to load it. That's not optimal.
Let's change: we only generate brand CSS files for brands that have at least one token (non-empty). Then in the HTML, we conditionally load the brand CSS only if the brand is not the base? But how do we know which brand is the base? We can have a convention: the base brand is called "base" or "default"? Or we can have a configuration that says which brand is the base.
Alternatively, we can generate a brand CSS file for every brand (including base) and then in the HTML we load the base.css and the brand-specific CSS only if the brand is not the base? But then we have to know which brand is the base.
Let's do:
We have a base token set (which is the default). Then we have brand tokens for brands that are not the default.
In the build script, we don't generate a brand CSS file for the base (because it's empty). We only generate for brands that have overrides.
Then in the HTML, if the brand is the base, we only load base.css. If the brand is not the base, we load base.css and the brand's CSS.
How do we know which brand is the base? We can have a configuration that says the base brand is the one that doesn't have a brand file? Or we can have a special brand name (like 'base') that we skip? Actually, we don't have a brand for base. We just have baseTokens.
So, in the HTML, we set data-brand to the brand name (if it's not the base). If it's the base, we don't set data-brand? Or we set it to an empty string? But then the [data-brand] selector won't match.
We can set:
<html data-brand="brandA"> for brandA.
<html> for base.
Then in the CSS, we have:
:root { ...base... }
[data-brand="brandA"] { ...overrides... }
So that works.
But what if we have a brand that is exactly the base? Then we don't set data-brand and we don't load a brand CSS. That's fine.
So, we only generate brand CSS for brands that have at least one token (non-empty). And we skip generating for the base (which doesn't have a brand file).
But note: what if we have a brand that is exactly the base? Then we don't have a brand file for it? Actually, we wouldn't create a brand file for it because it would be empty. So we don't generate a CSS file for it.
So, in the HTML, for a brand that is exactly the base, we don't set data-brand and we don't load a brand CSS.
That's acceptable.
Final note: This is a complex system, but it provides compile-time safety and a clean separation of concerns.
Let me know if you have any questions or need further details.
I'll design a comprehensive multi-brand theming system using design tokens, CSS variables, and compile-time guardrails. This architecture ensures consistency while allowing brand-specific customization.