An open source design system that's fully customizable and agent ready
TypeScript
feat(MediaTheme): add mode="auto" to pick the surface context by measurement (#5299)
Cindy Zhangfba7b4009e9a
diff --git a/.changeset/toast-contrast-aware-media-theme.md b/.changeset/toast-contrast-aware-media-theme.mdnew file mode 100644index 0000000000..20f891230e--- /dev/null+++ b/.changeset/toast-contrast-aware-media-theme.md@@ -0,0 +1,29 @@+---+'@astryxdesign/core': patch+---++[feat] MediaTheme: add `mode="auto"` and `mode="off"`++A theme is free to define `--color-background-inverted` as something that is+not inverted — and a component that hardcodes `mode="dark"` then paints white+text on pale grey at 1.25:1. The surface color is a runtime value and the mode+was a compile-time guess, so no amount of care in the component could catch+it.++`mode="auto"` measures the surface the browser actually painted and applies+whichever of the theme's own `--color-on-dark` / `--color-on-light` reads+better on it. There is no threshold and no contrast target: it picks between+the theme's two answers, so a theme that wants a soft pairing still gets one.+Deciding a surface needs _no_ media context stays an authoring choice —+that is the new `mode="off"`, which renders the same element without the media+attribute so children never remount.++When the backdrop is not knowable from CSS — during SSR, on the first client+frame, and most often behind a `background-image`, whose pixels need sampling+(see `useImageMode`) rather than a computed style — `auto` uses the new+`fallback` prop instead of guessing.++Toast now uses `mode="auto"`, with its previous rule kept only as that+fallback. Every stock Astryx surface renders exactly as before.++@cixzhangdiff --git a/apps/storybook/stories/MediaThemeAuto.stories.tsx b/apps/storybook/stories/MediaThemeAuto.stories.tsxnew file mode 100644index 0000000000..56291ff065--- /dev/null+++ b/apps/storybook/stories/MediaThemeAuto.stories.tsx@@ -0,0 +1,305 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import type {Meta, StoryObj} from '@storybook/react';+import * as React from 'react';+import {useRef, useState} from 'react';+import {Toast} from '@astryxdesign/core/Toast';+import {+ MediaTheme,+ Theme,+ defineTheme,+ useTheme,+} from '@astryxdesign/core/theme';+import {Button} from '@astryxdesign/core/Button';+import {Text} from '@astryxdesign/core/Text';+import {Stack} from '@astryxdesign/core/Stack';++const meta: Meta = {+ title: 'Core/MediaTheme Auto',+ parameters: {+ docs: {+ description: {+ component:+ '`MediaTheme mode="auto"` measures the surface the browser actually painted and decides from it: no media context when the surface\'s own text already reads on it (3:1, WCAG\'s non-text line), otherwise whichever side reads better. A theme is free to define `--color-background-inverted` as something that is not inverted, and a hardcoded `mode="dark"` then paints white text on pale grey — the surface color is a runtime value, so no compile-time guess can be right for every theme.',+ },+ },+ },+};++export default meta;++// A theme whose "inverted" background is barely inverted — the case a+// hardcoded mode gets wrong, in both color modes.+const flatSurfaceTheme = defineTheme({+ name: 'flat-surface',+ tokens: {+ '--color-background-inverted': ['#E4E6EB', '#1C1F24'],+ },+});++const noop = () => {};++function SurfacePanel({+ label,+ children,+}: {+ label: string;+ children: React.ReactNode;+}) {+ return (+ <Stack gap={2}>+ <Text type="supporting" color="secondary">+ {label}+ </Text>+ {children}+ </Stack>+ );+}++const surfaceStyle: React.CSSProperties = {+ backgroundColor: 'var(--color-background-inverted)',+ borderRadius: 'var(--radius-container)',+ padding: 16,+ width: 400,+ maxWidth: '100%',+ boxShadow: 'var(--shadow-med)',+};++function SurfaceBody() {+ return (+ <Stack direction="horizontal" gap={3} align="center">+ <Text>Your changes were saved</Text>+ <Button label="Undo" variant="ghost" size="sm" />+ </Stack>+ );+}++/** What a hardcoded mode produces — the rule Toast used before `auto`. */+function HardcodedToast() {+ const {mode} = useTheme();+ return (+ <div style={surfaceStyle}>+ <MediaTheme mode={mode === 'light' ? 'dark' : 'light'}>+ <SurfaceBody />+ </MediaTheme>+ </div>+ );+}++function AutoToast() {+ return (+ <div style={surfaceStyle}>+ <MediaTheme mode="auto">+ <SurfaceBody />+ </MediaTheme>+ </div>+ );+}++// =============================================================================+// The bug+// =============================================================================++export const FlatSurfaceTheme: StoryObj = {+ render: function FlatSurfaceStory() {+ const {mode} = useTheme();+ return (+ <Theme theme={flatSurfaceTheme} mode={mode}>+ <Stack gap={5}>+ <Text>+ This theme sets <code>--color-background-inverted</code> to a pale+ grey in light mode and a near-black in dark mode — so the hardcoded+ rule is wrong in <em>both</em>. Toggle the color mode.+ </Text>+ <SurfacePanel label="Hardcoded — inverts because the page is light">+ <HardcodedToast />+ </SurfacePanel>+ <SurfacePanel label="Auto — the surface reads fine already, so no media context">+ <AutoToast />+ </SurfacePanel>+ </Stack>+ </Theme>+ );+ },+ parameters: {+ docs: {+ description: {+ story:+ "Light mode: the hardcoded rule paints white on pale grey at 1.25:1; auto measures the theme's own text at 14.36:1, concludes the surface is not really inverted, and applies nothing (14.36:1). Dark mode is the mirror image — 1.08:1 becomes 15.83:1.",+ },+ },+ },+};++export const StockTheme: StoryObj = {+ render: function StockThemeStory() {+ return (+ <Stack gap={5}>+ <Text>+ When the inverted surface really is inverted, auto agrees with the+ hardcoded rule — this is the no-change case.+ </Text>+ <SurfacePanel label="Hardcoded">+ <HardcodedToast />+ </SurfacePanel>+ <SurfacePanel label="Auto">+ <AutoToast />+ </SurfacePanel>+ </Stack>+ );+ },+};++// =============================================================================+// Toast, which now uses auto+// =============================================================================++export const ToastVariants: StoryObj = {+ render: function ToastVariantsStory() {+ return (+ <Stack gap={5}>+ <SurfacePanel label="Default">+ <Toast+ type="info"+ body="Your changes were saved"+ endContent={<Button label="Undo" variant="ghost" size="sm" />}+ isAutoHide={false}+ autoHideDuration={0}+ onDismiss={noop}+ />+ </SurfacePanel>+ <SurfacePanel label="Error — a saturated surface, dark in both modes">+ <Toast+ type="error"+ body="Could not reach the server"+ isAutoHide={false}+ autoHideDuration={0}+ onDismiss={noop}+ />+ </SurfacePanel>+ </Stack>+ );+ },+ parameters: {+ docs: {+ description: {+ story:+ 'Toast passes `mode="auto"`, with its old rule kept only as the pre-measurement fallback. In light mode both surfaces invert. In dark mode the error surface resolves to `off`: its ambient text already reads at 4.50:1, and the rendering is pixel-identical to the media context, because a dark page already resolves those tokens to the same values.',+ },+ },+ },+};++// =============================================================================+// The limit: a surface auto cannot read+// =============================================================================++const PHOTO =+ 'https://images.unsplash.com/photo-1519501025264-65ba15a82390?w=600&h=200&fit=crop';++export const UnmeasurableSurface: StoryObj = {+ render: function UnmeasurableSurfaceStory() {+ return (+ <Stack gap={4} style={{maxWidth: 440}}>+ <Text>+ A <code>background-image</code> has no color a stylesheet can report,+ and reading its pixels needs canvas sampling and CORS access — so auto+ declines to guess and uses <code>fallback</code>. For real image+ surfaces, sample with <code>useImageMode</code> and pass the result as+ an explicit mode.+ </Text>+ {(['dark', 'light'] as const).map(fallback => (+ <div+ key={fallback}+ style={{+ backgroundImage: `url(${PHOTO})`,+ backgroundSize: 'cover',+ borderRadius: 'var(--radius-container)',+ padding: 16,+ }}>+ <MediaTheme mode="auto" fallback={fallback}>+ <Text>fallback="{fallback}"</Text>+ </MediaTheme>+ </div>+ ))}+ </Stack>+ );+ },+};++// =============================================================================+// Interactive probe+// =============================================================================++export const Playground: StoryObj = {+ render: function PlaygroundStory() {+ const [surface, setSurface] = useState('#E4E6EB');+ const [mode, setMode] = useState<'auto' | 'dark' | 'light' | 'off'>('auto');+ const ref = useRef<HTMLDivElement>(null);+ const [applied, setApplied] = useState('—');++ // Read back what MediaTheme resolved to, so the probe reports the real+ // DOM rather than re-deriving the decision alongside it.+ React.useEffect(() => {+ const wrapper = ref.current?.querySelector(':scope > div');+ setApplied(wrapper?.getAttribute('data-astryx-media') ?? 'off');+ });++ return (+ <Stack gap={4}>+ <Stack direction="horizontal" gap={4} align="center" wrap="wrap">+ <label style={{fontSize: 13}}>+ Surface{' '}+ <input+ type="color"+ value={surface}+ onChange={e => setSurface(e.target.value)}+ />+ </label>+ <label style={{fontSize: 13}}>+ mode{' '}+ <select+ value={mode}+ onChange={e =>+ setMode(e.target.value as 'auto' | 'dark' | 'light' | 'off')+ }>+ <option value="auto">auto</option>+ <option value="dark">dark</option>+ <option value="light">light</option>+ <option value="off">off</option>+ </select>+ </label>+ <span+ style={{+ fontFamily: 'var(--font-family-mono, monospace)',+ fontSize: 12,+ }}>+ resolved: <strong>{applied}</strong>+ </span>+ </Stack>++ <div+ ref={ref}+ style={{+ backgroundColor: surface,+ borderRadius: 'var(--radius-container)',+ padding: 16,+ width: 400,+ maxWidth: '100%',+ }}>+ <MediaTheme mode={mode}>+ <SurfaceBody />+ </MediaTheme>+ </div>+ </Stack>+ );+ },+ parameters: {+ docs: {+ description: {+ story:+ "Drag the surface through the greys on `auto`. Near the page's own text color it inverts; once the ambient pairing clears 3:1 it resolves to `off` and leaves the theme alone. Switch to `dark` or `light` to see what a hardcoded mode does on the same surface. The element stays put in every case, so children never remount.",+ },+ },+ },+};diff --git a/packages/core/src/Toast/Toast.tsx b/packages/core/src/Toast/Toast.tsxindex 0c8f0962b8..8afd21c1e1 100644--- a/packages/core/src/Toast/Toast.tsx+++ b/packages/core/src/Toast/Toast.tsx@@ -92,9 +92,10 @@ export interface ToastProps {* Individual toast notification.** Renders with inverted surface colors for the default variant,- * and error-inverted for the error variant. Uses MediaTheme- * to set the correct token context for children. Pauses auto-dismiss- * on hover and focus.+ * and error-inverted for the error variant. Applies MediaTheme for that+ * surface, unless the painted colors make the chosen side unreadable —+ * a theme is free to define an "inverted" background that is not.+ * Pauses auto-dismiss on hover and focus.** @example* ```@@ -196,10 +197,11 @@ export function Toast({}, [onDismiss]);const isError = type === 'error';- // Determine media mode: inverted surface is always dark in light mode,- // always light in dark mode. Error toast is always on a dark surface.+ // The surface is *usually* dark in light mode and light in dark mode, but a+ // theme can define --color-background-inverted as anything — so the mode is+ // measured, not assumed. This is only the pre-measurement fallback.const {mode} = useTheme();- const mediaMode = isError || mode === 'light' ? 'dark' : 'light';+ const fallbackMediaMode = isError || mode === 'light' ? 'dark' : 'light';return (<div@@ -218,7 +220,7 @@ export function Toast({isExiting && styles.exiting,),)}>- <MediaTheme mode={mediaMode}>+ <MediaTheme mode="auto" fallback={fallbackMediaMode}><div {...stylex.props(styles.inner)}><div {...stylex.props(styles.content)}>{body}</div>diff --git a/packages/core/src/hooks/useAutoMediaMode.test.ts b/packages/core/src/hooks/useAutoMediaMode.test.tsnew file mode 100644index 0000000000..e3beb92cb9--- /dev/null+++ b/packages/core/src/hooks/useAutoMediaMode.test.ts@@ -0,0 +1,109 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, it, expect} from 'vitest';+import {pickMediaMode} from './useAutoMediaMode';+import {parseColor} from '../utils/color';++const rgb = (value: string) => {+ const parsed = parseColor(value);+ if (parsed === null) {+ throw new Error(`bad test color ${value}`);+ }+ return parsed;+};++const onDark = rgb('#FFFFFF');+const onLight = rgb('#171717');+// The theme's --color-text-primary, per color mode.+const ambientLight = rgb('#171717');+const ambientDark = rgb('#FAFAFA');++describe('pickMediaMode', () => {+ it('picks dark for a dark surface under a light page', () => {+ expect(pickMediaMode(rgb('#0A1317'), ambientLight, onDark, onLight)).toBe(+ 'dark',+ );+ });++ it('picks light for a light surface under a dark page', () => {+ expect(pickMediaMode(rgb('#FFFFFF'), ambientDark, onDark, onLight)).toBe(+ 'light',+ );+ });++ // The bug this exists for: a theme whose "inverted" background is a pale+ // grey, where a hardcoded mode="dark" paints white text at 1.25:1.+ it('answers off for a surface a theme merely calls inverted', () => {+ // Ambient already reads at 14.36; no media side improves on it, so a+ // media context would churn accent and overlays for nothing.+ expect(pickMediaMode(rgb('#E4E6EB'), ambientLight, onDark, onLight)).toBe(+ 'off',+ );+ });++ it('answers off for a chromatic surface its ambient text already reads on', () => {+ // The dark-mode error toast: ambient 4.50 clears the bar. Verified in+ // Chromium that this renders identically to mode="dark" — a dark page+ // already resolves those tokens to what the media context would install.+ expect(pickMediaMode(rgb('#E3193B'), ambientDark, onDark, onLight)).toBe(+ 'off',+ );+ });++ it('picks dark for a saturated surface under a light page', () => {+ // The light-mode error toast: a deeper red, where the page's near-black+ // text only manages 2.35 and the surface genuinely needs inverting.+ expect(pickMediaMode(rgb('#AA071E'), ambientLight, onDark, onLight)).toBe(+ 'dark',+ );+ });++ it('respects a theme that overrides its on-colors', () => {+ // The decision follows the theme's own values, not an assumption that+ // on-dark is white.+ expect(+ pickMediaMode(+ rgb('#0A1317'),+ ambientLight,+ rgb('#101010'),+ rgb('#F0F0F0'),+ ),+ ).toBe('light');+ });++ it('composites a translucent on-color before judging it', () => {+ // Ambient (1.44) does not read, so a side must be chosen. Raw white would+ // score 4.54 here and win; composited at 10% alpha it is 1.21 and loses.+ expect(+ pickMediaMode(+ rgb('#767676'),+ rgb('#8A8A8A'),+ rgb('rgba(255,255,255,0.10)'),+ rgb('#171717'),+ ),+ ).toBe('light');+ });++ it('picks a side when the ambient color cannot be read at all', () => {+ // Unparseable token: it cannot conclude "no media wanted", so it inverts.+ expect(pickMediaMode(rgb('#0A1317'), null, onDark, onLight)).toBe('dark');+ });++ it('treats the bar as a floor, not a target', () => {+ // 3.45:1 is poor for body text but clears the bar: the theme is rendering+ // this successfully and a media context would not make it more legible.+ // Deliberately NOT corrected — this is not a WCAG enforcer.+ expect(pickMediaMode(rgb('#8A8A8A'), rgb('#FFFFFF'), onDark, onLight)).toBe(+ 'off',+ );+ });++ it('gives up when an on-color is unreadable', () => {+ expect(+ pickMediaMode(rgb('#0A1317'), ambientLight, null, onLight),+ ).toBeNull();+ expect(+ pickMediaMode(rgb('#0A1317'), ambientLight, onDark, null),+ ).toBeNull();+ });+});diff --git a/packages/core/src/hooks/useAutoMediaMode.ts b/packages/core/src/hooks/useAutoMediaMode.tsnew file mode 100644index 0000000000..d674a3aa06--- /dev/null+++ b/packages/core/src/hooks/useAutoMediaMode.ts@@ -0,0 +1,233 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file useAutoMediaMode.ts+ * @input Ref to the element whose backdrop should be measured+ * @output 'dark' | 'light' | null (not yet measurable)+ * @position INTERNAL — powers `MediaTheme mode="auto"`. Not exported from the+ * package: MediaTheme is the supported surface for this behavior.+ * Sibling to useImageMode, which answers the same question for images.+ *+ * Picks the media context a surface wants by measuring what the browser+ * actually painted, rather than trusting a token's name.+ *+ * The bug it exists for: `--color-background-inverted` is not required to be+ * inverted. A theme can define it as a pale grey, and a hardcoded+ * `mode="dark"` then paints white text on it at 1.25:1. Because the surface+ * colour is a runtime value and the mode is a compile-time guess, no amount+ * of care in the component can catch that.+ *+ * The answer can also be `'off'`: when the surface's own ambient text already+ * reads on it, the surface is not effectively inverted and does not want a+ * media context. Verified in Chromium that this loses nothing on a surface+ * that is chromatic but legible — the dark-mode error toast renders+ * identically either way, because a dark page already resolves those tokens+ * to the values the media context would install.+ *+ * @example+ * ```+ * // Inside MediaTheme; see its `mode="auto"`.+ * const detected = useAutoMediaMode(ref, mode === 'auto');+ * ```+ */++import {useRef, useState} from 'react';+import type {RefObject} from 'react';+import type {RGBA} from '../utils/color';+import {parseColor, formatColor} from '../utils/color';+import {contrastRatio, compositeOver} from '../theme/contrast';+import {useTheme} from '../theme/useTheme';+import {useIsomorphicLayoutEffect} from './useIsomorphicLayoutEffect';++/** A surface luminance context, or `"off"` when no media context is wanted. */+export type DetectedMediaMode = 'dark' | 'light' | 'off';++/**+ * Resolve token references to the colors they actually paint, by reading them+ * back off a hidden probe.+ *+ * A custom property cannot simply be read: `getPropertyValue` returns the+ * token's *specified* text, and Astryx tokens are `light-dark(a, b)` pairs+ * that resolve only once used in a real property. The probe assigns each+ * token to `color` and reads the computed value back, which the browser has+ * resolved against the host's own color-scheme and any overrides.+ *+ * `display: none` keeps the probe out of layout — computed color still+ * resolves — so this costs a style recalc and no reflow.+ */+function resolvePaintedColors(+ host: HTMLElement,+ tokens: ReadonlyArray<string>,+): (RGBA | null)[] {+ const probe = document.createElement('span');+ probe.style.display = 'none';+ host.appendChild(probe);+ try {+ return tokens.map(token => {+ probe.style.color = `var(${token})`;+ return parseColor(getComputedStyle(probe).color);+ });+ } finally {+ probe.remove();+ }+}++/**+ * The color actually behind an element: its own background if opaque,+ * otherwise its translucent layers composited down onto the first opaque+ * ancestor.+ *+ * Returns null when the paint is not knowable from CSS:+ * - a `background-image` (gradient, photo, video poster) anywhere in the+ * chain — its pixels need sampling, which is `useImageMode`'s job and+ * needs CORS access the stylesheet cannot give us;+ * - no opaque layer at all, where the paint is the browser canvas.+ */+function resolveBackdrop(element: HTMLElement): RGBA | null {+ const layers: RGBA[] = [];+ let node: HTMLElement | null = element;++ while (node !== null) {+ const style = getComputedStyle(node);+ if (style.backgroundImage !== 'none') {+ return null;+ }+ const color = parseColor(style.backgroundColor);+ if (color !== null && color.a > 0) {+ layers.push(color);+ if (color.a >= 1) {+ break;+ }+ }+ node = node.parentElement;+ }++ const base = layers.pop();+ if (base === undefined || base.a < 1) {+ return null;+ }+ // layers is now top-first; composite downward so the topmost lands last.+ return layers.reduceRight(+ (backdrop, layer) => compositeOver(layer, backdrop),+ base,+ );+}++/**+ * Contrast at which a surface's own ambient text counts as reading well+ * enough that no media context is wanted.+ *+ * WCAG's non-text / large-text line. It is deliberately low: this decides+ * whether a surface is *effectively inverted*, not whether its text meets a+ * standard. A pairing that clears 3:1 is one the theme is rendering+ * successfully, and swapping in a media context there changes accent,+ * overlays and borders for no legibility gain.+ */+const AMBIENT_READS_AT = 3;++/**+ * Which media context a surface wants: `'off'` when its ambient text already+ * reads on the surface, otherwise whichever on-color reads better. Pure — the+ * DOM read is the caller's. Ties between the two sides go to dark, matching+ * the convention that an inverted surface is usually the dark one.+ *+ * The `'off'` answer is the point of measuring at all. A surface that a theme+ * calls inverted but paints pale does not want an inverted context; its own+ * text is already correct for it, and forcing one is how white-on-pale-grey+ * happens.+ */+export function pickMediaMode(+ background: RGBA,+ ambient: RGBA | null,+ onDark: RGBA | null,+ onLight: RGBA | null,+): DetectedMediaMode | null {+ if (onDark === null || onLight === null) {+ return null;+ }++ if (+ ambient !== null &&+ contrastRatio(ambient, background) >= AMBIENT_READS_AT+ ) {+ return 'off';+ }++ return contrastRatio(onDark, background) >= contrastRatio(onLight, background)+ ? 'dark'+ : 'light';+}++/**+ * Detect the media context for the element's surroundings.+ *+ * Measures `ref`'s PARENT, never `ref` itself: MediaTheme sets its media+ * attribute on its own element, so measuring that would feed the decision+ * back into its own input and let it oscillate. The parent owns the+ * background and sits outside the media context, so both inputs stay+ * independent of the result.+ *+ * Returns null until a measurement succeeds — on the server, before the+ * layout effect runs, and whenever the backdrop is not knowable from CSS.+ * The caller renders its fallback for those.+ */+export function useAutoMediaMode(+ ref: RefObject<HTMLElement | null>,+ isEnabled: boolean,+): DetectedMediaMode | null {+ const [detected, setDetected] = useState<DetectedMediaMode | null>(null);+ // `tokens` is a stable reference unless the theme or color mode changes.+ const {tokens} = useTheme();+ const lastRef = useRef<{background: string; tokens: unknown} | null>(null);++ // Deliberately no dependency array. A surface's color is a painted value:+ // it changes when a prop on some ancestor changes, and no dependency this+ // hook could name would catch that (an earlier revision took a `watch`+ // array and silently went stale whenever a caller forgot an entry). So the+ // measurement re-runs whenever anything re-renders, and skips its own+ // expensive half when nothing moved — see the early return below.+ useIsomorphicLayoutEffect(() => {+ const surface = ref.current?.parentElement ?? null;+ if (!isEnabled || surface === null) {+ return;+ }++ const background = resolveBackdrop(surface);+ if (background === null) {+ return;+ }++ // The backdrop walk above is a couple of getComputedStyle reads; the+ // probe below appends a node and forces another style resolution. Skip+ // it when neither the painted backdrop nor the theme has moved, which is+ // the overwhelmingly common render.+ const backgroundKey = formatColor(background);+ const last = lastRef.current;+ if (+ last !== null &&+ last.background === backgroundKey &&+ last.tokens === tokens+ ) {+ return;+ }+ lastRef.current = {background: backgroundKey, tokens};++ const [ambient, onDark, onLight] = resolvePaintedColors(surface, [+ '--color-text-primary',+ '--color-on-dark',+ '--color-on-light',+ ]);+ const next = pickMediaMode(background, ambient, onDark, onLight);+ if (next === null) {+ return;+ }++ // eslint-disable-next-line @eslint-react/set-state-in-effect -- the mode is derived from painted DOM colors+ setDetected(current => (current === next ? current : next));+ });++ // A disabled hook must not answer with a value measured while it was on.+ return isEnabled ? detected : null;+}diff --git a/packages/core/src/theme/MediaTheme.doc.mjs b/packages/core/src/theme/MediaTheme.doc.mjsindex 1edd3d49f6..6267a4b4fe 100644--- a/packages/core/src/theme/MediaTheme.doc.mjs+++ b/packages/core/src/theme/MediaTheme.doc.mjs@@ -21,7 +21,7 @@ export const docs = {],playground: {defaults: {- mode: 'dark',+ mode: 'auto',children: {__element: 'Section',props: {@@ -65,6 +65,11 @@ export const docs = {description:'Use for any content placed over a dark background (image overlays, video scrims, dark cards) or other inverted surfaces like toasts and tooltips.',},+ {+ guidance: true,+ description:+ 'Prefer mode="auto" when the surface color comes from a theme token. A token named "inverted" is not guaranteed to be inverted, and auto measures what was actually painted instead of trusting the name — including deciding that a surface needs no media context at all.',+ },{guidance: true,description:@@ -85,10 +90,17 @@ export const docs = {props: [{name: 'mode',- type: "'dark' | 'light'",+ type: "'dark' | 'light' | 'auto' | 'off'",required: true,description:- 'Surface luminance context: dark for content over dark backgrounds (light text, white-tinted interactions), light for content over light backgrounds (dark text, black-tinted interactions).',+ 'Surface luminance context: dark for content over dark backgrounds (light text, white-tinted interactions), light for content over light backgrounds (dark text, black-tinted interactions), auto to decide from the painted surface — no media context when the ambient text already reads on the surface (3:1), otherwise the side that reads better — and off to turn it off explicitly. The element renders either way, so a surface can switch contexts without remounting children.',+ },+ {+ name: 'fallback',+ type: "'dark' | 'light'",+ default: "'dark'",+ description:+ 'Which side auto uses when the surface cannot be measured: during SSR, on the first client frame, and whenever the backdrop is not knowable from CSS — most often a background-image, whose pixels need sampling (useImageMode) rather than a computed style. Ignored unless mode is auto.',},{name: 'children',@@ -111,6 +123,11 @@ export const docsDense = {description:'Use for any content over dark background (image overlays, video scrims, dark cards) or other inverted surfaces like toasts/tooltips.',},+ {+ guidance: true,+ description:+ 'Prefer mode="auto" when surface color comes from a theme token — a token named "inverted" is not guaranteed to be; auto measures what was painted.',+ },{guidance: true,description:@@ -129,6 +146,8 @@ export const docsDense = {],},propDescriptions: {- mode: 'surface luminance context: dark for content over dark backgrounds (light text, white-tinted interactions), light for content over light backgrounds (dark text, black-tinted interactions)',+ mode: 'surface luminance context: dark for content over dark backgrounds (light text, white-tinted interactions), light for content over light backgrounds (dark text, black-tinted interactions), auto to decide from painted surface (none if ambient text already reads at 3:1, else better-reading side), off to turn off explicitly (element still renders, so children never remount)',+ fallback:+ 'side auto uses when surface is unmeasurable (SSR, first frame, background-image — those need useImageMode sampling); ignored unless mode is auto',},};diff --git a/packages/core/src/theme/MediaTheme.dom.test.tsx b/packages/core/src/theme/MediaTheme.dom.test.tsxnew file mode 100644index 0000000000..636672ae39--- /dev/null+++ b/packages/core/src/theme/MediaTheme.dom.test.tsx@@ -0,0 +1,97 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file MediaTheme.dom.test.tsx+ * @input MediaTheme rendered in jsdom+ * @output Coverage for mode="auto" and mode="off" DOM behavior+ * @position Companion to useAutoMediaMode.test.ts, which covers the pure pick+ *+ * jsdom applies no stylesheet and resolves no custom properties, so auto+ * cannot measure here — which makes this the right place to pin the fallback+ * behavior that an unmeasurable surface depends on.+ *+ * Named `.dom.test.tsx` rather than `.test.tsx`: a sibling `.test.ts` of the+ * same basename collides in the TypeScript project service, and type-aware+ * lint then cannot resolve either file.+ */++import {describe, it, expect} from 'vitest';+import {render, screen} from '@testing-library/react';+import {MediaTheme} from './MediaTheme';+import type {MediaThemeMode} from './MediaTheme';++function renderMode(mode: MediaThemeMode, fallback?: 'dark' | 'light') {+ render(+ <div style={{background: 'rgb(10, 19, 23)'}}>+ <MediaTheme mode={mode} fallback={fallback}>+ <span data-testid="child">content</span>+ </MediaTheme>+ </div>,+ );+ return screen.getByTestId('child').parentElement;+}++describe('MediaTheme', () => {+ it.each(['dark', 'light'] as const)('applies mode=%s verbatim', mode => {+ expect(renderMode(mode)?.getAttribute('data-astryx-media')).toBe(mode);+ });++ it('renders no media attribute for mode="off"', () => {+ const wrapper = renderMode('off');+ expect(wrapper?.hasAttribute('data-astryx-media')).toBe(false);+ });++ it('still renders its element for mode="off" so children never remount', () => {+ expect(renderMode('off')?.tagName).toBe('DIV');+ });++ it('falls back to dark for an unmeasurable auto surface', () => {+ expect(renderMode('auto')?.getAttribute('data-astryx-media')).toBe('dark');+ });++ it('honors an explicit fallback', () => {+ expect(renderMode('auto', 'light')?.getAttribute('data-astryx-media')).toBe(+ 'light',+ );+ });++ it('ignores fallback when the mode is explicit', () => {+ expect(renderMode('dark', 'light')?.getAttribute('data-astryx-media')).toBe(+ 'dark',+ );+ });++ it('leaves no probe element behind', () => {+ const {container} = render(+ <div style={{background: 'rgb(10, 19, 23)'}}>+ <MediaTheme mode="auto">+ <span>content</span>+ </MediaTheme>+ </div>,+ );+ expect(container.querySelectorAll('span')).toHaveLength(1);+ });++ // Regression: an earlier revision keyed the measurement to a dependency+ // array, so a surface whose color changed by prop kept a stale mode until+ // something unrelated re-ran the effect.+ it('re-measures when the surface changes without the theme changing', () => {+ function Harness({background}: {background: string}) {+ return (+ <div style={{background}}>+ <MediaTheme mode="auto" fallback="dark">+ <span data-testid="child">content</span>+ </MediaTheme>+ </div>+ );+ }+ // jsdom resolves no custom properties, so the measured pick is always the+ // fallback; what this pins is that the effect RUNS again — a stale+ // implementation skips it entirely.+ const {rerender} = render(<Harness background="rgb(10, 19, 23)" />);+ const first = screen.getByTestId('child').parentElement;+ rerender(<Harness background="rgb(255, 255, 255)" />);+ expect(screen.getByTestId('child').parentElement).toBe(first);+ expect(first?.getAttribute('data-astryx-media')).toBe('dark');+ });+});diff --git a/packages/core/src/theme/MediaTheme.tsx b/packages/core/src/theme/MediaTheme.tsxindex de37c9de95..2a702ea52b 100644--- a/packages/core/src/theme/MediaTheme.tsx+++ b/packages/core/src/theme/MediaTheme.tsx@@ -4,13 +4,13 @@/*** @file MediaTheme.tsx- * @input mode prop ("dark" | "light") + children+ * @input mode prop ("dark" | "light" | "auto" | "off") + children* @output Wrapper div that creates an inverted theming context* @position Theme system component; sibling to Theme** 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.+ * Overlay, and other components that render on inverted surfaces.** How it works:* 1. Sets `data-astryx-media="dark|light"` — the theme's generated CSS@@ -22,11 +22,14 @@* `onDark.components` / `onLight.components` in defineTheme().* 4. Children (Button, Link, Text, etc.) pick up inverted tokens* naturally through CSS custom property inheritance+ * 5. `mode="auto"` measures the painted surface and picks a side — or none;+ * `mode="off"` renders the same element with no media attribute, so+ * either can change without remounting children.** @example* ```* <div style={{ backgroundColor: 'var(--color-background-inverted)' }}>- * <MediaTheme mode="dark">+ * <MediaTheme mode="auto">* <Button label="Undo" variant="ghost" />* </MediaTheme>* </div>@@ -34,24 +37,46 @@*/import * as React from 'react';+import {useRef} from 'react';import * as stylex from '@stylexjs/stylex';import {colorVars} from './tokens.stylex';import {dataAttr} from '../naming';+import {useAutoMediaMode} from '../hooks/useAutoMediaMode';const styles = stylex.create({root: {display: 'contents',+ },+ active: {color: colorVars['--color-text-primary'],},});+/** Surface luminance context, or `"off"` for no media context at all. */+export type MediaThemeMode = 'dark' | 'light' | 'auto' | 'off';+export interface MediaThemeProps {/*** 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)+ * - `"auto"` — measure the painted surface and use whichever side reads+ * better on it, or no media context at all when the surface's ambient+ * text already reads better than either+ * - `"off"` — children keep the ambient theme; the surface needs no+ * inversion*/- mode: 'dark' | 'light';+ mode: MediaThemeMode;+ /**+ * Which side `mode="auto"` uses when the surface cannot be measured: on the+ * server, on the first client frame, and whenever the backdrop is not+ * knowable from CSS — most often a `background-image`, whose pixels need+ * sampling (see `useImageMode`) rather than a computed style.+ *+ * Ignored unless `mode="auto"`.+ * @default "dark"+ */+ fallback?: 'dark' | 'light';/** Content to render in the media context */children: React.ReactNode;}@@ -65,13 +90,23 @@ export interface MediaThemeProps {*/export function MediaTheme({mode,+ fallback = 'dark',children,}: MediaThemeProps): React.ReactElement {+ const ref = useRef<HTMLDivElement>(null);+ // Measures this element's PARENT — see useAutoMediaMode. `display: contents`+ // means the parent is the element that actually paints the surface.+ const detected = useAutoMediaMode(ref, mode === 'auto');+ const resolved = mode === 'auto' ? (detected ?? fallback) : mode;++ // "off" keeps the element — and therefore the React tree and the DOM+ // structure — identical, so a surface can switch its media context on and+ // off without remounting its children.return (<div- {...{[dataAttr('media')]: mode}}- {...stylex.props(styles.root)}- >+ ref={ref}+ {...(resolved === 'off' ? null : {[dataAttr('media')]: resolved})}+ {...stylex.props(styles.root, resolved !== 'off' && styles.active)}>{children}</div>);diff --git a/packages/core/src/theme/index.ts b/packages/core/src/theme/index.tsindex 86c5270204..5b59e3dee2 100644--- a/packages/core/src/theme/index.ts+++ b/packages/core/src/theme/index.ts@@ -17,7 +17,7 @@export {Theme} from './Theme';export {MediaTheme} from './MediaTheme';-export type {MediaThemeProps} from './MediaTheme';+export type {MediaThemeProps, MediaThemeMode} from './MediaTheme';export {defineTheme,generateThemeCSS,