We are designing a system to transform design tokens (which could be in various formats like JSON, YAML, etc.) into multiple outputs:
CSS variables (for web)
JavaScript exports (for JS projects, possibly for React, Vue, etc.)
Native platform bindings (for iOS, Android, etc. - we'll assume we can generate code for these platforms)
We assume the design tokens are structured in a way that they have:
A category (like color, typography, spacing, etc.)
A token name (e.g., primary, heading, small)
A value (which could be a primitive like a string, number, or an object for complex tokens)
We'll design a transformer that can take a set of tokens and produce the three outputs.
Steps:
Parse the input tokens (we assume they are provided as a JavaScript object, but could be adapted).
For CSS variables: we'll output a CSS file with custom properties (variables) for each token. We need to handle the fact that CSS variables are flat and we might have nested tokens. We'll flatten the structure with a delimiter (like double underscore) or we can use a nested structure in CSS? But CSS custom properties are flat. So we'll flatten.
For JS exports: we'll output a JavaScript module that exports each token as a constant. Again, we need to flatten the structure or we can export an object with the same structure? We'll let the user choose? But the requirement says "JS exports", which could be either. Let's assume we want to export an object that mirrors the structure? Or we can do both? We'll design for an object that mirrors the structure, but note that in JS we can have nested objects.
For native bindings: we might generate code for iOS (Swift) and Android (Kotlin/Java). We'll assume we are generating a file for each platform. We'll need to map the token types to native types (e.g., color to UIColor/Color, spacing to CGFloat, etc.)
However, note: the problem says "Design a design token transformer", so we are to design the architecture and possibly the code for such a transformer.
Option 1: Flatten all tokens into a single level with a naming convention (e.g., color__primary, typography__heading) for CSS and JS? But for JS we might want to keep the structure.
Alternatively, we can have two modes for JS: flat (like CSS) and structured.
However, the requirement says "JS exports", which doesn't specify. Let's assume we want to export an object that has the same structure as the input.
For CSS, we must flatten because CSS custom properties are flat.
For native, we might want to generate a struct (Swift) or object (Kotlin) that mirrors the structure.
Steps for the transformer:
We'll have a configuration that specifies the output formats (CSS, JS, iOS, Android) and options for each.
We'll process the tokens:
a. For CSS:
- Flatten the tokens with a delimiter (e.g., "--color-primary" for a token at color.primary). But note: CSS custom properties must start with '--'. We can use the full path as the variable name, with each part separated by a delimiter (like '-'). But we must avoid invalid characters. We'll convert to kebab-case? Or just use the raw key? We can sanitize.
code
Example:
Input: { "color": { "primary": { "value": "#FF0000" } } }
Output: :root { --color-primary: #FF0000; }
But note: the token might have a type that tells us how to output? For example, a color value in CSS is just the string, but for spacing we have "8px", which is fine. But for typography we have multiple properties? How do we handle that?
We have two types of tokens:
- Primitive: a single value (color, spacing, etc.)
- Complex: an object with multiple properties (like typography, boxShadow, etc.)
For primitive tokens, we output a CSS variable with the value.
For complex tokens, we have two options in CSS:
Option 1: Flatten each property of the complex token.
Example: typography.heading.fontFamily -> --typography-heading-fontFamily
Option 2: Output a JSON string? But that's not very useful in CSS.
Let's go with Option 1 for CSS: flatten complex tokens by concatenating the keys.
b. For JS:
We can output an object that has the same structure as the input, but only the values (without the 'type' and 'value' wrappers?).
code
I'll design a comprehensive design token transformer system that outputs multiple platforms from a single source of truth. Here's the architecture:
import UIKit
import SwiftUI
@available(iOS 13.0, *)
public enum DesignTokens {
public enum color {
public static let primary = UIColor(red: 1.0, green: 0.42, blue: 0.42, alpha: 1.0)
public static let secondary = UIColor(red: 0.31, green: 0.8, blue: 0.77, alpha: 1.0)
}
public enum spacing {
public static let small = CGFloat(8.0)
public static let medium = CGFloat(16.0)
public static let large = CGFloat(24.0)
}
public enum typography {
public static let heading = UIFont(name: "Inter", size: 24.0)!
}
}
Kotlin:
kotlin
package com.design.tokens
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.compose.ui.text.font.FontWeight
object DesignTokens {
object color {
val primary = Color(0xFFFF6B6B)
val secondary = Color(0xFF4ECDC4)
}
object spacing {
val small = 8.dp
val medium = 16.dp
val large = 24.dp
}
object typography {
val heading = TextStyle(
fontFamily = FontFamily("Inter"),
fontWeight = FontWeight(700),
fontSize = 24.sp
)
}
}
Key Features
Single Source of Truth: One JSON/YAML token file generates all platform outputs
Type Safety: Token types guide platform-specific transformations
Customizable: Configurable naming conventions, access levels, and value transforms
Extensible: Easy to add new platforms (React Native, XML, etc.)
This system provides a robust, scalable solution for design token management across multiple platforms while maintaining consistency and reducing duplication.
Example input token for color.primary:
{
"value": "#FF0000",
"type": "color"
}
We want the output to be:
export const tokens = {
color: {
primary: "#FF0000"
}
}
But note: the input might have more metadata. We are only interested in the 'value' for each token.
However, what about complex tokens? They are already an object of values. So we can just take the entire token (without the 'type' if present) or if the token is an object without 'value', then it's a complex token and we take the whole object.
We need to normalize:
Let's define a function to extract the value from a token:
function getTokenValue(token) {
if (token.hasOwnProperty('value')) {
return token.value;
} else {
// It's a complex token, return the entire object (which is the value)
return token;
}
}
Then we build the output object by traversing the structure and applying getTokenValue.
c. For native bindings (iOS example):
code
We want to generate a Swift file that has a struct (or enum) with static properties.
Example for color.primary:
struct DesignTokens {
struct Color {
static let primary = UIColor(red: 1, green: 0, blue: 0, alpha: 1) // but we have hex, so we need a conversion.
}
}
But note: the value is a string "#FF0000". We need to convert hex to UIColor.
Similarly, for spacing: we might want a CGFloat.
So we need to know the type of the token to generate the correct code.
We have the 'type' field in the token. We can use that.
Steps for native:
- For each token, we have a path (e.g., ["color", "primary"]) and a token object with at least a 'type' and a 'value'.
- We generate a nested structure (structs) for each category.
- For each token, we generate a static property with the appropriate type and conversion.
But note: complex tokens (like typography) might have multiple properties. We might want to generate a struct for the complex token and then properties inside.
Example typography:
{
"typography": {
"heading": {
"fontFamily": "Arial",
"fontSize": "24px"
}
}
}
We don't have a 'type' for the complex token? We can infer from the structure? Or we can require that complex tokens have a type? Let's assume:
- If a token has a 'value' property, then it's a primitive and the type is given by 'type'.
- If it doesn't have a 'value', then it's a complex token and we treat it as a dictionary of properties, each of which might be primitive or complex.
But note: the example above for typography doesn't have a 'type'. So we can treat it as a complex token and then each property inside (fontFamily, fontSize) are primitives? But they don't have a 'type' either.
We need a way to know the type for conversion in native. We can:
Option 1: Require that every leaf token (primitive) has a 'type' field. Then for complex tokens, we don't have a type, but we generate a struct that groups the properties.
Option 2: Have a mapping of the path to the type? That's not flexible.
Let's go with Option 1: every leaf token must have a 'type'. Then:
Input:
"typography": {
"heading": {
"fontFamily": { "value": "Arial", "type": "fontFamily" },
"fontSize": { "value": "24px", "type": "fontSize" }
}
}
But that's verbose. Alternatively, we can have the type at the leaf level without the 'value' wrapper? But then we have two formats.
Alternatively, we can have two formats:
Format A (with wrapper for type and value):
"color": {
"primary": {
"value": "#FF0000",
"type": "color"
}
}
Format B (for complex, without wrapper):
"typography": {
"heading": {
"fontFamily": "Arial",
"fontSize": "24px"
}
}
But then we don't have type information for the properties in Format B.
So we must have type for every leaf. We can do:
"typography": {
"heading": {
"fontFamily": {
"value": "Arial",
"type": "string" // or maybe we don't need type for fontFamily? In Swift we just use String.
},
"fontSize": {
"value": "24px",
"type": "spacing" // or maybe a specific type for fontSize?
}
}
}
This becomes very heavy.
Alternatively, we can have a separate type mapping that is not in the token value? But the requirement is to have the tokens self-contained.
Let's change the requirement: we assume that the design token input is in the Style Dictionary format (which is a common format). In Style Dictionary, each token has a value and a type, and complex tokens are built from multiple tokens.
But in our example, we are trying to have a hierarchical structure. Style Dictionary uses a flat structure with names that imply hierarchy.
We can design our transformer to accept two formats:
Format 1: Hierarchical (like the example above) but then we require that every leaf has a 'type' and 'value'.
Format 2: Flat (like Style Dictionary) with names like "color.primary" and then we have a type and value.
Since the problem says "design a design token transformer", we can decide to support both? But to keep it simple, let's assume:
We have a hierarchical structure where each node can be:
- A leaf: { "value": any, "type": string }
- A complex node: { [key]: node } (without a 'value' and 'type')
Then for complex nodes, we generate a nested structure in the output (for JS and native) and for CSS we flatten.
But for CSS, we don't have a way to represent a complex node. So we must flatten the complex node's children.
Example:
Input:
{
"typography": {
"heading": {
"fontFamily": { "value": "Arial", "type": "string" },
"fontSize": { "value": "24px", "type": "spacing" }
}
}
}
CSS output:
:root {
--typography-heading-fontFamily: Arial;
--typography-heading-fontSize: 24px;
}
JS output:
export const tokens = {
typography: {
heading: {
fontFamily: "Arial",
fontSize: "24px"
}
}
}
Swift output:
struct DesignTokens {
struct Typography {
struct Heading {
static let fontFamily = "Arial"
static let fontSize = CGFloat(24) // but we have "24px", so we need to parse the unit? Or assume all spacings are in px and convert to points?
}
}
}
But note: the type for fontSize is "spacing", so we know to convert to CGFloat? And we have to parse the string "24px" to a number.
This is getting complex. We might need a mapping from token type to:
- CSS: how to output (just the value string, but for colors we might want to convert to a different format? or leave as is)
- JS: just the value (no conversion)
- Native: how to convert the string value to the native type.
We'll need a registry of type handlers.
Let's define:
type Handlers = {
[type: string]: {
css: (value: string) => string, // returns the CSS string
js: (value: string) => any, // returns the JS value (could be number, string, etc.)
ios: (value: string) => string, // returns the Swift code as a string (e.g., "UIColor(red: 1, green: 0, blue: 0, alpha: 1)")
android: (value: string) => string // returns the Kotlin/Java code as a string
}
}
But note: for complex tokens, we don't have a type? Actually, we don't need to handle complex tokens in the type handlers because they are broken down into leaves.
So we only need handlers for leaf tokens.
Steps:
1. Flatten the token tree for CSS and for native? For native we want to keep the structure, but we need to convert each leaf.
2. For CSS: we flatten the tree and then for each leaf, we use the handler for its type to produce the CSS string (which might be the same as the value or converted).
3. For JS: we want to keep the structure, but for each leaf we use the JS handler to convert the string value to the appropriate JS value (e.g., a number for spacing, a string for color, etc.)
4. For native: we want to generate code that mirrors the structure, and for each leaf we use the native handler (for iOS or Android) to produce the code for that value.
But note: for native, we are generating code, so we need to generate the entire nested structure. We can do:
For each category (top-level key), we generate a struct (Swift) or object (Kotlin).
Then for each token in that category, if it's a leaf, we generate a static property with the converted value.
If it's a complex node (without a 'value'), then we generate a nested struct/object and recurse.
However, in our input format, complex nodes are just objects without 'value' and 'type'. So we can check:
if (token.hasOwnProperty('value')) {
// leaf
} else {
// complex, so we generate a nested structure and then process each child.
}
But wait: what if a complex node also has a 'type'? We said leaf has 'value' and 'type', complex doesn't have 'value'. So we can use that.
Let's adjust:
A token node can be:
- Leaf: must have 'value' and 'type'
- Complex: must not have 'value', and may have 'type'? Actually, we don't use the type for complex. So we ignore type for complex.
So algorithm for generating the structure for JS and native:
function processNode(node, path) {
if (node.hasOwnProperty('value')) {
// leaf
const value = node.value;
const type = node.type;
// For JS: convert using jsHandler[type](value)
// For native: convert using nativeHandler[type](value) and then generate the property code.
return { value: convertedValue, type: 'leaf' };
} else {
// complex
const result = {};
for (const key in node) {
result[key] = processNode(node[key], path.concat(key));
}
return result;
}
}
But for native, we are generating code, so we need to generate the entire nested structure as code strings.
Alternatively, we can first convert the entire token tree to an intermediate representation that has only the values (converted for JS and native) and then generate the code from that.
Let's break the transformer into steps:
Step 1: Parse the input tokens (already an object).
Step 2: For each output format, we traverse the tree and generate the output.
We'll have:
generateCSS(tokens) -> string
generateJS(tokens) -> string
generateIOS(tokens) -> string
generateAndroid(tokens) -> string
Each of these will traverse the tree and build the output.
However, we want to avoid duplicating the traversal logic. We can have a generic traversal that builds an intermediate representation (IR) that is then formatted by each generator.
Let's define the IR:
The IR will be a tree that has:
- For a leaf: { type: string, value: any, originalValue: string }? But we want to keep the original value string for some conversions? Actually, the handlers will convert the string to the appropriate type.
Alternatively, we can store the string value and the type, and then each generator will use the appropriate handler to convert the string to the desired format.
So let's keep the token tree as is, and each generator will:
- Traverse the tree.
- When it hits a leaf, it uses the type and the string value and applies the handler for that output format.
But then we need to have the same traversal for each? We can write a helper that traverses and calls a callback for each leaf and for each complex node?
Alternatively, we can convert the entire tree to a flat map for CSS, and for JS and native we keep the structure.
Let's do:
For CSS: we flatten the tree and then for each leaf we generate a CSS variable.
For JS: we traverse and build an object that has the same structure, but with the values converted by the JS handler.
For native: we traverse and build a string that represents the code (with nested structs/objects).
We'll create:
function flattenTokens(tokens, delimiter = '-', prefix = '--') {
const result = {};
function recurse(node, path) {
if (node.hasOwnProperty('value')) {
const key = path.join(delimiter);
result[prefix + key] = node.value; // but we might want to convert the value for CSS? We'll do that later.
} else {
for (const k in node) {
recurse(node[k], path.concat(k));
}
}
}
recurse(tokens, []);
return result;
}
Then for CSS, we take the flattened object and then for each key, we apply the CSS handler for the token's type? But wait, in the flattened object we lost the type? We need to keep the type.
So we need to flatten and keep the type? We can store an object with both value and type? But then the CSS handler might need the type.
Alternatively, we can flatten and store the original token? But then we are storing the entire token tree in the flattened map? That's not efficient.
Let's change: when we flatten, we store an object with:
{ value: string, type: string }
Then we can apply the CSS handler.
But note: the CSS handler might need to know the entire path? Probably not.
So:
function flattenTokensWithMeta(tokens, delimiter = '-', prefix = '--') {
const result = {};
function recurse(node, path) {
if (node.hasOwnProperty('value')) {
const key = path.join(delimiter);
result[prefix + key] = { value: node.value, type: node.type };
} else {
for (const k in node) {
recurse(node[k], path.concat(k));
}
}
}
recurse(tokens, []);
return result;
}
Then for CSS:
const flat = flattenTokensWithMeta(tokens);
let css = ':root {\n';
for (const [varName, token] of Object.entries(flat)) {
const cssValue = cssHandler[token.type] ? cssHandler[token.type](token.value) : token.value;
css += ` ${varName}: ${cssValue};\n`;
}
css += '}';
For JS:
We want to build an object that has the same structure, but with the values converted by the JS handler.
function buildJSTokens(tokens) {
function recurse(node) {
if (node.hasOwnProperty('value')) {
const type = node.type;
const value = node.value;
return jsHandler[type] ? jsHandler[type](value) : value;
} else {
const result = {};
for (const key in node) {
result[key] = recurse(node[key]);
}
return result;
}
}
return recurse(tokens);
}
Then we stringify:
const jsTokens = buildJSTokens(tokens);
let js = 'export const tokens = ' + JSON.stringify(jsTokens, null, 2) + ';';
But note: we might want to export as a named export? We are exporting a single object.
For native (iOS):
We want to generate a Swift file with nested structs.
We can do:
function generateIOS(tokens, indent = '') {
let code = '';
// We'll generate a struct for the root? Or we can generate a struct for each top-level category?
// Let's generate a struct for the root, and then nested structs for each category.
// But note: the root might be an object with keys: color, spacing, etc.
// We want:
// struct DesignTokens {
// struct Color {
// static let primary = ...
// }
// }
// So we treat the root as a struct, and then each key that is a complex node (without value) becomes a nested struct.
// But what if the root has a leaf? That would be unusual. We assume the root is a complex node.
// Algorithm:
// We traverse the tree and for each node:
// If it's a leaf: we generate a static property with the converted value (using iosHandler) and the type (we need to know the Swift type? The handler can return a string that is the code for the value, but we also need to declare the type? We can let the handler return the entire property line? Or we can have the handler return the value expression and we know the type from the token type?
// Let's define the iosHandler to return an object: { type: string, value: string }? Then we can generate:
// static let propertyName: Type = value
// Alternatively, we can have the handler return the entire line? But then we lose the property name.
// Let's have the handler return:
// For a leaf token: { swiftType: string, swiftValue: string }
// Then we generate:
// static let propertyName: swiftType = swiftValue
// For complex nodes, we generate a nested struct.
// Steps:
// function generateIOSNode(node, structName) {
// let code = '';
// const properties = [];
// const nestedStructs = [];
// for (const key in node) {
// const child = node[key];
// if (child.hasOwnProperty('value')) {
// const { swiftType, swiftValue } = iosHandler[child.type](child.value);
// properties.push(`static let ${key}: ${swiftType} = ${swiftValue}`);
// } else {
// // complex, generate nested struct
// const nestedCode = generateIOSNode(child, key);
// nestedStructs.push(nestedCode);
// }
// }
// if (properties.length > 0 || nestedStructs.length > 0) {
// code += `struct ${structName} {\n`;
// for (const prop of properties) {
// code += ` ${prop}\n`;
// }
// for (const nested of nestedStructs) {
// code += ` ${nested}\n`; // but nested is a string that already has indentation? We need to adjust.
// }
// code += '}\n';
// }
// return code;
// }
// But wait: the nested structs we generate are already indented? We are passing the current indent.
// Alternatively, we can build the code without worrying about indentation and then at the end format? Or we can pass the indent level.
// Let's do:
function generateIOSNode(node, name, indent = '') {
let code = '';
const childIndent = indent + ' ';
let hasContent = false;
// First, collect the static properties (leaves)
const staticProps = [];
const nestedStructs = [];
for (const key in node) {
const child = node[key];
if (child.hasOwnProperty('value')) {
const { swiftType, swiftValue } = iosHandler[child.type](child.value);
staticProps.push(`static let ${key}: ${swiftType} = ${swiftValue}`);
} else {
// complex, generate nested struct
const nestedCode = generateIOSNode(child, key, childIndent);
nestedStructs.push(nestedCode);
}
}
if (staticProps.length > 0 || nestedStructs.length > 0) {
code += indent + `struct ${name} {\n`;
for (const prop of staticProps) {
code += childIndent + prop + '\n';
}
for (const nested of nestedStructs) {
code += nested + '\n'; // nested already has its own indentation and closing brace?
}
code += indent + '}\n';
hasContent = true;
}
return code;
}
// Then for the root:
const rootCode = generateIOSNode(tokens, 'DesignTokens');
// But note: the root might be an object with multiple top-level keys (color, spacing). We want them to be nested under DesignTokens? Yes.
// However, the root might not be a complex node? It should be, because we expect categories.
// Also, we might have multiple top-level categories. The above will generate:
// struct DesignTokens {
// struct Color { ... }
// struct Spacing { ... }
// }
// But wait: in the example, the root has keys: color, spacing. So when we call generateIOSNode(tokens, 'DesignTokens'), it will see that tokens is a complex node (no value) and then for each key (color, spacing) it will generate a nested struct.
// That's correct.
// But what if we have a leaf at the root? Then we would generate:
// struct DesignTokens {
// static let someLeaf = ...
// }
// That's acceptable.
// However, we must note: the root might be a leaf? Unlikely, but possible.
We have to write the iosHandler for each type.
Example for color:
iosHandler = {
color: (value) => {
// value is like "#FF0000"
// Convert to UIColor
// We need a function to convert hex to UIColor components.
// Let's assume we have a helper function in the generated file? Or we can generate the code with the conversion inline.
// We can generate:
// static let primary: UIColor = UIColor(red: 1, green: 0, blue: 0, alpha: 1)
// But note: we might have different color formats (rgb, rgba, etc.). We assume hex for now.
// We'll write a helper function to convert hex to CGFloat components.
// Alternatively, we can generate a extension on UIColor? But we are generating a struct.
// Let's generate the code that uses a helper function defined elsewhere? Or we can define the helper in the same file.
// We'll generate:
// import UIKit
// private func hexToUIColor(hex: String) -> UIColor {
// // ... implementation
// }
// struct DesignTokens {
// static let primary: UIColor = hexToUIColor(hex: "#FF0000")
// }
// But then we have to generate the helper function too.
// Alternatively, we can convert the hex to decimal and write the initializer directly.
// Let's do:
// static let primary: UIColor = UIColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)
// So we need to parse the hex string.
// We can write a function that returns the string for the initializer.
// However, note: the hex might be 3, 4, 6, or 8 digits. We'll assume 6 or 8.
// Let's write a helper in the transformer to convert hex to RGBA.
// But note: the transformer is in JS, so we can do the conversion in the transformer and then output the numbers.
// So in the iosHandler for color, we convert the hex string to an object {r, g, b, a} and then return:
// swiftType: 'UIColor',
// swiftValue: `UIColor(red: ${r}, green: ${g}, blue: ${b}, alpha: ${a})`
// But wait: the UIColor initializer expects CGFloat (0 to 1). So we need to convert the 0-255 range to 0-1.
// We can do that in the transformer.
// So:
// function hexToRGBA(hex) {
// // ... parse hex and return {r, g, b, a} in 0-1 range.
// }
// Then:
// iosHandler.color = (value) => {
// const {r, g, b, a} = hexToRGBA(value);
// return {
// swiftType: 'UIColor',
// swiftValue: `UIColor(red: ${r}, green: ${g}, blue: ${b}, alpha: ${a})`
// };
// };
}
Similarly for spacing:
iosHandler.spacing = (value) => {
// value is like "8px"
// We want to convert to CGFloat. We assume the value is in pixels and we want points (1pt = 1px on non-retina? Actually, on iOS 1pt = 1px on non-retina, but on retina 1pt = 2px or 3px. We want to use points, so we take the number and use it as points? But the design might be in pixels.
// We can just strip the 'px' and use the number as the point value? That's common.
const num = parseFloat(value);
return {
swiftType: 'CGFloat',
swiftValue: `${num}`
};
};
For fontFamily: it's a string, so:
iosHandler.fontFamily = (value) => {
return {
swiftType: 'String',
swiftValue: `"${value}"`
};
};
For Android, we would generate Kotlin code.
But note: we are designing the transformer, so we need to define the handlers for each platform and type.
We'll have:
const handlers = {
css: {
color: (value) => value, // by default, but we might want to convert to a different format?
spacing: (value) => value,
// ...
},
js: {
color: (value) => value,
spacing: (value) => parseFloat(value), // convert to number?
// ...
},
ios: {
color: (value) => { ... }, // returns {swiftType, swiftValue}
spacing: (value) => { ... },
// ...
},
android: {
// similar for Android
}
};
But note: for JS, we might want to keep the string for color? Or convert to an object? It depends on the usage. We'll let the handler decide.
Now, let's write the transformer in code:
We assume the input tokens are in the hierarchical format with leaves having 'value' and 'type'.
Steps:
// 1. Flatten for CSS
const flatTokens = flattenTokensWithMeta(tokens);
// 2. Generate CSS string
let css = ':root {\n';
for (const [varName, token] of Object.entries(flatTokens)) {
const cssValue = handlers.css[token.type] ? handlers.css[token.type](token.value) : token.value;
css += ` ${varName}: ${cssValue};\n`;
}
css += '}';
// 3. Generate JS
const jsTokens = buildJSTokens(tokens); // this uses handlers.js
const js = `export const tokens = ${JSON.stringify(jsTokens, null, 2)};`;
// 4. Generate iOS
const iosCode = generateIOS(tokens); // uses handlers.ios
// 5. Generate Android (similar)
But note: the buildJSTokens function uses the handlers.js. We need to write that.
function buildJSTokens(tokens) {
function recurse(node) {
if (node.hasOwnProperty('value')) {
const type = node.type;
const value = node.value;
return handlers.js[type] ? handlers.js[type](value) : value;
} else {
const result = {};
for (const key in node) {
result[key] = recurse(node[key]);
}
return result;
}
}
return recurse(tokens);
}
However, note: for complex nodes, we don't have a type, so we just build the object.
This should work.
But wait: what about the CSS flattening? We are flattening with a delimiter and prefix. We might want to make those configurable.
Let's make the transformer configurable:
const config = {
css: {
delimiter: '-',
prefix: '--'
},
js: {
// maybe export format? default is an object.
},
ios: {
structName: 'DesignTokens',
// maybe module name?
}
};
We'll adjust the functions to use config.
Also, for iOS, we are generating a struct named 'DesignTokens' by default.
We'll write:
function generateIOS(tokens, config) {
const { structName = 'DesignTokens' } = config.ios || {};
// ... then use generateIOSNode with the root structName.
}
But note: the root might have multiple top-level keys. We want to generate a struct for each top-level key? Or we want one root struct that contains all?
In the example, we have:
tokens = {
color: { ... },
spacing: { ... }
}
We want:
struct DesignTokens {
struct Color { ... }
struct Spacing { ... }
}
So we treat the root as a struct that contains the top-level keys as nested structs? But what if the top-level key is a leaf? Then we would generate:
struct DesignTokens {
static let someLeaf = ...
}
That's acceptable.
So we call generateIOSNode(tokens, structName).
But note: if the root is a leaf (unlikely) then we generate:
struct DesignTokens {
static let value = ...
}
But then the leaf's key is lost? Actually, the root in our example is an object with keys. So if the root is a leaf, then the input would be:
{ "value": "...", "type": "..." }
Then we would generate:
struct DesignTokens {
static let value = ... // but we don't have a key for the leaf? The leaf doesn't have a key? It's the root.
This is a problem. We assume the root is always a complex node (object) with keys. If the root is a leaf, then we don't have a key. We can use a default key? Or we can say the root must be a complex node.
Let's assume the root is always a complex node (i.e., an object without 'value').
If the input is a single leaf token, then we would have:
{ "value": "...", "type": "..." }
Then we would not generate any struct? Because in generateIOSNode, we check if the node has a value. If it does, then we generate a static property, but we don't have a key? We are iterating over the keys of the node. If the node is a leaf, then it has no keys? It has 'value' and 'type'. So we wouldn't generate anything.
So we must ensure the root is a complex node.
Alternatively, we can change the generateIOSNode to handle the case when the root is a leaf? But then we need a name for the leaf. We can use a default name? Or we can require the root to be a complex node.
Let's require the root to be a complex node (i.e., an object that does not have a 'value' property). Then every top-level key is a category.
So if the user has a single token, they should wrap it in a category.
Example:
{
"color": {
"primary": { "value": "#FF0000", "type": "color" }
}
}
This is acceptable.
Now, let's write the code for the transformer.
We'll write it as a class or a set of functions.
We'll define:
class DesignTokenTransformer {
constructor(config = {}) {
this.config = config;
this.handlers = this.getDefaultHandlers();
// Merge custom handlers from config?
if (config.handlers) {
for (const format in config.handlers) {
for (const type in config.handlers[format]) {
this.handlers[format][type] = config.handlers[format][type];
}
}
}
}
getDefaultHandlers() {
return {
css: {
color: (value) => value,
spacing: (value) => value,
// ... others
},
js: {
color: (value) => value,
spacing: (value) => parseFloat(value),
// ...
},
ios: {
color: (value) => {
const {r, g, b, a} = this.hexToRGBA(value);
return {
swiftType: 'UIColor',
swiftValue: `UIColor(red: ${r}, green: ${g}, blue: ${b}, alpha: ${a})`
};
},
spacing: (value) => {
const num = parseFloat(value);
return {
swiftType: 'CGFloat',
swiftValue: `${num}`
};
},
// ...
},
android: {
// ...
}
};
}
hexToRGBA(hex) {
// ... implementation
}
flattenTokensWithMeta(tokens, delimiter, prefix) {
// ...
}
buildJSTokens(tokens) {
// ...
}
generateCSS(tokens) {
const { delimiter = '-', prefix = '--' } = this.config.css || {};
const flat = this.flattenTokensWithMeta(tokens, delimiter, prefix);
let css = ':root {\n';
for (const [varName, token] of Object.entries(flat)) {
const cssValue = this.handlers.css[token.type] ? this.handlers.css[token.type](token.value) : token.value;
css += ` ${varName}: ${cssValue};\n`;
}
css += '}';
return css;
}
generateJS(tokens) {
const jsTokens = this.buildJSTokens(tokens);
return `export const tokens = ${JSON.stringify(jsTokens, null, 2)};`;
}
generateIOS(tokens) {
const { structName = 'DesignTokens' } = this.config.ios || {};
return this.generateIOSNode(tokens, structName);
}
generateIOSNode(node, name, indent = '') {
// ... as above, but using this.handlers.ios
}
// ... similarly for Android
}
This is a basic design.
However, note: for iOS, we are generating a struct, but what if we want to generate a class? Or an enum? We can make that configurable.
Also, for Android, we might want to generate an object or a class.
We can extend the config for each platform to specify the template.
But to keep it simple, we'll stick with struct for iOS and object for Android.
Let's write the generateIOSNode in more detail:
generateIOSNode(node, name, indent = '') {
let code = '';
const childIndent = indent + ' ';
let hasContent = false;
const staticProps = [];
const nestedStructs = [];
for (const key in node) {
const child = node[key];
if (child.hasOwnProperty('value')) {
const handler = this.handlers.ios[child.type];
if (handler) {
const { swiftType, swiftValue } = handler(child.value);
staticProps.push(`static let ${key}: ${swiftType} = ${swiftValue}`);
} else {
// Fallback: treat as string?
staticProps.push(`static let ${key}: String = "${child.value}"`);
}
} else {
// complex node
const nestedCode = this.generateIOSNode(child, key, childIndent);
nestedStructs.push(nestedCode);
}
}
if (staticProps.length > 0 || nestedStructs.length > 0) {
code += indent + `struct ${name} {\n`;
for (const prop of staticProps) {
code += childIndent + prop + '\n';
}
for (const nested of nestedStructs) {
code += nested + '\n';
}
code += indent + '}\n';
hasContent = true;
}
return code;
}
But note: the nestedCode already has the closing brace and newline? In our recursive call, we return a string that ends with a newline? We are adding a newline after each nested struct. So we might have an extra newline? We can adjust.
Alternatively, we can build without the trailing newline and then add when needed.
Let's change:
In the recursive call, we return the code for the struct without a trailing newline? Then when we append, we add a newline.
But then the last nested struct would have a newline and then we add another? We can do:
for (const nested of nestedStructs) {
code += nested + (nested.endsWith('\n') ? '' : '\n');
}
But that's messy.
Instead, let's have the recursive function return the code for the struct (with the closing brace and a newline). Then when we are building the parent, we just append.
Example:
function generateIOSNode(node, name, indent) {
let code = '';
// ... build the struct and then at the end:
code += indent + '}\n'; // note: we add a newline after the closing brace.
return code;
}
Then in the parent:
for (const nested of nestedStructs) {
code += nested; // nested already has a newline at the end.
}
But wait: the nested struct is already indented? We passed childIndent to the recursive call, so the nested struct is indented by childIndent. Then when we append it to the parent's code (which is at indent level), we are appending an already indented string. That's correct.
However, the parent's struct body is indented by childIndent, and the nested struct is also indented by childIndent? Then we are double-indented? Let's see:
Parent:
struct DesignTokens {
struct Color { // this line is at childIndent (2 spaces)
...
}
}
In the parent, we are at indent (0) and we write:
indent + 'struct DesignTokens {\n' -> 'struct DesignTokens {\n'
Then for the nested struct, we call generateIOSNode(child, 'Color', childIndent) which returns:
childIndent + 'struct Color {\n' -> ' struct Color {\n'
... properties and nested structs of Color ...
childIndent + '}\n' -> ' }\n'
Then we append that to the parent's code. So the parent's code becomes:
'struct DesignTokens {\n'
' struct Color {\n'
...
' }\n'
'}\n'
That's correct.
But note: the parent's own static properties are written at childIndent, and the nested structs are also at childIndent? Then they are at the same level. That's correct.
So we don't need to adjust.
However, we must be cautious: the recursive function for a node that has both static properties and nested structs will output:
indent + 'struct Name {\n'
for each static property: childIndent + property + '\n'
for each nested struct: nestedCode (which is already indented by childIndent and has a newline at the end)
indent + '}\n'
So the static properties and the nested structs are both at childIndent level. That's correct.
But what if there are no static properties and only nested structs? Then we have:
struct Name {
struct Nested { ... }
}
That's fine.
What if there are no nested structs and only static properties? Then we have:
struct Name {
static let ...
}
That's fine.
What if there are both? Then we have:
struct Name {
static let ...
struct Nested { ... }
}
That's fine.
Now, what about the root? We call generateIOSNode(tokens, structName). If the root has no keys? Then we return an empty string? We might want to generate an empty struct? Or nothing? We can return an empty string.
But if the root has keys, we generate the struct.
Now, let's consider the Android generation. We would do something similar, but generate Kotlin code.
Example for Android:
We want:
object DesignTokens {
object Color {
val primary = Color.parseColor("#FF0000")
}
}
But note: for spacing, we might want a dimension? We can use:
val small = 8.dp
But we need to convert the value string to the appropriate code.
We'll have a handler for Android that returns:
{ kotlinType: string, kotlinValue: string }
Then we generate:
val key: kotlinType = kotlinValue
But note: for color, we might use `Color.parseColor` and the value is a string.
So:
androidHandler.color = (value) => {
return {
kotlinType: 'Int', // because Color.parseColor returns Int (the color value)
kotlinValue: `Color.parseColor("${value}")`
};
};
For spacing:
androidHandler.spacing = (value) => {
const num = parseFloat(value);
return {
kotlinType: 'Int', // or maybe Dp? But Dp is a class. We can use an extension property?
// We can generate:
// val small = 8.dp
// But note: the .dp is an extension on Int. So we can return:
kotlinValue: `${num}.dp`
};
};
But then the type would be `Int`? Actually, the type of `8.dp` is `Dp`. So we should set kotlinType to 'Dp'? But we don't have a Dp type without the extension. We can assume the user has the extension.
Alternatively, we can generate:
val small = Dimension(8) // if we have a Dimension class.
We'll let the user define the handlers.
So the structure for Android generation is similar to iOS.
We'll write:
generateAndroid(tokens) {
const { objectName = 'DesignTokens' } = this.config.android || {};
return this.generateAndroidNode(tokens, objectName);
}
generateAndroidNode(node, name, indent = '') {
// similar to iOS, but generate Kotlin code.
}
However, note: in Kotlin, we can have nested objects.
Example:
object DesignTokens {
object Color {
val primary = ...
}
}
So we generate:
indent + "object ${name} {\n"
... children ...
indent + "}\n"
And for a leaf:
"val ${key}: ${kotlinType} = ${kotlinValue}"
But note: if the node is a leaf, we are generating a val. But if the node is a complex node, we generate an object.
So the algorithm is the same as iOS, just different syntax.
We can abstract the code generation for native platforms? But they are different enough.
Alternatively, we can have a template for each platform.
Given the complexity, we'll leave them separate.
This is a basic design. We have to handle:
- The token structure (hierarchical with leaves having value and type)
- Different output formats (CSS, JS, iOS, Android)
- Custom handlers for each type and format.
We also need to consider:
- How to handle token references? (e.g., a token that references another token) This is common in design tokens. We don't handle that in this design.
- How to handle multiple themes? We might want to generate CSS variables for each theme.
But the requirement doesn't specify, so we stick to the basic.
Let's write the code for the transformer with the above design.
We'll write it in JavaScript (Node.js) and assume we are running in a Node environment.
We'll write the class and then export it.
Note: This is a design, so we don't have to write the entire code, but we can write the skeleton.
However, the problem says "Design a design token transformer", so we are expected to provide the design and possibly the code.
We'll provide the code for the transformer with the above design, but we'll leave the handlers as stubs and let the user extend.
Let's code:
We'll create a file: DesignTokenTransformer.js
We'll implement:
- flattenTokensWithMeta
- buildJSTokens
- generateCSS
- generateJS
- generateIOS
- generateAndroid (stub)
And the default handlers.
We'll also provide a way to transform all at once.
Example usage:
const transformer = new DesignTokenTransformer({
css: { delimiter: '-', prefix: '--' },
ios: { structName: 'DesignTokens' }
});
const tokens = { ... }; // the input tokens
const css = transformer.generateCSS(tokens);
const js = transformer.generateJS(tokens);
const ios = transformer.generateIOS(tokens);
const android = transformer.generateAndroid(tokens);
Now, let's write the code.
We'll assume the input tokens are in the format described.
We'll write the helper function hexToRGBA for iOS color handler.
But note: the color value might not be hex. We can have other formats? We'll assume hex for now.
We'll write:
hexToRGBA(hex) {
// Remove the hash
hex = hex.replace(/^#/, '');
let r, g, b, a = 1;
if (hex.length === 3) {
r = parseInt(hex[0] + hex[0], 16) / 255;
g = parseInt(hex[1] + hex[1], 16) / 255;
b = parseInt(hex[2] + hex[2], 16) / 255;
} else if (hex.length === 6) {
r = parseInt(hex.substring(0,2), 16) / 255;
g = parseInt(hex.substring(2,4), 16) / 255;
b = parseInt(hex.substring(4,6), 16) / 255;
} else if (hex.length === 8) {
r = parseInt(hex.substring(0,2), 16) / 255;
g = parseInt(hex.substring(2,4), 16) / 255;
b = parseInt(hex.substring(4,6), 16) / 255;
a = parseInt(hex.substring(6,8), 16) / 255;
} else {
// fallback to black
r = 0; g = 0; b = 0;
}
return {r, g, b, a};
}
But note: the UIColor initializer expects CGFloat, which is a Double in Swift. We can format the numbers to have up to 3 decimal places? Or leave as is.
We'll format to 3 decimal places:
r = Math.round(r * 1000) / 1000;
But note: 1.0 is fine.
We'll do:
function toFixed(num, digits) {
return Number(num.toFixed(digits));
}
Then:
r = toFixed(r, 3);
But note: 0.5 becomes 0.5, 0.333333 becomes 0.333.
We'll do:
const format = (num) => Number(num.toFixed(3));
Then:
return {
r: format(r),
g: format(g),
b: format(b),
a: format(a)
};
Now, let's code the transformer.
We'll write the class.
Note: This is a simplified version. We might want to handle more cases.
Let's code.</think>