Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(theme): add useXDSTheme hook for programmatic token access (#1031)

Cindy Zhangd9f7aa081fd9
diff --git a/apps/storybook/stories/XDSTheme.stories.tsx b/apps/storybook/stories/XDSTheme.stories.tsx
new file mode 100644
index 0000000000..f02201f776
--- /dev/null
+++ b/apps/storybook/stories/XDSTheme.stories.tsx
@@ -0,0 +1,429 @@
+import type {Meta, StoryObj} from '@storybook/react';
+import * as React from 'react';
+import {XDSTheme, defineTheme, useXDSTheme} from '@xds/core/theme';
+import {XDSCard} from '@xds/core/Card';
+import {XDSStack} from '@xds/core/Stack';
+import {XDSHeading} from '@xds/core/Text';
+import {XDSBadge} from '@xds/core/Badge';
+import {defaultTheme} from '@xds/theme-default';
+
+// =============================================================================
+// Sample data for the chart
+// =============================================================================
+
+const CHART_DATA = [
+ {label: 'Mon', value: 42},
+ {label: 'Tue', value: 78},
+ {label: 'Wed', value: 56},
+ {label: 'Thu', value: 91},
+ {label: 'Fri', value: 64},
+ {label: 'Sat', value: 35},
+ {label: 'Sun', value: 48},
+];
+
+const MULTI_SERIES = [
+ {label: 'Q1', series: [120, 90, 70]},
+ {label: 'Q2', series: [140, 110, 85]},
+ {label: 'Q3', series: [100, 130, 95]},
+ {label: 'Q4', series: [160, 105, 120]},
+];
+
+// =============================================================================
+// Chart component using useXDSTheme
+// =============================================================================
+
+/**
+ * A simple SVG bar chart that reads theme tokens via useXDSTheme.
+ * Demonstrates how data viz components can use raw token values
+ * without CSS custom properties or DOM reads.
+ */
+function ThemeAwareBarChart({
+ data,
+ width = 400,
+ height = 200,
+}: {
+ data: typeof CHART_DATA;
+ width?: number;
+ height?: number;
+}) {
+ const {token} = useXDSTheme();
+
+ const maxValue = Math.max(...data.map(d => d.value));
+ const barWidth = (width - 60) / data.length - 8;
+ const chartHeight = height - 40;
+
+ return (
+ <svg width={width} height={height} role="img" aria-label="Bar chart">
+ {/* Grid lines */}
+ {[0.25, 0.5, 0.75, 1].map(pct => {
+ const y = chartHeight - chartHeight * pct + 20;
+ return (
+ <g key={pct}>
+ <line
+ x1={50}
+ y1={y}
+ x2={width - 10}
+ y2={y}
+ stroke={token('--color-border')}
+ strokeDasharray="4 4"
+ />
+ <text
+ x={45}
+ y={y + 4}
+ textAnchor="end"
+ fontSize={10}
+ fill={token('--color-text-secondary')}>
+ {Math.round(maxValue * pct)}
+ </text>
+ </g>
+ );
+ })}
+
+ {/* Bars */}
+ {data.map((d, i) => {
+ const barHeight = (d.value / maxValue) * chartHeight;
+ const x = 55 + i * (barWidth + 8);
+ const y = chartHeight - barHeight + 20;
+
+ return (
+ <g key={d.label}>
+ <rect
+ x={x}
+ y={y}
+ width={barWidth}
+ height={barHeight}
+ rx={3}
+ fill={token('--color-accent')}
+ />
+ <text
+ x={x + barWidth / 2}
+ y={height - 5}
+ textAnchor="middle"
+ fontSize={11}
+ fill={token('--color-text-secondary')}>
+ {d.label}
+ </text>
+ </g>
+ );
+ })}
+ </svg>
+ );
+}
+
+/**
+ * A multi-series grouped bar chart demonstrating multiple color tokens.
+ */
+function ThemeAwareGroupedChart({
+ data,
+ width = 480,
+ height = 220,
+}: {
+ data: typeof MULTI_SERIES;
+ width?: number;
+ height?: number;
+}) {
+ const {token} = useXDSTheme();
+
+ const seriesColors = [
+ token('--color-accent'),
+ token('--color-success'),
+ token('--color-warning'),
+ ];
+ const seriesLabels = ['Revenue', 'Users', 'Sessions'];
+
+ const maxValue = Math.max(...data.flatMap(d => d.series));
+ const groupWidth = (width - 80) / data.length;
+ const barWidth = (groupWidth - 16) / 3;
+ const chartHeight = height - 50;
+
+ return (
+ <div>
+ <svg
+ width={width}
+ height={height}
+ role="img"
+ aria-label="Grouped bar chart">
+ {/* Grid lines */}
+ {[0.25, 0.5, 0.75, 1].map(pct => {
+ const y = chartHeight - chartHeight * pct + 20;
+ return (
+ <line
+ key={pct}
+ x1={55}
+ y1={y}
+ x2={width - 10}
+ y2={y}
+ stroke={token('--color-border')}
+ strokeDasharray="4 4"
+ />
+ );
+ })}
+
+ {/* Grouped bars */}
+ {data.map((group, gi) => {
+ const groupX = 60 + gi * groupWidth;
+ return (
+ <g key={group.label}>
+ {group.series.map((value, si) => {
+ const barHeight = (value / maxValue) * chartHeight;
+ const x = groupX + si * (barWidth + 2);
+ const y = chartHeight - barHeight + 20;
+ return (
+ <rect
+ key={si}
+ x={x}
+ y={y}
+ width={barWidth}
+ height={barHeight}
+ rx={2}
+ fill={seriesColors[si]}
+ opacity={0.85}
+ />
+ );
+ })}
+ <text
+ x={groupX + (groupWidth - 16) / 2}
+ y={height - 26}
+ textAnchor="middle"
+ fontSize={11}
+ fill={token('--color-text-secondary')}>
+ {group.label}
+ </text>
+ </g>
+ );
+ })}
+ </svg>
+
+ {/* Legend */}
+ <div style={{display: 'flex', gap: 16, paddingLeft: 55}}>
+ {seriesLabels.map((label, i) => (
+ <div
+ key={label}
+ style={{display: 'flex', alignItems: 'center', gap: 6}}>
+ <div
+ style={{
+ width: 10,
+ height: 10,
+ borderRadius: 2,
+ backgroundColor: seriesColors[i],
+ opacity: 0.85,
+ }}
+ />
+ <span
+ style={{
+ fontSize: 11,
+ color: token('--color-text-secondary'),
+ }}>
+ {label}
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+}
+
+/**
+ * Displays the raw token values for inspection.
+ */
+function TokenInspector() {
+ const {token, mode, name} = useXDSTheme();
+
+ const inspectedTokens = [
+ '--color-accent',
+ '--color-success',
+ '--color-warning',
+ '--color-error',
+ '--color-text-primary',
+ '--color-text-secondary',
+ '--color-background-surface',
+ '--color-border',
+ '--spacing-4',
+ '--radius-element',
+ ];
+
+ return (
+ <XDSCard>
+ <XDSStack direction="vertical" gap={2}>
+ <XDSStack direction="horizontal" gap={2} vAlign="center">
+ <XDSHeading level={4}>Token Inspector</XDSHeading>
+ <XDSBadge label={name} />
+ <XDSBadge
+ variant={mode === 'dark' ? 'neutral' : 'info'}
+ label={mode}
+ />
+ </XDSStack>
+ <div
+ style={{
+ display: 'grid',
+ gridTemplateColumns: '1fr auto',
+ gap: '4px 16px',
+ fontFamily: 'monospace',
+ fontSize: 12,
+ }}>
+ {inspectedTokens.map(tokenName => (
+ <React.Fragment key={tokenName}>
+ <span style={{color: token('--color-text-secondary')}}>
+ {tokenName}
+ </span>
+ <span style={{display: 'flex', alignItems: 'center', gap: 6}}>
+ {tokenName.startsWith('--color-') && (
+ <span
+ style={{
+ display: 'inline-block',
+ width: 14,
+ height: 14,
+ borderRadius: 3,
+ backgroundColor: token(tokenName),
+ border: `1px solid ${token('--color-border-emphasized')}`,
+ }}
+ />
+ )}
+ <code>{token(tokenName)}</code>
+ </span>
+ </React.Fragment>
+ ))}
+ </div>
+ </XDSStack>
+ </XDSCard>
+ );
+}
+
+// =============================================================================
+// Custom theme for demonstrating override behavior
+// =============================================================================
+
+const oceanTheme = defineTheme({
+ name: 'ocean',
+ tokens: {
+ '--color-accent': ['#0077B6', '#48CAE4'],
+ '--color-success': ['#2D6A4F', '#52B788'],
+ '--color-warning': ['#E76F51', '#F4A261'],
+ '--color-background-surface': ['#F0F8FF', '#0A1628'],
+ '--color-text-primary': ['#023E8A', '#CAF0F8'],
+ '--color-text-secondary': ['#4A7FB5', '#89C2D9'],
+ '--color-border': ['#ADE8F433', '#02394A66'],
+ },
+ typography: {scale: {base: 14, ratio: 1.2}},
+});
+
+// =============================================================================
+// Stories
+// =============================================================================
+
+const meta: Meta = {
+ title: 'Components/XDSTheme',
+ parameters: {
+ docs: {
+ description: {
+ component:
+ '`XDSTheme` applies a theme to its children via CSS custom properties and ' +
+ 'provides programmatic token access through `useXDSTheme()`.\n\n' +
+ '`useXDSTheme()` returns resolved token values for the current color mode — ' +
+ 'designed for non-CSS consumers like data visualization libraries, canvas rendering, ' +
+ 'and SVG charts that need concrete values (hex colors, px values) rather than ' +
+ 'CSS custom property references.\n\n' +
+ '**No double render.** Values are available on first paint \u2014 no `getComputedStyle` ' +
+ 'or `useEffect` needed.',
+ },
+ },
+ },
+};
+
+export default meta;
+
+/**
+ * A simple bar chart using `useXDSTheme` to read token values.
+ * The chart colors, text, and grid lines all come from the theme.
+ */
+export const BarChart: StoryObj = {
+ render: () => (
+ <XDSTheme theme={defaultTheme} mode="light">
+ <XDSStack direction="vertical" gap={4}>
+ <XDSHeading level={3}>Weekly Activity</XDSHeading>
+ <XDSCard>
+ <ThemeAwareBarChart data={CHART_DATA} />
+ </XDSCard>
+ </XDSStack>
+ </XDSTheme>
+ ),
+};
+
+/**
+ * The same chart in dark mode \u2014 token values automatically resolve
+ * to their dark variants.
+ */
+export const BarChartDark: StoryObj = {
+ render: () => (
+ <XDSTheme theme={defaultTheme} mode="dark">
+ <XDSStack direction="vertical" gap={4}>
+ <XDSHeading level={3}>Weekly Activity</XDSHeading>
+ <XDSCard>
+ <ThemeAwareBarChart data={CHART_DATA} />
+ </XDSCard>
+ </XDSStack>
+ </XDSTheme>
+ ),
+};
+
+/**
+ * A grouped bar chart using multiple color tokens (accent, success, warning)
+ * to differentiate data series.
+ */
+export const GroupedChart: StoryObj = {
+ render: () => (
+ <XDSTheme theme={defaultTheme} mode="light">
+ <XDSStack direction="vertical" gap={4}>
+ <XDSHeading level={3}>Quarterly Metrics</XDSHeading>
+ <XDSCard>
+ <ThemeAwareGroupedChart data={MULTI_SERIES} />
+ </XDSCard>
+ </XDSStack>
+ </XDSTheme>
+ ),
+};
+
+/**
+ * Side-by-side comparison: same chart rendered with two different themes.
+ * The ocean theme overrides accent, success, and warning colors.
+ */
+export const ThemeComparison: StoryObj = {
+ render: () => (
+ <div style={{display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16}}>
+ <XDSTheme theme={defaultTheme} mode="light">
+ <XDSStack direction="vertical" gap={2}>
+ <XDSHeading level={4}>Default Theme</XDSHeading>
+ <XDSCard>
+ <ThemeAwareGroupedChart data={MULTI_SERIES} width={360} />
+ </XDSCard>
+ </XDSStack>
+ </XDSTheme>
+ <XDSTheme theme={oceanTheme} mode="light">
+ <XDSStack direction="vertical" gap={2}>
+ <XDSHeading level={4}>Ocean Theme</XDSHeading>
+ <XDSCard>
+ <ThemeAwareGroupedChart data={MULTI_SERIES} width={360} />
+ </XDSCard>
+ </XDSStack>
+ </XDSTheme>
+ </div>
+ ),
+};
+
+/**
+ * Shows the raw resolved token values for both themes side by side.
+ * Useful for debugging and understanding what values your charts receive.
+ */
+export const TokenInspectorStory: StoryObj = {
+ name: 'Token Inspector',
+ render: () => (
+ <div style={{display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16}}>
+ <XDSTheme theme={defaultTheme} mode="light">
+ <TokenInspector />
+ </XDSTheme>
+ <XDSTheme theme={oceanTheme} mode="dark">
+ <TokenInspector />
+ </XDSTheme>
+ </div>
+ ),
+};
diff --git a/packages/core/src/theme/XDSTheme.tsx b/packages/core/src/theme/XDSTheme.tsx
index b4207a9953..82d70df96a 100644
--- a/packages/core/src/theme/XDSTheme.tsx
+++ b/packages/core/src/theme/XDSTheme.tsx
@@ -20,12 +20,19 @@
* ```
*/
-import React, {useId, useInsertionEffect, useLayoutEffect, useRef} from 'react';
+import React, {
+ useId,
+ useInsertionEffect,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {ThemeMode} from './types';
import {colorVars, typographyVars} from './tokens.stylex';
import {registerIcons} from '../Icon/globalIconRegistry';
import {generateThemeCSS, type XDSDefinedTheme} from './defineTheme';
+import {XDSThemeContext} from './useXDSTheme';
/**
* XDSTheme provider props
@@ -202,13 +209,18 @@ export function XDSTheme({
registerIcons(icons);
}
+ // Memoize the context value to prevent unnecessary re-renders
+ const ctxValue = useMemo(() => ({theme, mode}), [theme, mode]);
+
return (
- <div
- {...stylex.props(wrapperStyles.base, colorSchemeStyle)}
- data-xds-theme={theme.name}
- data-theme={mode === 'system' ? undefined : mode}>
- {children}
- </div>
+ <XDSThemeContext.Provider value={ctxValue}>
+ <div
+ {...stylex.props(wrapperStyles.base, colorSchemeStyle)}
+ data-xds-theme={theme.name}
+ data-theme={mode === 'system' ? undefined : mode}>
+ {children}
+ </div>
+ </XDSThemeContext.Provider>
);
}
diff --git a/packages/core/src/theme/defineTheme.ts b/packages/core/src/theme/defineTheme.ts
index ebbac4f0cb..1328501789 100644
--- a/packages/core/src/theme/defineTheme.ts
+++ b/packages/core/src/theme/defineTheme.ts
@@ -257,6 +257,13 @@ export interface XDSDefinedTheme {
* Passed through from defineTheme input unchanged.
*/
fonts?: ThemeFontSource[];
+ /**
+ * Raw input tokens preserved from defineTheme() input.
+ * Keeps [light, dark] tuples intact for programmatic access
+ * (e.g. data viz, canvas rendering) without parsing light-dark() strings.
+ * @internal
+ */
+ __inputTokens?: Partial<Record<string, XDSTokenValue>>;
}
// =============================================================================
@@ -495,6 +502,7 @@ export function defineTheme(input: XDSDefineThemeInput): XDSDefinedTheme {
components,
icons: input.icons,
fonts,
+ __inputTokens: input.tokens,
};
}
diff --git a/packages/core/src/theme/index.ts b/packages/core/src/theme/index.ts
index ee415ddca8..2e13d96080 100644
--- a/packages/core/src/theme/index.ts
+++ b/packages/core/src/theme/index.ts
@@ -97,6 +97,9 @@ export type {
TypeScaleVarName,
} from './tokens.stylex';
+export {useXDSTheme} from './useXDSTheme';
+export type {UseXDSThemeReturn} from './useXDSTheme';
+
export type {
ThemeMode,
HeadingLevel,
diff --git a/packages/core/src/theme/useXDSTheme.test.tsx b/packages/core/src/theme/useXDSTheme.test.tsx
new file mode 100644
index 0000000000..eceec492dc
--- /dev/null
+++ b/packages/core/src/theme/useXDSTheme.test.tsx
@@ -0,0 +1,112 @@
+import {describe, it, expect, vi} from 'vitest';
+import {renderHook} from '@testing-library/react';
+import React from 'react';
+import {XDSTheme} from './XDSTheme';
+import {defineTheme} from './defineTheme';
+import {useXDSTheme} from './useXDSTheme';
+
+// Mock useMediaQuery — default to light mode
+vi.mock('../hooks/useMediaQuery', () => ({
+ useMediaQuery: vi.fn(() => false),
+}));
+
+const testTheme = defineTheme({
+ name: 'test',
+ tokens: {
+ '--color-accent': ['#AA0000', '#FF5555'],
+ '--spacing-4': '20px',
+ },
+});
+
+function wrapper({
+ children,
+ mode,
+}: {
+ children: React.ReactNode;
+ mode?: 'light' | 'dark' | 'system';
+}) {
+ return (
+ <XDSTheme theme={testTheme} mode={mode}>
+ {children}
+ </XDSTheme>
+ );
+}
+
+describe('useXDSTheme', () => {
+ it('returns defaults when used outside XDSTheme', () => {
+ const {result} = renderHook(() => useXDSTheme());
+ expect(result.current.name).toBe('default');
+ // Should resolve default light-dark() tokens for light mode (useMediaQuery mocked to false = light)
+ expect(result.current.token('--color-text-primary')).toBe('#0A1317');
+ expect(result.current.token('--spacing-1')).toBe('4px');
+ expect(result.current.mode).toBe('light');
+ });
+
+ it('returns the theme name', () => {
+ const {result} = renderHook(() => useXDSTheme(), {
+ wrapper: ({children}) => wrapper({children, mode: 'light'}),
+ });
+ expect(result.current.name).toBe('test');
+ });
+
+ it('resolves tuple tokens to light values in light mode', () => {
+ const {result} = renderHook(() => useXDSTheme(), {
+ wrapper: ({children}) => wrapper({children, mode: 'light'}),
+ });
+ expect(result.current.token('--color-accent')).toBe('#AA0000');
+ });
+
+ it('resolves tuple tokens to dark values in dark mode', () => {
+ const {result} = renderHook(() => useXDSTheme(), {
+ wrapper: ({children}) => wrapper({children, mode: 'dark'}),
+ });
+ expect(result.current.token('--color-accent')).toBe('#FF5555');
+ });
+
+ it('resolves single-value tokens unchanged', () => {
+ const {result} = renderHook(() => useXDSTheme(), {
+ wrapper: ({children}) => wrapper({children, mode: 'light'}),
+ });
+ expect(result.current.token('--spacing-4')).toBe('20px');
+ });
+
+ it('falls back to defaults for tokens not in theme', () => {
+ const {result} = renderHook(() => useXDSTheme(), {
+ wrapper: ({children}) => wrapper({children, mode: 'light'}),
+ });
+ // --spacing-1 is not overridden — should be the default '4px'
+ expect(result.current.token('--spacing-1')).toBe('4px');
+ });
+
+ it('resolves default light-dark() string tokens for the mode', () => {
+ const {result} = renderHook(() => useXDSTheme(), {
+ wrapper: ({children}) => wrapper({children, mode: 'dark'}),
+ });
+ // --color-text-primary defaults to light-dark(#0A1317, #DFE2E5)
+ expect(result.current.token('--color-text-primary')).toBe('#DFE2E5');
+ });
+
+ it('returns empty string for unknown tokens', () => {
+ const {result} = renderHook(() => useXDSTheme(), {
+ wrapper: ({children}) => wrapper({children, mode: 'light'}),
+ });
+ expect(result.current.token('--nonexistent')).toBe('');
+ });
+
+ it('exposes mode reflecting effective mode', () => {
+ const {result} = renderHook(() => useXDSTheme(), {
+ wrapper: ({children}) => wrapper({children, mode: 'dark'}),
+ });
+ expect(result.current.mode).toBe('dark');
+ });
+
+ it('provides a tokens map with all resolved values', () => {
+ const {result} = renderHook(() => useXDSTheme(), {
+ wrapper: ({children}) => wrapper({children, mode: 'light'}),
+ });
+ const tokens = result.current.tokens;
+ expect(tokens['--color-accent']).toBe('#AA0000');
+ expect(tokens['--spacing-4']).toBe('20px');
+ expect(tokens['--spacing-1']).toBe('4px');
+ });
+});
diff --git a/packages/core/src/theme/useXDSTheme.ts b/packages/core/src/theme/useXDSTheme.ts
new file mode 100644
index 0000000000..dc49fa4912
--- /dev/null
+++ b/packages/core/src/theme/useXDSTheme.ts
@@ -0,0 +1,200 @@
+'use client';
+
+/**
+ * @file useXDSTheme.ts
+ * @input XDSThemeContext provided by XDSTheme
+ * @output Exports useXDSTheme hook for programmatic access to resolved theme tokens
+ * @position Theme hook; used by data viz, canvas, and non-CSS consumers
+ *
+ * Provides synchronous access to theme token values resolved for the
+ * current color mode — no DOM reads, no double render.
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/theme/index.ts
+ * - /packages/core/src/theme/README.md (if present)
+ */
+
+import {createContext, useContext, useMemo} from 'react';
+import type {ThemeMode} from './types';
+import type {XDSDefinedTheme, XDSTokenValue} from './defineTheme';
+import {xdsTokenDefaults} from './defineTheme';
+import {useMediaQuery} from '../hooks/useMediaQuery';
+
+// =============================================================================
+// Context
+// =============================================================================
+
+/**
+ * Internal context value — carries the theme + mode from XDSTheme.
+ * @internal
+ */
+export interface XDSThemeContextValue {
+ /** The defined theme object */
+ theme: XDSDefinedTheme;
+ /** The color mode prop passed to XDSTheme */
+ mode: ThemeMode;
+}
+
+/**
+ * React context for the nearest XDSTheme provider.
+ * null when no provider is present.
+ * @internal
+ */
+export const XDSThemeContext = createContext<XDSThemeContextValue | null>(null);
+
+// =============================================================================
+// Return type
+// =============================================================================
+
+/**
+ * Resolved theme data returned by useXDSTheme.
+ */
+export interface UseXDSThemeReturn {
+ /** Theme name */
+ name: string;
+ /** Resolved effective mode ('light' | 'dark') — never 'system' */
+ mode: 'light' | 'dark';
+ /**
+ * Resolve a token to its raw CSS value for the current color mode.
+ *
+ * For tokens with [light, dark] tuples, returns the value matching
+ * the current mode. For single-value tokens, returns the value as-is.
+ *
+ * Falls back to xdsTokenDefaults if the token isn't overridden by the theme.
+ *
+ * @example
+ * ```
+ * const accent = token('--color-accent'); // "#0064E0" in light mode
+ * const spacing = token('--spacing-4'); // "16px"
+ * ```
+ */
+ token: (name: string) => string;
+ /**
+ * All tokens resolved for the current color mode.
+ *
+ * Merges xdsTokenDefaults with the theme's overrides, resolving
+ * light-dark() values based on the effective color mode.
+ *
+ * Memoized — stable reference unless theme or mode changes.
+ */
+ tokens: Record<string, string>;
+}
+
+// =============================================================================
+// Helpers
+// =============================================================================
+
+/**
+ * Resolve a single token value for a given mode.
+ * - [light, dark] tuple → picks the correct side
+ * - string → if it's a light-dark() CSS function, parse and pick; otherwise pass through
+ */
+function resolveValue(value: XDSTokenValue, mode: 'light' | 'dark'): string {
+ if (Array.isArray(value)) {
+ return mode === 'dark' ? value[1] : value[0];
+ }
+ // For string values, try to parse light-dark(a, b) from defaults
+ const match = value.match(/^light-dark\(\s*(.+?)\s*,\s*(.+?)\s*\)$/);
+ if (match) {
+ return mode === 'dark' ? match[2] : match[1];
+ }
+ return value;
+}
+
+/**
+ * Build the full resolved token map for a theme + mode.
+ */
+function buildResolvedTokens(
+ theme: XDSDefinedTheme,
+ mode: 'light' | 'dark',
+): Record<string, string> {
+ const resolved = buildDefaultTokens(mode);
+
+ // Layer theme overrides on top
+ // Prefer __inputTokens (preserves tuples) over .tokens (already resolved to light-dark() strings)
+ if (theme.__inputTokens) {
+ for (const [key, value] of Object.entries(theme.__inputTokens)) {
+ if (value !== undefined) {
+ resolved[key] = resolveValue(value, mode);
+ }
+ }
+ } else {
+ // Fallback: parse light-dark() strings from .tokens
+ for (const [key, value] of Object.entries(theme.tokens)) {
+ resolved[key] = resolveValue(value, mode);
+ }
+ }
+
+ return resolved;
+}
+
+/**
+ * Build the resolved token map from defaults only (no theme provider).
+ */
+function buildDefaultTokens(mode: 'light' | 'dark'): Record<string, string> {
+ const resolved: Record<string, string> = {};
+ for (const [key, value] of Object.entries(xdsTokenDefaults)) {
+ resolved[key] = resolveValue(value, mode);
+ }
+ return resolved;
+}
+
+// =============================================================================
+// Hook
+// =============================================================================
+
+/**
+ * Access the current XDS theme's token values, resolved for the active color mode.
+ *
+ * Returns raw CSS values (hex colors, px values, etc.) suitable for
+ * non-CSS consumers like canvas, SVG, or data visualization libraries
+ * (e.g. Vega, D3, Chart.js) that need concrete values rather than
+ * CSS custom property references.
+ *
+ * Must be called inside an <XDSTheme> provider.
+ *
+ * @example
+ * ```
+ * function Chart() {
+ * const { token, mode } = useXDSTheme();
+ * return (
+ * <svg>
+ * <rect fill={token('--color-accent')} />
+ * <text fill={token('--color-text-primary')}>Sales</text>
+ * </svg>
+ * );
+ * }
+ * ```
+ */
+export function useXDSTheme(): UseXDSThemeReturn {
+ const ctx = useContext(XDSThemeContext);
+
+ // Resolve 'system' to 'light' | 'dark' using the OS preference
+ const prefersDark = useMediaQuery('(prefers-color-scheme: dark)');
+
+ const mode = ctx?.mode ?? 'system';
+ const theme = ctx?.theme ?? null;
+
+ const effectiveMode: 'light' | 'dark' =
+ mode === 'system' ? (prefersDark ? 'dark' : 'light') : mode;
+
+ // Build the full resolved map, memoized on theme + effective mode
+ const tokens = useMemo(
+ () =>
+ theme
+ ? buildResolvedTokens(theme, effectiveMode)
+ : buildDefaultTokens(effectiveMode),
+ [theme, effectiveMode],
+ );
+
+ const token = (name: string): string => {
+ return tokens[name] ?? '';
+ };
+
+ return {
+ name: theme?.name ?? 'default',
+ mode: effectiveMode,
+ token,
+ tokens,
+ };
+}