An open source design system that's fully customizable and agent ready
TypeScript
feat(sandbox): Color Studio — palette generator (#1891)
rubyycheung94554326a6c3
diff --git a/apps/sandbox/src/app/(sandbox)/pages/color-studio/colorUtils.ts b/apps/sandbox/src/app/(sandbox)/pages/color-studio/colorUtils.tsnew file mode 100644index 0000000000..0d57aafcb1--- /dev/null+++ b/apps/sandbox/src/app/(sandbox)/pages/color-studio/colorUtils.ts@@ -0,0 +1,724 @@+/**+ * Color Studio — Color Utilities+ *+ * HCT perceptual color space, tonal palette generation, color harmonies,+ * image extraction, semantic role derivation, and WCAG contrast.+ */++// === sRGB ↔ Linear ===+function srgbToLinear(c: number): number {+ const s = c / 255;+ return s <= 0.04045 ? s / 12.92 : Math.pow((s + 0.055) / 1.055, 2.4);+}+function linearToSrgb(c: number): number {+ const s = c <= 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;+ return Math.round(Math.min(255, Math.max(0, s * 255)));+}++// === Linear RGB ↔ XYZ (D65) ===+function linearRgbToXyz(+ r: number,+ g: number,+ b: number,+): [number, number, number] {+ return [+ 0.4124564 * r + 0.3575761 * g + 0.1804375 * b,+ 0.2126729 * r + 0.7151522 * g + 0.072175 * b,+ 0.0193339 * r + 0.119192 * g + 0.9503041 * b,+ ];+}+function xyzToLinearRgb(+ x: number,+ y: number,+ z: number,+): [number, number, number] {+ return [+ 3.2404542 * x - 1.5371385 * y - 0.4985314 * z,+ -0.969266 * x + 1.8760108 * y + 0.041556 * z,+ 0.0556434 * x - 0.2040259 * y + 1.0572252 * z,+ ];+}++// === XYZ ↔ CIELab ===+const D65: [number, number, number] = [0.95047, 1.0, 1.08883];+function labF(t: number): number {+ const d = 6 / 29;+ return t > d * d * d ? Math.cbrt(t) : t / (3 * d * d) + 4 / 29;+}+function labFInv(t: number): number {+ const d = 6 / 29;+ return t > d ? t * t * t : 3 * d * d * (t - 4 / 29);+}+function xyzToLab(x: number, y: number, z: number): [number, number, number] {+ const fx = labF(x / D65[0]),+ fy = labF(y / D65[1]),+ fz = labF(z / D65[2]);+ return [116 * fy - 16, 500 * (fx - fy), 200 * (fy - fz)];+}+function labToXyz(L: number, a: number, b: number): [number, number, number] {+ const fy = (L + 16) / 116,+ fx = a / 500 + fy,+ fz = fy - b / 200;+ return [labFInv(fx) * D65[0], labFInv(fy) * D65[1], labFInv(fz) * D65[2]];+}++// === HCT Types ===+export interface HCT {+ hue: number;+ chroma: number;+ tone: number;+}++export function hexToRgb(hex: string): [number, number, number] {+ const h = hex.replace('#', '');+ const full =+ h.length === 3 ? h[0] + h[0] + h[1] + h[1] + h[2] + h[2] : h.slice(0, 6);+ const n = parseInt(full, 16);+ return [(n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff];+}++export function rgbToHex(r: number, g: number, b: number): string {+ return (+ '#' ++ [r, g, b]+ .map(c =>+ Math.round(Math.max(0, Math.min(255, c)))+ .toString(16)+ .padStart(2, '0'),+ )+ .join('')+ );+}++export function hexToHct(hex: string): HCT {+ const [r, g, b] = hexToRgb(hex);+ const [x, y, z] = linearRgbToXyz(+ srgbToLinear(r),+ srgbToLinear(g),+ srgbToLinear(b),+ );+ const [L, a, bLab] = xyzToLab(x, y, z);+ let hue = (Math.atan2(bLab, a) * 180) / Math.PI;+ if (hue < 0) hue += 360;+ return {+ hue,+ chroma: Math.sqrt(a * a + bLab * bLab),+ tone: Math.max(0, Math.min(100, L)),+ };+}++export function hctToHex(hct: HCT): string {+ const {hue, chroma, tone} = hct;+ if (tone <= 0) return '#000000';+ if (tone >= 100) return '#ffffff';+ if (chroma < 0.5) {+ const y = labFInv((tone + 16) / 116);+ const g = linearToSrgb(y);+ return rgbToHex(g, g, g);+ }+ let lo = 0,+ hi = chroma,+ best = '#000000';+ for (let i = 0; i < 16; i++) {+ const mid = (lo + hi) / 2;+ const hRad = (hue * Math.PI) / 180;+ const a = Math.cos(hRad) * mid,+ b = Math.sin(hRad) * mid;+ const [x, y, z] = labToXyz(tone, a, b);+ const [lr, lg, lb] = xyzToLinearRgb(x, y, z);+ const r = linearToSrgb(lr),+ g = linearToSrgb(lg),+ bv = linearToSrgb(lb);+ const ok =+ Math.abs(srgbToLinear(r) - lr) < 0.02 &&+ Math.abs(srgbToLinear(g) - lg) < 0.02 &&+ Math.abs(srgbToLinear(bv) - lb) < 0.02 &&+ r >= 0 &&+ r <= 255 &&+ g >= 0 &&+ g <= 255 &&+ bv >= 0 &&+ bv <= 255;+ if (ok) {+ best = rgbToHex(r, g, bv);+ lo = mid;+ } else {+ hi = mid;+ }+ }+ return best;+}++// === Tonal Palette ===+export const TONE_STEPS = [+ 0, 5, 10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 99, 100,+];+export function tonalPalette(+ hue: number,+ chroma: number,+): Record<number, string> {+ const result: Record<number, string> = {};+ for (const t of TONE_STEPS) result[t] = hctToHex({hue, chroma, tone: t});+ return result;+}++// === Color Harmonies ===+export type HarmonyType =+ | 'complementary'+ | 'analogous'+ | 'triadic'+ | 'split-complementary'+ | 'tetradic'+ | 'monochromatic';+export interface HarmonyColor {+ label: string;+ hue: number;+ chroma: number;+ hex: string;+}++export function generateHarmony(seed: HCT, type: HarmonyType): HarmonyColor[] {+ const {hue: h, chroma: c} = seed;+ const mk = (label: string, hue: number, chr?: number): HarmonyColor => ({+ label,+ hue: ((hue % 360) + 360) % 360,+ chroma: chr ?? c,+ hex: hctToHex({hue: ((hue % 360) + 360) % 360, chroma: chr ?? c, tone: 50}),+ });+ switch (type) {+ case 'complementary':+ return [mk('Primary', h), mk('Complement', h + 180)];+ case 'analogous':+ return [+ mk('Analogous A', h - 30),+ mk('Primary', h),+ mk('Analogous B', h + 30),+ ];+ case 'triadic':+ return [+ mk('Primary', h),+ mk('Triadic B', h + 120),+ mk('Triadic C', h + 240),+ ];+ case 'split-complementary':+ return [mk('Primary', h), mk('Split B', h + 150), mk('Split C', h + 210)];+ case 'tetradic':+ return [+ mk('Primary', h),+ mk('Tetradic B', h + 90),+ mk('Tetradic C', h + 180),+ mk('Tetradic D', h + 270),+ ];+ case 'monochromatic':+ return [+ mk('Muted', h, c * 0.3),+ mk('Light', h, c * 0.6),+ mk('Primary', h),+ mk('Vivid', h, Math.min(c * 1.4, 120)),+ ];+ default:+ return [mk('Primary', h)];+ }+}++// === Semantic Roles (Layer 2) ===+export interface SemanticRole {+ name: string;+ group: string;+ light: string;+ dark: string;+ highContrast: string;+ pairedWith?: string;+}++function alpha(hex: string, a: number): string {+ return (+ hex.substring(0, 7) ++ Math.round(a * 255)+ .toString(16)+ .padStart(2, '0')+ );+}++export function deriveSemanticRoles(+ seedHex: string,+ warmth: 'warm' | 'cool' | 'neutral',+ surfaceStyle: 'tinted' | 'neutral' = 'tinted',+ exactAccent: boolean = false,+): SemanticRole[] {+ const seed = hexToHct(seedHex);+ const h = seed.hue;+ const pc = Math.max(seed.chroma, 48);+ const nc =+ surfaceStyle === 'neutral'+ ? 0+ : warmth === 'warm'+ ? 7+ : warmth === 'cool'+ ? 5+ : 3;+ const nvc = surfaceStyle === 'neutral' ? 2 : nc + 3;+ const P = tonalPalette(h, pc);+ const N = tonalPalette(h, nc);+ const NV = tonalPalette(h, nvc);++ // Feedback colors: fixed hues, but chroma + tone adapt to seed character.+ // Vivid seeds get punchier feedback; muted seeds get softer feedback.+ const chromaScale = Math.max(0.7, Math.min(1.3, seed.chroma / 50));+ const E = tonalPalette(25, Math.round(70 * chromaScale));+ const S = tonalPalette(145, Math.round(60 * chromaScale));+ const W = tonalPalette(90, Math.round(70 * chromaScale));+ const I = tonalPalette(250, Math.round(50 * chromaScale));++ return [+ {+ name: 'accent',+ group: 'Interactive',+ light: exactAccent ? seedHex : P[40],+ dark: exactAccent+ ? hctToHex({hue: h, chroma: pc, tone: Math.max(seed.tone, 70)})+ : P[80],+ highContrast: P[30],+ pairedWith: 'surface',+ },+ {+ name: 'accent-muted',+ group: 'Interactive',+ light: exactAccent ? alpha(seedHex, 0.2) : alpha(P[40], 0.2),+ dark: exactAccent+ ? alpha(+ hctToHex({hue: h, chroma: pc, tone: Math.max(seed.tone, 70)}),+ 0.25,+ )+ : alpha(P[80], 0.25),+ highContrast: alpha(P[30], 0.25),+ },+ {+ name: 'on-accent',+ group: 'Interactive',+ light: P[100],+ dark: P[20],+ highContrast: P[100],+ pairedWith: 'accent',+ },+ {+ name: 'accent-hover',+ group: 'Interactive',+ light: exactAccent+ ? hctToHex({hue: h, chroma: pc, tone: Math.max(seed.tone - 8, 15)})+ : P[30],+ dark: exactAccent+ ? hctToHex({hue: h, chroma: pc, tone: Math.min(seed.tone + 8, 85)})+ : P[70],+ highContrast: P[20],+ },+ {+ name: 'accent-pressed',+ group: 'Interactive',+ light: exactAccent+ ? hctToHex({hue: h, chroma: pc, tone: Math.max(seed.tone - 15, 10)})+ : P[20],+ dark: exactAccent+ ? hctToHex({hue: h, chroma: pc, tone: Math.min(seed.tone + 15, 80)})+ : P[60],+ highContrast: P[10],+ },+ {+ name: 'focus-ring',+ group: 'Interactive',+ light: alpha(P[50], 0.5),+ dark: alpha(P[70], 0.5),+ highContrast: P[40],+ },+ {+ name: 'surface',+ group: 'Surface',+ light: surfaceStyle === 'neutral' ? '#ffffff' : N[99],+ dark: N[10],+ highContrast: '#ffffff',+ },+ {+ name: 'body',+ group: 'Surface',+ light: surfaceStyle === 'neutral' ? '#ffffff' : N[95],+ dark: N[5],+ highContrast: '#ffffff',+ },+ {+ name: 'card',+ group: 'Surface',+ light: surfaceStyle === 'neutral' ? '#ffffff' : N[99],+ dark: N[10],+ highContrast: '#ffffff',+ },+ {+ name: 'popover',+ group: 'Surface',+ light: surfaceStyle === 'neutral' ? '#ffffff' : N[99],+ dark: N[20],+ highContrast: '#ffffff',+ },+ {+ name: 'overlay',+ group: 'Surface',+ light: alpha(N[10], 0.4),+ dark: alpha(N[10], 0.6),+ highContrast: alpha(N[0], 0.7),+ },+ {+ name: 'muted',+ group: 'Surface',+ light: alpha(N[10], 0.05),+ dark: alpha(N[10], 0.5),+ highContrast: alpha(N[10], 0.08),+ },+ {+ name: 'inverted',+ group: 'Surface',+ light: N[10],+ dark: surfaceStyle === 'neutral' ? '#ffffff' : N[99],+ highContrast: '#000000',+ },+ {+ name: 'text-primary',+ group: 'Content',+ light: N[10],+ dark: N[90],+ highContrast: N[0],+ pairedWith: 'surface',+ },+ {+ name: 'text-secondary',+ group: 'Content',+ light: NV[30],+ dark: NV[70],+ highContrast: NV[20],+ pairedWith: 'surface',+ },+ {+ name: 'text-disabled',+ group: 'Content',+ light: NV[60],+ dark: NV[40],+ highContrast: NV[50],+ pairedWith: 'surface',+ },+ {+ name: 'text-accent',+ group: 'Content',+ light: exactAccent ? seedHex : P[30],+ dark: exactAccent+ ? hctToHex({hue: h, chroma: pc, tone: Math.max(seed.tone, 70)})+ : P[80],+ highContrast: P[20],+ pairedWith: 'surface',+ },+ {+ name: 'icon-primary',+ group: 'Content',+ light: N[10],+ dark: N[90],+ highContrast: N[0],+ pairedWith: 'surface',+ },+ {+ name: 'icon-secondary',+ group: 'Content',+ light: NV[30],+ dark: NV[70],+ highContrast: NV[20],+ pairedWith: 'surface',+ },+ {+ name: 'icon-disabled',+ group: 'Content',+ light: NV[60],+ dark: NV[40],+ highContrast: NV[50],+ pairedWith: 'surface',+ },+ {+ name: 'error',+ group: 'Feedback',+ light: E[40],+ dark: E[60],+ highContrast: E[30],+ pairedWith: 'surface',+ },+ {+ name: 'error-muted',+ group: 'Feedback',+ light: alpha(E[40], 0.2),+ dark: alpha(E[60], 0.25),+ highContrast: alpha(E[30], 0.25),+ },+ {+ name: 'on-error',+ group: 'Feedback',+ light: E[100],+ dark: E[10],+ highContrast: E[100],+ pairedWith: 'error',+ },+ {+ name: 'success',+ group: 'Feedback',+ light: S[40],+ dark: S[60],+ highContrast: S[30],+ pairedWith: 'surface',+ },+ {+ name: 'success-muted',+ group: 'Feedback',+ light: alpha(S[40], 0.2),+ dark: alpha(S[60], 0.25),+ highContrast: alpha(S[30], 0.25),+ },+ {+ name: 'on-success',+ group: 'Feedback',+ light: S[100],+ dark: S[10],+ highContrast: S[100],+ pairedWith: 'success',+ },+ {+ name: 'warning',+ group: 'Feedback',+ light: W[50],+ dark: W[60],+ highContrast: W[40],+ pairedWith: 'surface',+ },+ {+ name: 'warning-muted',+ group: 'Feedback',+ light: alpha(W[50], 0.2),+ dark: alpha(W[50], 0.25),+ highContrast: alpha(W[40], 0.25),+ },+ {+ name: 'on-warning',+ group: 'Feedback',+ light: N[10],+ dark: N[10],+ highContrast: N[0],+ pairedWith: 'warning',+ },+ {+ name: 'info',+ group: 'Feedback',+ light: I[40],+ dark: I[70],+ highContrast: I[30],+ pairedWith: 'surface',+ },+ {+ name: 'info-muted',+ group: 'Feedback',+ light: alpha(I[40], 0.2),+ dark: alpha(I[70], 0.25),+ highContrast: alpha(I[30], 0.25),+ },+ {+ name: 'border',+ group: 'Border',+ light: alpha(N[10], 0.1),+ dark: alpha(N[95], 0.1),+ highContrast: N[0],+ },+ {+ name: 'border-emphasized',+ group: 'Border',+ light: NV[70],+ dark: NV[30],+ highContrast: NV[0],+ },+ ];+}++// === Categorical Colors (Layer 3) ===+export interface CategoricalColor {+ label: string;+ hex: string;+ hue: number;+}+export function generateCategorical(+ _seedHue: number,+ seedChroma: number,+): CategoricalColor[] {+ // Fixed hues for maximum mutual distinctness. Chroma and tone adapt+ // to the seed's character — vivid seeds produce vivid categoricals,+ // muted seeds produce softer ones.+ const chromaScale = Math.max(0.6, Math.min(1.4, seedChroma / 50));+ const defs: Array<{+ label: string;+ hue: number;+ baseChroma: number;+ baseTone: number;+ }> = [+ {label: 'Blue', hue: 260, baseChroma: 70, baseTone: 55},+ {label: 'Orange', hue: 70, baseChroma: 80, baseTone: 65},+ {label: 'Green', hue: 155, baseChroma: 55, baseTone: 60},+ {label: 'Purple', hue: 310, baseChroma: 60, baseTone: 50},+ {label: 'Teal', hue: 200, baseChroma: 40, baseTone: 60},+ {label: 'Pink', hue: 0, baseChroma: 65, baseTone: 60},+ {label: 'Amber', hue: 85, baseChroma: 75, baseTone: 75},+ {label: 'Indigo', hue: 290, baseChroma: 55, baseTone: 45},+ {label: 'Red', hue: 30, baseChroma: 80, baseTone: 50},+ {label: 'Cyan', hue: 220, baseChroma: 45, baseTone: 65},+ ];+ return defs.map(({label, hue, baseChroma, baseTone}) => {+ const chroma = Math.round(baseChroma * chromaScale);+ const tone = baseTone;+ return {+ label,+ hue,+ hex: hctToHex({hue, chroma, tone}),+ };+ });+}++// === Expressive Colors (Layer 4) ===+export interface ExpressiveColor {+ label: string;+ hex: string;+ hue: number;+ chroma: number;+}+export function generateExpressive(+ seedHue: number,+ seedChroma: number,+): ExpressiveColor[] {+ const configs: Array<{label: string; dH: number; cM: number; t: number}> = [+ {label: 'Vivid', dH: 0, cM: 1.5, t: 55},+ {label: 'Warm', dH: 30, cM: 1.2, t: 60},+ {label: 'Cool', dH: -60, cM: 1.0, t: 55},+ {label: 'Deep', dH: 0, cM: 1.3, t: 30},+ {label: 'Pastel', dH: 15, cM: 0.5, t: 85},+ {label: 'Electric', dH: -30, cM: 1.6, t: 50},+ ];+ return configs.map(({label, dH, cM, t}) => {+ const hue = (((seedHue + dH) % 360) + 360) % 360;+ const chroma = Math.min(seedChroma * cM, 120);+ return {label, hue, chroma, hex: hctToHex({hue, chroma, tone: t})};+ });+}++// === WCAG Contrast ===+export function luminance(hex: string): number {+ if (hex.length > 7) hex = hex.substring(0, 7);+ const [r, g, b] = hexToRgb(hex).map(c => {+ const s = c / 255;+ return s <= 0.03928 ? s / 12.92 : Math.pow((s + 0.055) / 1.055, 2.4);+ });+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;+}+export function contrastRatio(fg: string, bg: string): number {+ const l1 = luminance(fg),+ l2 = luminance(bg);+ return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);+}+export function wcagGrade(ratio: number): 'AAA' | 'AA' | 'AA18' | 'FAIL' {+ if (ratio >= 7) return 'AAA';+ if (ratio >= 4.5) return 'AA';+ if (ratio >= 3) return 'AA18';+ return 'FAIL';+}++// === Image Color Extraction (Median Cut) ===+export function extractColorsFromImage(+ img: HTMLImageElement,+ count = 8,+): string[] {+ const canvas = document.createElement('canvas');+ const ctx = canvas.getContext('2d');+ if (!ctx) return [];+ const w = 200,+ h = Math.round((img.naturalHeight * 200) / img.naturalWidth);+ canvas.width = w;+ canvas.height = h;+ ctx.drawImage(img, 0, 0, w, h);+ const data = ctx.getImageData(0, 0, w, h).data;+ const pixels: [number, number, number][] = [];+ for (let i = 0; i < data.length; i += 4) {+ if (data[i + 3] < 128) continue;+ const lum = 0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2];+ if (lum < 15 || lum > 245) continue;+ pixels.push([data[i], data[i + 1], data[i + 2]]);+ }+ if (!pixels.length) return ['#0064e0'];+ function medianCut(px: [number, number, number][], depth: number): string[] {+ if (depth === 0 || px.length < 2) {+ const avg = px.reduce(+ (a, p) => [a[0] + p[0], a[1] + p[1], a[2] + p[2]],+ [0, 0, 0],+ );+ const n = px.length || 1;+ return [rgbToHex(avg[0] / n, avg[1] / n, avg[2] / n)];+ }+ const ranges = [0, 1, 2].map(ch => {+ const v = px.map(p => p[ch]);+ return Math.max(...v) - Math.min(...v);+ });+ const ch = ranges.indexOf(Math.max(...ranges));+ px.sort((a, b) => a[ch] - b[ch]);+ const mid = Math.floor(px.length / 2);+ return [+ ...medianCut(px.slice(0, mid), depth - 1),+ ...medianCut(px.slice(mid), depth - 1),+ ];+ }+ const colors = medianCut(pixels, Math.ceil(Math.log2(count)));+ const unique = [colors[0]];+ for (const c of colors.slice(1)) {+ const h1 = hexToHct(c);+ if (+ !unique.some(u => {+ const h2 = hexToHct(u);+ return (+ Math.abs(h1.tone - h2.tone) < 8 &&+ Math.abs(h1.chroma - h2.chroma) < 10+ );+ })+ )+ unique.push(c);+ }+ unique.sort((a, b) => hexToHct(b).chroma - hexToHct(a).chroma);+ return unique.slice(0, count);+}++// === Parse color string ===+export function parseColorInput(input: string): string | null {+ const s = input.trim();+ if (/^#?[0-9a-f]{3}$/i.test(s)) {+ const h = s.replace('#', '');+ return '#' + h[0] + h[0] + h[1] + h[1] + h[2] + h[2];+ }+ if (/^#?[0-9a-f]{6}$/i.test(s)) return '#' + s.replace('#', '');+ const rgbM = s.match(/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);+ if (rgbM) return rgbToHex(+rgbM[1], +rgbM[2], +rgbM[3]);+ const hslM = s.match(/^hsla?\(\s*([\d.]+)\s*,\s*([\d.]+)%\s*,\s*([\d.]+)%/);+ if (hslM) {+ const hh = +hslM[1] / 360,+ ss = +hslM[2] / 100,+ ll = +hslM[3] / 100;+ const q = ll < 0.5 ? ll * (1 + ss) : ll + ss - ll * ss,+ p = 2 * ll - q;+ const h2r = (pp: number, qq: number, t: number) => {+ if (t < 0) t += 1;+ if (t > 1) t -= 1;+ if (t < 1 / 6) return pp + (qq - pp) * 6 * t;+ if (t < 1 / 2) return qq;+ if (t < 2 / 3) return pp + (qq - pp) * (2 / 3 - t) * 6;+ return pp;+ };+ return rgbToHex(+ Math.round(h2r(p, q, hh + 1 / 3) * 255),+ Math.round(h2r(p, q, hh) * 255),+ Math.round(h2r(p, q, hh - 1 / 3) * 255),+ );+ }+ return null;+}diff --git a/apps/sandbox/src/app/(sandbox)/pages/color-studio/page.tsx b/apps/sandbox/src/app/(sandbox)/pages/color-studio/page.tsxnew file mode 100644index 0000000000..16af8b23e2--- /dev/null+++ b/apps/sandbox/src/app/(sandbox)/pages/color-studio/page.tsx@@ -0,0 +1,1529 @@+'use client';++import {useState, useCallback, useEffect, useMemo, useRef} from 'react';+import {+ hexToHct,+ hctToHex,+ tonalPalette,+ TONE_STEPS,+ generateHarmony,+ deriveSemanticRoles,+ generateCategorical,+ generateExpressive,+ contrastRatio,+ wcagGrade,+ extractColorsFromImage,+ parseColorInput,+ type HarmonyType,+} from './colorUtils';++// =============================================================================+// Styles+// =============================================================================++const S = {+ page: {+ display: 'flex',+ minHeight: '100vh',+ background: '#0e0e10',+ color: '#fafafa',+ fontFamily:+ "'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",+ } as React.CSSProperties,+ sidebar: {+ width: 320,+ flexShrink: 0,+ borderRight: '1px solid rgba(255,255,255,0.08)',+ background: '#18181b',+ padding: 20,+ overflowY: 'auto',+ } as React.CSSProperties,+ main: {flex: 1, overflowY: 'auto', padding: 24} as React.CSSProperties,+ section: {marginBottom: 24} as React.CSSProperties,+ sectionTitle: {+ fontSize: 11,+ fontWeight: 600,+ textTransform: 'uppercase' as const,+ letterSpacing: '0.8px',+ color: '#71717a',+ marginBottom: 12,+ paddingBottom: 8,+ borderBottom: '1px solid rgba(255,255,255,0.06)',+ } as React.CSSProperties,+ sourcePicker: {+ display: 'flex',+ alignItems: 'center',+ gap: 12,+ background: '#1f1f23',+ borderRadius: 10,+ padding: 12,+ border: '1px solid rgba(255,255,255,0.08)',+ } as React.CSSProperties,+ swatch: (bg: string) =>+ ({+ width: 56,+ height: 56,+ borderRadius: 8,+ background: bg,+ border: '2px solid rgba(255,255,255,0.12)',+ flexShrink: 0,+ position: 'relative' as const,+ overflow: 'hidden',+ cursor: 'pointer',+ }) as React.CSSProperties,+ colorInput: {+ position: 'absolute' as const,+ inset: -8,+ width: 'calc(100% + 16px)',+ height: 'calc(100% + 16px)',+ border: 'none',+ cursor: 'pointer',+ background: 'none',+ } as React.CSSProperties,+ hexInput: {+ background: 'transparent',+ border: 'none',+ color: '#fafafa',+ fontFamily: "'JetBrains Mono', 'SF Mono', monospace",+ fontSize: 16,+ fontWeight: 500,+ width: '100%',+ outline: 'none',+ padding: 0,+ } as React.CSSProperties,+ hctLabel: {+ fontSize: 11,+ color: '#71717a',+ fontFamily: "'JetBrains Mono', monospace",+ } as React.CSSProperties,+ shuffleBtn: {+ width: '100%',+ padding: '10px',+ marginTop: 10,+ borderRadius: 8,+ background: '#1f1f23',+ border: '1px solid rgba(255,255,255,0.08)',+ color: '#a1a1aa',+ fontSize: 12,+ cursor: 'pointer',+ fontFamily: 'inherit',+ textAlign: 'center' as const,+ } as React.CSSProperties,+ pills: {+ display: 'flex',+ flexWrap: 'wrap' as const,+ gap: 6,+ } as React.CSSProperties,+ pill: (active: boolean) =>+ ({+ padding: '5px 12px',+ borderRadius: 999,+ background: active ? 'rgba(99,102,241,0.15)' : '#1f1f23',+ border: `1px solid ${active ? 'rgba(99,102,241,0.5)' : 'rgba(255,255,255,0.08)'}`,+ color: active ? '#a5b4fc' : '#a1a1aa',+ fontSize: 11,+ cursor: 'pointer',+ fontFamily: 'inherit',+ }) as React.CSSProperties,+ dropZone: {+ border: '2px dashed rgba(255,255,255,0.12)',+ borderRadius: 10,+ padding: '24px 16px',+ textAlign: 'center' as const,+ cursor: 'pointer',+ position: 'relative' as const,+ minHeight: 100,+ } as React.CSSProperties,+ dropInput: {+ position: 'absolute' as const,+ inset: 0,+ opacity: 0,+ cursor: 'pointer',+ } as React.CSSProperties,+ imgThumb: {+ width: '100%',+ height: 80,+ objectFit: 'cover' as const,+ borderRadius: 8,+ marginTop: 10,+ } as React.CSSProperties,+ extractedRow: {+ display: 'flex',+ gap: 4,+ marginTop: 10,+ flexWrap: 'wrap' as const,+ } as React.CSSProperties,+ extractedDot: (bg: string, sel: boolean) =>+ ({+ width: 28,+ height: 28,+ borderRadius: '50%',+ background: bg,+ border: sel ? '2px solid #fff' : '2px solid transparent',+ cursor: 'pointer',+ boxShadow: sel ? '0 0 0 2px #6366f1' : 'none',+ transition: 'all 0.15s',+ }) as React.CSSProperties,+ tabs: {+ display: 'flex',+ gap: 2,+ background: '#18181b',+ borderRadius: 10,+ padding: 4,+ marginBottom: 24,+ width: 'fit-content',+ } as React.CSSProperties,+ tab: (active: boolean) =>+ ({+ padding: '8px 18px',+ borderRadius: 8,+ background: active ? '#27272a' : 'transparent',+ border: 'none',+ color: active ? '#fafafa' : '#71717a',+ fontSize: 13,+ fontWeight: active ? 500 : 400,+ cursor: 'pointer',+ fontFamily: 'inherit',+ }) as React.CSSProperties,+ tonaLabel: {+ width: 70,+ fontSize: 11,+ color: '#71717a',+ fontFamily: "'JetBrains Mono', monospace",+ flexShrink: 0,+ textTransform: 'capitalize' as const,+ } as React.CSSProperties,+ tonalStrip: {+ display: 'flex',+ flex: 1,+ borderRadius: 8,+ overflow: 'hidden',+ border: '1px solid rgba(255,255,255,0.06)',+ } as React.CSSProperties,+ tonalCell: (bg: string) =>+ ({+ flex: 1,+ height: 44,+ background: bg,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'flex-end',+ justifyContent: 'center',+ paddingBottom: 3,+ transition: 'transform 0.15s',+ position: 'relative' as const,+ }) as React.CSSProperties,+ tonalNum: {+ fontSize: 8,+ fontFamily: "'JetBrains Mono', monospace",+ color: 'rgba(255,255,255,0.5)',+ textShadow: '0 1px 2px rgba(0,0,0,0.5)',+ pointerEvents: 'none' as const,+ } as React.CSSProperties,+ roleGrid: {+ display: 'grid',+ gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))',+ gap: 8,+ } as React.CSSProperties,+ roleCard: {+ background: '#18181b',+ border: '1px solid rgba(255,255,255,0.06)',+ borderRadius: 10,+ overflow: 'hidden',+ cursor: 'pointer',+ transition: 'all 0.15s',+ } as React.CSSProperties,+ roleSwatchWrap: {+ height: 48,+ display: 'flex',+ position: 'relative' as const,+ } as React.CSSProperties,+ roleSwatchHalf: (bg: string) =>+ ({flex: 1, background: bg}) as React.CSSProperties,+ roleBody: {padding: '8px 10px'} as React.CSSProperties,+ roleName: {+ fontSize: 11,+ fontFamily: "'JetBrains Mono', monospace",+ color: '#a1a1aa',+ } as React.CSSProperties,+ roleValue: {+ fontSize: 10,+ fontFamily: "'JetBrains Mono', monospace",+ color: '#52525b',+ } as React.CSSProperties,+ wcagBadge: (grade: string) =>+ ({+ fontSize: 9,+ fontFamily: "'JetBrains Mono', monospace",+ padding: '1px 5px',+ borderRadius: 3,+ position: 'absolute' as const,+ top: 4,+ right: 4,+ background:+ grade === 'AAA'+ ? '#059669'+ : grade === 'AA'+ ? '#2563eb'+ : grade === 'AA18'+ ? '#d97706'+ : '#dc2626',+ color: '#fff',+ }) as React.CSSProperties,+ catRow: {+ display: 'flex',+ gap: 6,+ flexWrap: 'wrap' as const,+ } as React.CSSProperties,+ catSwatch: (bg: string) =>+ ({+ width: 48,+ height: 48,+ borderRadius: 10,+ background: bg,+ display: 'flex',+ alignItems: 'flex-end',+ justifyContent: 'center',+ paddingBottom: 4,+ cursor: 'pointer',+ border: '1px solid rgba(255,255,255,0.06)',+ }) as React.CSSProperties,+ catLabel: {+ fontSize: 8,+ color: 'rgba(255,255,255,0.6)',+ textShadow: '0 1px 2px rgba(0,0,0,0.5)',+ } as React.CSSProperties,+ previewFrame: {+ background: '#18181b',+ border: '1px solid rgba(255,255,255,0.06)',+ borderRadius: 16,+ overflow: 'hidden',+ } as React.CSSProperties,+ previewToolbar: {+ display: 'flex',+ alignItems: 'center',+ gap: 8,+ padding: '10px 16px',+ borderBottom: '1px solid rgba(255,255,255,0.06)',+ } as React.CSSProperties,+ previewBody: (bg: string, fg: string) =>+ ({padding: 24, background: bg, color: fg}) as React.CSSProperties,+ previewGrid: {+ display: 'grid',+ gridTemplateColumns: '1fr 1fr',+ gap: 16,+ } as React.CSSProperties,+ mockCard: (bg: string, border: string) =>+ ({+ borderRadius: 12,+ padding: 16,+ border: `1px solid ${border}`,+ background: bg,+ }) as React.CSSProperties,+ mockBtn: (bg: string, fg: string) =>+ ({+ display: 'inline-flex',+ alignItems: 'center',+ padding: '8px 18px',+ borderRadius: 8,+ fontSize: 13,+ fontWeight: 500,+ border: 'none',+ background: bg,+ color: fg,+ fontFamily: 'inherit',+ cursor: 'default',+ }) as React.CSSProperties,+ mockBtnOutline: (border: string, fg: string) =>+ ({+ display: 'inline-flex',+ alignItems: 'center',+ padding: '7px 17px',+ borderRadius: 8,+ fontSize: 13,+ fontWeight: 500,+ border: `1px solid ${border}`,+ background: 'transparent',+ color: fg,+ fontFamily: 'inherit',+ cursor: 'default',+ }) as React.CSSProperties,+ mockInput: (bg: string, border: string, fg: string) =>+ ({+ width: '100%',+ padding: '10px 12px',+ borderRadius: 8,+ fontSize: 13,+ fontFamily: 'inherit',+ border: `1px solid ${border}`,+ background: bg,+ color: fg,+ outline: 'none',+ cursor: 'default',+ }) as React.CSSProperties,+ mockChip: (bg: string, fg: string) =>+ ({+ display: 'inline-flex',+ padding: '3px 10px',+ borderRadius: 999,+ fontSize: 11,+ background: bg,+ color: fg,+ border: 'none',+ }) as React.CSSProperties,+ mockDot: (bg: string) =>+ ({+ width: 8,+ height: 8,+ borderRadius: '50%',+ background: bg,+ flexShrink: 0,+ }) as React.CSSProperties,+ mockSwitch: (on: boolean, onColor: string, offColor: string) =>+ ({+ width: 36,+ height: 20,+ borderRadius: 10,+ background: on ? onColor : offColor,+ position: 'relative' as const,+ cursor: 'default',+ flexShrink: 0,+ }) as React.CSSProperties,+ mockSwitchDot: (on: boolean) =>+ ({+ width: 16,+ height: 16,+ borderRadius: '50%',+ background: '#fff',+ position: 'absolute' as const,+ top: 2,+ ...(on ? {right: 2} : {left: 2}),+ }) as React.CSSProperties,+ exportPanel: {+ background: '#18181b',+ border: '1px solid rgba(255,255,255,0.06)',+ borderRadius: 16,+ overflow: 'hidden',+ } as React.CSSProperties,+ exportBar: {+ display: 'flex',+ alignItems: 'center',+ gap: 8,+ padding: '12px 16px',+ borderBottom: '1px solid rgba(255,255,255,0.06)',+ } as React.CSSProperties,+ exportTab: (active: boolean) =>+ ({+ padding: '5px 14px',+ borderRadius: 999,+ background: active ? '#6366f1' : 'transparent',+ border: `1px solid ${active ? '#6366f1' : 'rgba(255,255,255,0.08)'}`,+ color: active ? '#fff' : '#a1a1aa',+ fontSize: 11,+ cursor: 'pointer',+ fontFamily: 'inherit',+ }) as React.CSSProperties,+ exportCopy: {+ marginLeft: 'auto',+ padding: '6px 16px',+ borderRadius: 8,+ background: '#27272a',+ border: 'none',+ color: '#fafafa',+ fontSize: 12,+ cursor: 'pointer',+ fontFamily: 'inherit',+ } as React.CSSProperties,+ exportCode: {+ padding: '16px 20px',+ fontFamily: "'JetBrains Mono', monospace",+ fontSize: 12,+ lineHeight: '1.7',+ color: '#a1a1aa',+ maxHeight: 400,+ overflow: 'auto',+ whiteSpace: 'pre' as const,+ background: '#0e0e10',+ } as React.CSSProperties,+ contrastGrid: {+ display: 'grid',+ gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))',+ gap: 8,+ } as React.CSSProperties,+ contrastCard: (pass: boolean) =>+ ({+ display: 'flex',+ alignItems: 'center',+ gap: 10,+ padding: '10px 12px',+ background: '#18181b',+ border: `1px solid ${pass ? 'rgba(255,255,255,0.06)' : 'rgba(220,38,38,0.3)'}`,+ borderRadius: 8,+ }) as React.CSSProperties,+ contrastSwatch: (fg: string, bg: string) =>+ ({+ width: 36,+ height: 36,+ borderRadius: 6,+ background: bg,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ fontSize: 14,+ fontWeight: 700,+ color: fg,+ flexShrink: 0,+ border: '1px solid rgba(255,255,255,0.06)',+ }) as React.CSSProperties,+ toast: {+ position: 'fixed' as const,+ bottom: 24,+ left: '50%',+ transform: 'translateX(-50%)',+ background: '#27272a',+ border: '1px solid rgba(255,255,255,0.12)',+ borderRadius: 10,+ padding: '10px 24px',+ fontSize: 13,+ boxShadow: '0 4px 24px rgba(0,0,0,0.4)',+ zIndex: 100,+ transition: 'opacity 0.2s',+ pointerEvents: 'none' as const,+ } as React.CSSProperties,+} as const;++// =============================================================================+// Info Popover+// =============================================================================++const LAYER_INFO: Record<string, {title: string; description: string}> = {+ palettes: {+ title: 'Tonal Palettes',+ description:+ 'A tonal palette is a single hue stretched across a full lightness range — from black (tone 0) to white (tone 100) in perceptually even steps. Unlike HSL, tone is perceptually uniform: tone 40 blue and tone 40 red look equally dark to human eyes. This uses the HCT color space (the same one behind Material Design 3). Each harmony color gets its own tonal strip. The UI Semantics layer then picks specific tones — e.g. "accent in light mode = tone 40, dark mode = tone 80."',+ },+ categorical: {+ title: 'Categorical Colors',+ description:+ "10 colors optimized for mutual distinctness — maximally spread across the hue wheel so they're easy to tell apart. Use these for data visualization series, icon sets, tag categories, or anywhere you need multiple colors that are clearly distinguishable from each other.",+ },+ expressive: {+ title: 'Expressive Colors',+ description:+ 'Illustration and brand colors that share hue angles with the tonal palette but push wider in chroma and range. Use these when you need more visual energy than the UI palette allows — hero sections, marketing graphics, illustrations, or decorative elements.',+ },+ roles: {+ title: 'Semantic Roles',+ description:+ 'Colors assigned to specific UI functions: Interactive (accent, hover, focus), Surface (backgrounds at different elevations), Content (text and icon hierarchy), Feedback (error, success, warning), and Border. Each role is automatically derived from the tonal palette with proper contrast for light, dark, and high-contrast modes. Click any role to copy its value.',+ },+ accessibility: {+ title: 'Accessibility',+ description:+ "WCAG 2.1 contrast ratios for key foreground/background pairs. AAA (≥ 7:1) is the gold standard. AA (≥ 4.5:1) is the minimum for normal text. AA18 (≥ 3:1) passes for large text (18px+) and UI components. FAIL means the pair doesn't meet any threshold — you'll need to adjust tones.",+ },+};++function InfoButton({layerKey}: {layerKey: string}) {+ const [open, setOpen] = useState(false);+ const ref = useRef<HTMLDivElement>(null);+ const info = LAYER_INFO[layerKey];++ useEffect(() => {+ if (!open) return;+ const handler = (e: MouseEvent) => {+ if (ref.current && !ref.current.contains(e.target as Node))+ setOpen(false);+ };+ document.addEventListener('mousedown', handler);+ return () => document.removeEventListener('mousedown', handler);+ }, [open]);++ if (!info) return null;++ return (+ <div ref={ref} style={{position: 'relative', display: 'inline-flex'}}>+ <button+ onClick={() => setOpen(!open)}+ style={{+ width: 18,+ height: 18,+ borderRadius: '50%',+ background: open ? 'rgba(99,102,241,0.2)' : 'rgba(255,255,255,0.06)',+ border: `1px solid ${open ? 'rgba(99,102,241,0.4)' : 'rgba(255,255,255,0.1)'}`,+ color: open ? '#a5b4fc' : '#71717a',+ fontSize: 11,+ fontWeight: 600,+ fontFamily: 'inherit',+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ transition: 'all 0.15s',+ lineHeight: 1,+ padding: 0,+ }}+ title={info.title}>+ ?+ </button>+ {open && (+ <div+ style={{+ position: 'absolute',+ top: 28,+ left: 0,+ zIndex: 50,+ width: 340,+ padding: 16,+ background: '#1f1f23',+ border: '1px solid rgba(255,255,255,0.12)',+ borderRadius: 12,+ boxShadow: '0 8px 32px rgba(0,0,0,0.5)',+ }}>+ <div+ style={{+ fontSize: 13,+ fontWeight: 600,+ marginBottom: 8,+ color: '#fafafa',+ }}>+ {info.title}+ </div>+ <div style={{fontSize: 12, lineHeight: 1.6, color: '#a1a1aa'}}>+ {info.description}+ </div>+ </div>+ )}+ </div>+ );+}++// =============================================================================+// Page Component+// =============================================================================++type Tab = 'palettes' | 'roles' | 'preview' | 'accessibility' | 'export';+type ExportFmt = 'css' | 'json' | 'tailwind' | 'xds';++export default function ColorStudioPage() {+ const [seedHex, setSeedHex] = useState('#0064E0');+ const [harmony, setHarmony] = useState<HarmonyType>('complementary');+ const [warmth, setWarmth] = useState<'warm' | 'cool' | 'neutral'>('cool');+ const [surfaceStyle, setSurfaceStyle] = useState<'tinted' | 'neutral'>(+ 'tinted',+ );+ const [exactAccent, setExactAccent] = useState(false);+ const [tab, setTab] = useState<Tab>('palettes');+ const [previewMode, setPreviewMode] = useState<'light' | 'dark'>('light');+ const [exportFmt, setExportFmt] = useState<ExportFmt>('css');+ const [toast, setToast] = useState('');+ const [imgSrc, setImgSrc] = useState<string | null>(null);+ const [extracted, setExtracted] = useState<string[]>([]);+ const fileRef = useRef<HTMLInputElement>(null);++ const seed = useMemo(() => hexToHct(seedHex), [seedHex]);+ const harmonies = useMemo(+ () => generateHarmony(seed, harmony),+ [seed, harmony],+ );+ const palettes = useMemo(+ () => harmonies.map(h => ({...h, tones: tonalPalette(h.hue, h.chroma)})),+ [harmonies],+ );+ const neutralPalette = useMemo(+ () => ({+ label: 'Neutral',+ tones: tonalPalette(+ seed.hue,+ surfaceStyle === 'neutral'+ ? 0+ : warmth === 'warm'+ ? 7+ : warmth === 'cool'+ ? 5+ : 3,+ ),+ }),+ [seed.hue, warmth, surfaceStyle],+ );+ const roles = useMemo(+ () => deriveSemanticRoles(seedHex, warmth, surfaceStyle, exactAccent),+ [seedHex, warmth, surfaceStyle, exactAccent],+ );+ const categorical = useMemo(+ () => generateCategorical(seed.hue, seed.chroma),+ [seed],+ );+ const expressive = useMemo(+ () => generateExpressive(seed.hue, seed.chroma),+ [seed],+ );++ const copy = useCallback((text: string) => {+ navigator.clipboard.writeText(text).then(() => {+ setToast('Copied!');+ setTimeout(() => setToast(''), 1200);+ });+ }, []);++ const setSource = useCallback((hex: string) => {+ setSeedHex(hex);+ }, []);++ const handleHexInput = useCallback(+ (e: React.ChangeEvent<HTMLInputElement>) => {+ const v = e.target.value.trim();+ const parsed = parseColorInput(v);+ if (parsed) setSeedHex(parsed);+ },+ [],+ );++ const handleShuffle = useCallback(() => {+ const h = Math.random() * 360;+ const c = 30 + Math.random() * 50;+ const hex = hctToHex({hue: h, chroma: c, tone: 50});+ setSeedHex(hex);+ }, []);++ const handleImage = useCallback((file: File) => {+ const reader = new FileReader();+ reader.onload = ev => {+ const src = ev.target?.result as string;+ setImgSrc(src);+ const img = new Image();+ img.onload = () => {+ const colors = extractColorsFromImage(img);+ setExtracted(colors);+ if (colors.length) setSeedHex(colors[0]);+ };+ img.src = src;+ };+ reader.readAsDataURL(file);+ }, []);++ // Role lookup helper for preview+ const r = useCallback(+ (name: string) => {+ const role = roles.find(ro => ro.name === name);+ if (!role) return '#888888';+ return (previewMode === 'light' ? role.light : role.dark) || '#888888';+ },+ [roles, previewMode],+ );++ // Contrast pairs for accessibility tab+ const contrastPairs = useMemo(() => {+ const pairs = [+ ['text-primary', 'surface', 'Text on Surface'],+ ['text-secondary', 'surface', 'Secondary on Surface'],+ ['text-accent', 'surface', 'Accent text on Surface'],+ ['on-accent', 'accent', 'Text on Accent'],+ ['on-error', 'error', 'Text on Error'],+ ['on-success', 'success', 'Text on Success'],+ ['on-warning', 'warning', 'Text on Warning'],+ ['text-primary', 'card', 'Text on Card'],+ ['icon-secondary', 'surface', 'Icon on Surface'],+ ['text-disabled', 'surface', 'Disabled on Surface'],+ ];+ return pairs+ .map(([fg, bg, label]) => {+ const fgRole = roles.find(ro => ro.name === fg);+ const bgRole = roles.find(ro => ro.name === bg);+ if (!fgRole || !bgRole) return null;+ const fgHex =+ (previewMode === 'light' ? fgRole.light : fgRole.dark) || '#000000';+ const bgHex =+ (previewMode === 'light' ? bgRole.light : bgRole.dark) || '#ffffff';+ // Strip alpha for contrast calc+ const fgClean = fgHex.substring(0, 7);+ const bgClean = bgHex.substring(0, 7);+ const ratio = contrastRatio(fgClean, bgClean);+ const grade = wcagGrade(ratio);+ return {label, fg: fgClean, bg: bgClean, ratio, grade};+ })+ .filter(Boolean) as Array<{+ label: string;+ fg: string;+ bg: string;+ ratio: number;+ grade: string;+ }>;+ }, [roles, previewMode]);++ // Export code+ const exportCode = useMemo(() => {+ const m = previewMode;+ if (exportFmt === 'css') {+ let code = '/* Color Studio — Generated Palette */\n\n:root {\n';+ for (const role of roles) {+ code += ` --color-${role.name}: ${role.light};\n`;+ }+ code += '}\n\n@media (prefers-color-scheme: dark) {\n :root {\n';+ for (const role of roles) {+ code += ` --color-${role.name}: ${role.dark};\n`;+ }+ code += ' }\n}\n\n@media (prefers-contrast: more) {\n :root {\n';+ for (const role of roles) {+ code += ` --color-${role.name}: ${role.highContrast};\n`;+ }+ code += ' }\n}\n';+ return code;+ }+ if (exportFmt === 'json') {+ const obj: Record<string, Record<string, string>> = {+ light: {},+ dark: {},+ highContrast: {},+ };+ for (const role of roles) {+ obj.light[role.name] = role.light;+ obj.dark[role.name] = role.dark;+ obj.highContrast[role.name] = role.highContrast;+ }+ return JSON.stringify(obj, null, 2);+ }+ if (exportFmt === 'tailwind') {+ let code =+ '// tailwind.config.js\nmodule.exports = {\n theme: {\n extend: {\n colors: {\n';+ for (const role of roles) {+ code += ` '${role.name}': '${role[m]}',\n`;+ }+ code += ' },\n },\n },\n};\n';+ return code;+ }+ // XDS defineTheme+ let code = `import { defineTheme } from '@xds/core/theme';\n\nexport const customTheme = defineTheme({\n name: 'custom',\n color: {\n accent: '${seedHex}',\n neutralStyle: '${warmth}',\n },\n tokens: {\n`;+ for (const role of roles) {+ code += ` '--color-${role.name}': 'light-dark(${role.light}, ${role.dark})',\n`;+ }+ code += ' },\n});\n';+ return code;+ }, [roles, exportFmt, seedHex, warmth, previewMode]);++ return (+ <div style={S.page}>+ {/* ═══ Sidebar ═══ */}+ <aside style={S.sidebar}>+ <div style={S.section}>+ <div style={S.sectionTitle}>Source Color</div>+ <div style={S.sourcePicker}>+ <div style={S.swatch(seedHex)}>+ <input+ type="color"+ value={seedHex}+ onChange={e => setSource(e.target.value)}+ style={S.colorInput}+ />+ </div>+ <div style={{flex: 1}}>+ <input+ type="text"+ value={seedHex.toUpperCase()}+ onChange={handleHexInput}+ spellCheck={false}+ style={S.hexInput}+ />+ <div style={S.hctLabel}>+ H:{seed.hue.toFixed(0)}° C:{seed.chroma.toFixed(0)} T:+ {seed.tone.toFixed(0)}+ </div>+ </div>+ </div>+ <button onClick={handleShuffle} style={S.shuffleBtn}>+ ↻ Randomize+ </button>+ </div>++ <div style={S.section}>+ <div style={S.sectionTitle}>Extract from Image</div>+ <div style={S.dropZone} onClick={() => fileRef.current?.click()}>+ <input+ ref={fileRef}+ type="file"+ accept="image/*"+ style={S.dropInput}+ onChange={e =>+ e.target.files?.[0] && handleImage(e.target.files[0])+ }+ />+ <div style={{fontSize: 20}}>🖼</div>+ <div style={{fontSize: 12, color: '#a1a1aa'}}>+ Drop image or click+ </div>+ </div>+ {imgSrc && <img src={imgSrc} alt="preview" style={S.imgThumb} />}+ {extracted.length > 0 && (+ <div style={S.extractedRow}>+ {extracted.map((c, i) => (+ <div+ key={i}+ style={S.extractedDot(c, c === seedHex)}+ onClick={() => setSource(c)}+ title={c}+ />+ ))}+ </div>+ )}+ </div>++ <div style={S.section}>+ <div style={S.sectionTitle}>Harmony</div>+ <div style={S.pills}>+ {(+ [+ 'complementary',+ 'analogous',+ 'triadic',+ 'split-complementary',+ 'tetradic',+ 'monochromatic',+ ] as HarmonyType[]+ ).map(h => (+ <button+ key={h}+ style={S.pill(harmony === h)}+ onClick={() => setHarmony(h)}>+ {h.replace('-', ' ').replace(/\b\w/g, c => c.toUpperCase())}+ </button>+ ))}+ </div>+ </div>++ <div style={S.section}>+ <div style={S.sectionTitle}>Neutral Warmth</div>+ <div style={S.pills}>+ {(['warm', 'cool', 'neutral'] as const).map(w => (+ <button+ key={w}+ style={S.pill(warmth === w)}+ onClick={() => setWarmth(w)}>+ {w.charAt(0).toUpperCase() + w.slice(1)}+ </button>+ ))}+ </div>+ </div>++ <div style={S.section}>+ <div style={S.sectionTitle}>Surfaces</div>+ <div style={S.pills}>+ <button+ style={S.pill(surfaceStyle === 'tinted')}+ onClick={() => setSurfaceStyle('tinted')}>+ Tinted+ </button>+ <button+ style={S.pill(surfaceStyle === 'neutral')}+ onClick={() => setSurfaceStyle('neutral')}>+ Pure White+ </button>+ </div>+ </div>++ <div style={S.section}>+ <div style={S.sectionTitle}>Accent</div>+ <div style={S.pills}>+ <button+ style={S.pill(!exactAccent)}+ onClick={() => setExactAccent(false)}>+ Derived+ </button>+ <button+ style={S.pill(exactAccent)}+ onClick={() => setExactAccent(true)}>+ Use Exact Color+ </button>+ </div>+ <div style={{fontSize: 11, color: '#52525b', marginTop: 6}}>+ {exactAccent+ ? 'Primary button uses your exact chosen color'+ : 'Accent derived from HCT tone 40 for optimal contrast'}+ </div>+ </div>+ </aside>++ {/* ═══ Main ═══ */}+ <main style={S.main}>+ <div style={S.tabs}>+ {(+ [+ ['palettes', 'Palettes'],+ ['roles', 'Roles'],+ ['preview', 'Preview'],+ ['accessibility', 'Accessibility'],+ ['export', 'Export'],+ ] as [Tab, string][]+ ).map(([t, label]) => (+ <button key={t} style={S.tab(tab === t)} onClick={() => setTab(t)}>+ {label}+ </button>+ ))}+ </div>++ {/* ─── Palettes Tab ─── */}+ {tab === 'palettes' && (+ <div>+ <div style={{...S.section, marginBottom: 32}}>+ <div+ style={{+ ...S.sectionTitle,+ display: 'flex',+ alignItems: 'center',+ gap: 8,+ }}>+ Tonal Palettes <InfoButton layerKey="palettes" />+ </div>+ {[...palettes, neutralPalette].map((p, pi) => (+ <div+ key={pi}+ style={{+ display: 'flex',+ alignItems: 'center',+ gap: 8,+ marginBottom: 6,+ }}>+ <span style={S.tonaLabel}>{p.label}</span>+ <div style={S.tonalStrip}>+ {TONE_STEPS.filter(t => t !== 99).map(t => (+ <div+ key={t}+ style={S.tonalCell(p.tones[t])}+ onClick={() => copy(p.tones[t])}+ title={`${p.tones[t]} (tone ${t})`}>+ <span style={S.tonalNum}>{t}</span>+ </div>+ ))}+ </div>+ </div>+ ))}+ </div>++ <div style={S.section}>+ <div+ style={{+ ...S.sectionTitle,+ display: 'flex',+ alignItems: 'center',+ gap: 8,+ }}>+ Categorical — 10 Distinguishable Colors{' '}+ <InfoButton layerKey="categorical" />+ </div>+ {categorical.map((c, i) => {+ const catHct = hexToHct(c.hex);+ const tones = tonalPalette(catHct.hue, catHct.chroma);+ return (+ <div+ key={i}+ style={{+ display: 'flex',+ alignItems: 'center',+ gap: 8,+ marginBottom: 6,+ }}>+ <span style={S.tonaLabel}>{c.label}</span>+ <div style={S.tonalStrip}>+ {TONE_STEPS.filter(t => t !== 99).map(t => (+ <div+ key={t}+ style={S.tonalCell(tones[t])}+ onClick={() => copy(tones[t])}+ title={`${c.label} ${tones[t]} (tone ${t})`}>+ <span style={S.tonalNum}>{t}</span>+ </div>+ ))}+ </div>+ </div>+ );+ })}+ </div>++ <div style={S.section}>+ <div style={S.sectionTitle}>+ Expressive — Illustration & Brand+ </div>+ <div style={S.catRow}>+ {expressive.map((c, i) => (+ <div+ key={i}+ style={{+ ...S.catSwatch(c.hex),+ width: 64,+ height: 64,+ borderRadius: 12,+ }}+ onClick={() => copy(c.hex)}+ title={c.hex}>+ <span style={S.catLabel}>{c.label}</span>+ </div>+ ))}+ </div>+ </div>+ </div>+ )}++ {/* ─── Roles Tab ─── */}+ {tab === 'roles' && (+ <div>+ {['Interactive', 'Surface', 'Content', 'Feedback', 'Border'].map(+ group => {+ const groupRoles = roles.filter(ro => ro.group === group);+ return (+ <div key={group} style={S.section}>+ <div style={S.sectionTitle}>+ {group}{' '}+ <span style={{float: 'right', fontWeight: 400}}>+ {groupRoles.length}+ </span>+ </div>+ <div style={S.roleGrid}>+ {groupRoles.map(role => {+ // Compute contrast if paired+ let grade = '';+ if (role.pairedWith) {+ const bg = roles.find(+ ro => ro.name === role.pairedWith,+ );+ if (bg) {+ const fgHex = (+ (previewMode === 'light'+ ? role.light+ : role.dark) || '#000000'+ ).substring(0, 7);+ const bgHex = (+ (previewMode === 'light' ? bg.light : bg.dark) ||+ '#ffffff'+ ).substring(0, 7);+ const ratio = contrastRatio(fgHex, bgHex);+ grade = wcagGrade(ratio);+ }+ }+ return (+ <div+ key={role.name}+ style={S.roleCard}+ onClick={() =>+ copy(`--color-${role.name}: ${role.light}`)+ }>+ <div style={S.roleSwatchWrap}>+ <div+ style={S.roleSwatchHalf(+ role.light || '#888888',+ )}+ />+ <div+ style={S.roleSwatchHalf(role.dark || '#888888')}+ />+ {grade && (+ <span style={S.wcagBadge(grade)}>{grade}</span>+ )}+ </div>+ <div style={S.roleBody}>+ <div style={S.roleName}>{role.name}</div>+ <div style={S.roleValue}>+ L: {role.light.substring(0, 7)} D:{' '}+ {role.dark.substring(0, 7)}+ </div>+ </div>+ </div>+ );+ })}+ </div>+ </div>+ );+ },+ )}+ </div>+ )}++ {/* ─── Preview Tab ─── */}+ {tab === 'preview' && (+ <div style={S.previewFrame}>+ <div style={S.previewToolbar}>+ <div+ style={{+ width: 10,+ height: 10,+ borderRadius: '50%',+ background: '#ff5f57',+ }}+ />+ <div+ style={{+ width: 10,+ height: 10,+ borderRadius: '50%',+ background: '#febc2e',+ }}+ />+ <div+ style={{+ width: 10,+ height: 10,+ borderRadius: '50%',+ background: '#28c840',+ }}+ />+ <div style={{flex: 1}} />+ <button+ style={S.pill(previewMode === 'light')}+ onClick={() => setPreviewMode('light')}>+ Light+ </button>+ <button+ style={S.pill(previewMode === 'dark')}+ onClick={() => setPreviewMode('dark')}>+ Dark+ </button>+ </div>+ <div style={S.previewBody(r('body'), r('text-primary'))}>+ {/* Nav mock */}+ <div+ style={{+ display: 'flex',+ gap: 2,+ padding: 4,+ borderRadius: 8,+ background: r('surface'),+ border: `1px solid ${r('border')}`,+ marginBottom: 16,+ }}>+ <div+ style={{+ padding: '6px 14px',+ borderRadius: 6,+ background: r('accent'),+ color: r('on-accent'),+ fontSize: 12,+ fontWeight: 500,+ }}>+ Dashboard+ </div>+ <div+ style={{+ padding: '6px 14px',+ fontSize: 12,+ color: r('text-secondary'),+ }}>+ Settings+ </div>+ <div+ style={{+ padding: '6px 14px',+ fontSize: 12,+ color: r('text-secondary'),+ }}>+ Reports+ </div>+ </div>++ <div style={S.previewGrid}>+ {/* Buttons & Inputs */}+ <div style={S.mockCard(r('card'), r('border'))}>+ <div+ style={{+ fontSize: 16,+ fontWeight: 600,+ color: r('text-primary'),+ marginBottom: 12,+ }}>+ Components+ </div>+ <div+ style={{+ display: 'flex',+ gap: 8,+ marginBottom: 12,+ flexWrap: 'wrap',+ }}>+ <div style={S.mockBtn(r('accent'), r('on-accent'))}>+ Primary+ </div>+ <div+ style={S.mockBtnOutline(r('accent'), r('text-accent'))}>+ Outline+ </div>+ <div style={S.mockBtn(r('muted'), r('text-primary'))}>+ Neutral+ </div>+ </div>+ <input+ readOnly+ value="Text input"+ style={S.mockInput(+ r('surface'),+ r('border-emphasized'),+ r('text-primary'),+ )}+ />+ <div+ style={{+ display: 'flex',+ gap: 6,+ marginTop: 10,+ flexWrap: 'wrap',+ }}>+ <span+ style={S.mockChip(r('accent-muted'), r('text-accent'))}>+ Tag One+ </span>+ <span style={S.mockChip(r('muted'), r('text-secondary'))}>+ Tag Two+ </span>+ </div>+ </div>++ {/* Status */}+ <div style={S.mockCard(r('card'), r('border'))}>+ <div+ style={{+ fontSize: 16,+ fontWeight: 600,+ color: r('text-primary'),+ marginBottom: 12,+ }}>+ Status+ </div>+ {[+ {+ dot: r('success'),+ text: 'Deployed',+ badge: '3',+ badgeBg: r('success'),+ badgeFg: r('on-success'),+ },+ {+ dot: r('warning'),+ text: 'Building',+ badge: '',+ badgeBg: '',+ badgeFg: '',+ },+ {+ dot: r('error'),+ text: '2 tests failing',+ badge: '2',+ badgeBg: r('error'),+ badgeFg: r('on-error'),+ },+ ].map((s, i) => (+ <div+ key={i}+ style={{+ display: 'flex',+ alignItems: 'center',+ gap: 8,+ marginBottom: 8,+ }}>+ <div style={S.mockDot(s.dot)} />+ <span+ style={{+ fontSize: 12,+ color: r('text-secondary'),+ flex: 1,+ }}>+ {s.text}+ </span>+ {s.badge && (+ <span+ style={{+ minWidth: 20,+ height: 20,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ borderRadius: 999,+ fontSize: 10,+ fontWeight: 600,+ background: s.badgeBg,+ color: s.badgeFg,+ padding: '0 6px',+ }}>+ {s.badge}+ </span>+ )}+ </div>+ ))}+ <div+ style={{+ display: 'flex',+ gap: 12,+ marginTop: 14,+ alignItems: 'center',+ }}>+ <div style={S.mockBtn(r('error'), r('on-error'))}>+ Delete+ </div>+ <div+ style={S.mockSwitch(+ true,+ r('success'),+ r('border-emphasized'),+ )}>+ <div style={S.mockSwitchDot(true)} />+ </div>+ <div+ style={S.mockSwitch(+ false,+ r('success'),+ r('border-emphasized'),+ )}>+ <div style={S.mockSwitchDot(false)} />+ </div>+ </div>+ </div>++ {/* Typography */}+ <div style={S.mockCard(r('card'), r('border'))}>+ <div+ style={{+ fontSize: 20,+ fontWeight: 700,+ color: r('text-primary'),+ marginBottom: 4,+ }}>+ Heading+ </div>+ <div+ style={{+ fontSize: 14,+ color: r('text-secondary'),+ marginBottom: 8,+ }}>+ Secondary body text with detail about the feature.+ </div>+ <div style={{fontSize: 12, color: r('text-disabled')}}>+ Disabled or placeholder text+ </div>+ <div+ style={{+ fontSize: 13,+ color: r('text-accent'),+ marginTop: 8,+ cursor: 'default',+ }}>+ Link text →+ </div>+ </div>++ {/* Spectrum */}+ <div style={S.mockCard(r('card'), r('border'))}>+ <div+ style={{+ fontSize: 16,+ fontWeight: 600,+ color: r('text-primary'),+ marginBottom: 12,+ }}>+ Categorical+ </div>+ <div+ style={{+ display: 'grid',+ gridTemplateColumns: 'repeat(5, 1fr)',+ gap: 6,+ }}>+ {categorical.slice(0, 10).map((c, i) => (+ <div+ key={i}+ style={{+ background: c.hex + '33',+ borderRadius: 8,+ padding: 6,+ textAlign: 'center',+ }}>+ <div+ style={{+ width: 16,+ height: 16,+ borderRadius: '50%',+ background: c.hex,+ margin: '0 auto 2px',+ }}+ />+ <div style={{fontSize: 8, color: r('text-secondary')}}>+ {c.label}+ </div>+ </div>+ ))}+ </div>+ </div>+ </div>+ </div>+ </div>+ )}++ {/* ─── Accessibility Tab ─── */}+ {tab === 'accessibility' && (+ <div>+ <div style={{...S.pills, marginBottom: 16}}>+ <button+ style={S.pill(previewMode === 'light')}+ onClick={() => setPreviewMode('light')}>+ Light+ </button>+ <button+ style={S.pill(previewMode === 'dark')}+ onClick={() => setPreviewMode('dark')}>+ Dark+ </button>+ </div>+ <div style={S.contrastGrid}>+ {contrastPairs.map((pair, i) => (+ <div key={i} style={S.contrastCard(pair.grade !== 'FAIL')}>+ <div style={S.contrastSwatch(pair.fg, pair.bg)}>Aa</div>+ <div style={{flex: 1, minWidth: 0}}>+ <div style={{fontSize: 12, fontWeight: 500}}>+ {pair.label}+ </div>+ <div+ style={{+ fontSize: 11,+ color: '#71717a',+ fontFamily: "'JetBrains Mono', monospace",+ }}>+ {pair.ratio.toFixed(1)}:1+ </div>+ </div>+ <span style={S.wcagBadge(pair.grade) as React.CSSProperties}>+ {pair.grade}+ </span>+ </div>+ ))}+ </div>+ </div>+ )}++ {/* ─── Export Tab ─── */}+ {tab === 'export' && (+ <div style={S.exportPanel}>+ <div style={S.exportBar}>+ {(+ [+ ['css', 'CSS Variables'],+ ['json', 'JSON'],+ ['tailwind', 'Tailwind'],+ ['xds', 'XDS Theme'],+ ] as [ExportFmt, string][]+ ).map(([f, label]) => (+ <button+ key={f}+ style={S.exportTab(exportFmt === f)}+ onClick={() => setExportFmt(f)}>+ {label}+ </button>+ ))}+ <button style={S.exportCopy} onClick={() => copy(exportCode)}>+ 📋 Copy+ </button>+ </div>+ <pre style={S.exportCode}>{exportCode}</pre>+ </div>+ )}+ </main>++ {/* Toast */}+ <div style={{...S.toast, opacity: toast ? 1 : 0}}>{toast}</div>+ </div>+ );+}diff --git a/apps/sandbox/src/app/sandboxPages.ts b/apps/sandbox/src/app/sandboxPages.tsindex eb8733435e..d9d7350e22 100644--- a/apps/sandbox/src/app/sandboxPages.ts+++ b/apps/sandbox/src/app/sandboxPages.ts@@ -138,6 +138,12 @@ export const categories: SandboxCategory[] = [description:'Test voice dictation, tune sound effects, and explore animation',},+ {+ name: 'Color Studio',+ href: '/pages/color-studio/',+ description:+ 'Generate and explore color palettes from an accent color or image',+ },],},];