This is a design token transformer tool. Let me create a comprehensive, interactive tool that can:
- Parse design tokens (JSON format)
- Transform them into:
- CSS Custom Properties (CSS Variables)
- JavaScript/TypeScript exports
- Native platform bindings (iOS Swift, Android Kotlin, Flutter)
Features I'll include:
- Live token editor
- Multiple output format previews
- Copy to clipboard functionality
- Syntax highlighting
- Token tree visualization
- Dark theme suitable for developers
- Smooth animations and transitions
- Real-time transformation
Design aesthetic:
- Technical/developer tool vibe
- Dark theme with neon accents
- Monospace fonts for code
- Clean grid-based layout
- Subtle glow effects
Let me build this properly with all the requirements met.
This is a comprehensive Design Token Transformer tool that parses JSON tokens and outputs CSS variables, JS exports, and native platform bindings (iOS Swift, Android Kotlin, Flutter). It features a live editor, real-time preview, copy functionality, and a polished developer-focused UI.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Token Forge — Design Token Transformer</title>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600&family=Space+Grotesk:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
:root {
--bg-deep: #0a0b0f;
--bg-surface: #12141a;
--bg-elevated: #1a1d25;
--bg-input: #0d0e12;
--fg-primary: #e8eaed;
--fg-secondary: #8b919e;
--fg-muted: #5a5f6d;
--accent-cyan: #22d3ee;
--accent-green: #4ade80;
--accent-orange: #fb923c;
--accent-pink: #f472b6;
--border-subtle: #2a2e38;
--border-active: #3d4351;
}
* {
box-sizing: border-box;
}
html {
font-family: 'Space Grotesk', sans-serif;
background: var(--bg-deep);
color: var(--fg-primary);
}
.font-mono {
font-family: 'JetBrains Mono', monospace;
}
.code-block {
background: var(--bg-input);
border: 1px solid var(--border-subtle);
border-radius: 8px;
overflow: hidden;
}
.code-content {
padding: 16px;
overflow: auto;
max-height: 400px;
font-size: 13px;
line-height: 1.6;
}
.code-content::-webkit-scrollbar {
width: 8px;
height: 8px;
}
.code-content::-webkit-scrollbar-track {
background: var(--bg-input);
}
.code-content::-webkit-scrollbar-thumb {
background: var(--border-active);
border-radius: 4px;
}
.token-key { color: var(--accent-cyan); }
.token-string { color: var(--accent-green); }
.token-number { color: var(--accent-orange); }
.token-comment { color: var(--fg-muted); font-style: italic; }
.token-punctuation { color: var(--fg-secondary); }
.output-css .prop-name { color: var(--accent-cyan); }
.output-css .prop-value { color: var(--accent-green); }
.output-css .selector { color: var(--accent-pink); }
.output-js .keyword { color: var(--accent-pink); }
.output-js .string { color: var(--accent-green); }
.output-js .property { color: var(--accent-cyan); }
.output-swift .keyword { color: var(--accent-pink); }
.output-swift .string { color: var(--accent-green); }
.output-swift .type { color: var(--accent-orange); }
.output-kotlin .keyword { color: var(--accent-pink); }
.output-kotlin .string { color: var(--accent-green); }
.output-kotlin .type { color: var(--accent-orange); }
.output-flutter .keyword { color: var(--accent-pink); }
.output-flutter .string { color: var(--accent-green); }
.output-flutter .class { color: var(--accent-orange); }
.tab-btn {
position: relative;
padding: 12px 20px;
font-weight: 500;
color: var(--fg-secondary);
transition: color 0.2s ease;
border-bottom: 2px solid transparent;
}
.tab-btn:hover {
color: var(--fg-primary);
}
.tab-btn.active {
color: var(--accent-cyan);
border-bottom-color: var(--accent-cyan);
}
.copy-btn {
padding: 6px 12px;
font-size: 12px;
font-weight: 500;
background: var(--bg-elevated);
border: 1px solid var(--border-subtle);
border-radius: 6px;
color: var(--fg-secondary);
cursor: pointer;
transition: all 0.2s ease;
}
.copy-btn:hover {
border-color: var(--border-active);
color: var(--fg-primary);
}
.copy-btn.copied {
border-color: var(--accent-green);
color: var(--accent-green);
}
.glow-line {
position: absolute;
height: 1px;
background: linear-gradient(90deg, transparent, var(--accent-cyan), transparent);
opacity: 0.5;
}
.token-tree-item {
padding: 6px 12px;
border-radius: 6px;
cursor: pointer;
transition: background 0.15s ease;
}
.token-tree-item:hover {
background: var(--bg-elevated);
}
.token-dot {
width: 8px;
height: 8px;
border-radius: 50%;
flex-shrink: 0;
}
textarea {
background: var(--bg-input);
border: 1px solid var(--border-subtle);
border-radius: 8px;
color: var(--fg-primary);
font-family: 'JetBrains Mono', monospace;
font-size: 13px;
line-height: 1.6;
resize: none;
transition: border-color 0.2s ease;
}
textarea:focus {
outline: none;
border-color: var(--accent-cyan);
}
.stat-card {
background: linear-gradient(135deg, var(--bg-elevated) 0%, var(--bg-surface) 100%);
border: 1px solid var(--border-subtle);
border-radius: 12px;
padding: 16px 20px;
}
@keyframes slideIn {
from {
opacity: 0;
transform: translateY(12px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
.animate-slide-in {
animation: slideIn 0.4s ease forwards;
}
.animate-fade-in {
animation: fadeIn 0.3s ease forwards;
}
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: 0.01ms !important;
transition-duration: 0.01ms !important;
}
}
.bg-grid {
background-image:
linear-gradient(var(--border-subtle) 1px, transparent 1px),
linear-gradient(90deg, var(--border-subtle) 1px, transparent 1px);
background-size: 40px 40px;
}
</style>
</head>
<body class="min-h-screen bg-grid">
<!-- Header -->
<header class="border-b border-[var(--border-subtle)] bg-[var(--bg-surface)]/80 backdrop-blur-sm sticky top-0 z-50">
<div class="max-w-7xl mx-auto px-6 py-4 flex items-center justify-between">
<div class="flex items-center gap-3">
<div class="w-10 h-10 rounded-lg bg-gradient-to-br from-[var(--accent-cyan)] to-[var(--accent-green)] flex items-center justify-center">
<svg class="w-5 h-5 text-[var(--bg-deep)]" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
<path d="M12 2L2 7l10 5 10-5-10-5z"/>
<path d="M2 17l10 5 10-5"/>
<path d="M2 12l10 5 10-5"/>
</svg>
</div>
<div>
<h1 class="text-lg font-bold tracking-tight">Token Forge</h1>
<p class="text-xs text-[var(--fg-muted)]">Design Token Transformer</p>
</div>
</div>
<div class="flex items-center gap-3">
<button id="loadSample" class="copy-btn flex items-center gap-2">
<svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
<polyline points="14 2 14 8 20 8"/>
<line x1="16" y1="13" x2="8" y2="13"/>
<line x1="16" y1="17" x2="8" y2="17"/>
</svg>
Load Sample
</button>
<button id="transformBtn" class="px-4 py-2 bg-[var(--accent-cyan)] text-[var(--bg-deep)] font-semibold rounded-lg hover:opacity-90 transition-opacity flex items-center gap-2">
<svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
<path d="M5 12h14"/>
<path d="M12 5l7 7-7 7"/>
</svg>
Transform
</button>
</div>
</div>
</header>
<!-- Main Content -->
<main class="max-w-7xl mx-auto px-6 py-8">
<!-- Stats Row -->
<div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8" id="statsRow">
<div class="stat-card animate-slide-in" style="animation-delay: 0.1s">
<p class="text-xs text-[var(--fg-muted)] mb-1">Total Tokens</p>
<p class="text-2xl font-bold" id="statTokens">0</p>
</div>
<div class="stat-card animate-slide-in" style="animation-delay: 0.15s">
<p class="text-xs text-[var(--fg-muted)] mb-1">Categories</p>
<p class="text-2xl font-bold" id="statCategories">0</p>
</div>
<div class="stat-card animate-slide-in" style="animation-delay: 0.2s">
<p class="text-xs text-[var(--fg-muted)] mb-1">CSS Variables</p>
<p class="text-2xl font-bold" id="statCSS">0</p>
</div>
<div class="stat-card animate-slide-in" style="animation-delay: 0.25s">
<p class="text-xs text-[var(--fg-muted)] mb-1">Output Formats</p>
<p class="text-2xl font-bold">5</p>
</div>
</div>
<!-- Input/Output Grid -->
<div class="grid lg:grid-cols-5 gap-6">
<!-- Input Panel -->
<div class="lg:col-span-2 space-y-4">
<div class="flex items-center justify-between">
<h2 class="font-semibold text-sm text-[var(--fg-secondary)] uppercase tracking-wider">Input Tokens</h2>
<span class="text-xs text-[var(--fg-muted)] font-mono">JSON</span>
</div>
<div class="code-block">
<div class="flex items-center justify-between px-4 py-2 border-b border-[var(--border-subtle)]">
<span class="text-xs text-[var(--fg-muted)]">tokens.json</span>
<button class="copy-btn text-xs" onclick="copyInput()">Copy</button>
</div>
<textarea id="tokenInput" class="w-full h-[420px] p-4" placeholder="Paste your design tokens JSON here..."></textarea>
</div>
<!-- Token Tree Preview -->
<div class="code-block">
<div class="px-4 py-2 border-b border-[var(--border-subtle)]">
<span class="text-xs text-[var(--fg-muted)]">Token Structure</span>
</div>
<div id="tokenTree" class="p-3 max-h-[200px] overflow-auto font-mono text-sm">
<p class="text-[var(--fg-muted)] text-center py-4">Transform tokens to see structure</p>
</div>
</div>
</div>
<!-- Output Panel -->
<div class="lg:col-span-3 space-y-4">
<div class="flex items-center justify-between">
<h2 class="font-semibold text-sm text-[var(--fg-secondary)] uppercase tracking-wider">Output</h2>
</div>
<!-- Tabs -->
<div class="code-block">
<div class="flex border-b border-[var(--border-subtle)] overflow-x-auto">
<button class="tab-btn active" data-tab="css">CSS Variables</button>
<button class="tab-btn" data-tab="js">JS/TS</button>
<button class="tab-btn" data-tab="swift">Swift (iOS)</button>
<button class="tab-btn" data-tab="kotlin">Kotlin (Android)</button>
<button class="tab-btn" data-tab="flutter">Flutter</button>
</div>
<div class="flex items-center justify-between px-4 py-2 border-b border-[var(--border-subtle)]">
<span class="text-xs text-[var(--fg-muted)] font-mono" id="outputFilename">tokens.css</span>
<button class="copy-btn" onclick="copyOutput()">Copy Output</button>
</div>
<div class="code-content font-mono" id="outputContent">
<pre class="text-[var(--fg-muted)]">Transform your tokens to see output...</pre>
</div>
</div>
<!-- All Outputs Preview -->
<div class="grid grid-cols-2 gap-4">
<div class="code-block">
<div class="px-4 py-2 border-b border-[var(--border-subtle)] flex items-center justify-between">
<span class="text-xs text-[var(--fg-muted)]">CSS Preview</span>
<div class="w-2 h-2 rounded-full bg-[var(--accent-cyan)]"></div>
</div>
<div class="code-content font-mono text-xs max-h-[120px]" id="cssPreview">
<pre class="text-[var(--fg-muted)]">--</pre>
</div>
</div>
<div class="code-block">
<div class="px-4 py-2 border-b border-[var(--border-subtle)] flex items-center justify-between">
<span class="text-xs text-[var(--fg-muted)]">JS Preview</span>
<div class="w-2 h-2 rounded-full bg-[var(--accent-pink)]"></div>
</div>
<div class="code-content font-mono text-xs max-h-[120px]" id="jsPreview">
<pre class="text-[var(--fg-muted)]">--</pre>
</div>
</div>
</div>
</div>
</div>
</main>
<!-- Footer -->
<footer class="border-t border-[var(--border-subtle)] mt-12 py-6">
<div class="max-w-7xl mx-auto px-6 flex items-center justify-between text-xs text-[var(--fg-muted)]">
<p>Token Forge v1.0 — Design Token Transformer</p>
<p>Supports CSS, JavaScript/TypeScript, Swift, Kotlin, Flutter</p>
</div>
</footer>
<script>
// Sample tokens data
const sampleTokens = {
"colors": {
"primary": {
"50": "#eef2ff",
"100": "#e0e7ff",
"200": "#c7d2fe",
"300": "#a5b4fc",
"400": "#818cf8",
"500": "#6366f1",
"600": "#4f46e5",
"700": "#4338ca",
"800": "#3730a3",
"900": "#312e81"
},
"neutral": {
"0": "#ffffff",
"50": "#f9fafb",
"100": "#f3f4f6",
"200": "#e5e7eb",
"300": "#d1d5db",
"400": "#9ca3af",
"500": "#6b7280",
"600": "#4b5563",
"700": "#374151",
"800": "#1f2937",
"900": "#111827"
},
"semantic": {
"background": "#0a0b0f",
"surface": "#12141a",
"text": "#e8eaed",
"textMuted": "#8b919e",
"accent": "#22d3ee",
"success": "#4ade80",
"warning": "#fb923c",
"error": "#f87171"
}
},
"spacing": {
"0": "0",
"1": "0.25rem",
"2": "0.5rem",
"3": "0.75rem",
"4": "1rem",
"5": "1.25rem",
"6": "1.5rem",
"8": "2rem",
"10": "2.5rem",
"12": "3rem",
"16": "4rem",
"20": "5rem",
"24": "6rem"
},
"typography": {
"fontFamily": {
"display": "Space Grotesk, sans-serif",
"body": "Inter, sans-serif",
"mono": "JetBrains Mono, monospace"
},
"fontSize": {
"xs": "0.75rem",
"sm": "0.875rem",
"base": "1rem",
"lg": "1.125rem",
"xl": "1.25rem",
"2xl": "1.5rem",
"3xl": "1.875rem",
"4xl": "2.25rem",
"5xl": "3rem"
},
"fontWeight": {
"normal": "400",
"medium": "500",
"semibold": "600",
"bold": "700"
},
"lineHeight": {
"tight": "1.25",
"normal": "1.5",
"relaxed": "1.75"
}
},
"borderRadius": {
"none": "0",
"sm": "0.125rem",
"default": "0.25rem",
"md": "0.375rem",
"lg": "0.5rem",
"xl": "0.75rem",
"2xl": "1rem",
"full": "9999px"
},
"shadows": {
"sm": "0 1px 2px 0 rgb(0 0 0 / 0.05)",
"default": "0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)",
"md": "0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",
"lg": "0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",
"xl": "0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)"
},
"animation": {
"duration": {
"fast": "150ms",
"normal": "300ms",
"slow": "500ms"
},
"easing": {
"default": "cubic-bezier(0.4, 0, 0.2, 1)",
"in": "cubic-bezier(0.4, 0, 1, 1)",
"out": "cubic-bezier(0, 0, 0.2, 1)",
"inOut": "cubic-bezier(0.4, 0, 0.2, 1)"
}
}
};
// State
let parsedTokens = null;
let outputs = {};
let currentTab = 'css';
// DOM Elements
const tokenInput = document.getElementById('tokenInput');
const outputContent = document.getElementById('outputContent');
const outputFilename = document.getElementById('outputFilename');
const tokenTree = document.getElementById('tokenTree');
const cssPreview = document.getElementById('cssPreview');
const jsPreview = document.getElementById('jsPreview');
const tabButtons = document.querySelectorAll('.tab-btn');
// Filenames for each tab
const filenames = {
css: 'tokens.css',
js: 'tokens.ts',
swift: 'DesignTokens.swift',
kotlin: 'DesignTokens.kt',
flutter: 'design_tokens.dart'
};
// Initialize
document.addEventListener('DOMContentLoaded', () => {
setupEventListeners();
});
function setupEventListeners() {
// Tab switching
tabButtons.forEach(btn => {
btn.addEventListener('click', () => {
tabButtons.forEach(b => b.classList.remove('active'));
btn.classList.add('active');
currentTab = btn.dataset.tab;
outputFilename.textContent = filenames[currentTab];
renderOutput();
});
});
// Transform button
document.getElementById('transformBtn').addEventListener('click', transformTokens);
// Load sample
document.getElementById('loadSample').addEventListener('click', () => {
tokenInput.value = JSON.stringify(sampleTokens, null, 2);
transformTokens();
});
// Auto-transform on input change (debounced)
let debounceTimer = null;
tokenInput.addEventListener('input', () => {
clearTimeout(debounceTimer);
debounceTimer = setTimeout(transformTokens, 500);
});
}
// Transform tokens
function transformTokens() {
const input = tokenInput.value.trim();
if (!input) {
parsedTokens = null;
outputs = {};
updateStats(0, 0, 0);
outputContent.innerHTML = '<pre class="text-[var(--fg-muted)]">Transform your tokens to see output...</pre>';
tokenTree.innerHTML = '<p class="text-[var(--fg-muted)] text-center py-4">Transform tokens to see structure</p>';
cssPreview.innerHTML = '<pre class="text-[var(--fg-muted)]">--</pre>';
jsPreview.innerHTML = '<pre class="text-[var(--fg-muted)]">--</pre>';
return;
}
try {
parsedTokens = JSON.parse(input);
// Generate all outputs
outputs = {
css: generateCSS(parsedTokens),
js: generateJS(parsedTokens),
swift: generateSwift(parsedTokens),
kotlin: generateKotlin(parsedTokens),
flutter: generateFlutter(parsedTokens)
};
// Update stats
const flatTokens = flattenTokens(parsedTokens);
const categories = Object.keys(parsedTokens).length;
updateStats(flatTokens.length, categories, flatTokens.length);
// Render token tree
renderTokenTree(parsedTokens);
// Render output
renderOutput();
// Update previews
updatePreviews();
} catch (e) {
outputContent.innerHTML = `<pre class="text-red-400">Error parsing JSON: ${e.message}</pre>`;
}
}
// Flatten tokens to array
function flattenTokens(obj, prefix = '') {
let result = [];
for (const [key, value] of Object.entries(obj)) {
const path = prefix ? `${prefix}.${key}` : key;
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
result = result.concat(flattenTokens(value, path));
} else {
result.push({ path, value, key });
}
}
return result;
}
// Generate CSS Variables
function generateCSS(tokens, prefix = '') {
let lines = [
'/* ====================================',
' * Design Tokens - CSS Custom Properties',
' * Auto-generated by Token Forge',
' * ==================================== */',
'',
':root {'
];
const flatten = (obj, pre) => {
for (const [key, value] of Object.entries(obj)) {
const varName = pre ? `--${pre}-${kebabCase(key)}` : `--${kebabCase(key)}`;
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
flatten(value, pre ? `${pre}-${kebabCase(key)}` : kebabCase(key));
} else {
lines.push(` ${varName}: ${value};`);
}
}
};
flatten(tokens, prefix);
lines.push('}');
return lines.join('\n');
}
// Generate JavaScript/TypeScript
function generateJS(tokens) {
let lines = [
'/**',
' * Design Tokens - TypeScript Constants',
' * Auto-generated by Token Forge',
' */',
'',
'export const tokens = {'
];
const processObject = (obj, indent = ' ') => {
const entries = [];
for (const [key, value] of Object.entries(obj)) {
const safeKey = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key) ? key : `"${key}"`;
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
entries.push(`${indent}${safeKey}: {`);
entries.push(processObject(value, indent + ' '));
entries.push(`${indent}},`);
} else if (typeof value === 'string') {
entries.push(`${indent}${safeKey}: "${escapeString(value)}",`);
} else {
entries.push(`${indent}${safeKey}: ${value},`);
}
}
return entries.join('\n');
};
lines.push(processObject(tokens));
lines.push('};');
lines.push('');
lines.push('export type TokenType = typeof tokens;');
return lines.join('\n');
}
// Generate Swift (iOS)
function generateSwift(tokens) {
let lines = [
'//',
'// Design Tokens - Swift Constants',
'// Auto-generated by Token Forge',
'//',
'',
'import SwiftUI',
'',
'enum DesignTokens {'
];
const categoryColors = {
colors: 'cyan',
spacing: 'green',
typography: 'orange',
borderRadius: 'pink',
shadows: 'purple',
animation: 'blue'
};
for (const [category, values] of Object.entries(tokens)) {
const swiftCategory = pascalCase(category);
lines.push(` enum ${swiftCategory} {`);
const processValue = (obj, prefix = '') => {
for (const [key, value] of Object.entries(obj)) {
const swiftKey = (prefix + key).replace(/[^a-zA-Z0-9]/g, '_');
const constName = `static let ${camelCase(key)}`;
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
lines.push(` // ${key}`);
for (const [k, v] of Object.entries(value)) {
const finalName = `static let ${camelCase(key)}_${camelCase(k)}`;
if (category === 'colors') {
lines.push(` ${finalName}: Color = Color(hex: "${v}")`);
} else if (category === 'spacing' || category === 'borderRadius') {
lines.push(` ${finalName}: CGFloat = ${parseDimension(v)}`);
} else {
lines.push(` ${finalName} = "${escapeString(v)}"`);
}
}
} else {
if (category === 'colors') {
lines.push(` ${constName}: Color = Color(hex: "${value}")`);
} else if (category === 'spacing' || category === 'borderRadius') {
lines.push(` ${constName}: CGFloat = ${parseDimension(value)}`);
} else {
lines.push(` ${constName} = "${escapeString(value)}"`);
}
}
}
};
processValue(values);
lines.push(' }');
lines.push('');
}
lines.push('}');
lines.push('');
lines.push('// Color extension for hex initialization');
lines.push('extension Color {');
lines.push(' init(hex: String) {');
lines.push(' let hex = hex.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)');
lines.push(' var int: UInt64 = 0');
lines.push(' Scanner(string: hex).scanHexInt64(&int)');
lines.push(' let a, r, g, b: UInt64');
lines.push(' switch hex.count {');
lines.push(' case 3: (a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)');
lines.push(' case 6: (a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)');
lines.push(' case 8: (a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)');
lines.push(' default: (a, r, g, b) = (255, 0, 0, 0)');
lines.push(' }');
lines.push(' self.init(.sRGB, red: Double(r) / 255, green: Double(g) / 255, blue: Double(b) / 255, opacity: Double(a) / 255)');
lines.push(' }');
lines.push('}');
return lines.join('\n');
}
// Generate Kotlin (Android)
function generateKotlin(tokens) {
let lines = [
'/**',
' * Design Tokens - Kotlin Constants',
' * Auto-generated by Token Forge',
' */',
'',
'package com.example.design',
'',
'import androidx.compose.ui.graphics.Color',
'import androidx.compose.ui.unit.*',
'',
'object DesignTokens {'
];
for (const [category, values] of Object.entries(tokens)) {
const kotlinCategory = pascalCase(category);
lines.push(` object ${kotlinCategory} {`);
const processValue = (obj) => {
for (const [key, value] of Object.entries(obj)) {
const constName = `val ${camelCase(key)}`;
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
lines.push(` // ${key}`);
for (const [k, v] of Object.entries(value)) {
const finalName = `val ${camelCase(key)}_${camelCase(k)}`;
if (category === 'colors') {
lines.push(` ${finalName} = Color(0xFF${v.replace('#', '')})`);
} else if (category === 'spacing') {
lines.push(` ${finalName} = ${parseDimension(v)}.dp`);
} else if (category === 'fontSize') {
lines.push(` ${finalName} = ${parseDimension(v)}.sp`);
} else {
lines.push(` ${finalName} = "${escapeString(v)}"`);
}
}
} else {
if (category === 'colors') {
lines.push(` ${constName} = Color(0xFF${value.replace('#', '')})`);
} else if (category === 'spacing') {
lines.push(` ${constName} = ${parseDimension(value)}.dp`);
} else {
lines.push(` ${constName} = "${escapeString(value)}"`);
}
}
}
};
processValue(values);
lines.push(' }');
lines.push('');
}
lines.push('}');
return lines.join('\n');
}
// Generate Flutter
function generateFlutter(tokens) {
let lines = [
'/**',
' * Design Tokens - Flutter Constants',
' * Auto-generated by Token Forge',
' */',
'',
'library design_tokens;',
'',
"import 'package:flutter/material.dart';",
'',
'class DesignTokens {'
];
for (const [category, values] of Object.entries(tokens)) {
const dartCategory = pascalCase(category);
lines.push(` static class ${dartCategory} {`);
const processValue = (obj) => {
for (const [key, value] of Object.entries(obj)) {
const constName = `static const ${camelCase(key)}`;
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
for (const [k, v] of Object.entries(value)) {
const finalName = `static const ${camelCase(key)}_${camelCase(k)}`;
if (category === 'colors') {
lines.push(` ${finalName} = Color(0xFF${v.replace('#', '')});`);
} else if (category === 'spacing') {
lines.push(` ${finalName} = ${parseDimension(v)}.0;`);
} else {
lines.push(` ${finalName} = '${escapeString(v)}';`);
}
}
} else {
if (category === 'colors') {
lines.push(` ${constName} = Color(0xFF${value.replace('#', '')});`);
} else if (category === 'spacing') {
lines.push(` ${constName} = ${parseDimension(value)}.0;`);
} else {
lines.push(` ${constName} = '${escapeString(value)}';`);
}
}
}
};
processValue(values);
lines.push(' }');
lines.push('');
}
lines.push('}');
return lines.join('\n');
}
// Render output with syntax highlighting
function renderOutput() {
if (!outputs[currentTab]) {
outputContent.innerHTML = '<pre class="text-[var(--fg-muted)]">Transform your tokens to see output...</pre>';
return;
}
const highlighted = highlightSyntax(outputs[currentTab], currentTab);
outputContent.innerHTML = `<pre>${highlighted}</pre>`;
}
// Syntax highlighting
function highlightSyntax(code, language) {
let highlighted = escapeHtml(code);
if (language === 'css') {
highlighted = highlighted
.replace(/(--[\w-]+)/g, '<span class="prop-name">$1</span>')
.replace(/(:root)/g, '<span class="selector">$1</span>')
.replace(/(#[\da-fA-F]{3,8})/g, '<span class="prop-value">$1</span>')
.replace(/(\/\*[\s\S]*?\*\/)/g, '<span class="token-comment">$1</span>');
} else if (language === 'js') {
highlighted = highlighted
.replace(/\b(export|const|let|var|type|typeof)\b/g, '<span class="keyword">$1</span>')
.replace(/("[^"]*")/g, '<span class="string">$1</span>')
.replace(/\b([\w]+)\s*:/g, '<span class="property">$1</span>:')
.replace(/(\/\/.*$)/gm, '<span class="token-comment">$1</span>')
.replace(/(\/\*\*[\s\S]*?\*\/)/g, '<span class="token-comment">$1</span>');
} else if (language === 'swift') {
highlighted = highlighted
.replace(/\b(enum|struct|class|let|var|func|import|static|case|switch|default|init|self)\b/g, '<span class="keyword">$1</span>')
.replace(/\b(Color|CGFloat|String|UInt64|Double|Int|Scanner|Character)\b/g, '<span class="type">$1</span>')
.replace(/("[^"]*")/g, '<span class="string">$1</span>')
.replace(/(\/\/.*$)/gm, '<span class="token-comment">$1</span>');
} else if (language === 'kotlin') {
highlighted = highlighted
.replace(/\b(object|class|val|var|fun|import|package|const)\b/g, '<span class="keyword">$1</span>')
.replace(/\b(Color|Int|String|Double|Float|Unit|Dp|Sp)\b/g, '<span class="type">$1</span>')
.replace(/("[^"]*")/g, '<span class="string">$1</span>')
.replace(/(\/\/.*$)/gm, '<span class="token-comment">$1</span>')
.replace(/(\/\*\*[\s\S]*?\*\/)/g, '<span class="token-comment">$1</span>');
} else if (language === 'flutter') {
highlighted = highlighted
.replace(/\b(class|static|const|final|import|library)\b/g, '<span class="keyword">$1</span>')
.replace(/\b(Color|String|double|int|MaterialApp|Widget)\b/g, '<span class="type">$1</span>')
.replace(/('[^']*')/g, '<span class="string">$1</span>')
.replace(/(\/\/.*$)/gm, '<span class="token-comment">$1</span>')
.replace(/(\/\*\*[\s\S]*?\*\/)/g, '<span class="token-comment">$1</span>');
}
return highlighted;
}
// Render token tree
function renderTokenTree(tokens, container = null, depth = 0) {
if (container === null) {
tokenTree.innerHTML = '';
container = tokenTree;
}
const colors = ['#22d3ee', '#4ade80', '#fb923c', '#f472b6', '#a78bfa', '#60a5fa'];
for (const [key, value] of Object.entries(tokens)) {
const item = document.createElement('div');
item.className = 'token-tree-item flex items-center gap-2';
item.style.paddingLeft = `${depth * 16}px`;
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
const colorIndex = depth % colors.length;
item.innerHTML = `
<span class="token-dot" style="background: ${colors[colorIndex]}"></span>
<span class="text-[var(--fg-primary)]">${key}</span>
<span class="text-[var(--fg-muted)] text-xs">(${Object.keys(value).length})</span>
`;
container.appendChild(item);
renderTokenTree(value, container, depth + 1);
} else {
item.innerHTML = `
<span class="token-dot bg-[var(--fg-muted)]"></span>
<span class="text-[var(--fg-secondary)]">${key}</span>
<span class="text-[var(--fg-muted)] text-xs ml-auto">${String(value).substring(0, 20)}${String(value).length > 20 ? '...' : ''}</span>
`;
container.appendChild(item);
}
}
}
// Update previews
function updatePreviews() {
if (outputs.css) {
const cssLines = outputs.css.split('\n').slice(7, 15).join('\n');
cssPreview.innerHTML = `<pre>${highlightSyntax(cssLines, 'css')}</pre>`;
}
if (outputs.js) {
const jsLines = outputs.js.split('\n').slice(7, 15).join('\n');
jsPreview.innerHTML = `<pre>${highlightSyntax(jsLines, 'js')}</pre>`;
}
}
// Update stats
function updateStats(tokens, categories, css) {
document.getElementById('statTokens').textContent = tokens;
document.getElementById('statCategories').textContent = categories;
document.getElementById('statCSS').textContent = css;
}
// Copy functions
function copyOutput() {
if (outputs[currentTab]) {
navigator.clipboard.writeText(outputs[currentTab]);
showCopyFeedback();
}
}
function copyInput() {
navigator.clipboard.writeText(tokenInput.value);
}
function showCopyFeedback() {
const btn = document.querySelector('.copy-btn:last-of-type');
btn.classList.add('copied');
btn.textContent = 'Copied!';
setTimeout(() => {
btn.classList.remove('copied');
btn.textContent = 'Copy Output';
}, 2000);
}
// Utility functions
function kebabCase(str) {
return str.replace(/([a-z])([A-Z])/g, '$1-$2').replace(/[\s_]+/g, '-').toLowerCase();
}
function camelCase(str) {
return str.replace(/[-_\s]+(.)?/g, (_, c) => c ? c.toUpperCase() : '').replace(/^(.)/, c => c.toLowerCase());
}
function pascalCase(str) {
return str.replace(/[-_\s]+(.)?/g, (_, c) => c ? c.toUpperCase() : '').replace(/^(.)/, c => c.toUpperCase());
}
function escapeHtml(str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
}
function escapeString(str) {
return str.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
}
function parseDimension(value) {
if (typeof value !== 'string') return value;
const match = value.match(/^([\d.]+)/);
return match ? parseFloat(match[1]) : value;
}
</script>
</body>
</html>
Key Features
Input Handling:
- JSON token editor with real-time parsing
- Sample tokens pre-loaded via "Load Sample" button
- Auto-transform on input (debounced)
- Error handling with clear feedback
Output Formats:
- CSS Variables —
:root block with kebab-case naming
- JavaScript/TypeScript — Nested object exports with type definitions
- Swift (iOS) — SwiftUI-ready with Color extensions and CGFloat values
- Kotlin (Android) — Jetpack Compose compatible with Color/Dp units
- Flutter/Dart — Static constants for Material Design
Visual Features:
- Live token tree visualization showing structure
- Syntax highlighting per language
- Mini-previews for CSS and JS output
- Token/category/variable statistics
- Tabbed interface with smooth transitions
Interactions:
- Click tabs to switch output formats
- Copy output to clipboard with feedback
- Real-time transformation as you type
- "Load Sample" for quick demo