An open source design system that's fully customizable and agent ready
TypeScript
feat(sandbox): theme audit drawer for token review + ramp snapping (#2173)
rubyycheunge2892c0ad4c4
diff --git a/apps/sandbox/src/app/(fullscreen)/pages/gothic-palette/page.tsx b/apps/sandbox/src/app/(fullscreen)/pages/gothic-palette/page.tsxindex ce7138e2bb..b7039cf6d3 100644--- a/apps/sandbox/src/app/(fullscreen)/pages/gothic-palette/page.tsx+++ b/apps/sandbox/src/app/(fullscreen)/pages/gothic-palette/page.tsx@@ -2,6 +2,8 @@import {XDSVStack} from '@xds/core/Layout';import {gothicTheme} from '@xds/theme-gothic/built';+// `gothicPalettes` is only exported from the source entry, not /built.+import {gothicPalettes} from '@xds/theme-gothic';import {ThemePalettePreview} from '@/components/ThemePalettePreview';import type {TonalColor} from '@/components/ThemePalettePreview';@@ -9,16 +11,16 @@ const GOTHIC ='"Manufacturing Consent", "UnifrakturMaguntia", "Old English Text MT", serif';const TONAL_COLORS: TonalColor[] = [- {name: 'Gothic Neutral', sourceHex: '#96A0AB', note: 'cool blue-gray'},- {name: 'Green', sourceHex: '#b3c79a', semantic: 'Success / sage moss'},- {name: 'Red', sourceHex: '#c6a6a2', semantic: 'Error / dusty rose'},- {name: 'Yellow', sourceHex: '#d3c490', semantic: 'Warning / aged gold'},- {name: 'Blue', sourceHex: '#a3b5d6', note: 'periwinkle midnight'},- {name: 'Purple', sourceHex: '#b29bc4', note: 'muted plum'},- {name: 'Pink', sourceHex: '#c89aab', note: 'dusty rose'},- {name: 'Cyan', sourceHex: '#a3c2cf', note: 'cathedral mist'},- {name: 'Orange', sourceHex: '#d3b89a', note: 'warm tan'},- {name: 'Teal', sourceHex: '#a3c2b6', note: 'sage verdigris'},+ {name: 'Gothic Neutral', sourceHex: '#96A0AB', note: 'cool blue-gray', tones: gothicPalettes.neutral},+ {name: 'Green', sourceHex: '#b3c79a', semantic: 'Success / sage moss', tones: gothicPalettes.green},+ {name: 'Red', sourceHex: '#c6a6a2', semantic: 'Error / dusty rose', tones: gothicPalettes.red},+ {name: 'Yellow', sourceHex: '#d3c490', semantic: 'Warning / aged gold', tones: gothicPalettes.yellow},+ {name: 'Blue', sourceHex: '#a3b5d6', note: 'periwinkle midnight', tones: gothicPalettes.blue},+ {name: 'Purple', sourceHex: '#b29bc4', note: 'muted plum', tones: gothicPalettes.purple},+ {name: 'Pink', sourceHex: '#c89aab', note: 'dusty rose', tones: gothicPalettes.pink},+ {name: 'Cyan', sourceHex: '#a3c2cf', note: 'cathedral mist', tones: gothicPalettes.cyan},+ {name: 'Orange', sourceHex: '#d3b89a', note: 'warm tan', tones: gothicPalettes.orange},+ {name: 'Teal', sourceHex: '#a3c2b6', note: 'sage verdigris', tones: gothicPalettes.teal},];const CORE = [diff --git a/apps/sandbox/src/app/(fullscreen)/pages/stone-palette/page.tsx b/apps/sandbox/src/app/(fullscreen)/pages/stone-palette/page.tsxindex 5711991f25..752e712ff4 100644--- a/apps/sandbox/src/app/(fullscreen)/pages/stone-palette/page.tsx+++ b/apps/sandbox/src/app/(fullscreen)/pages/stone-palette/page.tsx@@ -2,23 +2,30 @@import {XDSVStack} from '@xds/core/Layout';import {stoneTheme} from '@xds/theme-stone/built';+// `stonePalettes` is only exported from the source entry, not /built.+import {stonePalettes} from '@xds/theme-stone';import {ThemePalettePreview} from '@/components/ThemePalettePreview';import type {TonalColor} from '@/components/ThemePalettePreview';const MONTSERRAT ='"Montserrat", "Figtree", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif';+// Pass the canonical hand-tuned `stonePalettes` ramps to the audit+// drawer so its snap-to-ramp detector matches against the actual+// stone palette values. Without this, tokens whose values come from+// the canonical ramp show up as "off-ramp" against the pure HCT+// generator's slightly different ramp.const TONAL_COLORS: TonalColor[] = [- {name: 'Stone Neutral', sourceHex: '#e2e2e2'},- {name: 'Blue', sourceHex: '#d7e4f5'},- {name: 'Cyan', sourceHex: '#cce8e5'},- {name: 'Green', sourceHex: '#d0e9ce', semantic: 'Success'},- {name: 'Teal', sourceHex: '#d4e7dc'},- {name: 'Yellow', sourceHex: '#f4e1b7', semantic: 'Warning'},- {name: 'Orange', sourceHex: '#ffdcbb'},- {name: 'Red', sourceHex: '#f9dcd7', semantic: 'Error'},- {name: 'Pink', sourceHex: '#f0dde8'},- {name: 'Purple', sourceHex: '#e8dff3'},+ {name: 'Stone Neutral', sourceHex: '#e2e2e2', tones: stonePalettes.neutral},+ {name: 'Blue', sourceHex: '#d7e4f5', tones: stonePalettes.blue},+ {name: 'Cyan', sourceHex: '#cce8e5', tones: stonePalettes.cyan},+ {name: 'Green', sourceHex: '#d0e9ce', semantic: 'Success', tones: stonePalettes.green},+ {name: 'Teal', sourceHex: '#d4e7dc', tones: stonePalettes.teal},+ {name: 'Yellow', sourceHex: '#f4e1b7', semantic: 'Warning', tones: stonePalettes.yellow},+ {name: 'Orange', sourceHex: '#ffdcbb', tones: stonePalettes.orange},+ {name: 'Red', sourceHex: '#f9dcd7', semantic: 'Error', tones: stonePalettes.red},+ {name: 'Pink', sourceHex: '#f0dde8', tones: stonePalettes.pink},+ {name: 'Purple', sourceHex: '#e8dff3', tones: stonePalettes.purple},];const CORE = [diff --git a/apps/sandbox/src/app/(fullscreen)/pages/y2k-palette/page.tsx b/apps/sandbox/src/app/(fullscreen)/pages/y2k-palette/page.tsxindex 49ef6a43c6..3aff01cd2a 100644--- a/apps/sandbox/src/app/(fullscreen)/pages/y2k-palette/page.tsx+++ b/apps/sandbox/src/app/(fullscreen)/pages/y2k-palette/page.tsx@@ -6,22 +6,24 @@import {XDSVStack} from '@xds/core/Layout';import {y2kTheme} from '@xds/theme-y2k/built';+// `y2kPalettes` is only exported from the source entry, not /built.+import {y2kPalettes} from '@xds/theme-y2k';import {ThemePalettePreview} from '@/components/ThemePalettePreview';import type {TonalColor} from '@/components/ThemePalettePreview';const CRIMSON = "'Crimson Text', Georgia, 'Times New Roman', serif";const TONAL_COLORS: TonalColor[] = [- {name: 'Y2K Neutral', sourceHex: '#c3b7ab', note: 'H=75 C=8'},- {name: 'Green', sourceHex: '#C5E17A', semantic: 'Success'},- {name: 'Red', sourceHex: '#FF9E9A', semantic: 'Error'},- {name: 'Yellow', sourceHex: '#FFCC55', semantic: 'Warning'},- {name: 'Blue', sourceHex: '#8ECFFF'},- {name: 'Pink', sourceHex: '#FFA0C8'},- {name: 'Purple', sourceHex: '#C0AAFF'},- {name: 'Cyan', sourceHex: '#70E8D0'},- {name: 'Orange', sourceHex: '#FFAA66'},- {name: 'Teal', sourceHex: '#78E0B0'},+ {name: 'Y2K Neutral', sourceHex: '#c3b7ab', note: 'H=75 C=8', tones: y2kPalettes.neutral},+ {name: 'Green', sourceHex: '#C5E17A', semantic: 'Success', tones: y2kPalettes.green},+ {name: 'Red', sourceHex: '#FF9E9A', semantic: 'Error', tones: y2kPalettes.red},+ {name: 'Yellow', sourceHex: '#FFCC55', semantic: 'Warning', tones: y2kPalettes.yellow},+ {name: 'Blue', sourceHex: '#8ECFFF', tones: y2kPalettes.blue},+ {name: 'Pink', sourceHex: '#FFA0C8', tones: y2kPalettes.pink},+ {name: 'Purple', sourceHex: '#C0AAFF', tones: y2kPalettes.purple},+ {name: 'Cyan', sourceHex: '#70E8D0', tones: y2kPalettes.cyan},+ {name: 'Orange', sourceHex: '#FFAA66', tones: y2kPalettes.orange},+ {name: 'Teal', sourceHex: '#78E0B0', tones: y2kPalettes.teal},];const sectionTitle: React.CSSProperties = {diff --git a/apps/sandbox/src/components/ThemePalettePreview.tsx b/apps/sandbox/src/components/ThemePalettePreview.tsxindex b8953e88fc..22b6cd4ca9 100644--- a/apps/sandbox/src/components/ThemePalettePreview.tsx+++ b/apps/sandbox/src/components/ThemePalettePreview.tsx@@ -1,5 +1,7 @@'use client';+import {useMemo, useReducer} from 'react';+import {XDSBanner} from '@xds/core/Banner';import {XDSSpinner} from '@xds/core/Spinner';import {XDSProgressBar} from '@xds/core/ProgressBar';@@ -15,6 +17,23 @@ import {XDSText, XDSHeading} from '@xds/core/Text';import {XDSTheme} from '@xds/core/theme';import type {XDSDefinedTheme} from '@xds/core/theme';import {XDSLayerProvider} from '@xds/core/Layer';+import {defaultTheme} from '@xds/theme-default/built';++import {+ ThemeAuditDrawer,+ useThemeAudit,+} from './themePreview/ThemeAuditDrawer';+import {+ buildTonalUsageMap,+ tonalUsageKey,+ type TonalUsageMap,+} from './themePreview/themeAudit';+import {+ buildOverrideCSSVars,+ overridesReducer,+ type OverridesMap,+ type SerializeContext,+} from './themePreview/themeOverrides';// === HCT color space helpers for tonal palettes ===@@ -233,15 +252,31 @@ export interface TonalColor {semantic?: string;note?: string;/**- * Optional pre-computed tonal ramp keyed by tone (0-100).- * When provided, the preview renders these exact values instead of- * deriving them from `sourceHex` via the built-in HCT algorithm —- * use this to keep the displayed strip in sync with the theme's- * own hand-tuned palette (so card/badge variants visually match).+ * Optional pre-computed canonical ramp keyed by tone (0-100).+ *+ * Two purposes, both served by the same field:+ *+ * 1. **Visible ramp accuracy** — when provided, the preview renders+ * these exact values instead of deriving them from `sourceHex`+ * via the built-in HCT algorithm, so the displayed strip stays+ * in sync with the theme's own hand-tuned palette (card/badge+ * variants visually match).+ *+ * 2. **Audit snap accuracy** — themes with hand-tuned palettes+ * (stone, gothic, y2k, butter) export `*Palettes` objects whose+ * values drift from the pure HCT generator by a couple of \u0394E+ * units. The audit drawer uses these canonical values for+ * snap-to-ramp matching so tokens whose values come from the+ * canonical ramp don't show up as "off-ramp".** Numeric keys are interpreted as tone steps; non-numeric keys- * (e.g. `hue`, `chroma`) are ignored. This shape matches theme- * palette exports like `butterPalettes.blue`.+ * (e.g. `hue`, `chroma`) are ignored. This permissive shape matches+ * theme palette exports like `stonePalettes.red` (which carry both).+ *+ * Omit for themes that don't carry a custom-tuned ramp — the audit+ * + preview both fall back to generating the ramp from `sourceHex`+ * via HCT, which is correct for those themes (their tokens were+ * generated the same way).*/tones?: Readonly<Record<string | number, string | number>>;/**@@ -467,11 +502,26 @@ const S = {top: 2,left: '50%',transform: 'translateX(-50%)',- width: 6,- height: 6,- borderRadius: '50%',- border: `1.5px solid ${tone >= 50 ? 'rgba(0,0,0,0.5)' : 'rgba(255,255,255,0.7)'}`,- background: tone >= 50 ? 'rgba(0,0,0,0.15)' : 'rgba(255,255,255,0.25)',+ minWidth: 8,+ height: 8,+ paddingInline: 2,+ borderRadius: 999,+ border: `1.5px solid ${tone >= 50 ? 'rgba(0,0,0,0.6)' : 'rgba(255,255,255,0.85)'}`,+ background: tone >= 50 ? 'rgba(0,0,0,0.2)' : 'rgba(255,255,255,0.3)',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ lineHeight: 1,+ }) as React.CSSProperties,+ // Pill shows the token count when more than one token snaps to the same+ // tone step. Stays inside the marker dot so the strip layout is unchanged.+ markerCount: (tone: number) =>+ ({+ fontSize: 7.5,+ fontWeight: 700,+ fontFamily: MONO,+ color: tone >= 50 ? 'rgba(0,0,0,0.85)' : 'rgba(255,255,255,0.95)',+ pointerEvents: 'none' as const,}) as React.CSSProperties,};@@ -973,11 +1023,13 @@ function InputSection() {function TonalSection({colors,mode = 'light',+ usage,}: {colors: TonalColor[];mode?: Mode;+ /** Audit-derived map of which tone steps are consumed by which tokens. */+ usage?: TonalUsageMap;}) {- const usedTones = [15, 25, 80, 90];const isDark = mode === 'dark';return (<div style={{marginBottom: 40}}>@@ -1009,7 +1061,9 @@ function TonalSection({vibrate against the dark canvas.</>)}{' '}- Badge tokens use T90/T30 (light) and T70/T15 (dark).+ {usage+ ? 'Markers ● show tone steps consumed by theme tokens (open the audit drawer for the full report).'+ : 'Badge tokens use T90/T30 (light) and T70/T15 (dark).'}</p>{colors.map(({name, sourceHex, semantic, note, tones: overrideTones, dark}) => {// In dark mode, use per-mode overrides if provided.@@ -1046,6 +1100,16 @@ function TonalSection({<div style={S.tonalStrip}>{steps.map(t => {const hex = resolveTone(t);+ const usages = usage?.[tonalUsageKey(name, mode, t)] ?? [];+ // Title summarises which tokens snap to this step (max 4+ // listed to keep the native tooltip readable on dense ramps).+ const titleLines = [+ `${name} T${t}: ${hex}`,+ ...usages+ .slice(0, 4)+ .map(u => `· ${u.name} (\u0394E ${u.deltaE.toFixed(1)})`),+ usages.length > 4 ? `· +${usages.length - 4} more` : '',+ ].filter(Boolean);return (<divkey={t}@@ -1053,9 +1117,15 @@ function TonalSection({...S.tonalCell(hex),position: 'relative' as const,}}- title={`${name} T${t}: ${hex}`}>+ title={titleLines.join('\n')}><span style={S.tonalNum(t)}>{t}</span>- {usedTones.includes(t) && <div style={S.markerDot(t)} />}+ {usages.length > 0 && (+ <div style={S.markerDot(t)}>+ {usages.length > 1 && (+ <span style={S.markerCount(t)}>{usages.length}</span>+ )}+ </div>+ )}</div>);})}@@ -1074,8 +1144,9 @@ function TonalSection({marginTop: 10,fontFamily: MONO,}}>- ● = token in use (T15 dark bg · T25 light text · T80 dark text · T90- light bg)+ {usage+ ? '● = tone step consumed by a theme token. Number = count when multiple tokens share the same step. Hover any cell for details.'+ : '● = token in use (T15 dark bg · T25 light text · T80 dark text · T90 light bg)'}</p></div>);@@ -1088,6 +1159,7 @@ function ModeColumn({extraSections,leadingExtras,shadowDescription,+ overrideVars,bare = false,}: {theme: XDSDefinedTheme;@@ -1096,6 +1168,16 @@ function ModeColumn({extraSections?: React.ReactNode;leadingExtras?: React.ReactNode;shadowDescription?: string;+ /**+ * Pending-overrides CSS custom properties spread onto the column's+ * outermost styled wrapper *inside* the XDSTheme scope. Required:+ * XDSTheme re-injects the canonical token values on its own scope+ * element, so any `--color-*` overrides applied above XDSTheme would+ * be stomped by the inner theme rules. Putting the overrides+ * inside the theme wrapper (as inline style on a child element)+ * wins via specificity.+ */+ overrideVars?: React.CSSProperties;/*** When true, render the column as a transparent layout container* (no background, border, or padding) — the outer page provides the@@ -1114,7 +1196,7 @@ function ModeColumn({return (<XDSTheme theme={theme} mode={mode}><XDSLayerProvider>- <div style={columnStyle}>+ <div style={{...columnStyle, ...overrideVars}}>{!bare && (<p style={S.modeLabel}>{mode === 'light' ? 'Light Mode' : 'Dark Mode'}@@ -1163,6 +1245,43 @@ export function ThemePalettePreview({? {display: 'block'}: S.twoCol;+ // Run audit once per (theme, tonalColors). The drawer reads diff + snap+ // tables; the Tonal section reads `usage` to draw token-driven markers.+ const audit = useThemeAudit(theme, tonalColors);++ // Pending-overrides state lives at the page level (not in the drawer)+ // so we can also feed it into a CSS-variable injection at the page+ // root — that way every component on the page (mode columns + tonal+ // strip) re-renders live as you reassign tokens in the drawer.+ const [overrides, dispatchOverrides] = useReducer(+ overridesReducer,+ {} as OverridesMap,+ );++ // Map of `--token: light-dark(#L, #D)` for every pending override.+ // Spread directly onto the page root so the values cascade into every+ // descendant via CSS custom property inheritance.+ const serializeCtx: SerializeContext = useMemo(() => {+ const map: SerializeContext['currentTokenValues'] = {};+ for (const e of audit.snap) {+ map[e.name] = {light: e.light, dark: e.dark};+ }+ return {currentTokenValues: map};+ }, [audit.snap]);+ const overrideVars = useMemo(+ () => buildOverrideCSSVars(overrides, serializeCtx),+ [overrides, serializeCtx],+ );++ // Tonal markers respect pending overrides — every reassignment shows+ // up as a new marker on the chosen ramp+tone the moment the user+ // changes a dropdown. Auto-detected matches still drive markers for+ // tokens that haven't been edited yet.+ const effectiveUsage = useMemo(+ () => buildTonalUsageMap(audit.snap, overrides),+ [audit.snap, overrides],+ );+const renderColumns = () => {if (singleMode) {return (@@ -1173,6 +1292,7 @@ export function ThemePalettePreview({extraSections={extraSections}leadingExtras={leadingExtras}shadowDescription={shadowDescription}+ overrideVars={overrideVars}bare/>);@@ -1186,6 +1306,7 @@ export function ThemePalettePreview({extraSections={extraSections}leadingExtras={leadingExtras}shadowDescription={shadowDescription}+ overrideVars={overrideVars}/><ModeColumntheme={theme}@@ -1194,12 +1315,15 @@ export function ThemePalettePreview({extraSections={extraSections}leadingExtras={leadingExtras}shadowDescription={shadowDescription}+ overrideVars={overrideVars}/></>);};if (componentPreviewOnly) {+ // Embedded usage (e.g. inside docsite layouts) skips the audit drawer too —+ // hosts that need it can mount <ThemeAuditDrawer> separately.return <div style={columnsStyle}>{renderColumns()}</div>;}@@ -1213,17 +1337,34 @@ export function ThemePalettePreview({const tonalModes: Mode[] = singleMode ? [singleMode] : ['light', 'dark'];return (- <XDSTheme theme={theme} mode={chromeMode}>- <XDSLayerProvider>- <div style={{...S.page, margin: -0, position: 'relative', zIndex: 1}}>+ <>+ {/* Preview surface — themed by the theme being audited. Override+ CSS vars live here so they cascade into every preview component+ (page background, tonal block, mode columns) but NOT into the+ audit drawer rendered in its own theme below. */}+ <XDSTheme theme={theme} mode={chromeMode}>+ <XDSLayerProvider>+ <div+ style={{+ ...S.page,+ ...overrideVars,+ margin: -0,+ position: 'relative',+ zIndex: 1,+ }}><div style={S.inner}><h1 style={S.title}>{title}</h1><p style={S.subtitle}>{subtitle}</p>{tonalModes.map(m => (<XDSTheme key={m} theme={theme} mode={m}><XDSLayerProvider>+ {/* Spread overrideVars *inside* the inner XDSTheme so+ pending overrides win over the theme's own+ `:scope { --color-*: … }` rules. Same trick the+ ModeColumn uses. */}<divstyle={{+ ...overrideVars,background: 'var(--color-background-body)',color: 'var(--color-text-primary)',borderRadius: 16,@@ -1236,15 +1377,37 @@ export function ThemePalettePreview({{m === 'light' ? 'Light Mode' : 'Dark Mode'}</p>)}- <TonalSection colors={tonalColors} mode={m} />+ <TonalSection+ colors={tonalColors}+ mode={m}+ usage={effectiveUsage}+ /></div></XDSLayerProvider></XDSTheme>))}<div style={columnsStyle}>{renderColumns()}</div></div>- </div>- </XDSLayerProvider>- </XDSTheme>+ </div>+ </XDSLayerProvider>+ </XDSTheme>++ {/* Audit drawer + draft indicator — mounted *outside* the audited+ theme so the drawer's own chrome (buttons, borders, text) stays+ stable regardless of which theme is being previewed. Uses the+ neutral default theme so it always looks the same across all 5+ palette pages. Position-fixed elements inside the drawer+ attach to the viewport, not this wrapper. */}+ <XDSTheme theme={defaultTheme} mode="light">+ <XDSLayerProvider>+ <ThemeAuditDrawer+ audit={audit}+ themeName={theme.name}+ overrides={overrides}+ dispatchOverrides={dispatchOverrides}+ />+ </XDSLayerProvider>+ </XDSTheme>+ </>);}diff --git a/apps/sandbox/src/components/themePreview/ThemeAuditDrawer.tsx b/apps/sandbox/src/components/themePreview/ThemeAuditDrawer.tsxnew file mode 100644index 0000000000..46e5b89341--- /dev/null+++ b/apps/sandbox/src/components/themePreview/ThemeAuditDrawer.tsx@@ -0,0 +1,1379 @@+'use client';++/**+ * Theme Audit Drawer.+ *+ * Mirrors the docsite Theme Editor layout (`apps/sandbox/src/app/+ * (fullscreen)/pages/docsite/ThemeEditorView.tsx`): one flat scroll of+ * color tokens grouped by `COLOR_CATEGORIES` ("Core Semantic", "Text",+ * "Surface Variants", "Palette: Blue", …). Each row shows the pretty+ * token label, a swatch, and an inline ramp + tone editor for the+ * current mode.+ *+ * Pending edits accumulate into a sticky footer; Export opens a modal+ * with a paste-able TS snippet plus an "Apply to source" button that+ * POSTs to `/api/theme-audit/apply` and rewrites the right+ * `defineTheme()` block on disk.+ *+ * Diff-vs-default and free-form filtering UI from the previous version+ * was dropped — the docsite-style category list IS the navigation, and+ * the snap verdict shows up as a subtle pill on each row.+ */++import {useEffect, useMemo, useReducer, useRef, useState} from 'react';+import type {XDSDefinedTheme} from '@xds/core/theme';++// XDS components — used in the editor popover, export dialog, and the+// row trigger so the audit drawer's interactive surfaces stay+// consistent with the rest of XDS instead of a hand-rolled clone of+// each one.+import {XDSPopover} from '@xds/core/Popover';+import {XDSTabList, XDSTab} from '@xds/core/TabList';+import {XDSButton} from '@xds/core/Button';+import {XDSTextInput} from '@xds/core/TextInput';+import {XDSHStack, XDSVStack} from '@xds/core/Layout';+import {XDSText} from '@xds/core/Text';++import {+ TONE_STEPS,+ type Mode,+ type RampSeed,+ type ToneStep,+} from './colorMath';+import {+ auditSnapToRamps,+ buildTonalUsageMap,+ diffThemeTokens,+ parseTokenColor,+ type SnapAuditEntry,+ type TokenDiff,+ type TokenDiffEntry,+ type TonalUsageMap,+} from './themeAudit';+import {+ buildCustomOverride,+ buildModeOverride,+ composeAlphaHex,+ countOverrides,+ describeOverride,+ formatHexWithAlpha,+ isValidHex,+ normalizeHex,+ overridesReducer,+ parseHexWithAlpha,+ resolveOverrideHex,+ serializeAsTokensBlock,+ type ModeOverride,+ type OverridesMap,+ type SerializeContext,+} from './themeOverrides';+import {+ getCategorizedColorTokens,+ getTokenLabel,+} from './colorCategories';++// =============================================================================+// Types & exports+// =============================================================================++export interface ThemeAuditData {+ diff: TokenDiff;+ snap: SnapAuditEntry[];+ /** Index by token name for fast lookup in the per-row renderer. */+ snapByToken: Record<string, SnapAuditEntry>;+ /** Diff entry index by token name — drives the "original" swatch on each row. */+ diffByToken: Record<string, TokenDiffEntry>;+ /** Tonal usage map — drives the markers in ThemePalettePreview's Tonal section. */+ usage: TonalUsageMap;+ /** Ramp seeds drive the ramp-name dropdown options. */+ rampSeeds: RampSeed[];+}++/**+ * Compute audit data once per (theme, seeds) pair.+ * Returned to ThemePalettePreview so the tonal markers can read the same+ * usage map the drawer renders, without re-running the snap math.+ */+export function useThemeAudit(+ theme: XDSDefinedTheme,+ rampSeeds: RampSeed[],+): ThemeAuditData {+ return useMemo(() => {+ const diff = diffThemeTokens(theme);+ const snap = auditSnapToRamps(theme, rampSeeds);+ const snapByToken: Record<string, SnapAuditEntry> = {};+ for (const e of snap) snapByToken[e.name] = e;+ const diffByToken: Record<string, TokenDiffEntry> = {};+ for (const e of diff.entries) diffByToken[e.name] = e;+ const usage = buildTonalUsageMap(snap);+ return {diff, snap, snapByToken, diffByToken, usage, rampSeeds};+ }, [theme, rampSeeds]);+}++// =============================================================================+// Style sheet+// =============================================================================++const MONO = "'JetBrains Mono', 'SF Mono', Menlo, monospace";+const drawerWidth = 520;++const S = {+ toggle: (open: boolean): React.CSSProperties => ({+ position: 'fixed',+ top: 24,+ right: open ? drawerWidth + 16 : 16,+ zIndex: 1001,+ appearance: 'none',+ border: '1px solid var(--color-border-emphasized)',+ background: 'var(--color-background-card)',+ color: 'var(--color-text-primary)',+ fontFamily: 'var(--font-family-body)',+ fontSize: 12,+ fontWeight: 600,+ letterSpacing: '0.02em',+ padding: '8px 12px',+ borderRadius: 8,+ cursor: 'pointer',+ boxShadow: 'var(--shadow-med)',+ transition: 'right 200ms ease',+ display: 'flex',+ alignItems: 'center',+ gap: 8,+ }),+ toggleBadge: (count: number): React.CSSProperties => ({+ display: 'inline-flex',+ alignItems: 'center',+ justifyContent: 'center',+ minWidth: 18,+ height: 18,+ padding: '0 5px',+ borderRadius: 9,+ background:+ count > 0 ? 'var(--color-accent)' : 'var(--color-background-muted)',+ color:+ count > 0 ? 'var(--color-on-accent)' : 'var(--color-text-secondary)',+ fontSize: 10,+ fontWeight: 700,+ fontFamily: MONO,+ }),+ drawer: (open: boolean): React.CSSProperties => ({+ position: 'fixed',+ top: 0,+ right: 0,+ bottom: 0,+ width: drawerWidth,+ background: 'var(--color-background-surface)',+ color: 'var(--color-text-primary)',+ borderLeft: '1px solid var(--color-border)',+ boxShadow: open ? 'var(--shadow-high)' : 'none',+ transform: open ? 'translateX(0)' : `translateX(${drawerWidth + 16}px)`,+ transition: 'transform 220ms ease',+ zIndex: 1000,+ display: 'flex',+ flexDirection: 'column',+ fontFamily: 'var(--font-family-body)',+ }),+ header: {+ padding: '16px 20px 12px',+ borderBottom: '1px solid var(--color-border)',+ display: 'flex',+ flexDirection: 'column' as const,+ gap: 6,+ } as React.CSSProperties,+ headerTopRow: {+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ gap: 12,+ } as React.CSSProperties,+ title: {+ margin: 0,+ fontSize: 14,+ fontWeight: 700,+ fontFamily: 'var(--font-family-heading)',+ } as React.CSSProperties,+ subtitle: {+ margin: 0,+ fontSize: 11,+ color: 'var(--color-text-secondary)',+ lineHeight: 1.5,+ } as React.CSSProperties,+ modeRow: {+ display: 'flex',+ gap: 4,+ padding: '8px 16px',+ borderBottom: '1px solid var(--color-border)',+ background: 'var(--color-background-surface)',+ alignItems: 'center',+ } as React.CSSProperties,+ modeButton: (active: boolean): React.CSSProperties => ({+ appearance: 'none',+ border: '1px solid transparent',+ background: active ? 'var(--color-background-muted)' : 'transparent',+ color: active ? 'var(--color-text-primary)' : 'var(--color-text-secondary)',+ fontSize: 11,+ fontWeight: 600,+ padding: '4px 10px',+ borderRadius: 6,+ cursor: 'pointer',+ fontFamily: 'var(--font-family-body)',+ }),+ body: {+ flex: 1,+ overflowY: 'auto' as const,+ padding: '4px 20px 24px',+ } as React.CSSProperties,+ // Category header — small uppercase secondary text, intentionally+ // restrained so the rows beneath read as the primary content (matches+ // the docsite editor exactly).+ categoryHeader: {+ fontSize: 10,+ fontWeight: 600,+ textTransform: 'uppercase' as const,+ letterSpacing: '0.06em',+ color: 'var(--color-text-secondary)',+ margin: 0,+ padding: '14px 0 4px',+ } as React.CSSProperties,+ // Each row is a 3-column grid: label · status · editor cluster. We use+ // a CSS grid (not flex) with `minmax(0, 1fr)` on the label column so+ // long token labels truncate cleanly when the drawer is narrow.+ row: {+ display: 'grid',+ gridTemplateColumns: 'minmax(0, 1fr) auto',+ columnGap: 10,+ alignItems: 'center',+ padding: '8px 0',+ borderBottom: '1px solid var(--color-border)',+ } as React.CSSProperties,+ labelCell: {+ minWidth: 0,+ display: 'flex',+ flexDirection: 'column' as const,+ gap: 2,+ } as React.CSSProperties,+ labelText: {+ fontSize: 12,+ fontWeight: 500,+ color: 'var(--color-text-primary)',+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap' as const,+ } as React.CSSProperties,+ tokenName: {+ fontSize: 10,+ fontFamily: MONO,+ color: 'var(--color-text-secondary)',+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap' as const,+ } as React.CSSProperties,+ // Right-side editor cluster — fixed grid so the original swatch+ // column, trigger button, and reset link always land in the same+ // horizontal positions across every row regardless of label length+ // or token state. Width tracks: 28px (original swatch) · 1fr (trigger+ // button stretches to fill) · auto (reset link, only when edited).+ editorCell: {+ display: 'grid',+ gridTemplateColumns: '28px minmax(0, 1fr) auto',+ columnGap: 8,+ alignItems: 'center',+ width: 240,+ flexShrink: 0,+ } as React.CSSProperties,+ // Combined swatch + value-label button. The swatch sits flush with+ // the button's left edge (no inset padding) so it visually aligns+ // with the standalone original swatch on its left. Vertical padding+ // matches the swatch border so the button height equals 30px (28px+ // swatch + 2px border = same height as the standalone original).+ triggerButton: {+ appearance: 'none' as const,+ display: 'flex',+ alignItems: 'center',+ gap: 8,+ padding: 0,+ paddingRight: 10,+ borderRadius: 6,+ border: '1px solid var(--color-border)',+ background: 'var(--color-background-body)',+ color: 'var(--color-text-primary)',+ fontFamily: 'var(--font-family-body)',+ fontSize: 11,+ cursor: 'pointer',+ minWidth: 0,+ width: '100%',+ height: 30,+ } as React.CSSProperties,+ triggerButtonEdited: {+ appearance: 'none' as const,+ display: 'flex',+ alignItems: 'center',+ gap: 8,+ padding: 0,+ paddingRight: 10,+ borderRadius: 6,+ border: '1px solid var(--color-text-accent)',+ background: 'var(--color-background-body)',+ color: 'var(--color-text-accent)',+ fontFamily: 'var(--font-family-body)',+ fontSize: 11,+ cursor: 'pointer',+ minWidth: 0,+ width: '100%',+ height: 30,+ } as React.CSSProperties,+ // Inline swatch sits flush against the trigger button's left edge.+ // Same 28×28 footprint as the standalone original swatch on the+ // outside, with the same radius matched to the button's inner radius+ // so the swatch corner tucks into the button's corner cleanly.+ swatchInline: {+ width: 28,+ height: 28,+ borderTopLeftRadius: 5,+ borderBottomLeftRadius: 5,+ borderRight: '1px solid var(--color-border)',+ flexShrink: 0,+ } as React.CSSProperties,+ triggerLabel: {+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap' as const,+ minWidth: 0,+ flex: 1,+ textAlign: 'left' as const,+ paddingLeft: 8,+ } as React.CSSProperties,+ // "Original" swatch rendered to the left of the active swatch. Always+ // present (even when default === current) so the row geometry is+ // consistent and you can sanity-check the original value at a glance.+ //+ // When the token has no XDS default (theme-only addition), the caller+ // passes `transparent` and we lay a faint diagonal-stripe pattern on+ // top so the empty slot reads as "no default exists" rather than a+ // glitched render.+ originalSwatch: (color: string): React.CSSProperties => ({+ width: 28,+ height: 28,+ borderRadius: 6,+ background: color,+ border: '1px solid var(--color-border-emphasized)',+ flexShrink: 0,+ backgroundImage:+ color === 'transparent'+ ? 'repeating-linear-gradient(45deg, transparent 0 4px, var(--color-background-muted) 4px 5px)'+ : undefined,+ }),+ // Native <select> used inside the popover's Palette tab for ramp+tone+ // — `XDSDropdownMenu` is heavier than needed for a small list and the+ // native control gives us free keyboard navigation.+ select: {+ appearance: 'none',+ border: '1px solid var(--color-border)',+ background: 'var(--color-background-body)',+ color: 'var(--color-text-primary)',+ fontFamily: MONO,+ fontSize: 11,+ padding: '4px 6px',+ borderRadius: 4,+ cursor: 'pointer',+ maxWidth: 90,+ } as React.CSSProperties,+ indirectNote: {+ fontSize: 9.5,+ color: 'var(--color-text-secondary)',+ fontStyle: 'italic' as const,+ } as React.CSSProperties,+ applyFooter: {+ borderTop: '1px solid var(--color-border)',+ padding: '12px 20px',+ background: 'var(--color-background-card)',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ gap: 12,+ } as React.CSSProperties,+};++// =============================================================================+// Drawer+// =============================================================================++export interface ThemeAuditDrawerProps {+ audit: ThemeAuditData;+ themeName: string;+ /**+ * Controlled pending-overrides state. When provided, the drawer becomes+ * a controlled component: it reads from `overrides` and routes every+ * edit through `dispatchOverrides`. Use this to wire the drawer's+ * edits into a live preview elsewhere on the page+ * (`ThemePalettePreview` does this so pending edits hot-update the+ * rendered components via CSS custom properties).+ *+ * When omitted, the drawer keeps its own internal overrides state.+ * Both `overrides` and `dispatchOverrides` must be provided together+ * or both omitted.+ */+ overrides?: OverridesMap;+ dispatchOverrides?: React.Dispatch<Parameters<typeof overridesReducer>[1]>;+}++export function ThemeAuditDrawer({+ audit,+ themeName,+ overrides: overridesProp,+ dispatchOverrides: dispatchProp,+}: ThemeAuditDrawerProps) {+ const [open, setOpen] = useState(false);+ // Mode toggle drives which side of light-dark() the swatches reflect.+ // We intentionally only show one mode at a time — the docsite editor+ // does the same and it keeps each row to a single editable hex.+ const [mode, setMode] = useState<Mode>('light');+ // Controlled or uncontrolled: if the parent passed both `overrides` and+ // `dispatchOverrides`, use them; otherwise keep our own reducer.+ const [internalOverrides, dispatchInternal] = useReducer(+ overridesReducer,+ {} as OverridesMap,+ );+ const overrides = overridesProp ?? internalOverrides;+ const dispatchOverrides = dispatchProp ?? dispatchInternal;+ // Brief "Copied" confirmation in the footer after a successful copy.+ const [justCopied, setJustCopied] = useState(false);++ const overrideCount = countOverrides(overrides);++ // Build current-value context so the export formatter knows what to fill+ // in for the side of a tuple the user didn't reassign.+ const serializeCtx: SerializeContext = useMemo(() => {+ const map: SerializeContext['currentTokenValues'] = {};+ for (const e of audit.snap) {+ map[e.name] = {light: e.light, dark: e.dark};+ }+ return {currentTokenValues: map};+ }, [audit.snap]);++ // LLM-friendly snippet — bare `tokens: { ... }` block prefixed with an+ // instruction prompt naming the target file path and the apply rule.+ // Pasting into Cursor / Claude / any other coding agent gives the model+ // enough context to apply the edits without further instruction.+ const promptSnippet = useMemo(() => {+ if (overrideCount === 0) return '';+ const inner = serializeAsTokensBlock(overrides, serializeCtx);+ const filePath = `packages/themes/${themeName}/src/${themeName}Theme.ts`;+ return [+ `Apply the following ${overrideCount} token override${overrideCount === 1 ? '' : 's'} to ${filePath}.`,+ '',+ 'Rules:',+ `- Locate the \`defineTheme(...)\` call and find the existing \`tokens: { ... }\` block inside it.`,+ `- For each entry below, find a line whose key matches the token name and replace its value with the value below. Preserve indentation, quote style, and trailing comma. Replace any existing trailing inline comment with the annotation comment provided.`,+ `- If a token is not present, insert a new line at the bottom of the \`tokens\` block (just before the closing \`}\`) using the same indentation and quote style as sibling entries.`,+ `- For \`--color-syntax-*\` entries: prefer to update the \`defineSyntaxTheme({ tokens: { ... } })\` block instead — strip the \`--color-syntax-\` prefix to get the key name (e.g. \`--color-syntax-keyword\` → \`keyword\`). Only fall back to inserting them as direct \`--color-syntax-*\` tokens inside \`defineTheme.tokens\` if no \`defineSyntaxTheme\` block exists.`,+ `- Do not modify any other tokens, comments, or surrounding code.`,+ '',+ inner,+ ].join('\n');+ }, [overrides, serializeCtx, themeName, overrideCount]);++ const handleCopySnippet = async () => {+ if (!promptSnippet) return;+ try {+ await navigator.clipboard.writeText(promptSnippet);+ setJustCopied(true);+ // Auto-clear the confirmation after a beat so the footer text+ // doesn't permanently say "Copied" — it should fade back to the+ // pending count.+ setTimeout(() => setJustCopied(false), 1800);+ } catch {+ // Clipboard permission denied (rare; some browsers when not+ // focused). Surface no UI fallback in this direct-copy flow —+ // the user can re-trigger after focusing the page. A future+ // version could re-introduce a preview modal as the fallback.+ }+ };++ // Pre-bucket tokens into the docsite categories. We pass the *union*+ // of every color token the audit knows about (theme-defined + XDS+ // defaults) so anything not covered by the curated categories falls+ // into the trailing "Other Colors" / "Syntax Highlighting" buckets+ // instead of being silently hidden.+ const categorized = useMemo(() => {+ const known = new Set<string>();+ for (const e of audit.snap) known.add(e.name);+ for (const e of audit.diff.entries) known.add(e.name);+ return getCategorizedColorTokens(known);+ }, [audit.snap, audit.diff.entries]);++ return (+ <>+ <button+ type="button"+ style={S.toggle(open)}+ onClick={() => setOpen(o => !o)}>+ Tokens+ {overrideCount > 0 && (+ <span style={S.toggleBadge(overrideCount)} title="Pending edits">+ {overrideCount}+ </span>+ )}+ </button>+ <aside style={S.drawer(open)} aria-hidden={!open}>+ <div style={S.header}>+ <div style={S.headerTopRow}>+ <h2 style={S.title}>Tokens · {themeName}</h2>+ <button+ type="button"+ onClick={() => setOpen(false)}+ aria-label="Close audit panel"+ style={{+ appearance: 'none',+ border: 'none',+ background: 'transparent',+ color: 'var(--color-text-secondary)',+ cursor: 'pointer',+ fontSize: 18,+ lineHeight: 1,+ padding: 4,+ }}>+ ×+ </button>+ </div>+ <p style={S.subtitle}>+ Reassign any token to a tonal-ramp step. Pending edits collect+ below; Export to copy or Apply to write back to source.+ </p>+ </div>+ <div style={S.modeRow}>+ <button+ type="button"+ style={S.modeButton(mode === 'light')}+ onClick={() => setMode('light')}>+ Light+ </button>+ <button+ type="button"+ style={S.modeButton(mode === 'dark')}+ onClick={() => setMode('dark')}>+ Dark+ </button>+ </div>+ <div style={S.body}>+ {categorized.map(({category, tokens}) => {+ // Skip categories whose tokens have no audit entries at all+ // (the theme doesn't define any of them) so we don't render+ // empty headers.+ const visibleTokens = tokens.filter(t => audit.snapByToken[t]);+ if (visibleTokens.length === 0) return null;+ return (+ <div key={category}>+ <h3 style={S.categoryHeader}>{category}</h3>+ {visibleTokens.map(tokenName => (+ <ColorRow+ key={tokenName}+ tokenName={tokenName}+ snap={audit.snapByToken[tokenName]}+ diff={audit.diffByToken[tokenName]}+ rampSeeds={audit.rampSeeds}+ mode={mode}+ override={overrides[tokenName]?.[mode]}+ onPickPalette={(rampName, tone, alpha) => {+ const seed = audit.rampSeeds.find(s => s.name === rampName);+ if (!seed) return;+ dispatchOverrides({+ type: 'set',+ token: tokenName,+ mode,+ override: buildModeOverride(seed, tone, mode, alpha),+ });+ }}+ onPickCustom={hex =>+ dispatchOverrides({+ type: 'set',+ token: tokenName,+ mode,+ // buildCustomOverride parses alpha out of the hex+ // input itself (#aabbccdd / '#aabbcc 10%' both work).+ override: buildCustomOverride(hex),+ })+ }+ onReset={() =>+ dispatchOverrides({+ type: 'clearMode',+ token: tokenName,+ mode,+ })+ }+ />+ ))}+ </div>+ );+ })}+ </div>+ {overrideCount > 0 && (+ <div style={S.applyFooter}>+ <XDSText type="supporting" color="secondary">+ {justCopied+ ? 'Copied to clipboard'+ : `${overrideCount} token${overrideCount === 1 ? '' : 's'} pending`}+ </XDSText>+ <XDSHStack gap={2}>+ <XDSButton+ label="Discard"+ variant="ghost"+ size="sm"+ onClick={() => dispatchOverrides({type: 'reset'})}+ />+ <XDSButton+ label={`Copy snippet (${overrideCount})`}+ variant="primary"+ size="sm"+ onClick={handleCopySnippet}+ />+ </XDSHStack>+ </div>+ )}+ </aside>+ </>+ );+}++// =============================================================================+// ColorRow+// =============================================================================++interface ColorRowProps {+ tokenName: string;+ snap: SnapAuditEntry;+ diff: TokenDiffEntry | undefined;+ rampSeeds: RampSeed[];+ mode: Mode;+ override: ModeOverride | undefined;+ /**+ * Commit a palette pick. `alpha` is the original token's alpha+ * (0-1, default 1) — passed through so a snap on a 10%-alpha overlay+ * commits the ramp swatch with the alpha layered back on.+ */+ onPickPalette: (rampName: string, tone: ToneStep, alpha?: number) => void;+ /**+ * Commit a custom hex pick. The hex string may include alpha+ * (8-digit `#aabbccdd` or `'#aabbcc 10%'`); `buildCustomOverride`+ * parses it and embeds the alpha on the override.+ */+ onPickCustom: (hex: string) => void;+ onReset: () => void;+}++function ColorRow({+ tokenName,+ snap,+ diff,+ rampSeeds,+ mode,+ override,+ onPickPalette,+ onPickCustom,+ onReset,+}: ColorRowProps) {+ const sourceHex = mode === 'light' ? snap.light : snap.dark;+ const match = mode === 'light' ? snap.lightMatch : snap.darkMatch;+ // Per-mode alpha — preserved end-to-end so a snap on a 10%-alpha+ // overlay token commits the ramp swatch with `1A` (10%) appended.+ const sourceAlpha = mode === 'light' ? snap.alphaLight : snap.alphaDark;+ const activeAlpha = override?.alpha ?? sourceAlpha;+ // Active hex — base 6-digit (no alpha). `activeHexWithAlpha` is the+ // 8-digit form used for the visible swatch + the popover preview so+ // transparency is honored everywhere it matters visually.+ const activeHexBase = override?.hex+ ? normalizeHex(override.hex)+ : sourceHex ?? '';+ const activeHexWithAlpha = activeHexBase+ ? composeAlphaHex(activeHexBase, activeAlpha)+ : '';++ // Resolve the XDS-default value for this token in the active mode.+ // Always rendered as the leftmost square so the row geometry is+ // consistent across the table, even when default === current. The+ // default's own alpha is layered back on so the comparison swatch+ // reads accurately for transparent tokens (overlay, shadow, etc.).+ const defaultParsed = diff?.defaultValue+ ? parseTokenColor(diff.defaultValue)+ : null;+ const defaultHexBase =+ mode === 'light' ? defaultParsed?.light ?? null : defaultParsed?.dark ?? null;+ const defaultAlpha =+ mode === 'light'+ ? defaultParsed?.alphaLight ?? 1+ : defaultParsed?.alphaDark ?? 1;+ const defaultHexWithAlpha = defaultHexBase+ ? composeAlphaHex(defaultHexBase, defaultAlpha)+ : null;++ // Single-source label rendered inside the trigger button:+ // - On-ramp (auto-detected exact/snapped, or edited via palette) → "Blue T35"+ // - Off-ramp (auto-detected near/off, or edited via custom hex) → "#28282a"+ // Alpha < 1 appends ` · 10%` so transparency is visible at a scan.+ // All editing happens in the popover — the trigger is read-only.+ const inputDisplay = (() => {+ let label: string;+ if (override?.kind === 'palette') {+ label = `${override.rampName} T${override.tone}`;+ } else if (+ !override &&+ match &&+ (match.verdict === 'exact' || match.verdict === 'snapped')+ ) {+ label = `${match.rampName} T${match.tone}`;+ } else {+ label = activeHexBase;+ }+ return activeAlpha < 1+ ? `${label} · ${Math.round(activeAlpha * 100)}%`+ : label;+ })();+ // Edited rows wear the accent color on the input so pending changes+ // are immediately scannable; unedited rows use the default border.+ const inputEdited = !!override;++ const [popoverOpen, setPopoverOpen] = useState(false);++ return (+ <div style={S.row}>+ <div style={S.labelCell}>+ <span style={S.labelText} title={tokenName}>+ {getTokenLabel(tokenName)}+ </span>+ <span style={S.tokenName}>{tokenName}</span>+ {snap.indirect && (+ <span style={S.indirectNote}>indirect (var() reference)</span>+ )}+ </div>+ <div style={S.editorCell}>+ <div+ style={S.originalSwatch(defaultHexWithAlpha ?? 'transparent')}+ title={+ defaultHexWithAlpha+ ? `Original (XDS default): ${formatHexWithAlpha(defaultHexBase ?? '#000000', defaultAlpha)}`+ : 'No XDS default — token added by theme'+ }+ aria-label={+ defaultHexWithAlpha+ ? `Original default value: ${defaultHexWithAlpha}`+ : 'No default value'+ }+ />+ {/* Trigger lives inside XDSPopover — it auto-locates the+ <button>, manages anchor positioning via CSS anchor+ positioning, handles outside-click + Esc + focus+ management, and stacks correctly above sibling content+ without needing a manual z-index. */}+ <XDSPopover+ isOpen={popoverOpen}+ onOpenChange={setPopoverOpen}+ isEnabled={!snap.indirect}+ placement="below"+ alignment="end"+ width={300}+ hasCloseButton={false}+ content={+ <EditorPopoverContent+ mode={mode}+ tokenName={tokenName}+ currentHex={activeHexBase || '#000000'}+ currentAlpha={activeAlpha}+ override={override}+ // Smart default: open Palette tab when the current value+ // sits cleanly on a ramp (exact / snapped / edited via+ // palette); open Custom tab otherwise so the immediate+ // affordance matches the value's actual nature.+ initialTab={+ override?.kind === 'palette' ||+ (!override &&+ (match?.verdict === 'exact' || match?.verdict === 'snapped'))+ ? 'palette'+ : 'custom'+ }+ rampSeeds={rampSeeds}+ // Pre-select the closest auto-detected ramp+tone so the+ // palette tab opens in a useful position even when the+ // current value is off-ramp.+ paletteHint={+ override?.kind === 'palette'+ ? {rampName: override.rampName, tone: override.tone}+ : match+ ? {rampName: match.rampName, tone: match.tone as ToneStep}+ : null+ }+ onPickPalette={(rampName, tone, alpha) => {+ onPickPalette(rampName, tone, alpha);+ setPopoverOpen(false);+ }}+ onPickCustom={hex => {+ onPickCustom(hex);+ setPopoverOpen(false);+ }}+ />+ }>+ <button+ type="button"+ style={inputEdited ? S.triggerButtonEdited : S.triggerButton}+ disabled={snap.indirect}+ aria-label={`Edit ${getTokenLabel(tokenName)} (${mode}) — current value: ${activeHexWithAlpha}`}>+ <span+ style={{+ ...S.swatchInline,+ background: activeHexWithAlpha || '#000000',+ }}+ aria-hidden="true"+ />+ <span style={S.triggerLabel}>{inputDisplay}</span>+ </button>+ </XDSPopover>+ {override ? (+ <XDSButton+ label="reset"+ variant="ghost"+ size="sm"+ onClick={onReset}+ />+ ) : match &&+ (match.verdict === 'near' || match.verdict === 'off') ? (+ // "Snap to nearest ramp step" — surfaces the auto-detected+ // closest match as a one-click action so the user doesn't+ // have to open the popover and pick the dropdowns manually+ // when they just want to round the row to its closest ramp.+ // Only shown for `near` / `off` rows since `exact` / `snapped`+ // rows are already on-ramp and `edited` rows show `reset`+ // instead.+ //+ // Original alpha is preserved through the snap — committing+ // a snap on a 10%-alpha overlay token writes the ramp+ // swatch with `1A` (10%) appended, not the bare 6-digit hex.+ <XDSButton+ label="snap"+ variant="ghost"+ size="sm"+ tooltip={+ activeAlpha < 1+ ? `Snap to ${match.rampName} T${match.tone} · ${Math.round(activeAlpha * 100)}% (ΔE ${match.deltaE.toFixed(1)})`+ : `Snap to ${match.rampName} T${match.tone} (ΔE ${match.deltaE.toFixed(1)})`+ }+ onClick={() =>+ onPickPalette(match.rampName, match.tone as ToneStep, activeAlpha)+ }+ />+ ) : null}+ </div>+ </div>+ );+}++// =============================================================================+// Editor popover content — rendered inside <XDSPopover> as the `content` prop+// =============================================================================++interface EditorPopoverContentProps {+ mode: Mode;+ tokenName: string;+ /** Base 6-digit hex, no alpha. Alpha is supplied separately via+ * `currentAlpha` so we can mix and match. */+ currentHex: string;+ /** Original alpha (0-1, default 1). Pre-fills the alpha control on+ * open so transparency round-trips through the popover. */+ currentAlpha: number;+ override: ModeOverride | undefined;+ initialTab: 'custom' | 'palette';+ rampSeeds: RampSeed[];+ paletteHint: {rampName: string; tone: ToneStep} | null;+ onPickPalette: (rampName: string, tone: ToneStep, alpha?: number) => void;+ onPickCustom: (hex: string) => void;+}++/**+ * Body of the editor popover. The popover chrome (positioning, outside-+ * click, Esc, focus management) is provided by `XDSPopover`; this is just+ * the content that renders inside.+ *+ * Both tabs commit edits live — picking a new tone or dragging the color+ * picker fires the appropriate `onPick*` callback immediately, and the+ * parent row closes the popover after a successful pick.+ */+function EditorPopoverContent({+ mode,+ tokenName,+ currentHex,+ currentAlpha,+ override,+ initialTab,+ rampSeeds,+ paletteHint,+ onPickPalette,+ onPickCustom,+}: EditorPopoverContentProps) {+ const [tab, setTab] = useState<'custom' | 'palette'>(initialTab);++ // Lift the in-progress selections out of the tabs so the preview+ // swatch can reflect "what would this commit produce?" rather than+ // the row's current value. Without this, opening the popover on a+ // near/off row shows the auto-detected ramp+tone in the dropdowns+ // (which the user sees as a *suggestion*) but the preview shows the+ // current source color — the two get visually out of sync.+ const initialPaletteRamp =+ override?.kind === 'palette'+ ? override.rampName+ : paletteHint?.rampName ?? rampSeeds[0]?.name ?? '';+ const initialPaletteTone = (override?.kind === 'palette'+ ? override.tone+ : paletteHint?.tone ?? 50) as ToneStep;+ const [paletteRamp, setPaletteRamp] = useState<string>(initialPaletteRamp);+ const [paletteTone, setPaletteTone] = useState<ToneStep>(initialPaletteTone);+ // Editable alpha lives at the popover level so both tabs can mutate+ // it independently of the underlying base hex / ramp+tone selection.+ // Initialised to the row's current alpha so the percent input opens+ // pre-filled with the existing transparency. Stored as a 0-100+ // integer (matches the input's units) and converted to 0-1 only+ // when emitted to onPick callbacks / preview composition.+ const [palettePct, setPalettePct] = useState<number>(+ Math.round(currentAlpha * 100),+ );+ // Custom tab draft starts in pretty form (`'#hex N%'`) so the input+ // shows the alpha suffix on open — keeps the round-trip consistent+ // with what the row's trigger label displays.+ const [customDraft, setCustomDraft] = useState<string>(+ formatHexWithAlpha(currentHex, currentAlpha),+ );+ const [customPct, setCustomPct] = useState<number>(+ Math.round(currentAlpha * 100),+ );++ // Resolved hex for the swatch — computed from whichever tab is+ // active and always carries the active alpha so the preview swatch+ // shows transparency accurately. Palette tab → ramp+tone resolved via+ // the canonical generator + palettePct. Custom tab → user's typed+ // draft + customPct (the input may also embed alpha via the `'#hex N%'`+ // syntax; we honour that when present, otherwise apply customPct).+ const seedForRamp = rampSeeds.find(s => s.name === paletteRamp);+ const previewHex = (() => {+ if (tab === 'palette' && seedForRamp) {+ const baseHex = resolveOverrideHex(seedForRamp, paletteTone, mode);+ return composeAlphaHex(baseHex, palettePct / 100);+ }+ if (isValidHex(customDraft)) {+ const parsed = parseHexWithAlpha(customDraft);+ // The input's embedded alpha (if any) wins over the stepper —+ // typing `'#hex 25%'` is a more direct gesture than spinning the+ // separate Opacity input. They're kept in sync via setCustomPct+ // when the input string includes a percent.+ return composeAlphaHex(parsed.hex, parsed.alpha);+ }+ return composeAlphaHex(currentHex, customPct / 100);+ })();++ return (+ <XDSVStack gap={3} style={{padding: 4, minWidth: 0}}>+ <XDSTabList+ value={tab}+ onChange={v => setTab(v as 'custom' | 'palette')}+ layout="fill"+ size="sm"+ hasDivider>+ <XDSTab value="custom" label="Custom" />+ <XDSTab value="palette" label="Palette" />+ </XDSTabList>+ {/* Live preview reflects the in-progress selection, NOT the row's+ current value. So when the user adjusts a dropdown, the swatch+ updates to show what committing would produce — even before+ they actually pick. */}+ <div+ style={{+ width: '100%',+ height: 48,+ borderRadius: 8,+ border: '1px solid var(--color-border-emphasized)',+ background: previewHex,+ }}+ aria-label={`Preview: ${previewHex}`}+ />+ {tab === 'custom' ? (+ <CustomTab+ currentHex={composeAlphaHex(currentHex, currentAlpha)}+ draft={customDraft}+ setDraft={(next: string) => {+ setCustomDraft(next);+ // Keep the Opacity stepper in sync when the user types a+ // value that embeds alpha — otherwise the two affordances+ // could fall out of agreement and confuse the preview.+ if (isValidHex(next)) {+ const parsed = parseHexWithAlpha(next);+ setCustomPct(Math.round(parsed.alpha * 100));+ }+ }}+ alphaPct={customPct}+ setAlphaPct={setCustomPct}+ mode={mode}+ tokenName={tokenName}+ onPick={onPickCustom}+ />+ ) : (+ <PaletteTab+ rampSeeds={rampSeeds}+ mode={mode}+ tokenName={tokenName}+ rampName={paletteRamp}+ setRampName={setPaletteRamp}+ tone={paletteTone}+ setTone={setPaletteTone}+ alphaPct={palettePct}+ setAlphaPct={setPalettePct}+ onPick={(rampName, tone, alphaOverride) =>+ onPickPalette(+ rampName,+ tone,+ alphaOverride ?? palettePct / 100,+ )+ }+ />+ )}+ </XDSVStack>+ );+}++function CustomTab({+ currentHex,+ draft,+ setDraft,+ alphaPct,+ setAlphaPct,+ mode,+ tokenName,+ onPick,+}: {+ currentHex: string;+ /** Controlled draft hex — lives in EditorPopoverContent so the+ * preview swatch can react to typing without committing. */+ draft: string;+ setDraft: (value: string) => void;+ /** Controlled alpha percentage (0-100). Round-trips with the alpha+ * embedded in `draft` (typing `'#hex 25%'` updates this too). */+ alphaPct: number;+ setAlphaPct: (next: number) => void;+ mode: Mode;+ tokenName: string;+ onPick: (hex: string) => void;+}) {+ // Hidden native color input — opened programmatically when the+ // start-icon swatch inside the hex field is clicked. We keep the+ // visible affordance to a single text-style input and tuck the OS+ // color picker behind a small clickable swatch glyph (matches the+ // Figma / Linear pattern for hex+picker hybrid fields).+ const colorInputRef = useRef<HTMLInputElement | null>(null);+ const openNativePicker = () => {+ const el = colorInputRef.current;+ if (!el) return;+ if (typeof el.showPicker === 'function') {+ el.showPicker();+ } else {+ el.click();+ }+ };+ // Currently-resolved swatch chip color — alpha-baked so the chip+ // matches the typed value's transparency (matches Figma / Linear+ // hybrid hex+picker fields). The OS color picker only handles+ // 6-digit hex, so dragging the picker preserves the input's alpha+ // while updating the base color.+ const draftParsed = isValidHex(draft)+ ? parseHexWithAlpha(draft)+ : parseHexWithAlpha(currentHex);+ const swatchColor = composeAlphaHex(draftParsed.hex, draftParsed.alpha);++ return (+ <XDSVStack gap={2}>+ <XDSHStack gap={2} vAlign="center">+ <XDSText type="supporting" color="secondary" style={{minWidth: 48}}>+ Hex+ </XDSText>+ <div style={{flex: 1, position: 'relative'}}>+ <XDSTextInput+ label={`Hex value for ${tokenName} (${mode})`}+ isLabelHidden+ size="sm"+ value={draft}+ onChange={(next: string) => setDraft(next)}+ onEnter={() => {+ if (isValidHex(draft)) {+ // Compose the typed hex with the current alpha percent+ // so a value of `'#abcdef'` (no inline alpha) still+ // commits with the popover's Opacity stepper applied.+ const parsed = parseHexWithAlpha(draft);+ const next = formatHexWithAlpha(parsed.hex, alphaPct / 100);+ onPick(next);+ } else {+ setDraft(formatHexWithAlpha(currentHex, alphaPct / 100));+ }+ }}+ placeholder="#000000 100%"+ startIcon={+ // Clickable swatch chip inside the input. `aria-haspopup`+ // signals the OS color picker affordance to assistive tech.+ <button+ type="button"+ onClick={e => {+ // The wrapper steals click → focus the input. We+ // stop propagation so clicking the swatch doesn't+ // also yank focus into the text field.+ e.stopPropagation();+ openNativePicker();+ }}+ aria-label={`Open color picker for ${tokenName} (${mode})`}+ aria-haspopup="dialog"+ style={{+ appearance: 'none',+ width: 18,+ height: 18,+ padding: 0,+ borderRadius: 4,+ border: '1px solid var(--color-border-emphasized)',+ background: swatchColor,+ cursor: 'pointer',+ display: 'inline-block',+ }}+ />+ }+ />+ {/* Hidden color input — receives the programmatic showPicker()+ call so the OS color wheel pops up where the user clicked+ the swatch chip. The OS picker only emits 6-digit hex; we+ preserve the input's alpha by re-rendering the draft in+ pretty form (`'#newhex N%'`) and routing that through onPick. */}+ <input+ ref={colorInputRef}+ type="color"+ value={normalizeHex(draftParsed.hex)}+ onChange={e => {+ const nextBase = normalizeHex(e.target.value);+ const nextDraft = formatHexWithAlpha(nextBase, alphaPct / 100);+ setDraft(nextDraft);+ onPick(nextDraft);+ }}+ aria-hidden="true"+ tabIndex={-1}+ style={{+ position: 'absolute',+ inset: 0,+ width: 0,+ height: 0,+ opacity: 0,+ border: 'none',+ padding: 0,+ margin: 0,+ pointerEvents: 'none',+ }}+ />+ </div>+ </XDSHStack>+ <AlphaInput+ alphaPct={alphaPct}+ setAlphaPct={(nextPct: number) => {+ setAlphaPct(nextPct);+ // Re-emit the draft so the input's pretty form stays in+ // sync with the stepper, AND commit the change live so the+ // preview surface updates without a separate Enter press.+ if (isValidHex(draft)) {+ const parsed = parseHexWithAlpha(draft);+ const nextDraft = formatHexWithAlpha(parsed.hex, nextPct / 100);+ setDraft(nextDraft);+ onPick(nextDraft);+ }+ }}+ labelFor={`Opacity for ${tokenName} (${mode})`}+ />+ </XDSVStack>+ );+}++/**+ * Numeric Opacity stepper input shared by both popover tabs. Renders+ * as `[Opacity %] [_ 50 _]` — XDSTextInput in number mode with native+ * step controls + a trailing "%" affordance. Range clamped 0-100;+ * non-numeric input snaps back to the current value.+ */+function AlphaInput({+ alphaPct,+ setAlphaPct,+ labelFor,+}: {+ alphaPct: number;+ setAlphaPct: (next: number) => void;+ labelFor: string;+}) {+ const [draft, setDraft] = useState<string>(String(alphaPct));+ // Keep the local draft in sync when the parent's alpha changes+ // (e.g. user typed `'#hex 30%'` in the Hex input above).+ useEffect(() => {+ setDraft(String(alphaPct));+ }, [alphaPct]);++ const commit = (raw: string) => {+ const n = Number(raw.replace(/%$/, '').trim());+ if (!Number.isFinite(n)) {+ setDraft(String(alphaPct));+ return;+ }+ const clamped = Math.max(0, Math.min(100, Math.round(n)));+ setDraft(String(clamped));+ if (clamped !== alphaPct) setAlphaPct(clamped);+ };++ return (+ <XDSHStack gap={2} vAlign="center">+ <XDSText type="supporting" color="secondary" style={{minWidth: 48}}>+ Opacity+ </XDSText>+ {/* Stretch to fill the column so the input lines up with the+ Ramp/Tone selects above (which use flex: 1, maxWidth: none). */}+ <div+ style={{+ flex: 1,+ display: 'flex',+ alignItems: 'center',+ gap: 4,+ position: 'relative',+ }}>+ <input+ type="number"+ min={0}+ max={100}+ step={1}+ value={draft}+ aria-label={labelFor}+ onChange={e => setDraft(e.target.value)}+ onBlur={e => commit(e.target.value)}+ onKeyDown={e => {+ if (e.key === 'Enter') {+ commit((e.target as HTMLInputElement).value);+ }+ }}+ style={{+ flex: 1,+ width: '100%',+ border: '1px solid var(--color-border)',+ borderRadius: 4,+ padding: '4px 22px 4px 6px',+ fontFamily: MONO,+ fontSize: 11,+ background: 'var(--color-background-body)',+ color: 'var(--color-text-primary)',+ outline: 'none',+ }}+ />+ {/* Trailing `%` glyph rendered as an absolutely-positioned+ suffix inside the input's right padding so it doesn't add+ its own column width — keeps the input edge aligned with+ the Ramp/Tone selects above. */}+ <span+ aria-hidden="true"+ style={{+ position: 'absolute',+ right: 8,+ top: '50%',+ transform: 'translateY(-50%)',+ fontFamily: 'var(--font-family-body)',+ fontSize: 11,+ color: 'var(--color-text-secondary)',+ pointerEvents: 'none',+ }}>+ %+ </span>+ </div>+ </XDSHStack>+ );+}++function PaletteTab({+ rampSeeds,+ mode,+ tokenName,+ rampName,+ setRampName,+ tone,+ setTone,+ alphaPct,+ setAlphaPct,+ onPick,+}: {+ rampSeeds: RampSeed[];+ mode: Mode;+ tokenName: string;+ /** Controlled selections live in EditorPopoverContent so the+ * preview swatch can react to dropdown changes without committing. */+ rampName: string;+ setRampName: (value: string) => void;+ tone: ToneStep;+ setTone: (value: ToneStep) => void;+ /** Controlled alpha percentage (0-100). Editing it commits the+ * current ramp+tone with the new alpha so the preview updates live. */+ alphaPct: number;+ setAlphaPct: (next: number) => void;+ /** Third arg (`alphaOverride` 0-1) lets the Opacity stepper pass the+ * *new* alpha alongside the unchanged ramp+tone, side-stepping the+ * React state-flush race: by the time `onPick` runs from the+ * Opacity handler, the parent's `palettePct` closure is still the+ * OLD value. The optional override wins when supplied. */+ onPick: (rampName: string, tone: ToneStep, alphaOverride?: number) => void;+}) {+ // Native <select>s here rather than XDSDropdownMenu — the menu+ // component is heavier than needed for a 10-item ramp / 21-step tone+ // picker, and the native control gives us free keyboard navigation.+ return (+ <XDSVStack gap={2}>+ <XDSHStack gap={2} vAlign="center">+ <XDSText type="supporting" color="secondary" style={{minWidth: 48}}>+ Ramp+ </XDSText>+ <select+ value={rampName}+ onChange={e => {+ setRampName(e.target.value);+ onPick(e.target.value, tone);+ }}+ style={{...S.select, flex: 1, maxWidth: 'none'}}+ aria-label={`Ramp for ${tokenName} (${mode})`}>+ {rampSeeds.map(s => (+ <option key={s.name} value={s.name}>+ {s.name}+ </option>+ ))}+ </select>+ </XDSHStack>+ <XDSHStack gap={2} vAlign="center">+ <XDSText type="supporting" color="secondary" style={{minWidth: 48}}>+ Tone+ </XDSText>+ <select+ value={tone}+ onChange={e => {+ const next = Number(e.target.value) as ToneStep;+ setTone(next);+ onPick(rampName, next);+ }}+ style={{...S.select, flex: 1, maxWidth: 'none'}}+ aria-label={`Tone for ${tokenName} (${mode})`}>+ {TONE_STEPS.map(t => (+ <option key={t} value={t}>+ T{t}+ </option>+ ))}+ </select>+ </XDSHStack>+ <AlphaInput+ alphaPct={alphaPct}+ setAlphaPct={(nextPct: number) => {+ setAlphaPct(nextPct);+ // Pass the new alpha through onPick's third arg so the parent+ // commits the override with the just-set value, not the stale+ // closure-captured `palettePct`.+ onPick(rampName, tone, nextPct / 100);+ }}+ labelFor={`Opacity for ${tokenName} (${mode})`}+ />+ </XDSVStack>+ );+}+diff --git a/apps/sandbox/src/components/themePreview/colorCategories.ts b/apps/sandbox/src/components/themePreview/colorCategories.tsnew file mode 100644index 0000000000..258b17e6d0--- /dev/null+++ b/apps/sandbox/src/components/themePreview/colorCategories.ts@@ -0,0 +1,215 @@+/**+ * Color token categories — copied verbatim from the docsite Theme Editor+ * (`apps/sandbox/src/app/(fullscreen)/pages/docsite/ThemeEditorView.tsx`)+ * so the audit drawer groups tokens exactly the way that surface does.+ *+ * Keeping the exact category names + ordering (rather than auto-bucketing+ * by token-name prefix) means the audit experience is visually identical+ * to the editor a theme author already knows.+ */++/**+ * Curated category buckets. Tokens not listed here fall through to a+ * catch-all "Other" category at render time, so the audit drawer never+ * silently hides a color token regardless of what core adds or what a+ * theme defines on top.+ *+ * Where this list extends the docsite editor's set:+ * - "Core Semantic" gains `--color-on-accent` (sibling of `--color-accent`)+ * - "Text" gains `--color-on-light` (sibling of `--color-on-dark`)+ * - "Icon" gains `--color-icon-accent` (sibling of the rest)+ * - "Surface Variants" gains the inverted backgrounds+ * (`--color-background-inverted`, `--color-background-error-inverted`)+ * - "Status/Sentiment" gains the on-* status tokens+ * (`--color-on-success/error/warning`)+ */+export const COLOR_CATEGORIES = {+ 'Core Semantic': [+ '--color-accent',+ '--color-accent-muted',+ '--color-on-accent',+ '--color-neutral',+ '--color-overlay',+ ],+ 'Interactive States': [+ '--color-overlay-hover',+ '--color-overlay-pressed',+ '--color-accent',+ '--color-error',+ '--color-success',+ '--color-warning',+ '--color-background-muted',+ ],+ Text: [+ '--color-text-primary',+ '--color-text-secondary',+ '--color-text-disabled',+ '--color-text-accent',+ '--color-on-dark',+ '--color-on-light',+ ],+ Icon: [+ '--color-icon-accent',+ '--color-icon-primary',+ '--color-icon-secondary',+ '--color-icon-disabled',+ ],+ 'Surface Variants': [+ '--color-background-surface',+ '--color-background-body',+ '--color-background-card',+ '--color-background-popover',+ '--color-background-inverted',+ '--color-background-error-inverted',+ ],+ 'Status/Sentiment': [+ '--color-success',+ '--color-success-muted',+ '--color-on-success',+ '--color-error',+ '--color-error-muted',+ '--color-on-error',+ '--color-warning',+ '--color-warning-muted',+ '--color-on-warning',+ ],+ Divider: ['--color-border', '--color-border-emphasized'],+ Effects: ['--color-skeleton', '--color-shadow', '--color-tint-hover'],+ 'Palette: Blue': [+ '--color-background-blue',+ '--color-border-blue',+ '--color-icon-blue',+ '--color-text-blue',+ ],+ 'Palette: Green': [+ '--color-background-green',+ '--color-border-green',+ '--color-icon-green',+ '--color-text-green',+ ],+ 'Palette: Red': [+ '--color-background-red',+ '--color-border-red',+ '--color-icon-red',+ '--color-text-red',+ ],+ 'Palette: Yellow': [+ '--color-background-yellow',+ '--color-border-yellow',+ '--color-icon-yellow',+ '--color-text-yellow',+ ],+ 'Palette: Orange': [+ '--color-background-orange',+ '--color-border-orange',+ '--color-icon-orange',+ '--color-text-orange',+ ],+ 'Palette: Purple': [+ '--color-background-purple',+ '--color-border-purple',+ '--color-icon-purple',+ '--color-text-purple',+ ],+ 'Palette: Pink': [+ '--color-background-pink',+ '--color-border-pink',+ '--color-icon-pink',+ '--color-text-pink',+ ],+ 'Palette: Teal': [+ '--color-background-teal',+ '--color-border-teal',+ '--color-icon-teal',+ '--color-text-teal',+ ],+ 'Palette: Cyan': [+ '--color-background-cyan',+ '--color-border-cyan',+ '--color-icon-cyan',+ '--color-text-cyan',+ ],+ 'Palette: Gray': [+ '--color-background-gray',+ '--color-border-gray',+ '--color-icon-gray',+ '--color-text-gray',+ ],+} as const;++/** Bucket name for theme-only color tokens that aren't in the curated+ * categories above (custom tokens a theme adds, future core tokens we+ * haven't slotted yet). */+export const OTHER_CATEGORY = 'Other Colors';++export type ColorCategoryName = keyof typeof COLOR_CATEGORIES;++/**+ * Convert a CSS custom property name into a human label.+ * Mirrors `getTokenLabel` in the docsite editor:+ * `--color-accent` → "Color Accent"+ * `--color-text-primary` → "Color Text Primary"+ */+export function getTokenLabel(tokenName: string): string {+ return tokenName+ .replace(/^--/, '')+ .replace(/-/g, ' ')+ .replace(/\b\w/g, c => c.toUpperCase());+}++export type CategorizedTokens = Array<{+ category: ColorCategoryName | typeof OTHER_CATEGORY;+ tokens: string[];+}>;++/**+ * Iterate categories in declaration order, deduplicating any tokens that+ * already appeared in an earlier category (some tokens are intentionally+ * cross-listed — e.g. `--color-accent` shows up under both Core Semantic+ * and Interactive States; the Inspector shows each token in its first+ * home only).+ *+ * When `knownTokens` is provided, any color-typed entry not covered by+ * the curated categories falls into a trailing "Other Colors" bucket.+ * This guarantees the audit drawer never silently hides a token regardless+ * of what core adds or what custom tokens a theme defines.+ *+ * Syntax-highlighting tokens (`--color-syntax-*`) are deliberately+ * excluded — they're better edited via the dedicated+ * `defineSyntaxTheme()` API rather than as raw color tokens, and+ * surfacing them here would create a confusing second source of truth.+ */+export function getCategorizedColorTokens(knownTokens?: Iterable<string>): CategorizedTokens {+ const seen = new Set<string>();+ const result: CategorizedTokens = [];+ for (const [category, tokenNames] of Object.entries(COLOR_CATEGORIES) as Array<+ [ColorCategoryName, readonly string[]]+ >) {+ const uniqueTokens = tokenNames.filter(t => {+ if (seen.has(t)) return false;+ seen.add(t);+ return true;+ });+ if (uniqueTokens.length === 0) continue;+ result.push({category, tokens: [...uniqueTokens]});+ }++ if (knownTokens) {+ // Any color-typed entry not in a curated category lands in "Other+ // Colors". Syntax tokens are filtered out entirely — see the JSDoc.+ const leftovers: string[] = [];+ for (const t of knownTokens) {+ if (!t.startsWith('--color-')) continue;+ if (t.startsWith('--color-syntax-')) continue;+ if (seen.has(t)) continue;+ seen.add(t);+ leftovers.push(t);+ }+ leftovers.sort();+ if (leftovers.length > 0) {+ result.push({category: OTHER_CATEGORY, tokens: leftovers});+ }+ }++ return result;+}diff --git a/apps/sandbox/src/components/themePreview/colorMath.ts b/apps/sandbox/src/components/themePreview/colorMath.tsnew file mode 100644index 0000000000..a06221a286--- /dev/null+++ b/apps/sandbox/src/components/themePreview/colorMath.ts@@ -0,0 +1,390 @@+/**+ * Shared color math for the theme preview + audit panel.+ *+ * Originally inlined in ThemePalettePreview.tsx — extracted so the+ * "snap-to-tonal-step" detector in the audit drawer can reuse the same+ * sRGB → linear → XYZ → Lab pipeline that builds the visible ramps.+ *+ * Color spaces used:+ * - sRGB: input/output (hex strings the rest of the app speaks)+ * - Linear RGB: gamma-stripped sRGB (so light blends linearly)+ * - XYZ (D65): canonical CIE space, intermediate+ * - Lab (D65): perceptually-uniform; ΔE = euclidean distance is "good enough"+ * for design tokens (~ΔE 76; we don't need ΔE2000 for swatch matching).+ *+ * "HCT" here is approximate: hue/chroma derived from Lab a/b, tone = L*.+ * It is NOT the full Material HCT (CAM16-based). It's the same approximation+ * the existing tonal preview already uses, kept consistent so what the audit+ * drawer reports matches what the visible ramps render.+ */++export type Rgb = [number, number, number];++export interface HCT {+ /** Hue, 0–360° (Lab a/b → polar angle) */+ hue: number;+ /** Chroma, sqrt(a² + b²) — distance from gray axis in Lab */+ chroma: number;+ /** Tone, equivalent to Lab L* (0–100) */+ tone: number;+}++// =============================================================================+// sRGB ↔ linear ↔ XYZ ↔ Lab+// =============================================================================++export function hexToRgb(hex: string): Rgb {+ const h = hex.replace('#', '').slice(0, 6);+ const full = h.length === 3 ? h[0] + h[0] + h[1] + h[1] + h[2] + h[2] : h;+ const n = parseInt(full, 16);+ return [(n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff];+}++export function rgbToHex(r: number, g: number, b: number): string {+ const clamp = (n: number) =>+ Math.max(0, Math.min(255, Math.round(n)))+ .toString(16)+ .padStart(2, '0');+ return '#' + clamp(r) + clamp(g) + clamp(b);+}++export 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);+}++export 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)));+}++export function linearRgbToXyz(r: number, g: number, b: number): Rgb {+ 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,+ ];+}++export function xyzToLinearRgb(x: number, y: number, z: number): Rgb {+ 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,+ ];+}++const D65: Rgb = [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);+}++export function xyzToLab(x: number, y: number, z: number): Rgb {+ const fx = labF(x / D65[0]);+ const fy = labF(y / D65[1]);+ const fz = labF(z / D65[2]);+ return [116 * fy - 16, 500 * (fx - fy), 200 * (fy - fz)];+}++export function labToXyz(L: number, a: number, b: number): Rgb {+ const fy = (L + 16) / 116;+ const fx = a / 500 + fy;+ const fz = fy - b / 200;+ return [labFInv(fx) * D65[0], labFInv(fy) * D65[1], labFInv(fz) * D65[2]];+}++export function hexToLab(hex: string): Rgb {+ const [r, g, b] = hexToRgb(hex);+ const [x, y, z] = linearRgbToXyz(srgbToLinear(r), srgbToLinear(g), srgbToLinear(b));+ return xyzToLab(x, y, z);+}++// =============================================================================+// HCT (approximate) — same approximation the visible tonal ramps use+// =============================================================================++export function hexToHct(hex: string): HCT {+ const [L, a, bL] = hexToLab(hex);+ let hue = (Math.atan2(bL, a) * 180) / Math.PI;+ if (hue < 0) hue += 360;+ return {+ hue,+ chroma: Math.sqrt(a * a + bL * bL),+ tone: Math.max(0, Math.min(100, L)),+ };+}++/**+ * Inverse of hexToHct — solves Lab → sRGB and binary-searches chroma so+ * the result lands inside the sRGB gamut (high-chroma tones at the dark/light+ * extremes can't be expressed without clipping; we back off chroma until they+ * round-trip cleanly through sRGB).+ */+export function hctToHex({hue, chroma, tone}: HCT): string {+ 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 '#' + [g, g, g].map(c => c.toString(16).padStart(2, '0')).join('');+ }+ let lo = 0;+ let hi = chroma;+ let 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;+ const 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);+ const g = linearToSrgb(lg);+ const 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 = '#' + [r, g, bv].map(c => c.toString(16).padStart(2, '0')).join('');+ lo = mid;+ } else {+ hi = mid;+ }+ }+ return best;+}++// =============================================================================+// Tonal ramps — must mirror the visible ramps in ThemePalettePreview+// =============================================================================++export const TONE_STEPS = [+ 0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95,+ 100,+] as const;++export type ToneStep = (typeof TONE_STEPS)[number];++/**+ * Light-mode tonal palette: 21 perceptually-uniform tones (T0 → T100).+ * Low-tone chroma is boosted (1 + (50 - tone) / 40) so dark colored text+ * stays visibly hued; capped at chroma × 1.8 so peak saturation doesn't+ * exceed what the gamut binary-search inside hctToHex can reach.+ */+export function tonalPalette(hue: number, chroma: number): Record<number, string> {+ const result: Record<number, string> = {};+ const maxChroma = chroma * 1.8;+ for (const t of TONE_STEPS) {+ const boost = t < 50 ? 1 + (50 - t) / 40 : 1;+ result[t] = hctToHex({+ hue,+ chroma: Math.min(chroma * boost, maxChroma),+ tone: t,+ });+ }+ return result;+}++/**+ * Dark-mode tonal palette per the audit rubric in issue #2150 §4:+ * mid-tones lift +5 (tapered between T80/T95), chroma × 0.85 across the+ * ramp so saturated stops don't vibrate against a dark canvas.+ */+const DARK_TONE_LIFT = 5;+const DARK_LIFT_TAPER_START = 80;+const DARK_LIFT_TAPER_END = 95;+const DARK_CHROMA_FACTOR = 0.85;++export function darkTonalPalette(+ hue: number,+ chroma: number,+): Record<number, string> {+ const adjustedChroma = chroma * DARK_CHROMA_FACTOR;+ const maxChroma = adjustedChroma * 1.8;+ const result: Record<number, string> = {};+ for (const t of TONE_STEPS) {+ let lift = DARK_TONE_LIFT;+ if (t >= DARK_LIFT_TAPER_END) {+ lift = 0;+ } else if (t > DARK_LIFT_TAPER_START) {+ const ratio =+ (DARK_LIFT_TAPER_END - t) /+ (DARK_LIFT_TAPER_END - DARK_LIFT_TAPER_START);+ lift = DARK_TONE_LIFT * ratio;+ }+ const liftedTone = Math.min(100, t + lift);+ const boost = liftedTone < 50 ? 1 + (50 - liftedTone) / 40 : 1;+ result[t] = hctToHex({+ hue,+ chroma: Math.min(adjustedChroma * boost, maxChroma),+ tone: liftedTone,+ });+ }+ return result;+}++export type Mode = 'light' | 'dark';++export function tonalPaletteForMode(+ hue: number,+ chroma: number,+ mode: Mode,+): Record<number, string> {+ return mode === 'dark'+ ? darkTonalPalette(hue, chroma)+ : tonalPalette(hue, chroma);+}++// =============================================================================+// ΔE (CIE76) — close-enough perceptual distance for swatch matching+// =============================================================================++/**+ * Plain euclidean distance in Lab. CIE76 is intentional: ΔE2000 is more+ * accurate but adds enough complexity that for "is this token snapped to+ * a ramp step?" we'd just be reporting the same answers with extra digits.+ * The thresholds in deltaEVerdict are calibrated for CIE76.+ */+export function deltaE(labA: Rgb, labB: Rgb): number {+ const dL = labA[0] - labB[0];+ const da = labA[1] - labB[1];+ const db = labA[2] - labB[2];+ return Math.sqrt(dL * dL + da * da + db * db);+}++export function deltaEHex(a: string, b: string): number {+ return deltaE(hexToLab(a), hexToLab(b));+}++/**+ * Bucket a ΔE into a human verdict.+ * Calibrated for "did a designer pick this off a ramp on purpose?":+ * - ≤1.0 → exact: round-trip noise, indistinguishable+ * - ≤2.5 → snapped: visually identical, almost certainly intentional+ * - ≤5.0 → near: probably picked off the ramp then nudged+ * - >5.0 → off: free-form color, not on any ramp+ */+export type SnapVerdict = 'exact' | 'snapped' | 'near' | 'off';++export function deltaEVerdict(d: number): SnapVerdict {+ if (d <= 1.0) return 'exact';+ if (d <= 2.5) return 'snapped';+ if (d <= 5.0) return 'near';+ return 'off';+}++// =============================================================================+// Snap detection — find the closest tonal step across a set of ramps+// =============================================================================++export interface RampSeed {+ /** Display name shown in audit reports ("Blue", "Stone Neutral", etc.) */+ name: string;+ /** Source hex used to compute hue/chroma (the same input the visible ramp uses) */+ sourceHex: string;+ /** Optional semantic tag ("Success", "Error", …) — informational only */+ semantic?: string;+ /**+ * Optional precomputed canonical ramp — `{0: '#…', 5: '#…', …, 100: '#…'}`.+ *+ * When present, the snap detector uses these exact hex values for+ * matching instead of regenerating the ramp from `sourceHex` via the+ * HCT pipeline. Use this when a theme exports a hand-tuned palette+ * (e.g. stone's `stonePalettes.red`) that drifts from the pure HCT+ * generator's output by more than a couple of \u0394E units — without it,+ * tokens whose values come from the canonical ramp would show up as+ * "off-ramp" against the generator's slightly different ramp.+ *+ * Same per-mode shape: a single map covers BOTH light and dark+ * resolutions. The dark-mode generator's tone-lift / chroma-attenuation+ * transforms aren't applied — the supplied canonical values are+ * treated as authoritative for both modes.+ *+ * Permissive `string | number` keys/values match the shape of theme+ * palette exports like `stonePalettes.red` which carry both numeric+ * tone steps and metadata keys (`hue`, `chroma`); non-numeric keys+ * and non-string values are skipped at lookup time.+ */+ tones?: Readonly<Record<string | number, string | number>>;+}++export interface SnapMatch {+ rampName: string;+ /** Optional semantic the matched ramp carries ("Success" etc.) */+ rampSemantic?: string;+ tone: ToneStep;+ hex: string;+ deltaE: number;+ verdict: SnapVerdict;+}++/**+ * Find the closest tone step across `seeds` for `targetHex`.+ * Returns the single best match (lowest ΔE). When no ramps are provided+ * or the target is non-color, returns null.+ *+ * Uses the same per-mode ramp generator the preview uses so audit results+ * line up with the visible swatches the user sees on the page.+ */+export function findClosestRampStep(+ targetHex: string,+ seeds: RampSeed[],+ mode: Mode,+): SnapMatch | null {+ if (seeds.length === 0) return null;+ const targetLab = hexToLab(targetHex);+ let best: SnapMatch | null = null;+ for (const seed of seeds) {+ // Canonical ramp wins when supplied — themes with hand-tuned+ // ramps (stone, gothic, y2k, butter) drift from the pure HCT+ // generator by enough to flip on-ramp tokens to "near"/"off" if+ // we ignore the canonical values. See `RampSeed.tones` for+ // context. The canonical map's permissive `string | number` value+ // type means we filter to strings at lookup (the metadata keys+ // `hue` and `chroma` carry numeric values that we ignore here).+ let lookup: (t: number) => string | undefined;+ if (seed.tones) {+ const map = seed.tones;+ lookup = t => {+ const v = map[t];+ return typeof v === 'string' ? v : undefined;+ };+ } else {+ const {hue, chroma} = hexToHct(seed.sourceHex);+ const ramp = tonalPaletteForMode(hue, chroma, mode);+ lookup = t => ramp[t];+ }+ for (const t of TONE_STEPS) {+ const swatch = lookup(t);+ // Canonical ramps may be sparse (e.g. only 0/5/10/…/100). Skip+ // tone steps without a value rather than crashing on `undefined`.+ if (!swatch) continue;+ const d = deltaE(targetLab, hexToLab(swatch));+ if (best == null || d < best.deltaE) {+ best = {+ rampName: seed.name,+ rampSemantic: seed.semantic,+ tone: t,+ hex: swatch,+ deltaE: d,+ verdict: deltaEVerdict(d),+ };+ }+ }+ }+ return best;+}diff --git a/apps/sandbox/src/components/themePreview/themeAudit.ts b/apps/sandbox/src/components/themePreview/themeAudit.tsnew file mode 100644index 0000000000..8fc13c4fd4--- /dev/null+++ b/apps/sandbox/src/components/themePreview/themeAudit.ts@@ -0,0 +1,561 @@+/**+ * Theme audit logic.+ *+ * Two questions this module answers, both painful to eyeball from raw+ * theme source files:+ *+ * 1. "Which tokens did this theme actually change vs the XDS defaults?"+ * — diff `theme.tokens` against `xdsTokenDefaults` and bucket each+ * entry as unchanged / overridden / new.+ *+ * 2. "Did each color token snap to a step on a tonal ramp, or did the+ * author free-form it?"+ * — for every color-typed token, find the closest tone step across+ * the theme's tonal seeds (the same seeds the visible Tonal Palettes+ * section renders) and bucket the ΔE as exact / snapped / near / off.+ */++import type {XDSDefinedTheme} from '@xds/core/theme';+import {xdsTokenDefaults} from '@xds/core/theme';+import {+ findClosestRampStep,+ type Mode,+ type RampSeed,+ type SnapMatch,+} from './colorMath';++// =============================================================================+// Token categorization+// =============================================================================++/**+ * Top-level audit category for grouping tokens in the audit UI.+ *+ * Derived from token name prefix because that's how the defaults file+ * already groups them (`colorDefaults`, `radiusDefaults`, …) — the prefix+ * is the source of truth, not a separate registry that can drift.+ */+export type TokenCategory =+ | 'color'+ | 'background'+ | 'text'+ | 'border'+ | 'shadow'+ | 'spacing'+ | 'size'+ | 'radius'+ | 'typography'+ | 'motion'+ | 'syntax'+ | 'other';++const CATEGORY_ORDER: TokenCategory[] = [+ 'color',+ 'background',+ 'text',+ 'border',+ 'shadow',+ 'radius',+ 'spacing',+ 'size',+ 'typography',+ 'motion',+ 'syntax',+ 'other',+];++export function categorizeToken(name: string): TokenCategory {+ if (name.startsWith('--color-syntax-')) return 'syntax';+ if (name.startsWith('--color-background-')) return 'background';+ if (name.startsWith('--color-text-') || name.startsWith('--color-icon-')) {+ return 'text';+ }+ if (name.startsWith('--color-border-') || name === '--color-border' || name === '--color-border-emphasized') {+ return 'border';+ }+ if (name.startsWith('--color-')) return 'color';+ if (name.startsWith('--shadow-')) return 'shadow';+ if (name.startsWith('--radius-')) return 'radius';+ if (name.startsWith('--space-') || name.startsWith('--spacing-')) {+ return 'spacing';+ }+ if (name.startsWith('--size-')) return 'size';+ if (+ name.startsWith('--font-') ||+ name.startsWith('--text-') ||+ name.startsWith('--type-')+ ) {+ return 'typography';+ }+ if (+ name.startsWith('--duration-') ||+ name.startsWith('--ease-') ||+ name.startsWith('--transition-')+ ) {+ return 'motion';+ }+ return 'other';+}++// =============================================================================+// Token diff — overridden / unchanged / new vs xdsTokenDefaults+// =============================================================================++export type DiffStatus =+ /** Token name exists in defaults; theme value === default */+ | 'unchanged'+ /** Token name exists in defaults; theme value !== default */+ | 'overridden'+ /** Token name only exists in the theme (theme adds a token defaults didn't have) */+ | 'new'+ /** Token name only exists in defaults (theme inherited it; not strictly possible+ * with the current defineTheme since defaults are merged in, but kept for+ * symmetry if we ever audit the inverse) */+ | 'removed';++export interface TokenDiffEntry {+ name: string;+ category: TokenCategory;+ status: DiffStatus;+ /** Default value (if the token has one) */+ defaultValue?: string;+ /** Current theme value (if the theme defines it) */+ themeValue?: string;+}++export interface TokenDiff {+ entries: TokenDiffEntry[];+ /** Aggregate counts — handy for the toolbar badge */+ counts: Record<DiffStatus, number>;+ /** Per-category counts of overridden + new — used to drive the section badges */+ changedByCategory: Record<TokenCategory, number>;+}++/**+ * Build a full token diff vs xdsTokenDefaults.+ *+ * Note: defineTheme pre-seeds `theme.tokens` from base + generated ++ * explicit overrides, so every token defaults supplies will also appear on+ * `theme.tokens` — meaning "unchanged" rows are common. We keep them in+ * the result so the UI can offer a "show unchanged" toggle for the+ * exhaustive case where a theme author wants to confirm a default landed.+ */+export function diffThemeTokens(theme: XDSDefinedTheme): TokenDiff {+ const themeTokens = theme.tokens;+ const allKeys = new Set<string>([+ ...Object.keys(xdsTokenDefaults),+ ...Object.keys(themeTokens),+ ]);++ const entries: TokenDiffEntry[] = [];+ const counts: Record<DiffStatus, number> = {+ unchanged: 0,+ overridden: 0,+ new: 0,+ removed: 0,+ };+ const changedByCategory = {} as Record<TokenCategory, number>;+ for (const c of CATEGORY_ORDER) changedByCategory[c] = 0;++ for (const name of allKeys) {+ const defaultValue = xdsTokenDefaults[name];+ const themeValue = themeTokens[name];+ const category = categorizeToken(name);++ let status: DiffStatus;+ if (defaultValue == null && themeValue != null) {+ status = 'new';+ } else if (defaultValue != null && themeValue == null) {+ status = 'removed';+ } else if (defaultValue === themeValue) {+ status = 'unchanged';+ } else {+ status = 'overridden';+ }++ counts[status]++;+ if (status === 'overridden' || status === 'new') {+ changedByCategory[category]++;+ }++ entries.push({name, category, status, defaultValue, themeValue});+ }++ // Sort: changed first, then by category order, then alphabetically.+ // Putting "changed" tokens at the top is the common case the audit+ // panel exists for; unchanged are present mostly for completeness.+ const statusRank: Record<DiffStatus, number> = {+ overridden: 0,+ new: 1,+ removed: 2,+ unchanged: 3,+ };+ const categoryRank = (c: TokenCategory) => CATEGORY_ORDER.indexOf(c);+ entries.sort((a, b) => {+ if (statusRank[a.status] !== statusRank[b.status]) {+ return statusRank[a.status] - statusRank[b.status];+ }+ if (a.category !== b.category) {+ return categoryRank(a.category) - categoryRank(b.category);+ }+ return a.name.localeCompare(b.name);+ });++ return {entries, counts, changedByCategory};+}++// =============================================================================+// light-dark() parsing+// =============================================================================++/**+ * Pull [light, dark] hex values out of a token value.+ *+ * Token values come in three shapes:+ * - `light-dark(#fff, #000)` — the standard form generated by defineTheme+ * - `#aabbcc` (or rgba(...) etc.) — same value in both modes+ * - `var(--something)` — a reference; we can't resolve it statically and+ * return null/null. The audit UI flags these as "indirect."+ *+ * Hex+alpha forms (`#aabbccdd`) are accepted; alpha is dropped — we only+ * care about the base color for snap detection.+ */+const LIGHT_DARK_RE = /^light-dark\(\s*([^,]+?)\s*,\s*([^)]+?)\s*\)$/;+const HEX_RE = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;++export interface TokenColor {+ light: string | null;+ dark: string | null;+ /** True when value is a `var(--…)` reference we can't statically resolve */+ indirect: boolean;+ /**+ * Per-mode alpha (0-1). Defaults to 1 (fully opaque) when the value+ * has no alpha component. Used by the audit drawer + snap action to+ * preserve transparency end-to-end — a snap on a 10%-alpha overlay+ * commits the ramp swatch with `1A` (10%) appended.+ */+ alphaLight: number;+ alphaDark: number;+ /**+ * Convenience: `alphaLight < 1 || alphaDark < 1`. Saves the row UI+ * from re-checking each side when it just needs to know "should I+ * format this with a percent suffix?".+ */+ hasAlpha: boolean;+}++export function parseTokenColor(value: string | undefined): TokenColor {+ if (!value) {+ return {+ light: null,+ dark: null,+ indirect: false,+ alphaLight: 1,+ alphaDark: 1,+ hasAlpha: false,+ };+ }+ const trimmed = value.trim();++ if (trimmed.startsWith('var(')) {+ return {+ light: null,+ dark: null,+ indirect: true,+ alphaLight: 1,+ alphaDark: 1,+ hasAlpha: false,+ };+ }++ const ld = trimmed.match(LIGHT_DARK_RE);+ if (ld) {+ const alphaLight = extractAlpha(ld[1]);+ const alphaDark = extractAlpha(ld[2]);+ return {+ light: normalizeColorString(ld[1]),+ dark: normalizeColorString(ld[2]),+ indirect: false,+ alphaLight,+ alphaDark,+ hasAlpha: alphaLight < 1 || alphaDark < 1,+ };+ }++ const single = normalizeColorString(trimmed);+ const alpha = extractAlpha(trimmed);+ return {+ light: single,+ dark: single,+ indirect: false,+ alphaLight: alpha,+ alphaDark: alpha,+ hasAlpha: alpha < 1,+ };+}++/**+ * Extract the alpha channel from a CSS color expression as a 0-1 value.+ * Returns 1 (fully opaque) when the value has no alpha component or+ * when we can't parse it. Recognizes:+ * - 8-digit hex `#aabbccdd` (last two hex digits are the alpha channel)+ * - 4-digit hex `#abcd` (last digit is the alpha channel, doubled)+ * - `rgba(r,g,b,a)` form+ */+function extractAlpha(input: string): number {+ const v = input.trim();+ const hex8 = v.match(/^#([0-9a-fA-F]{6})([0-9a-fA-F]{2})$/);+ if (hex8) return parseInt(hex8[2], 16) / 255;+ const hex4 = v.match(/^#([0-9a-fA-F]{3})([0-9a-fA-F])$/);+ if (hex4) {+ const aChar = hex4[2];+ return parseInt(aChar + aChar, 16) / 255;+ }+ const rgba = v.match(+ /^rgba\(\s*\d+(?:\.\d+)?\s*,\s*\d+(?:\.\d+)?\s*,\s*\d+(?:\.\d+)?\s*,\s*([\d.]+)\s*\)$/i,+ );+ if (rgba) {+ const a = Number(rgba[1]);+ if (Number.isFinite(a)) return Math.max(0, Math.min(1, a));+ }+ return 1;+}++/**+ * Normalize a CSS color expression to a #rrggbb string (alpha dropped).+ * Returns null for color expressions we can't resolve cheaply (color-mix,+ * named colors other than black/white, etc.) — the audit UI surfaces these+ * as "skipped."+ */+function normalizeColorString(input: string): string | null {+ const v = input.trim();+ if (HEX_RE.test(v)) {+ if (v.length === 5) {+ // #rgba → #rrggbb (drop alpha)+ return ('#' + v[1] + v[1] + v[2] + v[2] + v[3] + v[3]).toLowerCase();+ }+ if (v.length === 4) {+ return ('#' + v[1] + v[1] + v[2] + v[2] + v[3] + v[3]).toLowerCase();+ }+ if (v.length === 9) return v.slice(0, 7).toLowerCase();+ return v.toLowerCase();+ }+ if (v === 'black') return '#000000';+ if (v === 'white') return '#ffffff';+ if (v === 'transparent') return null;+ // rgb()/rgba() - parse the three channels+ const rgbMatch = v.match(+ /^rgba?\(\s*(\d+(?:\.\d+)?)\s*[,\s]\s*(\d+(?:\.\d+)?)\s*[,\s]\s*(\d+(?:\.\d+)?)/,+ );+ if (rgbMatch) {+ const r = Math.round(Number(rgbMatch[1]));+ const g = Math.round(Number(rgbMatch[2]));+ const b = Math.round(Number(rgbMatch[3]));+ const hex = (n: number) =>+ Math.max(0, Math.min(255, n)).toString(16).padStart(2, '0');+ return ('#' + hex(r) + hex(g) + hex(b)).toLowerCase();+ }+ return null;+}++// =============================================================================+// Snap audit — closest tonal step for every color token+// =============================================================================++export interface SnapAuditEntry {+ name: string;+ category: TokenCategory;+ /** Per-mode resolved hex (null when unresolvable — indirect/color-mix/etc.) */+ light: string | null;+ dark: string | null;+ /** Per-mode alpha (0-1, 1 = fully opaque). Preserved through snap ++ * custom edits so transparency survives end-to-end. */+ alphaLight: number;+ alphaDark: number;+ /** Per-mode closest ramp match — base color only, alpha is layered+ * on at commit time. */+ lightMatch: SnapMatch | null;+ darkMatch: SnapMatch | null;+ /** True for `var(--…)` references that we couldn't resolve */+ indirect: boolean;+ /** Convenience: `alphaLight < 1 || alphaDark < 1`. */+ hasAlpha: boolean;+}++/**+ * Run snap audit across every color-ish token in the theme.+ * "Color-ish" = a token whose category is color/background/text/border AND+ * parses to a real hex (no var(), no color-mix). Everything else is filtered+ * out so the audit table stays focused on actionable rows.+ */+export function auditSnapToRamps(+ theme: XDSDefinedTheme,+ rampSeeds: RampSeed[],+): SnapAuditEntry[] {+ const out: SnapAuditEntry[] = [];+ // Every category whose tokens are *meant* to be a color literal. The+ // drawer needs a snap entry for every color-typed token (even+ // `syntax` highlighting tokens) so the row renderer can show a swatch+ // and editor for it; tokens that aren't colors (spacing/radius/etc)+ // stay excluded.+ const eligibleCategories: TokenCategory[] = [+ 'color',+ 'background',+ 'text',+ 'border',+ 'syntax',+ ];+ for (const [name, value] of Object.entries(theme.tokens)) {+ const category = categorizeToken(name);+ if (!eligibleCategories.includes(category)) continue;+ const {light, dark, indirect, alphaLight, alphaDark, hasAlpha} =+ parseTokenColor(value);+ if (!light && !dark && !indirect) continue;+ const lightMatch = light ? findClosestRampStep(light, rampSeeds, 'light') : null;+ const darkMatch = dark ? findClosestRampStep(dark, rampSeeds, 'dark') : null;+ out.push({+ name,+ category,+ light,+ dark,+ alphaLight,+ alphaDark,+ lightMatch,+ darkMatch,+ indirect,+ hasAlpha,+ });+ }+ // Sort: worst (off-ramp) first so the noisy rows surface to the top.+ // Within the same verdict, alphabetical for stable ordering.+ const verdictRank = (m: SnapMatch | null) =>+ m == null+ ? 99+ : {off: 0, near: 1, snapped: 2, exact: 3}[m.verdict];+ out.sort((a, b) => {+ const aWorst = Math.min(verdictRank(a.lightMatch), verdictRank(a.darkMatch));+ const bWorst = Math.min(verdictRank(b.lightMatch), verdictRank(b.darkMatch));+ if (aWorst !== bWorst) return aWorst - bWorst;+ return a.name.localeCompare(b.name);+ });+ return out;+}++// =============================================================================+// Tonal markers — which tone steps does this theme actually consume?+// =============================================================================++export interface TonalUsage {+ /** Token name */+ name: string;+ /** light or dark mode the snap matched in */+ mode: Mode;+ /** Verdict for this snap (drives marker color) */+ verdict: SnapMatch['verdict'];+ /** ΔE — for hover details */+ deltaE: number;+}++/**+ * Per-ramp, per-mode, per-tone map of which tokens consume that step.+ * Keyed: `${rampName} :: ${mode} :: ${tone}` → list of usages.+ *+ * Used by ThemePalettePreview to draw a marker on each tone step that any+ * theme token has snapped to (with hover showing the token list). Drives+ * an evidence-based "where do my tokens land?" view rather than the+ * existing hardcoded `usedTones = [15, 25, 80, 90]` list.+ */+export type TonalUsageMap = Record<string, TonalUsage[]>;++/**+ * Per-token overrides recognised by `buildTonalUsageMap`. The drawer's+ * override map matches this shape exactly; we accept a generic shape+ * here so this module doesn't have to import from themeOverrides.ts and+ * create a circular dep.+ *+ * The full ModeOverride is a discriminated union (palette | custom);+ * for marker purposes we only care about palette picks since custom+ * hexes aren't on a ramp by definition. Either side may be a custom+ * override and that side is simply ignored here.+ */+export interface TonalUsageModeOverride {+ /** Discriminator — only `'palette'` produces a marker. */+ kind: 'palette' | 'custom';+ rampName?: string;+ tone?: number;+}+export interface TonalUsageOverride {+ light?: TonalUsageModeOverride;+ dark?: TonalUsageModeOverride;+}++export function buildTonalUsageMap(+ audit: SnapAuditEntry[],+ /** Optional pending overrides — when provided, the override's ramp+tone+ * replaces the auto-detected snap match for that token. The marker+ * shows up as `verdict: 'snapped'` (the user explicitly placed it+ * there, so it can't be off-ramp by definition). */+ overrides?: Record<string, TonalUsageOverride>,+): TonalUsageMap {+ const map: TonalUsageMap = {};+ const push = (+ rampName: string,+ mode: Mode,+ tone: number,+ usage: TonalUsage,+ ) => {+ const k = `${rampName}::${mode}::${tone}`;+ if (!map[k]) map[k] = [];+ map[k].push(usage);+ };++ for (const e of audit) {+ const ov = overrides?.[e.name];+ // Light side: prefer a *palette* override, then fall back to the+ // auto-detected match when not off-ramp. Custom overrides bypass the+ // markers entirely (they're explicitly off-ramp by definition);+ // off-ramp tokens with no override also get no marker — there's+ // nowhere on the ramp to put one.+ if (ov?.light?.kind === 'palette' && ov.light.rampName && ov.light.tone != null) {+ push(ov.light.rampName, 'light', ov.light.tone, {+ name: e.name,+ mode: 'light',+ verdict: 'snapped',+ deltaE: 0,+ });+ } else if (!ov?.light && e.lightMatch && e.lightMatch.verdict !== 'off') {+ push(e.lightMatch.rampName, 'light', e.lightMatch.tone, {+ name: e.name,+ mode: 'light',+ verdict: e.lightMatch.verdict,+ deltaE: e.lightMatch.deltaE,+ });+ }+ if (ov?.dark?.kind === 'palette' && ov.dark.rampName && ov.dark.tone != null) {+ push(ov.dark.rampName, 'dark', ov.dark.tone, {+ name: e.name,+ mode: 'dark',+ verdict: 'snapped',+ deltaE: 0,+ });+ } else if (!ov?.dark && e.darkMatch && e.darkMatch.verdict !== 'off') {+ push(e.darkMatch.rampName, 'dark', e.darkMatch.tone, {+ name: e.name,+ mode: 'dark',+ verdict: e.darkMatch.verdict,+ deltaE: e.darkMatch.deltaE,+ });+ }+ }+ return map;+}++export function tonalUsageKey(+ rampName: string,+ mode: Mode,+ tone: number,+): string {+ return `${rampName}::${mode}::${tone}`;+}++export {CATEGORY_ORDER};diff --git a/apps/sandbox/src/components/themePreview/themeOverrides.ts b/apps/sandbox/src/components/themePreview/themeOverrides.tsnew file mode 100644index 0000000000..6e9b20adf6--- /dev/null+++ b/apps/sandbox/src/components/themePreview/themeOverrides.ts@@ -0,0 +1,484 @@+/**+ * Pending-overrides model for the audit drawer's interactive editor.+ *+ * The audit drawer lets you reassign each color token to a different+ * (rampName, tone) per mode. We track those reassignments here as an+ * in-memory map, then format them out two ways:+ *+ * - serializeAsTokensBlock() → a `tokens: { ... }` snippet ready to+ * paste into the theme's defineTheme() call.+ * - toApplyPayload() → the JSON payload the /api/theme-audit/apply+ * endpoint expects, which writes the same values back into the source+ * theme file.+ */++import type {Mode, RampSeed} from './colorMath';+import {hexToHct, tonalPaletteForMode, type ToneStep} from './colorMath';++// =============================================================================+// Types+// =============================================================================++/**+ * A single per-mode reassignment for one token.+ *+ * Discriminated by `kind`:+ * - `'palette'` — the user picked a step on a tonal ramp. We retain+ * `rampName`, `rampSourceHex`, and `tone` so the editor can show+ * "Blue T35" as the row subtitle and re-resolve the hex if the+ * ramp seed changes upstream.+ * - `'custom'` — the user typed a free-form hex (or used the native+ * color picker). We only carry the hex itself; the editor renders+ * the row subtitle as "Custom".+ *+ * Both shapes carry the resolved `hex` so the export formatter, CSS+ * variable injector, and active swatch all read from a single field.+ */+export type ModeOverride =+ | {+ kind: 'palette';+ /** Display name of the ramp (e.g. "Blue", "Stone Neutral") */+ rampName: string;+ /** Source hex of the ramp seed — keeps us decoupled from the seed+ * list so reassignments survive reordering of `tonalColors`. */+ rampSourceHex: string;+ /** Tone step the user picked (0-100, in 5-step increments) */+ tone: ToneStep;+ /**+ * Optional alpha channel (0-1, default 1). Preserved when the+ * source token had transparency so a snapped overlay/shadow+ * keeps its low-opacity treatment. The resolved `hex` field is+ * the 8-digit form (`#rrggbbaa`) when alpha < 1.+ */+ alpha: number;+ /** Resolved hex at that ramp+tone+mode (8-digit when alpha < 1). */+ hex: string;+ }+ | {+ kind: 'custom';+ /** Optional alpha channel (0-1, default 1). */+ alpha: number;+ /** Free-form hex value (8-digit when alpha < 1). */+ hex: string;+ };++/** Pending edits for a single token. Either side may be undefined when+ * the user hasn't reassigned that mode. */+export interface TokenOverride {+ light?: ModeOverride;+ dark?: ModeOverride;+}++/** Full pending-overrides map, keyed by token name (e.g. `--color-text-primary`). */+export type OverridesMap = Record<string, TokenOverride>;++// =============================================================================+// State helpers (called by useReducer in ThemeAuditDrawer)+// =============================================================================++export type OverridesAction =+ | {type: 'set'; token: string; mode: Mode; override: ModeOverride}+ | {type: 'clearMode'; token: string; mode: Mode}+ | {type: 'clearToken'; token: string}+ | {type: 'reset'};++export function overridesReducer(+ state: OverridesMap,+ action: OverridesAction,+): OverridesMap {+ switch (action.type) {+ case 'set': {+ const prev = state[action.token] ?? {};+ const next: TokenOverride = {...prev, [action.mode]: action.override};+ return {...state, [action.token]: next};+ }+ case 'clearMode': {+ const prev = state[action.token];+ if (!prev) return state;+ const next: TokenOverride = {...prev};+ delete next[action.mode];+ // Drop the token entry entirely when neither mode is set so the+ // count badges read cleanly without "phantom" empty entries.+ if (!next.light && !next.dark) {+ const {[action.token]: _, ...rest} = state;+ return rest;+ }+ return {...state, [action.token]: next};+ }+ case 'clearToken': {+ const {[action.token]: _, ...rest} = state;+ return rest;+ }+ case 'reset':+ return {};+ }+}++// =============================================================================+// Resolve a (rampSeed, tone, mode) → hex+// =============================================================================++/**+ * Compute the hex for a given ramp+tone+mode. When the seed carries a+ * canonical hand-tuned ramp (`seed.tones`), that's the source of+ * truth — falls back to generating via HCT only when no canonical+ * ramp is supplied. Always returns a 6-digit hex; alpha is the+ * caller's concern (apply via `composeAlphaHex`).+ */+export function resolveOverrideHex(+ seed: RampSeed,+ tone: ToneStep,+ mode: Mode,+): string {+ if (seed.tones) {+ const v = seed.tones[tone];+ if (typeof v === 'string') return v;+ }+ const {hue, chroma} = hexToHct(seed.sourceHex);+ return tonalPaletteForMode(hue, chroma, mode)[tone];+}++/**+ * Build a palette-style ModeOverride from a ramp seed + tone + mode.+ * Optional `alpha` (0-1) is preserved on the override so a snapped+ * overlay/shadow token retains its transparency end-to-end (the+ * resolved hex becomes 8-digit when alpha < 1).+ */+export function buildModeOverride(+ seed: RampSeed,+ tone: ToneStep,+ mode: Mode,+ alpha?: number,+): ModeOverride {+ const baseHex = resolveOverrideHex(seed, tone, mode);+ return {+ kind: 'palette',+ rampName: seed.name,+ rampSourceHex: seed.sourceHex,+ tone,+ alpha: clampAlpha(alpha),+ hex: composeAlphaHex(baseHex, alpha),+ };+}++/**+ * Build a custom (free-form hex) ModeOverride. The input may carry+ * either a 6-digit hex (no alpha) or an 8-digit hex / `'#hex N%'`+ * shape (with alpha) — alpha round-trips through to the resolved+ * `hex` field (8-digit when alpha < 1) and is also surfaced as a+ * separate `alpha` value for UI display.+ */+export function buildCustomOverride(input: string): ModeOverride {+ const {hex, alpha} = parseHexWithAlpha(input);+ const cleaned = normalizeHex(hex);+ return {+ kind: 'custom',+ alpha: clampAlpha(alpha),+ hex: composeAlphaHex(cleaned, alpha),+ };+}++/**+ * Validate + normalise a free-form hex to 6-digit `#rrggbb`. Returns+ * `#000000` for unparseable input. Alpha (4th channel of 8-digit hex+ * or `#abcd`) is dropped — combine with `composeAlphaHex` to put it+ * back on for emit / preview.+ */+export function normalizeHex(input: string): string {+ const trimmed = input.trim().toLowerCase();+ const m = trimmed.match(/^#?([0-9a-f]{3,8})$/);+ if (!m) return '#000000';+ const body = m[1];+ if (body.length === 3) {+ return '#' + body[0] + body[0] + body[1] + body[1] + body[2] + body[2];+ }+ if (body.length === 4) {+ return '#' + body[0] + body[0] + body[1] + body[1] + body[2] + body[2];+ }+ if (body.length === 6) return '#' + body;+ if (body.length === 8) return '#' + body.slice(0, 6);+ return '#000000';+}++export function isValidHex(input: string): boolean {+ // Accept either a bare hex or the `'#hex N%'` shape used by the+ // alpha-aware Custom-tab input.+ if (/^#?[0-9a-fA-F]{3,8}$/.test(input.trim())) return true;+ return /^#?[0-9a-fA-F]{3,8}\s+\d{1,3}%?$/.test(input.trim());+}++// =============================================================================+// Alpha helpers — `'#28282a 10%'` ⇄ `{hex: '#28282a', alpha: 0.1}` ⇄ `'#28282a1A'`+// =============================================================================++/**+ * Clamp an alpha (0-1) into [0, 1]. Treats undefined / NaN / out-of-range+ * input as 1 (fully opaque) — the safe default that matches "no alpha+ * specified" in CSS color literals.+ */+export function clampAlpha(alpha: number | undefined): number {+ if (alpha == null || !Number.isFinite(alpha)) return 1;+ if (alpha < 0) return 0;+ if (alpha > 1) return 1;+ return alpha;+}++/**+ * Convert a 0-1 alpha to a 2-digit lowercase hex pair (e.g. 0.1 → '1a',+ * 0.5 → '80', 1 → 'ff'). Used to build 8-digit hex emit values.+ */+export function alphaToHex(alpha: number): string {+ const v = Math.round(clampAlpha(alpha) * 255);+ return v.toString(16).padStart(2, '0');+}++/**+ * Compose a base 6-digit hex with an alpha into the canonical 8-digit+ * emit form (`#rrggbbaa`). When alpha is 1 (or omitted), returns the+ * 6-digit hex unchanged so we don't gratuitously upgrade the form.+ */+export function composeAlphaHex(hex: string, alpha?: number): string {+ const a = clampAlpha(alpha);+ const base = normalizeHex(hex);+ if (a === 1) return base;+ return base + alphaToHex(a);+}++/**+ * Format a base hex + alpha as `'#rrggbb 10%'` for display in inputs+ * and trigger labels. When alpha is 1, returns the base hex with no+ * suffix so on-ramp opaque tokens read cleanly.+ */+export function formatHexWithAlpha(hex: string, alpha?: number): string {+ const a = clampAlpha(alpha);+ const base = normalizeHex(hex);+ if (a === 1) return base;+ return base + ' ' + Math.round(a * 100) + '%';+}++/**+ * Inverse of `formatHexWithAlpha`. Accepts:+ * - `'#28282a 10%'` — the canonical pretty form+ * - `'#28282a1a'` — 8-digit hex (alpha embedded as last 2 chars)+ * - `'#28282a'` — bare hex, alpha defaults to 1+ * - `'28282a 10'` — leading `#` and trailing `%` are tolerated+ *+ * Returns `{hex: '#rrggbb', alpha: 0-1}`. Unparseable input returns+ * `{hex: '#000000', alpha: 1}`.+ */+export function parseHexWithAlpha(input: string): {hex: string; alpha: number} {+ const trimmed = input.trim().toLowerCase();+ // Pretty form: hex + percent (handles `#28282a 10%`, `28282a 10`, etc.)+ const pretty = trimmed.match(/^#?([0-9a-f]{3,8})\s+(\d{1,3})%?$/);+ if (pretty) {+ const baseBody = pretty[1];+ const pct = Math.min(100, Math.max(0, Number(pretty[2])));+ return {+ hex: normalizeHex(baseBody),+ alpha: pct / 100,+ };+ }+ // Bare hex form (3/4/6/8 digit)+ const bare = trimmed.match(/^#?([0-9a-f]{3,8})$/);+ if (bare) {+ const body = bare[1];+ if (body.length === 8) {+ // Last 2 hex chars carry alpha+ const a = parseInt(body.slice(6, 8), 16) / 255;+ return {hex: normalizeHex(body.slice(0, 6)), alpha: a};+ }+ if (body.length === 4) {+ // 4-digit shorthand: last digit doubled = alpha pair+ const aChar = body[3];+ const a = parseInt(aChar + aChar, 16) / 255;+ return {hex: normalizeHex(body.slice(0, 3)), alpha: a};+ }+ return {hex: normalizeHex(body), alpha: 1};+ }+ return {hex: '#000000', alpha: 1};+}++// =============================================================================+// Count helpers+// =============================================================================++/** Count of tokens with any pending override. Drives the toolbar badge. */+export function countOverrides(state: OverridesMap): number {+ return Object.keys(state).length;+}++/** Total per-mode reassignments across all tokens. Drives sub-counts. */+export function countModeOverrides(state: OverridesMap): {+ light: number;+ dark: number;+} {+ let light = 0;+ let dark = 0;+ for (const t of Object.values(state)) {+ if (t.light) light++;+ if (t.dark) dark++;+ }+ return {light, dark};+}++// =============================================================================+// Export — TypeScript tokens block+// =============================================================================++/**+ * Format the pending overrides as a TypeScript `tokens: { ... }` snippet+ * suitable for pasting into a `defineTheme()` call.+ *+ * Per-token shape:+ * - both modes set: '--color-foo': ['#light', '#dark'], // Ramp T35 / Ramp T80+ * - only light set: '--color-foo': ['#light', '<existing dark>'],+ * - only dark set: '--color-foo': ['<existing light>', '#dark'],+ *+ * The "unchanged" side falls back to the current theme value (passed in via+ * `currentTokenValues`) so the resulting array is always a valid replacement+ * for the existing entry — copy-paste won't accidentally drop the other mode.+ */+export interface SerializeContext {+ /** Current resolved hex per token per mode — used to fill in the side+ * the user didn't reassign. */+ currentTokenValues: Record<string, {light: string | null; dark: string | null}>;+}++export function serializeAsTokensBlock(+ state: OverridesMap,+ ctx: SerializeContext,+): string {+ const lines: string[] = [];+ // Sort tokens alphabetically — predictable diff output.+ const tokens = Object.keys(state).sort();+ for (const token of tokens) {+ const ov = state[token];+ const current = ctx.currentTokenValues[token] ?? {light: null, dark: null};+ const lightHex = ov.light?.hex ?? current.light;+ const darkHex = ov.dark?.hex ?? current.dark;++ // When light === dark, defineTheme accepts a single string. Keep tuple+ // form when either mode comes from the user (so the comment annotation+ // attaches to the right side); collapse to single only when both modes+ // are unmanaged (shouldn't happen here but kept defensive).+ const value =+ lightHex && darkHex && lightHex === darkHex && !ov.light && !ov.dark+ ? `'${lightHex}'`+ : `[${formatHex(lightHex)}, ${formatHex(darkHex)}]`;++ const annotations: string[] = [];+ if (ov.light) annotations.push(`light: ${describeOverride(ov.light)}`);+ if (ov.dark) annotations.push(`dark: ${describeOverride(ov.dark)}`);+ const comment = annotations.length ? ` // ${annotations.join(' · ')}` : '';++ lines.push(` '${token}': ${value},${comment}`);+ }+ return `tokens: {\n${lines.join('\n')}\n }`;+}++/**+ * Human-readable description of a ModeOverride for export comments and+ * inline subtitles. Palette overrides read as `Blue T35`; custom+ * overrides read as `Custom`. When the override carries non-1 alpha,+ * appends ` · 10%` so transparency is visible in the source comments+ * and trigger labels.+ */+export function describeOverride(ov: ModeOverride): string {+ const base = ov.kind === 'palette' ? `${ov.rampName} T${ov.tone}` : 'Custom';+ return ov.alpha < 1 ? `${base} · ${Math.round(ov.alpha * 100)}%` : base;+}++function formatHex(hex: string | null): string {+ if (!hex) return `''`;+ return `'${hex}'`;+}++// =============================================================================+// Apply payload — JSON sent to /api/theme-audit/apply+// =============================================================================++export interface ApplyPayloadEntry {+ token: string;+ /** Final value to write — either a single hex (both modes equal) or a+ * [light, dark] tuple. */+ value: string | [string, string];+ /** Human-readable annotation string the endpoint can use as a trailing+ * `// ...` comment when inserting a new token entry. */+ annotation?: string;+}++export interface ApplyPayload {+ themeName: string;+ entries: ApplyPayloadEntry[];+}++export function toApplyPayload(+ themeName: string,+ state: OverridesMap,+ ctx: SerializeContext,+): ApplyPayload {+ const entries: ApplyPayloadEntry[] = [];+ for (const token of Object.keys(state).sort()) {+ const ov = state[token];+ const current = ctx.currentTokenValues[token] ?? {light: null, dark: null};+ const lightHex = ov.light?.hex ?? current.light ?? '';+ const darkHex = ov.dark?.hex ?? current.dark ?? '';+ const value: string | [string, string] =+ lightHex === darkHex ? lightHex : [lightHex, darkHex];++ const annotations: string[] = [];+ if (ov.light) annotations.push(`light: ${describeOverride(ov.light)}`);+ if (ov.dark) annotations.push(`dark: ${describeOverride(ov.dark)}`);+ entries.push({+ token,+ value,+ annotation: annotations.length > 0 ? annotations.join(' · ') : undefined,+ });+ }+ return {themeName, entries};+}++// =============================================================================+// Live preview — convert pending overrides into a CSS-custom-property style map+// =============================================================================++/**+ * Build the set of CSS custom properties that, when applied to a parent+ * element, cause every descendant component to render with the pending+ * overrides instead of the committed theme values.+ *+ * Each entry comes out as `light-dark(#light, #dark)`:+ * - the user-edited side uses the new ramp+tone hex+ * - the unedited side falls back to the current theme value (so we+ * never accidentally collapse a [light, dark] tuple to a single+ * value when the user only touched one mode)+ *+ * Returns the empty object when nothing is pending — the caller can spread+ * unconditionally without an extra branch.+ *+ * Note: returned as `React.CSSProperties` so it composes cleanly with+ * other inline styles, but the keys are CSS custom properties which the+ * built-in CSSProperties type doesn't model — `as` cast required.+ */+export function buildOverrideCSSVars(+ state: OverridesMap,+ ctx: SerializeContext,+): React.CSSProperties {+ const vars: Record<string, string> = {};+ for (const [token, ov] of Object.entries(state)) {+ const current = ctx.currentTokenValues[token] ?? {light: null, dark: null};+ const lightHex = ov.light?.hex ?? current.light;+ const darkHex = ov.dark?.hex ?? current.dark;+ if (!lightHex && !darkHex) continue;+ if (lightHex === darkHex && lightHex) {+ vars[token] = lightHex;+ } else {+ // Either side may be null when the original theme value was+ // unparseable (e.g. var() reference). Fall back to a transparent+ // sentinel rather than emitting `light-dark(null, ...)` which is+ // invalid CSS and would silently break the cascade for that token.+ vars[token] = `light-dark(${lightHex ?? 'transparent'}, ${darkHex ?? 'transparent'})`;+ }+ }+ return vars as React.CSSProperties;+}diff --git a/packages/themes/stone/src/stoneTheme.ts b/packages/themes/stone/src/stoneTheme.tsindex c0795fdc9e..7cc56a4e0f 100644--- a/packages/themes/stone/src/stoneTheme.ts+++ b/packages/themes/stone/src/stoneTheme.ts@@ -29,23 +29,30 @@ const INPUT_STATUS_VARS = {},} as const;-/** Stone syntax palette — derived from categorical hues at T40 (light) / T70 (dark). */+/**+ * Stone syntax palette — light values snap to T40 / T45 stops on the+ * stone categorical ramps (per audit drawer); dark values stay at T70.+ *+ * `string` and `property` both land on Teal T40 — intentional; the audit+ * unified them since green and teal are visually adjacent at T40 and+ * the stone neutral palette doesn't carry a distinct green stop.+ */const stoneSyntax = defineSyntaxTheme({name: 'xds-stone',tokens: {- keyword: ['#645a72', '#b2a7c1'], // Purple H=307 C=15- string: ['#50634f', '#9bb19a'], // Green H=142 C=15- comment: ['#5e5e63', '#ababb0'], // Gray H=291 C=3- number: ['#6f5b48', '#bea792'], // Orange H=70 C=15- function: ['#4d6076', '#99adc6'], // Blue H=265 C=15- type: ['#645a72', '#b2a7c1'], // Purple H=307 C=15- variable: ['#5e5e63', '#ababb0'], // Gray H=291 C=3- operator: ['#5e5e63', '#ababb0'], // Gray H=291 C=3- constant: ['#6f5b48', '#bea792'], // Orange H=70 C=15- tag: ['#775751', '#c7a39d'], // Red H=33 C=15- attribute: ['#675d46', '#b6aa90'], // Yellow H=90 C=15- property: ['#496455', '#94b2a0'], // Teal H=158 C=15- punctuation: ['#5e5e63', '#ababb0'], // Gray H=291 C=3+ keyword: ['#645a72', '#b2a7c1'], // Purple T40 / T70+ string: ['#4e6357', '#9bb19a'], // Teal T40 / Green T70+ comment: ['#5e5e5e', '#ababb0'], // Stone Neutral T40 / T70+ number: ['#755752', '#bea792'], // Red T40 / Orange T70+ function: ['#506072', '#99adc6'], // Blue T40 / T70+ type: ['#645a72', '#b2a7c1'], // Purple T40 / T70+ variable: ['#5e5e5e', '#ababb0'], // Stone Neutral T40 / T70+ operator: ['#5e5e5e', '#ababb0'], // Stone Neutral T40 / T70+ constant: ['#755752', '#bea792'], // Red T40 / Orange T70+ tag: ['#775751', '#c7a39d'], // Red T40 / T70+ attribute: ['#79693f', '#b6aa90'], // Yellow T45 / T70+ property: ['#4e6357', '#94b2a0'], // Teal T40 / T70+ punctuation: ['#5e5e5e', '#ababb0'], // Stone Neutral T40 / T70background: ['#f3f3f5', '#171719'],},});@@ -87,39 +94,39 @@ export const stoneTheme = defineTheme({// Core semantic — all neutrals H=291// Stone 900 T=16 C=1.4, Stone 500 T=55 C=4, Stone 300 T=86 C=1.6, Stone 100 T=96 C=1- '--color-accent': ['#28282a', '#f3f3f5'],- '--color-accent-muted': ['#28282a14', '#f3f3f520'],- '--color-neutral': ['#28282a0F', '#f3f3f51A'],- '--color-background-surface': ['#FFFFFF', '#1f1f21'], // T12- '--color-background-body': ['#f3f3f5', '#171719'], // T8- '--color-overlay': ['#28282a80', '#28282aCC'],- '--color-overlay-hover': ['#28282a0D', '#f3f3f50D'],- '--color-overlay-pressed': ['#28282a1A', '#f3f3f51A'],- '--color-background-muted': ['#dddcdf', '#3b3b3f'], // T88 C=1.5 / T25 C=3+ '--color-accent': ['#25252a', '#f3f3f5'], // light: Stone Neutral T15+ '--color-accent-muted': ['#25252a14', '#f3f3f5'], // light: Stone Neutral T15 · 8%+ '--color-neutral': ['#25252a0f', '#f3f3f5'], // light: Stone Neutral T15 · 6%+ '--color-background-surface': ['#ffffff', '#1b1b1f'], // dark: Stone Neutral T10+ '--color-background-body': ['#f3f3f5', '#111015'], // dark: Stone Neutral T5+ '--color-overlay': ['#25252a80', '#28282a'], // light: Stone Neutral T15 · 50%+ '--color-overlay-hover': ['#25252a0d', '#f3f3f5'], // light: Stone Neutral T15 · 5%+ '--color-overlay-pressed': ['#25252a1a', '#f3f3f5'], // light: Stone Neutral T15 · 10%+ '--color-background-muted': ['#e2e2e8', '#3b3b3f'], // light: Stone Neutral T90// Text — H=291- '--color-text-primary': ['#28282a', '#f3f3f5'], // T16 / T96+ '--color-text-primary': ['#25252a', '#f3f3f5'], // light: Stone Neutral T15'--color-text-secondary': ['#83838a', '#9d9da3'], // T55 C=4 / T65 C=3'--color-text-disabled': ['#d7d7da', '#5e5e61'], // T86 C=1.6 / T40 C=2- '--color-text-accent': ['#28282a', '#f3f3f5'],+ '--color-text-accent': ['#25252a', '#f3f3f5'], // light: Stone Neutral T15'--color-on-dark': '#FFFFFF',- '--color-on-light': '#28282a',- '--color-on-accent': ['#FFFFFF', '#28282a'],+ '--color-on-light': ['#25252a', '#28282a'], // light: Stone Neutral T15+ '--color-on-accent': ['#ffffff', '#25252a'], // dark: Stone Neutral T15// Text on top of matching status surface (badge fill, banner content).'--color-on-success': ['#374c36', '#d0e9ce'], // Green T30 / T90'--color-on-error': ['#58413e', '#f9dcd7'], // Red T30 / T90'--color-on-warning': ['#524622', '#f4e1b7'], // Yellow T30 / T90// Icon — H=291- '--color-icon-accent': ['#28282a', '#f3f3f5'],- '--color-icon-primary': ['#28282a', '#f3f3f5'],+ '--color-icon-accent': ['#25252a', '#f3f3f5'], // light: Stone Neutral T15+ '--color-icon-primary': ['#25252a', '#f3f3f5'], // light: Stone Neutral T15'--color-icon-secondary': ['#83838a', '#9d9da3'], // T55 C=4 / T65 C=3'--color-icon-disabled': ['#d7d7da', '#5e5e61'], // T86 C=1.6 / T40 C=2// Surface variants — H=291'--color-background-card': ['#FFFFFF', '#242325'], // T14- '--color-background-popover': ['#FFFFFF', '#28282a'], // T16- '--color-background-inverted': ['#28282a', '#f3f3f5'],+ '--color-background-popover': ['#ffffff', '#25252a'], // dark: Stone Neutral T15+ '--color-background-inverted': ['#25252a', '#f3f3f5'], // light: Stone Neutral T15// Status / Sentiment — T50 from palette for icons/borders (visible color)'--color-success': ['#374c36', '#b4cdb2'], // Green T30 / T80@@ -130,12 +137,12 @@ export const stoneTheme = defineTheme({'--color-warning-muted': ['#f4e1b7', '#d7c59c'], // Yellow T90 / T80// Border — H=291- '--color-border': ['#dddcdf', '#f3f3f51A'], // T88 C=1.5+ '--color-border': ['#e2e2e8', '#f3f3f5'], // light: Stone Neutral T90'--color-border-emphasized': ['#83838a', '#5e5e61'], // T55 C=4 / T40 C=2// Effects — H=291'--color-skeleton': ['#d4d4da', '#5e5e64'], // T85 / T40 from H=291 C=3- '--color-shadow': ['#28282a1A', '#0000004D'],+ '--color-shadow': ['#25252a1a', '#000000'], // light: Stone Neutral T15 · 10%'--color-tint-hover': ['black', 'white'],// Typography override@@ -164,10 +171,10 @@ export const stoneTheme = defineTheme({// Categorical — Gray (pure neutral, C=0). Same T35/T25/T90 pattern from// the neutral H=291 C=3 ramp.- '--color-background-gray': ['#e2e2e2', '#525257'], // dark neutral T35- '--color-border-gray': ['#d4d4d4', '#3b3b3f'], // dark neutral T25- '--color-icon-gray': ['#474747', '#e2e2e8'], // dark neutral T90- '--color-text-gray': ['#474747', '#e2e2e8'],+ '--color-background-gray': ['#e2e2e8', '#525257'], // light: Stone Neutral T90+ '--color-border-gray': ['#d4d4da', '#3b3b3f'], // light: Stone Neutral T85+ '--color-icon-gray': ['#46464b', '#e2e2e8'], // light: Stone Neutral T30+ '--color-text-gray': ['#46464b', '#e2e2e8'], // light: Stone Neutral T30// Categorical — Green H=142 C=17'--color-background-green': ['#d0e9ce', '#425841'],