An open source design system that's fully customizable and agent ready
TypeScript
feat(theme): resolve token references and CSS color functions to raw values in useTheme() (#3703)
Cindy Zhangd3b6700083da
diff --git a/.changeset/resolve-token-references.md b/.changeset/resolve-token-references.mdnew file mode 100644index 0000000000..0290b50253--- /dev/null+++ b/.changeset/resolve-token-references.md@@ -0,0 +1,9 @@+---+'@astryxdesign/core': patch+---++[fix] `useTheme()` / `resolveThemeTokens()` now resolve derived tokens that reference other tokens (e.g. `--color-text-accent: var(--color-accent)`) to concrete raw values, following reference chains iteratively. Supported CSS color functions (`color-mix(in srgb, …)`) are evaluated against those values, so canvas/SVG/data-viz consumers get usable colors instead of `var(...)` or `color-mix(...)` strings (#3697).++Also adds shared color parsing/formatting primitives (`parseHex`, `parseRgb`, `parseColor`, `formatHex`, `formatColor`) under `@astryxdesign/core/utils`, unifying the color parsers previously duplicated across the theme layer.++@cixzhangdiff --git a/packages/core/src/theme/hct.ts b/packages/core/src/theme/hct.tsindex 044f13150b..56c7507398 100644--- a/packages/core/src/theme/hct.ts+++ b/packages/core/src/theme/hct.ts@@ -16,6 +16,8 @@* - Tone from L* (CIE Lightness, 0=black, 100=white)*/+import {parseHex, formatHex} from '../utils/color';+// =============================================================================// Types// =============================================================================@@ -121,21 +123,11 @@ export function yToTone(y: number): number {// =============================================================================function hexToRgb(hex: string): [number, number, number] {- const h = hex.replace('#', '');- const full =- h.length === 3 ? h[0] + h[0] + h[1] + h[1] + h[2] + h[2] : h.slice(0, 6);- const n = parseInt(full, 16);- return [(n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff];-}--function rgbToHex(r: number, g: number, b: number): string {- return (- '#' +- [r, g, b]- .map(c => c.toString(16).padStart(2, '0'))- .join('')- .toUpperCase()- );+ const parsed = parseHex(hex);+ if (parsed === null) {+ return [0, 0, 0];+ }+ return [parsed.r, parsed.g, parsed.b];}// =============================================================================@@ -181,7 +173,7 @@ export function hctToHex(hct: HCT): string {}if (chroma < 0.5) {const gray = toneToGray(tone);- return rgbToHex(gray, gray, gray);+ return formatHex(gray, gray, gray);}let lo = 0;@@ -241,7 +233,7 @@ function hctComponentToHex(return null;}- return rgbToHex(r, g, bVal);+ return formatHex(r, g, bVal);}// =============================================================================diff --git a/packages/core/src/theme/tokens.test.ts b/packages/core/src/theme/tokens.test.tsindex a6ed049f90..1dc7808dd5 100644--- a/packages/core/src/theme/tokens.test.ts+++ b/packages/core/src/theme/tokens.test.ts@@ -20,9 +20,7 @@ const testTheme = defineTheme({describe('tokenVar', () => {it('returns a CSS var() reference for known token names', () => {- expect(tokenVar('--color-text-primary')).toBe(- 'var(--color-text-primary)',- );+ expect(tokenVar('--color-text-primary')).toBe('var(--color-text-primary)');});it('returns a CSS var() reference for custom token names', () => {@@ -32,9 +30,7 @@ describe('tokenVar', () => {describe('tokenVars', () => {it('contains var() references for known tokens', () => {- expect(tokenVars['--color-text-primary']).toBe(- 'var(--color-text-primary)',- );+ expect(tokenVars['--color-text-primary']).toBe('var(--color-text-primary)');expect(tokenVars['--spacing-4']).toBe('var(--spacing-4)');});});@@ -87,9 +83,9 @@ describe('resolveThemeTokens', () => {describe('resolveThemeToken', () => {it('resolves one token', () => {- expect(- resolveThemeToken(testTheme, '--color-accent', {mode: 'dark'}),- ).toBe('#FF5555');+ expect(resolveThemeToken(testTheme, '--color-accent', {mode: 'dark'})).toBe(+ '#FF5555',+ );});it('returns fallback for unknown token names', () => {@@ -107,3 +103,180 @@ describe('resolveThemeToken', () => {).toBe('');});});++describe('resolveThemeTokens — reference resolution', () => {+ it('resolves a token that references another token to a raw value', () => {+ const theme = defineTheme({+ name: 'ref',+ tokens: {+ '--color-accent': ['#0058D2', '#BBC2FF'],+ '--color-text-accent': 'var(--color-accent)',+ },+ });++ const light = resolveThemeTokens(theme, {mode: 'light'});+ const dark = resolveThemeTokens(theme, {mode: 'dark'});++ expect(light['--color-text-accent']).toBe('#0058D2');+ expect(dark['--color-text-accent']).toBe('#BBC2FF');+ });++ it('resolves reference chains iteratively', () => {+ const theme = defineTheme({+ name: 'chain',+ tokens: {+ '--color-accent': ['#112233', '#445566'],+ '--color-icon-accent': 'var(--color-accent)',+ '--color-text-accent': 'var(--color-icon-accent)',+ },+ });++ const light = resolveThemeTokens(theme, {mode: 'light'});+ expect(light['--color-icon-accent']).toBe('#112233');+ expect(light['--color-text-accent']).toBe('#112233');+ });++ it('uses the var() fallback when the referenced token is unknown', () => {+ const theme = defineTheme({+ name: 'fallback',+ tokens: {+ '--color-text-accent': 'var(--not-a-token, #ABCDEF)',+ },+ });++ const tokens = resolveThemeTokens(theme, {mode: 'light'});+ expect(tokens['--color-text-accent']).toBe('#ABCDEF');+ });++ it('leaves an unresolvable reference as a literal var()', () => {+ const theme = defineTheme({+ name: 'unresolvable',+ tokens: {+ '--color-text-accent': 'var(--not-a-token)',+ },+ });++ const tokens = resolveThemeTokens(theme, {mode: 'light'});+ expect(tokens['--color-text-accent']).toBe('var(--not-a-token)');+ });++ it('does not loop forever on a reference cycle', () => {+ const theme = defineTheme({+ name: 'cycle',+ tokens: {+ '--color-text-accent': 'var(--color-icon-accent)',+ '--color-icon-accent': 'var(--color-text-accent)',+ },+ });++ const tokens = resolveThemeTokens(theme, {mode: 'light'});+ // The cycle collapses to a literal reference rather than hanging.+ expect(tokens['--color-text-accent']).toContain('var(');+ expect(tokens['--color-icon-accent']).toContain('var(');+ });+});++describe('resolveThemeTokens — CSS color functions', () => {+ it('evaluates color-mix with transparent to an rgba() value', () => {+ const theme = defineTheme({+ name: 'mix',+ tokens: {+ '--color-accent': ['#0058D2', '#BBC2FF'],+ '--color-accent-muted':+ 'color-mix(in srgb, var(--color-accent) 20%, transparent)',+ },+ });++ const light = resolveThemeTokens(theme, {mode: 'light'});+ const dark = resolveThemeTokens(theme, {mode: 'dark'});++ expect(light['--color-accent-muted']).toBe('rgba(0, 88, 210, 0.2)');+ expect(dark['--color-accent-muted']).toBe('rgba(187, 194, 255, 0.2)');+ });++ it('resolves the muted token inside a light-dark() tuple per mode', () => {+ const theme = defineTheme({+ name: 'ld-mix',+ tokens: {+ '--color-accent': ['#FF0000', '#00FF00'],+ '--color-accent-muted': [+ 'color-mix(in srgb, var(--color-accent) 20%, transparent)',+ 'color-mix(in srgb, var(--color-accent) 25%, transparent)',+ ],+ },+ });++ const light = resolveThemeTokens(theme, {mode: 'light'});+ const dark = resolveThemeTokens(theme, {mode: 'dark'});++ expect(light['--color-accent-muted']).toBe('rgba(255, 0, 0, 0.2)');+ expect(dark['--color-accent-muted']).toBe('rgba(0, 255, 0, 0.25)');+ });++ it('mixes two opaque colors by weight', () => {+ const theme = defineTheme({+ name: 'two-color',+ tokens: {+ '--color-neutral': 'color-mix(in srgb, #000000, #FFFFFF)',+ },+ });++ const tokens = resolveThemeTokens(theme, {mode: 'light'});+ expect(tokens['--color-neutral']).toBe('#808080');+ });++ it('mixes two opaque colors with an explicit percentage', () => {+ const theme = defineTheme({+ name: 'weighted',+ tokens: {+ '--color-neutral': 'color-mix(in srgb, #000000 25%, #FFFFFF)',+ },+ });++ const tokens = resolveThemeTokens(theme, {mode: 'light'});+ expect(tokens['--color-neutral']).toBe('#BFBFBF');+ });++ it('preserves an unsupported color space rather than guessing', () => {+ const theme = defineTheme({+ name: 'oklab',+ tokens: {+ '--color-accent': ['#0058D2', '#BBC2FF'],+ '--color-neutral':+ 'color-mix(in oklab, var(--color-accent), black 15%)',+ },+ });++ const tokens = resolveThemeTokens(theme, {mode: 'light'});+ // var() still resolves; the unsupported mix stays as a color-mix() expression.+ expect(tokens['--color-neutral']).toContain('color-mix(in oklab');+ expect(tokens['--color-neutral']).toContain('#0058D2');+ });+});++describe('resolveThemeTokens — generated themes end to end', () => {+ it('resolves derived accent tokens from defineTheme({color}) to raw values', () => {+ const theme = defineTheme({name: 'brand', color: {accent: '#0064E0'}});++ const light = resolveThemeTokens(theme, {mode: 'light'});+ const dark = resolveThemeTokens(theme, {mode: 'dark'});++ const isConcreteColor = (value: string): boolean => /^(#|rgb)/.test(value);++ for (const key of [+ '--color-accent',+ '--color-text-accent',+ '--color-icon-accent',+ '--color-accent-muted',+ ]) {+ expect(isConcreteColor(light[key])).toBe(true);+ expect(isConcreteColor(dark[key])).toBe(true);+ expect(light[key]).not.toContain('var(');+ expect(light[key]).not.toContain('color-mix');+ }++ // The derived accent tokens resolve to the base accent.+ expect(light['--color-text-accent']).toBe(light['--color-accent']);+ expect(light['--color-icon-accent']).toBe(light['--color-accent']);+ });+});diff --git a/packages/core/src/theme/tokens.ts b/packages/core/src/theme/tokens.tsindex 504f847140..741d42e4d9 100644--- a/packages/core/src/theme/tokens.ts+++ b/packages/core/src/theme/tokens.ts@@ -10,6 +10,11 @@* build-time theme adapters, chart configuration, canvas/SVG rendering, tests,* or plain JS theme objects for other styling libraries.*+ * Derived tokens can reference other tokens (`var(--color-accent)`) and use CSS+ * color functions (`color-mix`). The resolver follows those references through+ * the theme iteratively and evaluates the supported color functions so callers+ * receive concrete raw values, not CSS expressions.+ ** SYNC: When modified, update:* - /packages/core/src/theme/useTheme.ts* - /packages/core/src/theme/index.ts@@ -21,6 +26,7 @@ import {type TokenName,type TokenValue,} from './defineTheme';+import {parseColor, formatColor} from '../utils/color';/** Resolved color mode used when choosing the side of light/dark token values. */export type ResolvedThemeMode = 'light' | 'dark';@@ -144,14 +150,243 @@ function resolveXDSTokenValue(return value;}+// =============================================================================+// Reference resolution — turn token expressions into concrete raw values+// =============================================================================+//+// Generated themes emit derived tokens as references to other tokens rather+// than baked-in values, so a scoped CSS override of a base token re-themes the+// subtree that references it. The CSS cascade resolves those references, but+// non-CSS consumers (canvas, SVG, data-viz) need the concrete value. These+// helpers replay the same resolution in JS: follow `var()` references through+// the resolved token map (iteratively, guarding against cycles) and evaluate+// the CSS color functions used by the theme generator against those values.++/** Index of the `)` matching the `(` at `openIndex`, or -1 when unbalanced. */+function findMatchingParen(input: string, openIndex: number): number {+ let depth = 0;+ for (let i = openIndex; i < input.length; i++) {+ const char = input[i];+ if (char === '(') {+ depth++;+ } else if (char === ')') {+ depth--;+ if (depth === 0) {+ return i;+ }+ }+ }+ return -1;+}++/** Split a color-mix component into its color and optional percentage. */+function parseMixComponent(+ part: string,+): {color: string; percentage: number | null} | null {+ const trimmed = part.trim();+ const match = trimmed.match(/\s+([\d.]+)%$/);+ if (match) {+ return {+ color: trimmed.slice(0, match.index).trim(),+ percentage: parseFloat(match[1]),+ };+ }+ return {color: trimmed, percentage: null};+}++/**+ * Evaluate `color-mix(in <space>, c1 [p1], c2 [p2])` to a concrete color.+ *+ * Supports the `srgb` color space (the one the theme generator emits) using+ * the CSS Color 5 algorithm: normalize the percentages, interpolate the+ * premultiplied channels, then apply the alpha multiplier when the mix weights+ * sum to less than 100%. Returns null for anything it can't evaluate so the+ * original expression is preserved rather than guessed.+ */+function evaluateColorMix(body: string): string | null {+ const spaceMatch = body.match(/^in\s+([\w-]+)\s*,\s*(.+)$/s);+ if (!spaceMatch) {+ return null;+ }+ const [, colorSpace, rest] = spaceMatch;+ if (colorSpace.toLowerCase() !== 'srgb') {+ return null;+ }++ const split = splitTopLevelComma(rest);+ if (split === null) {+ return null;+ }+ const first = parseMixComponent(split[0]);+ const second = parseMixComponent(split[1]);+ if (first === null || second === null) {+ return null;+ }++ const c1 = parseColor(first.color);+ const c2 = parseColor(second.color);+ if (c1 === null || c2 === null) {+ return null;+ }++ // Fill in omitted percentages, then normalize so they sum to 100%.+ let p1: number;+ let p2: number;+ if (first.percentage !== null && second.percentage !== null) {+ p1 = first.percentage;+ p2 = second.percentage;+ } else if (first.percentage !== null) {+ p1 = first.percentage;+ p2 = 100 - p1;+ } else if (second.percentage !== null) {+ p2 = second.percentage;+ p1 = 100 - p2;+ } else {+ p1 = 50;+ p2 = 50;+ }+ const sum = p1 + p2;+ if (sum <= 0) {+ return null;+ }+ const w1 = p1 / sum;+ const w2 = p2 / sum;+ const alphaMultiplier = sum < 100 ? sum / 100 : 1;++ // Interpolate in premultiplied sRGB, then un-premultiply.+ const mixedA = w1 * c1.a + w2 * c2.a;+ const premix = (k1: number, k2: number): number =>+ w1 * k1 * c1.a + w2 * k2 * c2.a;+ const rp = premix(c1.r, c2.r);+ const gp = premix(c1.g, c2.g);+ const bp = premix(c1.b, c2.b);+ const rgb =+ mixedA === 0+ ? {r: 0, g: 0, b: 0}+ : {r: rp / mixedA, g: gp / mixedA, b: bp / mixedA};++ return formatColor({...rgb, a: mixedA * alphaMultiplier});+}++/** Evaluate every supported color function in an expression, innermost first. */+function evaluateColorFunctions(expr: string): string {+ const idx = expr.indexOf('color-mix(');+ if (idx === -1) {+ return expr;+ }+ const openIndex = idx + 'color-mix'.length;+ const closeIndex = findMatchingParen(expr, openIndex);+ if (closeIndex === -1) {+ return expr;+ }+ const body = evaluateColorFunctions(expr.slice(openIndex + 1, closeIndex));+ const evaluated = evaluateColorMix(body);+ const replacement = evaluated ?? `color-mix(${body})`;+ return (+ expr.slice(0, idx) ++ replacement ++ evaluateColorFunctions(expr.slice(closeIndex + 1))+ );+}++/**+ * Substitute `var(--name[, fallback])` references with their resolved values.+ * `seen` tracks the reference chain so cycles resolve to the literal reference+ * instead of recursing forever.+ */+function substituteVars(+ expr: string,+ raw: Record<string, string>,+ cache: Record<string, string>,+ seen: Set<string>,+): string {+ const start = expr.indexOf('var(');+ if (start === -1) {+ return expr;+ }+ const openIndex = start + 'var'.length;+ const closeIndex = findMatchingParen(expr, openIndex);+ if (closeIndex === -1) {+ return expr;+ }++ const inner = expr.slice(openIndex + 1, closeIndex);+ const commaSplit = splitTopLevelComma(inner);+ const name = (commaSplit ? commaSplit[0] : inner).trim();+ const fallback = commaSplit ? commaSplit[1] : null;++ let replacement: string;+ if (seen.has(name)) {+ replacement = expr.slice(start, closeIndex + 1);+ } else if (name in raw) {+ seen.add(name);+ replacement = resolveReference(name, raw, cache, seen);+ seen.delete(name);+ } else if (fallback !== null) {+ replacement = substituteVars(fallback.trim(), raw, cache, seen);+ } else {+ replacement = expr.slice(start, closeIndex + 1);+ }++ const rest = substituteVars(expr.slice(closeIndex + 1), raw, cache, seen);+ return expr.slice(0, start) + replacement + rest;+}++/** Fully resolve a single expression: substitute references, then evaluate colors. */+function resolveExpression(+ expr: string,+ raw: Record<string, string>,+ cache: Record<string, string>,+ seen: Set<string>,+): string {+ if (!expr.includes('var(') && !expr.includes('color-mix(')) {+ return expr;+ }+ const substituted = substituteVars(expr, raw, cache, seen);+ return evaluateColorFunctions(substituted);+}++/** Resolve one token by name, memoizing the result in `cache`. */+function resolveReference(+ name: string,+ raw: Record<string, string>,+ cache: Record<string, string>,+ seen: Set<string>,+): string {+ if (name in cache) {+ return cache[name];+ }+ const value = raw[name];+ if (value === undefined) {+ return '';+ }+ const resolved = resolveExpression(value, raw, cache, seen);+ cache[name] = resolved;+ return resolved;+}++/** Resolve every reference/color function in a raw token map to concrete values. */+function resolveReferences(+ raw: Record<string, string>,+): Record<string, string> {+ const cache: Record<string, string> = {};+ for (const name of Object.keys(raw)) {+ resolveReference(name, raw, cache, new Set<string>());+ }+ return cache;+}+/*** Resolve all Astryx token values for a theme and effective color mode.** The result starts with `tokenDefaults`, applies `theme.tokens`, then* reapplies `theme.__inputTokens` when available so explicit tuple overrides* retain their original light/dark sides instead of relying on CSS parsing.- * This mirrors the token resolution used by `useTheme()` but does not need- * React context or media queries.+ * A final pass resolves any `var()` references between tokens and evaluates+ * the CSS color functions the theme generator emits (e.g. `color-mix`), so+ * derived tokens like `--color-text-accent` return concrete values rather than+ * `var(--color-accent)`. This mirrors the token resolution used by+ * `useTheme()` but does not need React context or media queries.** Pass `theme` as null/undefined to resolve defaults only.*/@@ -167,7 +402,7 @@ export function resolveThemeTokens(}if (theme == null) {- return resolved;+ return resolveReferences(resolved);}for (const [key, value] of Object.entries(theme.tokens)) {@@ -182,7 +417,7 @@ export function resolveThemeTokens(}}- return resolved;+ return resolveReferences(resolved);}/** Resolve one Astryx token value for a theme and effective color mode. */diff --git a/packages/core/src/theme/useTheme.test.tsx b/packages/core/src/theme/useTheme.test.tsxindex 9f21d83ac0..6674f82443 100644--- a/packages/core/src/theme/useTheme.test.tsx+++ b/packages/core/src/theme/useTheme.test.tsx@@ -122,4 +122,24 @@ describe('useTheme', () => {resolveThemeTokens(testTheme, {mode: 'dark'}),);});++ it('resolves derived accent tokens to raw values, not var()/color-mix', () => {+ const brandTheme = defineTheme({name: 'brand', color: {accent: '#0064E0'}});+ const {result} = renderHook(() => useTheme(), {+ wrapper: ({children}) => (+ <Theme theme={brandTheme} mode="light">+ {children}+ </Theme>+ ),+ });++ const accent = result.current.token('--color-accent');+ expect(result.current.token('--color-text-accent')).toBe(accent);+ expect(result.current.token('--color-icon-accent')).toBe(accent);+ expect(result.current.token('--color-accent-muted')).toMatch(/^(#|rgb)/);+ expect(result.current.token('--color-accent-muted')).not.toContain('var(');+ expect(result.current.token('--color-accent-muted')).not.toContain(+ 'color-mix',+ );+ });});diff --git a/packages/core/src/utils/color.test.ts b/packages/core/src/utils/color.test.tsnew file mode 100644index 0000000000..b91d79271c--- /dev/null+++ b/packages/core/src/utils/color.test.ts@@ -0,0 +1,133 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, expect, it} from 'vitest';+import {parseHex, parseRgb, parseColor, formatHex, formatColor} from './color';++describe('parseHex', () => {+ it('parses #rrggbb', () => {+ expect(parseHex('#0064E0')).toEqual({r: 0, g: 100, b: 224, a: 1});+ });++ it('parses without a leading #', () => {+ expect(parseHex('0064E0')).toEqual({r: 0, g: 100, b: 224, a: 1});+ });++ it('expands #rgb shorthand', () => {+ expect(parseHex('#abc')).toEqual({r: 0xaa, g: 0xbb, b: 0xcc, a: 1});+ });++ it('parses #rrggbbaa alpha', () => {+ expect(parseHex('#00000080')).toEqual({r: 0, g: 0, b: 0, a: 128 / 255});+ });++ it('expands #rgba shorthand alpha', () => {+ expect(parseHex('#f008')).toEqual({+ r: 0xff,+ g: 0,+ b: 0,+ a: 0x88 / 255,+ });+ });++ it('returns null for non-hex input', () => {+ expect(parseHex('rgb(0,0,0)')).toBeNull();+ expect(parseHex('#12')).toBeNull();+ expect(parseHex('#zzzzzz')).toBeNull();+ // @ts-expect-error runtime guard for non-string input+ expect(parseHex(null)).toBeNull();+ });+});++describe('parseRgb', () => {+ it('parses comma-separated rgb()', () => {+ expect(parseRgb('rgb(0, 100, 224)')).toEqual({+ r: 0,+ g: 100,+ b: 224,+ a: 1,+ });+ });++ it('parses rgba() with alpha', () => {+ expect(parseRgb('rgba(0, 0, 0, 0.5)')).toEqual({r: 0, g: 0, b: 0, a: 0.5});+ });++ it('parses space-separated with slash alpha', () => {+ expect(parseRgb('rgb(0 100 224 / 0.25)')).toEqual({+ r: 0,+ g: 100,+ b: 224,+ a: 0.25,+ });+ });++ it('parses percentage channels', () => {+ expect(parseRgb('rgb(100%, 0%, 0%)')).toEqual({+ r: 255,+ g: 0,+ b: 0,+ a: 1,+ });+ });++ it('clamps alpha and channels into range', () => {+ expect(parseRgb('rgba(300, -20, 10, 2)')).toEqual({+ r: 255,+ g: 0,+ b: 10,+ a: 1,+ });+ });++ it('returns null when it cannot parse', () => {+ expect(parseRgb('rgb(0, 0)')).toBeNull();+ expect(parseRgb('#000000')).toBeNull();+ });+});++describe('parseColor', () => {+ it('routes hex and rgb strings to the right parser', () => {+ expect(parseColor('#FFFFFF')).toEqual({r: 255, g: 255, b: 255, a: 1});+ expect(parseColor('rgb(1, 2, 3)')).toEqual({r: 1, g: 2, b: 3, a: 1});+ });++ it('resolves the named colors used in token expressions', () => {+ expect(parseColor('transparent')).toEqual({r: 0, g: 0, b: 0, a: 0});+ expect(parseColor('BLACK')).toEqual({r: 0, g: 0, b: 0, a: 1});+ expect(parseColor('white')).toEqual({r: 255, g: 255, b: 255, a: 1});+ });++ it('returns null for unsupported colors so callers can preserve them', () => {+ expect(parseColor('var(--color-accent)')).toBeNull();+ expect(parseColor('oklch(0.5 0.1 200)')).toBeNull();+ expect(parseColor('rebeccapurple')).toBeNull();+ });+});++describe('formatHex', () => {+ it('formats channels as uppercase #RRGGBB', () => {+ expect(formatHex(0, 100, 224)).toBe('#0064E0');+ });++ it('rounds and clamps out-of-range channels', () => {+ expect(formatHex(-5, 300, 127.6)).toBe('#00FF80');+ });+});++describe('formatColor', () => {+ it('formats opaque colors as hex', () => {+ expect(formatColor({r: 0, g: 100, b: 224, a: 1})).toBe('#0064E0');+ });++ it('formats translucent colors as rgba()', () => {+ expect(formatColor({r: 0, g: 100, b: 224, a: 0.2})).toBe(+ 'rgba(0, 100, 224, 0.2)',+ );+ });++ it('round-trips through parseColor', () => {+ const parsed = parseColor('rgba(10, 20, 30, 0.5)');+ expect(parsed).not.toBeNull();+ expect(formatColor(parsed!)).toBe('rgba(10, 20, 30, 0.5)');+ });+});diff --git a/packages/core/src/utils/color.ts b/packages/core/src/utils/color.tsnew file mode 100644index 0000000000..fd11b9f904--- /dev/null+++ b/packages/core/src/utils/color.ts@@ -0,0 +1,148 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file color.ts+ * @input CSS color strings (hex, rgb()/rgba(), a small set of named colors)+ * @output Shared color parsing/formatting primitives used across the design system+ * @position Package utility; backs theme token resolution, HCT color math, and chart rendering+ *+ * A single home for the color parsers that were previously duplicated across+ * the theme layer, charts, and lab. Consumers get one well-tested definition of+ * "parse this color" rather than several subtly different regexes.+ */++/** A color decomposed into 0-255 RGB channels and a 0-1 alpha. */+export interface RGBA {+ r: number;+ g: number;+ b: number;+ a: number;+}++/** The named colors the design system relies on in token expressions. */+const NAMED_COLORS: Record<string, RGBA> = {+ transparent: {r: 0, g: 0, b: 0, a: 0},+ black: {r: 0, g: 0, b: 0, a: 1},+ white: {r: 255, g: 255, b: 255, a: 1},+};++const clamp = (value: number, min: number, max: number): number =>+ Math.max(min, Math.min(max, value));++/** Expand a shorthand hex body (`rgb`/`rgba`) to its full form (`rrggbb`/`rrggbbaa`). */+function expandShorthand(body: string): string {+ return body+ .split('')+ .map(c => c + c)+ .join('');+}++/**+ * Parse a hex color into {@link RGBA}. Accepts `#rgb`, `#rgba`, `#rrggbb`, and+ * `#rrggbbaa`, with or without the leading `#`. Returns null for anything else.+ */+export function parseHex(hex: string): RGBA | null {+ if (typeof hex !== 'string') {+ return null;+ }+ const body = hex.trim().replace(/^#/, '');+ const normalized =+ body.length === 3 || body.length === 4 ? expandShorthand(body) : body;++ if (+ (normalized.length !== 6 && normalized.length !== 8) ||+ !/^[0-9a-fA-F]+$/.test(normalized)+ ) {+ return null;+ }++ return {+ r: parseInt(normalized.slice(0, 2), 16),+ g: parseInt(normalized.slice(2, 4), 16),+ b: parseInt(normalized.slice(4, 6), 16),+ a: normalized.length === 8 ? parseInt(normalized.slice(6, 8), 16) / 255 : 1,+ };+}++/**+ * Parse an `rgb()`/`rgba()` color into {@link RGBA}. Accepts comma- or+ * space-separated channels, an optional `/ alpha`, and percentage channels.+ */+export function parseRgb(value: string): RGBA | null {+ const open = value.indexOf('(');+ if (open === -1 || !value.trim().endsWith(')')) {+ return null;+ }+ const body = value+ .slice(open + 1, value.lastIndexOf(')'))+ .replace(/\//g, ' ');+ const parts = body+ .split(/[\s,]+/)+ .map(p => p.trim())+ .filter(Boolean);+ if (parts.length < 3) {+ return null;+ }++ const channel = (p: string): number => {+ const n = p.endsWith('%') ? (parseFloat(p) / 100) * 255 : parseFloat(p);+ return clamp(n, 0, 255);+ };+ const r = channel(parts[0]);+ const g = channel(parts[1]);+ const b = channel(parts[2]);+ if ([r, g, b].some(Number.isNaN)) {+ return null;+ }++ let a = 1;+ if (parts.length >= 4) {+ const raw = parts[3];+ a = raw.endsWith('%') ? parseFloat(raw) / 100 : parseFloat(raw);+ if (Number.isNaN(a)) {+ return null;+ }+ a = clamp(a, 0, 1);+ }+ return {r, g, b, a};+}++/**+ * Parse a concrete CSS color string into {@link RGBA}. Supports hex,+ * `rgb()`/`rgba()`, and the named colors used in token expressions. Returns+ * null for anything it can't evaluate (e.g. `var()`, `oklch()`, unknown names)+ * so callers can preserve the original expression rather than guessing.+ */+export function parseColor(value: string): RGBA | null {+ const trimmed = value.trim();+ const named = NAMED_COLORS[trimmed.toLowerCase()];+ if (named) {+ return {...named};+ }+ if (trimmed.startsWith('#')) {+ return parseHex(trimmed);+ }+ if (/^rgba?\(/i.test(trimmed)) {+ return parseRgb(trimmed);+ }+ return null;+}++/** Format RGB channels (0-255) as an uppercase `#RRGGBB` string. */+export function formatHex(r: number, g: number, b: number): string {+ const channel = (c: number): string =>+ clamp(Math.round(c), 0, 255).toString(16).padStart(2, '0').toUpperCase();+ return `#${channel(r)}${channel(g)}${channel(b)}`;+}++/**+ * Serialize {@link RGBA} to a compact, JS-usable CSS color: `#RRGGBB` when+ * fully opaque, otherwise `rgba(r, g, b, a)`.+ */+export function formatColor({r, g, b, a}: RGBA): string {+ if (a >= 1) {+ return formatHex(r, g, b);+ }+ const round = (n: number): number => clamp(Math.round(n), 0, 255);+ return `rgba(${round(r)}, ${round(g)}, ${round(b)}, ${parseFloat(a.toFixed(4))})`;+}diff --git a/packages/core/src/utils/index.ts b/packages/core/src/utils/index.tsindex d3b7ccd4ed..888343b4ab 100644--- a/packages/core/src/utils/index.ts+++ b/packages/core/src/utils/index.ts@@ -81,3 +81,6 @@ export {observeResize, unobserveResize} from './sharedResizeObserver';export {isRenderable} from './isRenderable';export {getInputARIA} from './inputAria';export type {InputARIA, InputARIAInputGroup} from './inputAria';++export {parseHex, parseRgb, parseColor, formatHex, formatColor} from './color';+export type {RGBA} from './color';