An open source design system that's fully customizable and agent ready
TypeScript
feat(theme): add XDSMediaTheme for inverted surface theming (#1211)
Cindy Zhangc849d96ef337
diff --git a/apps/storybook/stories/XDSMediaTheme.stories.tsx b/apps/storybook/stories/XDSMediaTheme.stories.tsxnew file mode 100644index 0000000000..cfd13224ef--- /dev/null+++ b/apps/storybook/stories/XDSMediaTheme.stories.tsx@@ -0,0 +1,596 @@+import type {Meta, StoryObj} from '@storybook/react';+import * as React from 'react';+import {XDSMediaTheme, defineTheme} from '@xds/core/theme';+import {XDSButton} from '@xds/core/Button';+import {XDSLink} from '@xds/core/Link';+import {XDSText} from '@xds/core/Text';+import {XDSBadge} from '@xds/core/Badge';+import {XDSIcon} from '@xds/core/Icon';+import {XDSStack} from '@xds/core/Stack';+import {XDSTheme} from '@xds/core/theme';+import {defaultTheme} from '@xds/theme-default';+import {neutralTheme} from '@xds/theme-neutral';+import {brutalistTheme} from '@xds/theme-brutalist';+import {XDSCard} from '@xds/core/Card';++// =============================================================================+// Meta+// =============================================================================++const meta: Meta = {+ title: 'Theme/XDSMediaTheme',+ parameters: {+ docs: {+ description: {+ component:+ 'Inverted surface theming context. Wraps children so they render correctly on dark or light backgrounds — buttons, links, text, and icons all pick up the right colors automatically.',+ },+ },+ },+};++export default meta;++// =============================================================================+// On Dark Surface+// =============================================================================++function OnDarkDemo() {+ return (+ <div+ style={{+ backgroundColor: 'var(--color-surface-inverted, light-dark(#0A1317, #FFFFFF))',+ borderRadius: 'var(--radius-container)',+ padding: 16,+ }}>+ <XDSMediaTheme mode="dark">+ <XDSStack gap={3}>+ <XDSText>+ Content on a dark surface — text, icons, and interactive elements+ automatically adapt.+ </XDSText>+ <XDSStack direction="row" gap={2} align="center" wrap="wrap">+ <XDSButton label="Primary" />+ <XDSButton label="Secondary" variant="secondary" />+ <XDSButton label="Ghost" variant="ghost" />+ <XDSLink href="#" hasUnderline>+ A link+ </XDSLink>+ </XDSStack>+ <XDSStack direction="row" gap={2} align="center" wrap="wrap">+ <XDSBadge label="Badge" />+ <XDSIcon icon="info" size="md" />+ <XDSIcon icon="checkCircle" size="md" />+ </XDSStack>+ </XDSStack>+ </XDSMediaTheme>+ </div>+ );+}++export const OnDark: StoryObj = {+ render: () => <OnDarkDemo />,+ parameters: {+ docs: {+ description: {+ story:+ 'Content on a dark (inverted) surface. Text becomes light, icons invert, and button interaction states use white-tinted overlays.',+ },+ },+ },+};++// =============================================================================+// On Light Surface (dark mode)+// =============================================================================++function OnLightDemo() {+ return (+ <XDSTheme theme={defaultTheme} mode="dark">+ <div+ style={{+ padding: 16,+ backgroundColor: 'var(--color-background-surface)',+ }}>+ <XDSText>Dark mode page background</XDSText>+ <div+ style={{+ backgroundColor: 'var(--color-surface-inverted, light-dark(#0A1317, #FFFFFF))',+ borderRadius: 'var(--radius-container)',+ padding: 16,+ marginTop: 12,+ }}>+ <XDSMediaTheme mode="light">+ <XDSStack gap={3}>+ <XDSText>+ Content on a light surface in dark mode — text and icons become+ dark.+ </XDSText>+ <XDSStack direction="row" gap={2} align="center" wrap="wrap">+ <XDSButton label="Primary" />+ <XDSButton label="Secondary" variant="secondary" />+ <XDSButton label="Ghost" variant="ghost" />+ <XDSLink href="#" hasUnderline>+ A link+ </XDSLink>+ </XDSStack>+ </XDSStack>+ </XDSMediaTheme>+ </div>+ </div>+ </XDSTheme>+ );+}++export const OnLight: StoryObj = {+ render: () => <OnLightDemo />,+ parameters: {+ docs: {+ description: {+ story:+ 'Content on a light surface in dark mode. The inverse of OnDark — dark text on a light background when the page is dark.',+ },+ },+ },+};++// =============================================================================+// Toast-like Example+// =============================================================================++function ToastDemo() {+ return (+ <XDSStack gap={3}>+ {/* Info toast */}+ <div+ style={{+ backgroundColor: 'var(--color-surface-inverted, light-dark(#0A1317, #FFFFFF))',+ borderRadius: 'var(--radius-container)',+ padding: '12px 16px',+ boxShadow: 'var(--shadow-med)',+ maxWidth: 400, width: '100%',+ }}>+ <XDSMediaTheme mode="dark">+ <XDSStack direction="row" gap={3} align="center" wrap="wrap">+ <XDSText style={{flex: 1}}>Changes saved successfully.</XDSText>+ <XDSButton label="Undo" variant="secondary" size="sm" />+ <XDSButton+ label="Dismiss"+ variant="ghost"+ size="sm"+ icon={<XDSIcon icon="close" size="sm" />}+ />+ </XDSStack>+ </XDSMediaTheme>+ </div>++ {/* Error toast */}+ <div+ style={{+ backgroundColor: 'var(--color-error-inverted, light-dark(#AA071E, #E3193B))',+ borderRadius: 'var(--radius-container)',+ padding: '12px 16px',+ boxShadow: 'var(--shadow-med)',+ maxWidth: 400, width: '100%',+ }}>+ <XDSMediaTheme mode="dark">+ <XDSStack direction="row" gap={3} align="center" wrap="wrap">+ <XDSText style={{flex: 1}}>+ Failed to save. Check your connection.+ </XDSText>+ <XDSButton+ label="Dismiss"+ variant="ghost"+ size="sm"+ icon={<XDSIcon icon="close" size="sm" />}+ />+ </XDSStack>+ </XDSMediaTheme>+ </div>+ </XDSStack>+ );+}++export const ToastExample: StoryObj = {+ render: () => <ToastDemo />,+ parameters: {+ docs: {+ description: {+ story:+ 'Toast-like notifications using XDSMediaTheme. The dark surface sets up the right token context — buttons and text just work without manual color overrides.',+ },+ },+ },+};++// =============================================================================+// Component Override Boundary+// =============================================================================++/**+ * This is the key demo: themes with component overrides (brutalist has pill+ * buttons, uppercase text, thick borders on cards/ghost buttons). Inside+ * XDSMediaTheme, those component overrides STILL apply — structural styling+ * is preserved. Only the color tokens change for the inverted surface.+ */++function ComponentOverrideBoundaryDemo() {+ return (+ <XDSTheme theme={brutalistTheme}>+ <XDSStack gap={4}>+ <XDSText weight="semibold">+ Brutalist theme — notice the component overrides: pill buttons,+ uppercase text, thick card borders, bordered ghost buttons.+ </XDSText>++ {/* Normal surface — themed component overrides apply */}+ <XDSCard>+ <XDSStack gap={2} style={{padding: 16}}>+ <XDSText type="supporting" weight="semibold">+ Normal surface (themed overrides)+ </XDSText>+ <XDSStack direction="row" gap={2} align="center" wrap="wrap">+ <XDSButton label="Primary" />+ <XDSButton label="Secondary" variant="secondary" />+ <XDSButton label="Ghost" variant="ghost" />+ <XDSBadge label="Badge" />+ </XDSStack>+ </XDSStack>+ </XDSCard>++ {/* Inverted surface — scope boundary blocks component overrides */}+ <div+ style={{+ backgroundColor: 'var(--color-surface-inverted, light-dark(#0A1317, #FFFFFF))',+ borderRadius: 'var(--radius-element)',+ padding: 16,+ }}>+ <XDSMediaTheme mode="dark">+ <XDSStack gap={2}>+ <XDSText type="supporting" weight="semibold">+ Dark surface (same overrides, inverted tokens)+ </XDSText>+ <XDSStack direction="row" gap={2} align="center" wrap="wrap">+ <XDSButton label="Primary" />+ <XDSButton label="Secondary" variant="secondary" />+ <XDSButton label="Ghost" variant="ghost" />+ <XDSBadge label="Badge" />+ </XDSStack>+ </XDSStack>+ </XDSMediaTheme>+ </div>+ </XDSStack>+ </XDSTheme>+ );+}++export const ComponentOverrideBoundary: StoryObj = {+ render: () => <ComponentOverrideBoundaryDemo />,+ parameters: {+ docs: {+ description: {+ story:+ 'Shows component overrides flowing through to the media context. Brutalist theme applies bold component overrides (pill buttons, uppercase, thick borders) — these are preserved inside XDSMediaTheme. Only the color tokens change for the inverted surface.',+ },+ },+ },+};++// =============================================================================+// Themed — shows it works across different themes+// =============================================================================++function ThemedDemo() {+ return (+ <XDSStack gap={4}>+ {[+ {theme: defaultTheme, label: 'Default Theme'},+ {theme: neutralTheme, label: 'Neutral Theme'},+ {theme: brutalistTheme, label: 'Brutalist Theme'},+ ].map(({theme, label}) => (+ <XDSTheme key={label} theme={theme}>+ <XDSStack gap={2}>+ <XDSText weight="semibold">{label}</XDSText>+ <XDSStack direction="row" gap={3}>+ {/* Normal surface */}+ <div+ style={{+ backgroundColor: 'var(--color-background-card)',+ border: '1px solid var(--color-border)',+ borderRadius: 'var(--radius-container)',+ padding: 16,+ flex: 1,+ }}>+ <XDSStack gap={2}>+ <XDSText type="supporting">Normal surface</XDSText>+ <XDSButton label="Button" variant="secondary" />+ <XDSButton label="Ghost" variant="ghost" />+ <XDSLink href="#">Link</XDSLink>+ </XDSStack>+ </div>+ {/* Inverted surface */}+ <div+ style={{+ backgroundColor: 'var(--color-surface-inverted, light-dark(#0A1317, #FFFFFF))',+ borderRadius: 'var(--radius-container)',+ padding: 16,+ flex: 1,+ }}>+ <XDSMediaTheme mode="dark">+ <XDSStack gap={2}>+ <XDSText type="supporting">Dark surface</XDSText>+ <XDSButton label="Button" variant="secondary" />+ <XDSButton label="Ghost" variant="ghost" />+ <XDSLink href="#">Link</XDSLink>+ </XDSStack>+ </XDSMediaTheme>+ </div>+ </XDSStack>+ </XDSStack>+ </XDSTheme>+ ))}+ </XDSStack>+ );+}++export const AcrossThemes: StoryObj = {+ render: () => <ThemedDemo />,+ parameters: {+ docs: {+ description: {+ story:+ 'Side-by-side comparison across themes. Left column shows normal surface with themed component overrides. Right column shows XDSMediaTheme dark surface — same components, inverted tokens, default styles.',+ },+ },+ },+};++// =============================================================================+// Custom on-media overrides+// =============================================================================++const customTheme = defineTheme({+ name: 'custom-media',+ tokens: {+ '--color-accent': ['#7C3AED', '#A78BFA'],+ },+ onDark: {+ tokens: {+ // Custom: use a tinted accent color on dark surfaces instead of white+ '--color-accent': '#C4B5FD',+ '--color-text-accent': '#C4B5FD',+ },+ },+});++function CustomOverridesDemo() {+ return (+ <XDSTheme theme={customTheme}>+ <XDSStack gap={3}>+ <XDSText>+ This theme has a custom <code>onDark</code> config — the accent color+ on dark surfaces is a lighter purple instead of plain white.+ </XDSText>+ <div+ style={{+ backgroundColor: 'var(--color-surface-inverted, light-dark(#0A1317, #FFFFFF))',+ borderRadius: 'var(--radius-container)',+ padding: 16,+ }}>+ <XDSMediaTheme mode="dark">+ <XDSStack direction="row" gap={2} align="center" wrap="wrap">+ <XDSButton label="Accent button" />+ <XDSButton label="Secondary" variant="secondary" />+ <XDSLink href="#" hasUnderline>+ Accent link+ </XDSLink>+ </XDSStack>+ </XDSMediaTheme>+ </div>+ </XDSStack>+ </XDSTheme>+ );+}++export const CustomOverrides: StoryObj = {+ render: () => <CustomOverridesDemo />,+ parameters: {+ docs: {+ description: {+ story:+ 'Themes can provide custom `onDark` / `onLight` overrides in `defineTheme()` to fine-tune how components look on inverted surfaces.',+ },+ },+ },+};++// =============================================================================+// Auto-detected surface from image+// =============================================================================++import {useImageMode} from '@xds/core/hooks';++const DEMO_IMAGES = [+ {+ label: 'Dark photo (night city)',+ url: 'https://images.unsplash.com/photo-1519501025264-65ba15a82390?w=600&h=400&fit=crop',+ },+ {+ label: 'Light photo (beach)',+ url: 'https://images.unsplash.com/photo-1507525428034-b723cf961d3e?w=600&h=400&fit=crop',+ },+ {+ label: 'Mixed (sunset)',+ url: 'https://images.unsplash.com/photo-1495616811223-4d98c6e9c869?w=600&h=400&fit=crop',+ },+ {+ label: 'Dark (forest)',+ url: 'https://images.unsplash.com/photo-1448375240586-882707db888b?w=600&h=400&fit=crop',+ },+ {+ label: 'Light (snow)',+ url: 'https://images.unsplash.com/photo-1491002052546-bf38f186af56?w=600&h=400&fit=crop',+ },+];++function ImageCard({url, label}: {url: string; label: string}) {+ const surface = useImageMode(url);++ return (+ <div+ style={{+ position: 'relative',+ borderRadius: 'var(--radius-container, 12px)',+ overflow: 'hidden',+ maxWidth: 300, width: '100%',+ height: 200,+ }}>+ <img+ src={url}+ alt={label}+ style={{+ width: '100%',+ height: '100%',+ objectFit: 'cover',+ display: 'block',+ }}+ />+ <div+ style={{+ position: 'absolute',+ bottom: 0,+ left: 0,+ right: 0,+ padding: '12px 16px',+ background:+ surface === 'light'+ ? 'linear-gradient(transparent, rgba(255,255,255,0.8))'+ : 'linear-gradient(transparent, rgba(0,0,0,0.7))',+ }}>+ <XDSMediaTheme mode={surface ?? 'dark'}>+ <XDSStack gap={1}>+ <XDSText weight="semibold">{label}</XDSText>+ <XDSText type="supporting">+ Detected: <strong>{surface ?? 'loading...'}</strong>+ </XDSText>+ </XDSStack>+ </XDSMediaTheme>+ </div>+ </div>+ );+}++function AutoDetectDemo() {+ return (+ <XDSStack gap={3}>+ <XDSText>+ Each card auto-detects whether the image is dark or light using{' '}+ <code>useImageMode</code>, then applies the correct{' '}+ <code>XDSMediaTheme</code> surface. Text color adapts automatically.+ </XDSText>+ <XDSStack direction="row" gap={3} style={{flexWrap: 'wrap'}}>+ {DEMO_IMAGES.map(img => (+ <ImageCard key={img.url} {...img} />+ ))}+ </XDSStack>+ </XDSStack>+ );+}++export const AutoDetectFromImage: StoryObj = {+ render: () => <AutoDetectDemo />,+ parameters: {+ docs: {+ description: {+ story:+ 'Auto-detects image luminance via `useImageMode` hook and applies the correct `XDSMediaTheme` surface. Uses OffscreenCanvas to sample the image without interrupting the render loop.',+ },+ },+ },+};++// =============================================================================+// Regional detection+// =============================================================================++function RegionalDetectDemo() {+ const url =+ 'https://images.unsplash.com/photo-1495616811223-4d98c6e9c869?w=600&h=400&fit=crop';+ // Sample just the bottom strip where text overlays+ const bottomSurface = useImageMode(url, {+ region: {x: 0, y: 0.7, width: 1, height: 0.3},+ });+ const fullSurface = useImageMode(url);++ return (+ <XDSStack gap={3}>+ <XDSText>+ The sunset image has a light sky and dark horizon. Full-image detection+ says <strong>{fullSurface ?? '...'}</strong>, but sampling just the+ bottom 30% (where text sits) says{' '}+ <strong>{bottomSurface ?? '...'}</strong>.+ </XDSText>+ <div+ style={{+ position: 'relative',+ borderRadius: 'var(--radius-container, 12px)',+ overflow: 'hidden',+ maxWidth: 400, width: '100%',+ height: 260,+ }}>+ <img+ src={url}+ alt="Sunset"+ style={{+ width: '100%',+ height: '100%',+ objectFit: 'cover',+ display: 'block',+ }}+ />+ {/* Highlight the sampled region */}+ <div+ style={{+ position: 'absolute',+ bottom: 0,+ left: 0,+ right: 0,+ height: '30%',+ border: '2px dashed rgba(255,255,255,0.5)',+ borderBottom: 'none',+ pointerEvents: 'none',+ }}+ />+ <div+ style={{+ position: 'absolute',+ bottom: 0,+ left: 0,+ right: 0,+ padding: '12px 16px',+ }}>+ <XDSMediaTheme mode={bottomSurface ?? 'dark'}>+ <XDSStack gap={1}>+ <XDSText weight="semibold">Regional sampling</XDSText>+ <XDSText type="supporting">+ Bottom 30% → {bottomSurface ?? 'loading...'}+ </XDSText>+ </XDSStack>+ </XDSMediaTheme>+ </div>+ </div>+ </XDSStack>+ );+}++export const RegionalDetection: StoryObj = {+ render: () => <RegionalDetectDemo />,+ parameters: {+ docs: {+ description: {+ story:+ 'Regional detection samples a specific area of the image instead of the full average. Useful when text overlays a specific region — the sunset image is light overall but dark at the bottom where the text sits.',+ },+ },+ },+};diff --git a/packages/core/src/hooks/index.ts b/packages/core/src/hooks/index.tsindex 74a3288c2d..335a8ba6e9 100644--- a/packages/core/src/hooks/index.ts+++ b/packages/core/src/hooks/index.ts@@ -33,3 +33,5 @@ export type {StreamingTextSpeed,UseStreamingTextOptions,} from './useXDSStreamingText';+export {useImageMode} from './useImageMode';+export type {ImageSampleRegion, UseImageModeOptions} from './useImageMode';diff --git a/packages/core/src/hooks/useImageMode.ts b/packages/core/src/hooks/useImageMode.tsnew file mode 100644index 0000000000..6492e5657e--- /dev/null+++ b/packages/core/src/hooks/useImageMode.ts@@ -0,0 +1,163 @@+'use client';++/**+ * @file useImageMode.ts+ * @input Image source URL+ * @output Detected mode luminance: 'dark' | 'light' | null+ * @position Hook; used alongside XDSMediaTheme for auto-detection+ *+ * Detects whether an image is predominantly dark or light by sampling+ * its pixels via OffscreenCanvas. Runs entirely off the paint path —+ * no visible canvas element, no layout thrash.+ *+ * The 1×1 downsample trick lets the browser's internal resampling do+ * the averaging — no manual pixel-by-pixel luminance calculation.+ *+ * For regional detection (e.g. "what's the luminance where the text+ * overlay sits"), pass a `region` option to sample a specific area.+ *+ * @example+ * ```tsx+ * function ImageCard({ src }: { src: string }) {+ * const mode = useImageMode(src);+ * return (+ * <div style={{ backgroundImage: `url(${src})` }}>+ * <XDSMediaTheme mode={mode ?? 'dark'}>+ * <XDSText>Auto-detected text color</XDSText>+ * </XDSMediaTheme>+ * </div>+ * );+ * }+ * ```+ */++import {useState, useEffect} from 'react';++/**+ * Region to sample within the image (normalized 0-1 coordinates).+ * Useful for detecting luminance where text will be overlaid,+ * rather than the full image average.+ */+export interface ImageSampleRegion {+ /** Left edge (0 = left, 1 = right) */+ x: number;+ /** Top edge (0 = top, 1 = bottom) */+ y: number;+ /** Width as fraction of image width */+ width: number;+ /** Height as fraction of image height */+ height: number;+}++export interface UseImageModeOptions {+ /**+ * Region to sample. Defaults to the full image.+ * Use normalized coordinates (0-1).+ */+ region?: ImageSampleRegion;+ /**+ * Luminance threshold for the dark/light split.+ * Below this = 'dark', above = 'light'.+ * @default 0.5+ */+ threshold?: number;+ /**+ * Fallback value while loading or on error.+ * @default null+ */+ fallback?: 'dark' | 'light' | null;+}++/**+ * Calculate perceptual brightness from sRGB values (0-255).+ * Uses BT.709 luma coefficients on gamma-encoded values (not linearized).+ * This gives a result that matches human perception better than+ * true relative luminance for the purpose of "is this image dark or light."+ * Returns 0-1 where 0 is black, 1 is white.+ */+function perceptualBrightness(r: number, g: number, b: number): number {+ return (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;+}++/**+ * Detect whether an image is predominantly dark or light.+ *+ * Uses OffscreenCanvas to sample the image without interrupting+ * the main render loop. Returns null while loading.+ */+export function useImageMode(+ src: string | null | undefined,+ options: UseImageModeOptions = {},+): 'dark' | 'light' | null {+ const {region, threshold = 0.5, fallback = null} = options;+ const [mode, setMode] = useState<'dark' | 'light' | null>(fallback);++ useEffect(() => {+ if (!src) {+ setMode(fallback);+ return;+ }++ let cancelled = false;++ async function detect() {+ try {+ // Load image as bitmap (async, doesn't block rendering)+ const response = await fetch(src!, {mode: 'cors'});+ const blob = await response.blob();+ const bitmap = await createImageBitmap(blob);++ if (cancelled) return;++ // Determine source region+ const sx = region ? Math.round(region.x * bitmap.width) : 0;+ const sy = region ? Math.round(region.y * bitmap.height) : 0;+ const sw = region+ ? Math.round(region.width * bitmap.width)+ : bitmap.width;+ const sh = region+ ? Math.round(region.height * bitmap.height)+ : bitmap.height;++ // Sample at a small size and average all pixels manually.+ // OffscreenCanvas 1×1 drawImage can produce inaccurate results+ // depending on the browser's resampling algorithm.+ const sampleSize = 10;+ const canvas = new OffscreenCanvas(sampleSize, sampleSize);+ const ctx = canvas.getContext('2d');+ if (!ctx) return;++ ctx.drawImage(bitmap, sx, sy, sw, sh, 0, 0, sampleSize, sampleSize);+ const imageData = ctx.getImageData(0, 0, sampleSize, sampleSize).data;++ // Average all sampled pixels+ let totalR = 0, totalG = 0, totalB = 0;+ const pixelCount = sampleSize * sampleSize;+ for (let i = 0; i < imageData.length; i += 4) {+ totalR += imageData[i];+ totalG += imageData[i + 1];+ totalB += imageData[i + 2];+ }+ const r = totalR / pixelCount;+ const g = totalG / pixelCount;+ const b = totalB / pixelCount;++ if (cancelled) return;++ const brightness = perceptualBrightness(r, g, b);+ setMode(brightness > threshold ? 'light' : 'dark');+ } catch {+ // CORS error, network error, etc. — keep fallback+ if (!cancelled) setMode(fallback);+ }+ }++ detect();++ return () => {+ cancelled = true;+ };+ }, [src, region?.x, region?.y, region?.width, region?.height, threshold, fallback]);++ return mode;+}diff --git a/packages/core/src/theme/XDSMediaTheme.tsx b/packages/core/src/theme/XDSMediaTheme.tsxnew file mode 100644index 0000000000..af1a96fc7d--- /dev/null+++ b/packages/core/src/theme/XDSMediaTheme.tsx@@ -0,0 +1,75 @@+'use client';++/**+ * @file XDSMediaTheme.tsx+ * @input mode prop ("dark" | "light") + children+ * @output Wrapper div that creates an inverted theming context+ * @position Theme system component; sibling to XDSTheme+ *+ * Provides semantic token overrides for content rendered on a surface+ * with a different luminance than the page background. Used by Toast,+ * Tooltip, and other components that render on inverted surfaces.+ *+ * How it works:+ * 1. Sets `data-xds-media="dark|light"` — the theme's generated CSS+ * targets this to apply token overrides (including color-scheme).+ * 2. Parent theme's component overrides pass through — structural+ * styling (border-radius, font-weight, etc.) is preserved.+ * Only tokens (colors, overlays, borders) change for the surface.+ * 3. Themes can further customize components on media surfaces via+ * `onDark.components` / `onLight.components` in defineTheme().+ * 4. Children (Button, Link, Text, etc.) pick up inverted tokens+ * naturally through CSS custom property inheritance+ *+ * @example+ * ```tsx+ * // Dark surface (e.g. toast on a light page)+ * <div style={{ backgroundColor: 'var(--color-surface-inverted)' }}>+ * <XDSMediaTheme mode="dark">+ * <XDSButton label="Undo" variant="ghost" />+ * </XDSMediaTheme>+ * </div>+ * ```+ */++import * as React from 'react';+import * as stylex from '@stylexjs/stylex';+import {colorVars} from './tokens.stylex';++const styles = stylex.create({+ root: {+ display: 'contents',+ color: colorVars['--color-text-primary'],+ },+});++export interface XDSMediaThemeProps {+ /**+ * The surface luminance context for children.+ * - `"dark"` — children are on a dark background (get light text/icons)+ * - `"light"` — children are on a light background (get dark text/icons)+ */+ mode: 'dark' | 'light';+ /** Content to render in the media context */+ children: React.ReactNode;+}++/**+ * Inverted surface theming context.+ *+ * Wraps children with `data-xds-media` — the theme's CSS targets this+ * attribute to apply inverted tokens. Parent component overrides flow+ * through unchanged; only tokens change for the surface context.+ */+export function XDSMediaTheme({+ mode,+ children,+}: XDSMediaThemeProps): React.ReactElement {+ return (+ <div data-xds-media={mode} {...stylex.props(styles.root)}>+ {children}+ </div>+ );+}++XDSMediaTheme.displayName = 'XDSMediaTheme';diff --git a/packages/core/src/theme/defineTheme.ts b/packages/core/src/theme/defineTheme.tsindex 7ad41d9ff5..72772a1df5 100644--- a/packages/core/src/theme/defineTheme.ts+++ b/packages/core/src/theme/defineTheme.ts@@ -30,6 +30,11 @@import type {XDSIconRegistry} from '../Icon/globalIconRegistry';import type {ThemeFontSource, TypographyConfig, FontWeight} from './types';+import {+ resolveOnMedia,+ type OnMediaOverrides,+ type ResolvedOnMedia,+} from './onMediaTokens';import {parseStyleKey} from '../utils/parseStyleKey';import {colorDefaults,@@ -238,6 +243,31 @@ export interface XDSDefineThemeInput {components?: XDSComponentStyleMap;/** Icon registry — maps semantic icon names to React nodes */icons?: Partial<XDSIconRegistry>;+ /**+ * Overrides for content on a dark surface (e.g. inverted toast,+ * dark tooltip). Accepts token and component overrides — same shape+ * as the main theme. Token defaults are generated if omitted.+ *+ * Used by `<XDSMediaTheme surface="dark">` to set semantic tokens+ * and component styles so children render correctly against a dark+ * background.+ *+ * @example+ * ```tsx+ * onDark: {+ * tokens: { '--color-accent': '#90CAF9' },+ * components: {+ * button: { 'variant:ghost': { borderWidth: '1px' } },+ * },+ * }+ * ```+ */+ onDark?: OnMediaOverrides;+ /**+ * Overrides for content on a light surface. Same shape as `onDark`+ * but for the inverse case (e.g. dark-mode page with a light popover).+ */+ onLight?: OnMediaOverrides;}/** A defined theme — ready to pass to <XDSTheme> */@@ -264,6 +294,18 @@ export interface XDSDefinedTheme {* @internal*/__inputTokens?: Partial<Record<string, XDSTokenValue>>;+ /**+ * Resolved on-media token overrides for dark surfaces.+ * Generated by defineTheme from defaults + user onDark overrides.+ * Used by XDSMediaTheme and generateThemeRules.+ * @internal+ */+ __onDark?: ResolvedOnMedia;+ /**+ * Resolved on-media overrides for light surfaces.+ * @internal+ */+ __onLight?: ResolvedOnMedia;}// =============================================================================@@ -496,6 +538,10 @@ export function defineTheme(input: XDSDefineThemeInput): XDSDefinedTheme {if (fontList.length > 0) fonts = fontList;}+ // 5. Resolve on-media token overrides (defaults + user overrides)+ const __onDark = resolveOnMedia('dark', input.onDark);+ const __onLight = resolveOnMedia('light', input.onLight);+return {name: input.name,tokens,@@ -503,6 +549,8 @@ export function defineTheme(input: XDSDefineThemeInput): XDSDefinedTheme {icons: input.icons,fonts,__inputTokens: input.tokens,+ __onDark,+ __onLight,};}@@ -674,6 +722,8 @@ export function generateThemeRules(theme: XDSDefinedTheme): string[] {}}+ // (on-media rules are generated separately -- see generateOnMediaCSS)+return parts;}@@ -758,6 +808,89 @@ export interface ThemeCSSOutput {* sit at reset-layer priority where any class-based style wins, while component* overrides sit above StyleX so themes can restyle components intentionally.*/++// =============================================================================+// On-media CSS generation+// =============================================================================++/**+ * Generate CSS for on-media token and component overrides.+ *+ * Emitted in an unbounded @scope (no `to` limit) so the rules can reach+ * [data-xds-media] elements. Parent theme component overrides flow through+ * to media contexts -- only tokens change. Themes can further customize+ * via onDark.components / onLight.components.+ */+export function generateOnMediaCSS(theme: XDSDefinedTheme): string {+ const parts: string[] = [];+ const scopeSelector = `[data-xds-theme="${theme.name}"]`;++ for (const surface of ['dark', 'light'] as const) {+ const onMedia = surface === 'dark' ? theme.__onDark : theme.__onLight;+ if (!onMedia) continue;++ // Token overrides+ const tokenEntries = Object.entries(onMedia.tokens);+ if (tokenEntries.length > 0) {+ const declarations = tokenEntries+ .map(([prop, value]) => ` ${prop}: ${value};`)+ .join('\n');+ parts.push(` [data-xds-media="${surface}"] {\n${declarations}\n }`);+ }++ // Component overrides+ if (onMedia.components) {+ for (const [component, rules] of Object.entries(onMedia.components)) {+ for (const [key, styles] of Object.entries(+ rules as Record<+ string,+ Record<string, string | Record<string, string>>+ >,+ )) {+ const entries = Object.entries(styles);+ if (entries.length > 0) {+ const suffix = parseStyleKey(key);+ const baseSelector = `[data-xds-media="${surface}"] .xds-${component}${suffix}`;++ const props: [string, string][] = [];+ const pseudos: [string, Record<string, string>][] = [];++ for (const [prop, value] of entries) {+ if (prop.startsWith(':') && typeof value === 'object') {+ pseudos.push([prop, value as Record<string, string>]);+ } else {+ props.push([prop, value as string]);+ }+ }++ if (props.length > 0) {+ const declarations = props+ .map(([prop, value]) => ` ${toKebabCase(prop)}: ${value};`)+ .join('\n');+ parts.push(` ${baseSelector} {\n${declarations}\n }`);+ }++ for (const [pseudo, pseudoStyles] of pseudos) {+ const pseudoEntries = Object.entries(pseudoStyles);+ if (pseudoEntries.length > 0) {+ const declarations = pseudoEntries+ .map(([prop, value]) => ` ${toKebabCase(prop)}: ${value};`)+ .join('\n');+ parts.push(` ${baseSelector}${pseudo} {\n${declarations}\n }`);+ }+ }+ }+ }+ }+ }+ }++ if (parts.length === 0) return '';++ const inner = parts.join('\n\n');+ return `@scope (${scopeSelector}) to ([data-xds-theme]) {\n${inner}\n}`;+}+export function generateThemeCSS(theme: XDSDefinedTheme): ThemeCSSOutput {const {component, prose} = generateThemeRulesSplit(theme);const scopeSelector = `[data-xds-theme="${theme.name}"]`;@@ -769,12 +902,19 @@ export function generateThemeCSS(theme: XDSDefinedTheme): ThemeCSSOutput {proseCss = `@scope (${scopeSelector}) to (${scopeTo}) {\n${proseInner}\n}`;}+ // Component rules: bounded scope (stops at nested themes) ++ // on-media rules in unbounded scope (can reach [data-xds-media] elements)let componentCss = '';if (component.length > 0) {const componentInner = component.join('\n\n');componentCss = `@scope (${scopeSelector}) to (${scopeTo}) {\n${componentInner}\n}`;}+ const onMediaCss = generateOnMediaCSS(theme);+ if (onMediaCss) {+ componentCss = componentCss ? `${componentCss}\n\n${onMediaCss}` : onMediaCss;+ }+return {prose: proseCss, component: componentCss};}diff --git a/packages/core/src/theme/index.ts b/packages/core/src/theme/index.tsindex 1ca24a174a..dfdcf2334d 100644--- a/packages/core/src/theme/index.ts+++ b/packages/core/src/theme/index.ts@@ -14,10 +14,13 @@*/export {XDSTheme} from './XDSTheme';+export {XDSMediaTheme} from './XDSMediaTheme';+export type {XDSMediaThemeProps} from './XDSMediaTheme';export {defineTheme,generateThemeCSS,generateThemeCSSFlat,+ generateOnMediaCSS,generateThemeRules,generateThemeRulesSplit,type ThemeCSSOutput,@@ -104,6 +107,13 @@ export type {export {useXDSTheme} from './useXDSTheme';export type {UseXDSThemeReturn} from './useXDSTheme';+export {+ defaultOnDarkTokens,+ defaultOnLightTokens,+ resolveOnMedia,+} from './onMediaTokens';+export type {OnMediaOverrides, ResolvedOnMedia} from './onMediaTokens';+export type {ThemeMode,HeadingLevel,diff --git a/packages/core/src/theme/onMediaTokens.test.ts b/packages/core/src/theme/onMediaTokens.test.tsnew file mode 100644index 0000000000..20610a8767--- /dev/null+++ b/packages/core/src/theme/onMediaTokens.test.ts@@ -0,0 +1,192 @@+import {describe, it, expect} from 'vitest';+import {defineTheme, generateOnMediaCSS} from './defineTheme';+import {+ defaultOnDarkTokens,+ defaultOnLightTokens,+ resolveOnMedia,+} from './onMediaTokens';++describe('onMediaTokens', () => {+ describe('defaultOnDarkTokens', () => {+ it('sets color-scheme to dark', () => {+ expect(defaultOnDarkTokens['color-scheme']).toBe('dark');+ });++ it('provides text primary as on-dark color', () => {+ expect(defaultOnDarkTokens['--color-text-primary']).toBe(+ 'var(--color-on-dark)',+ );+ });++ it('provides icon primary as on-dark color', () => {+ expect(defaultOnDarkTokens['--color-icon-primary']).toBe(+ 'var(--color-on-dark)',+ );+ });++ it('collapses accent to on-dark color', () => {+ expect(defaultOnDarkTokens['--color-accent']).toBe(+ 'var(--color-on-dark)',+ );+ });+ });++ describe('defaultOnLightTokens', () => {+ it('sets color-scheme to light', () => {+ expect(defaultOnLightTokens['color-scheme']).toBe('light');+ });++ it('provides text primary as on-light color', () => {+ expect(defaultOnLightTokens['--color-text-primary']).toBe(+ 'var(--color-on-light)',+ );+ });+ });++ describe('resolveOnMedia', () => {+ it('returns defaults when no user overrides', () => {+ const result = resolveOnMedia('dark');+ expect(result.tokens).toEqual(defaultOnDarkTokens);+ expect(result.components).toBeUndefined();+ });++ it('merges user token overrides with defaults', () => {+ const result = resolveOnMedia('dark', {+ tokens: {'--color-accent': '#90CAF9'},+ });+ expect(result.tokens['--color-accent']).toBe('#90CAF9');+ expect(result.tokens['--color-text-primary']).toBe(+ 'var(--color-on-dark)',+ );+ });++ it('resolves [light, dark] tuple tokens', () => {+ const result = resolveOnMedia('dark', {+ tokens: {'--color-accent': ['#AAA', '#BBB']},+ });+ expect(result.tokens['--color-accent']).toBe('light-dark(#AAA, #BBB)');+ });++ it('passes through component overrides', () => {+ const components = {+ button: {+ 'variant:ghost': {borderWidth: '1px'},+ },+ };+ const result = resolveOnMedia('dark', {components});+ expect(result.components).toBe(components);+ });++ it('returns light defaults for surface=light', () => {+ const result = resolveOnMedia('light');+ expect(result.tokens).toEqual(defaultOnLightTokens);+ });+ });+});++describe('defineTheme with onDark/onLight', () => {+ it('stores resolved onDark on the theme', () => {+ const theme = defineTheme({+ name: 'test',+ onDark: {+ tokens: {'--color-accent': '#90CAF9'},+ },+ });+ expect(theme.__onDark).toBeDefined();+ expect(theme.__onDark!.tokens['--color-accent']).toBe('#90CAF9');+ expect(theme.__onDark!.tokens['--color-text-primary']).toBe(+ 'var(--color-on-dark)',+ );+ });++ it('stores resolved onLight on the theme', () => {+ const theme = defineTheme({+ name: 'test',+ onLight: {+ tokens: {'--color-accent': '#333'},+ },+ });+ expect(theme.__onLight).toBeDefined();+ expect(theme.__onLight!.tokens['--color-accent']).toBe('#333');+ });++ it('generates defaults even without explicit onDark/onLight', () => {+ const theme = defineTheme({name: 'test'});+ expect(theme.__onDark).toBeDefined();+ expect(theme.__onLight).toBeDefined();+ expect(theme.__onDark!.tokens['color-scheme']).toBe('dark');+ expect(theme.__onLight!.tokens['color-scheme']).toBe('light');+ });++ it('stores component overrides on onDark', () => {+ const theme = defineTheme({+ name: 'test',+ onDark: {+ components: {+ button: {'variant:ghost': {borderWidth: '1px'}},+ },+ },+ });+ expect(theme.__onDark!.components).toBeDefined();+ expect(theme.__onDark!.components!.button['variant:ghost']).toEqual({+ borderWidth: '1px',+ });+ });+});++describe('generateOnMediaCSS', () => {+ it('emits @scope with [data-xds-media] token rules', () => {+ const theme = defineTheme({name: 'test'});+ const css = generateOnMediaCSS(theme);+ expect(css).toContain('@scope ([data-xds-theme="test"])');+ // Same scope boundary as main theme+ expect(css).toContain('to ([data-xds-theme])');+ expect(css).toContain('[data-xds-media="dark"]');+ expect(css).toContain('color-scheme: dark');+ expect(css).toContain('var(--color-on-dark)');+ });++ it('emits light media rules', () => {+ const theme = defineTheme({name: 'test'});+ const css = generateOnMediaCSS(theme);+ expect(css).toContain('[data-xds-media="light"]');+ expect(css).toContain('color-scheme: light');+ });++ it('emits component override rules', () => {+ const theme = defineTheme({+ name: 'test',+ onDark: {+ components: {+ button: {+ 'variant:secondary': {+ backgroundColor: 'color-mix(in srgb, white 20%, transparent)',+ },+ },+ },+ },+ });+ const css = generateOnMediaCSS(theme);+ expect(css).toContain('[data-xds-media="dark"] .xds-button.secondary');+ expect(css).toContain('background-color: color-mix(in srgb, white 20%, transparent)');+ });++ it('emits pseudo-class rules for on-media components', () => {+ const theme = defineTheme({+ name: 'test',+ onDark: {+ components: {+ button: {+ base: {+ color: 'white',+ ':hover': {color: 'rgba(255,255,255,0.8)'},+ },+ },+ },+ },+ });+ const css = generateOnMediaCSS(theme);+ expect(css).toContain('.xds-button:hover');+ expect(css).toContain('color: rgba(255,255,255,0.8)');+ });+});diff --git a/packages/core/src/theme/onMediaTokens.ts b/packages/core/src/theme/onMediaTokens.tsnew file mode 100644index 0000000000..3b958a0ddc--- /dev/null+++ b/packages/core/src/theme/onMediaTokens.ts@@ -0,0 +1,112 @@+/**+ * @file onMediaTokens.ts+ * @input Theme token values from defineTheme+ * @output Default on-dark / on-light token overrides for XDSMediaTheme+ * @position Theme system utility; consumed by defineTheme and generateThemeRules+ *+ * Generates semantic token overrides for content rendered on inverted surfaces.+ * "onDark" = content on a dark background (light text, white-tinted interactions)+ * "onLight" = content on a light background (dark text, black-tinted interactions)+ *+ * The primary mechanism is `color-scheme` — setting `color-scheme: dark` on the+ * media element makes all `light-dark()` tokens resolve to their dark-side values.+ * Only a small set of tokens need explicit overrides (text/icon primary use+ * `var(--color-on-dark)` instead of the dark-mode grey, accent collapses to+ * on-color, etc.).+ *+ * Themes can provide additional token and component overrides via the+ * `onDark`/`onLight` fields in `defineTheme()`.+ */++import type {XDSTokenValue, XDSComponentStyleMap} from './defineTheme';++/**+ * On-media theme overrides — same shape as the main theme but scoped+ * to a surface luminance context.+ */+export interface OnMediaOverrides {+ /** Token overrides for this surface context */+ tokens?: Partial<Record<string, XDSTokenValue>>;+ /** Component style overrides for this surface context */+ components?: XDSComponentStyleMap;+}++/**+ * Resolved on-media overrides stored on XDSDefinedTheme.+ * @internal+ */+export interface ResolvedOnMedia {+ /** Resolved token CSS values */+ tokens: Record<string, string>;+ /** Component style overrides (passthrough from input) */+ components?: XDSComponentStyleMap;+}++/**+ * Default token overrides for content on a dark surface.+ *+ * Most tokens work automatically via `color-scheme: dark` which flips+ * `light-dark()` values. These overrides handle the tokens that need+ * different values on an inverted surface vs a dark page background.+ */+export const defaultOnDarkTokens: Record<string, string> = {+ 'color-scheme': 'dark',++ // Text/icon primary — pure on-color, not dark-mode grey+ '--color-text-primary': 'var(--color-on-dark)',+ '--color-icon-primary': 'var(--color-on-dark)',++ // Accent collapses to on-color in inverted context+ '--color-accent': 'var(--color-on-dark)',+};++/**+ * Default token overrides for content on a light surface.+ */+export const defaultOnLightTokens: Record<string, string> = {+ 'color-scheme': 'light',++ // Text/icon primary — pure on-color, not light-mode dark+ '--color-text-primary': 'var(--color-on-light)',+ '--color-icon-primary': 'var(--color-on-light)',++ // Accent collapses to on-color+ '--color-accent': 'var(--color-on-light)',+};++/**+ * Resolve a token value to a CSS string.+ */+function resolveValue(value: XDSTokenValue): string {+ if (Array.isArray(value)) {+ return `light-dark(${value[0]}, ${value[1]})`;+ }+ return value;+}++/**+ * Resolve on-media overrides: merge user tokens with defaults,+ * pass through component overrides.+ */+export function resolveOnMedia(+ surface: 'dark' | 'light',+ input?: OnMediaOverrides,+): ResolvedOnMedia {+ const defaults =+ surface === 'dark' ? defaultOnDarkTokens : defaultOnLightTokens;++ const tokens = {...defaults};++ if (input?.tokens) {+ for (const [key, value] of Object.entries(input.tokens)) {+ if (value !== undefined) {+ tokens[key] = resolveValue(value);+ }+ }+ }++ return {+ tokens,+ components: input?.components,+ };+}diff --git a/packages/themes/default/src/defaultTheme.ts b/packages/themes/default/src/defaultTheme.tsindex 465cc7d8bc..c88d23ab8c 100644--- a/packages/themes/default/src/defaultTheme.ts+++ b/packages/themes/default/src/defaultTheme.ts@@ -45,5 +45,32 @@ export const defaultTheme = defineTheme({// No manual heading: { ... } or text: { ... } blocks needed.},+ // =========================================================================+ // On-media overrides+ // =========================================================================+ // Customize how components look on inverted surfaces (e.g. dark toast on+ // a light page). color-scheme + base token overrides are provided by+ // default; these add component-level adjustments.++ onDark: {+ components: {+ button: {+ 'variant:secondary': {+ backgroundColor: 'color-mix(in srgb, white 20%, transparent)',+ },+ },+ },+ },++ onLight: {+ components: {+ button: {+ 'variant:secondary': {+ backgroundColor: 'color-mix(in srgb, black 10%, transparent)',+ },+ },+ },+ },+icons: defaultIconRegistry,});diff --git a/packages/themes/neutral/src/neutralTheme.ts b/packages/themes/neutral/src/neutralTheme.tsindex 55498c26dd..56d9f43b68 100644--- a/packages/themes/neutral/src/neutralTheme.ts+++ b/packages/themes/neutral/src/neutralTheme.ts@@ -61,8 +61,8 @@ export const neutralTheme = defineTheme({'--color-text-secondary': ['oklch(0.556 0 0)', 'oklch(0.708 0 0)'],'--color-text-disabled': ['oklch(0.708 0 0)', 'oklch(0.439 0 0)'],'--color-text-accent': ['oklch(0.205 0 0)', 'oklch(0.922 0 0)'],- '--color-on-dark': ['oklch(1 0 0)', 'oklch(0.145 0 0)'],- '--color-on-light': ['oklch(0.145 0 0)', 'oklch(0.145 0 0)'],+ '--color-on-dark': 'oklch(1 0 0)',+ '--color-on-light': 'oklch(0.145 0 0)',// Contrast: neutral accent is near-black (L) / near-white (D)'--color-on-accent': ['oklch(1 0 0)', 'oklch(0.145 0 0)'],'--color-on-success': ['oklch(1 0 0)', 'oklch(0.145 0 0)'],