Skip to content

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

TypeScript

fix(core): resolve Toast fallback viewport's theme mode instead of OS preference (#3743)

Minseon Kima3c2f4710dc9
diff --git a/.changeset/toast-fallback-theme-mode.md b/.changeset/toast-fallback-theme-mode.md
new file mode 100644
index 0000000000..b42c4b32b7
--- /dev/null
+++ b/.changeset/toast-fallback-theme-mode.md
@@ -0,0 +1,8 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Toast fallback viewport resolves the app's theme mode instead of OS preference (#3743)
+
+The fallback mounts via createRoot() on a disconnected tree, so Toast's useTheme() couldn't see ThemeContext and fell back to prefers-color-scheme — when that disagreed with `<Theme mode>`, the toast's inverted-surface text/icon could compute to the same color as its own background. useToast's fallback container now mirrors `<html data-theme>` and `data-astryx-theme` directly (kept live via MutationObserver), and useTheme() itself falls back to reading `<html data-theme>` before assuming OS preference when no ThemeContext ancestor is reachable — the mechanism that actually resolves Toast's JS-computed mode for disconnected trees like this one.
+@let-sunny
diff --git a/packages/core/src/Toast/useToast.test.tsx b/packages/core/src/Toast/useToast.test.tsx
new file mode 100644
index 0000000000..4f12555acb
--- /dev/null
+++ b/packages/core/src/Toast/useToast.test.tsx
@@ -0,0 +1,258 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useToast.test.tsx
+ * @input Uses vitest, @testing-library/react, useToast/ToastViewport/Theme
+ * @output Unit tests for the fallback viewport's theme mode resolution
+ * @position Testing; validates useToast.tsx's attribute mirroring onto the
+ * fallback container, plus useTheme.ts's <html data-theme> fallback (which
+ * is what actually resolves Toast's JS-computed mode; see useTheme.test.tsx
+ * for direct coverage of that half)
+ *
+ * SYNC: When useToast.tsx's fallback container setup changes, update these tests
+ *
+ * The fallback viewport root is a module-level singleton, so it's mounted
+ * once (by whichever test runs first) and persists across every test in the
+ * file below — mirroring a real app whose root <Theme> mode changes over
+ * time. Each test dismisses its own toast in afterEach (see
+ * dismissAllFallbackToasts) so none linger as a useTheme subscriber into the
+ * next test.
+ */
+
+import {describe, it, expect, vi, afterEach} from 'vitest';
+import {render, screen, fireEvent, act, waitFor} from '@testing-library/react';
+import React from 'react';
+import {Theme} from '../theme/Theme';
+import {defineTheme} from '../theme/defineTheme';
+import {ToastViewport} from './ToastViewport';
+import {useToast} from './useToast';
+import type {ToastOptions} from './types';
+
+const testTheme = defineTheme({name: 'test', tokens: {}});
+const NO_AUTO_HIDE: ToastOptions = {body: 'hello', isAutoHide: false};
+
+function mockMatchMedia(prefersDark: boolean) {
+ window.matchMedia = vi.fn().mockImplementation((query: string) => ({
+ matches: query.includes('dark') ? prefersDark : false,
+ media: query,
+ onchange: null,
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+ }));
+}
+
+function ShowToastButton({label = 'Trigger'}: {label?: string}) {
+ const toast = useToast();
+ return (
+ <button type="button" onClick={() => toast(NO_AUTO_HIDE)}>
+ {label}
+ </button>
+ );
+}
+
+// The fallback's toasts accumulate in one persistent viewport across tests
+// (see file header) — take the most recently added one.
+function newestMediaAttr(scope: ParentNode): string | null {
+ const nodes = scope.querySelectorAll('[data-astryx-media]');
+ const last = nodes[nodes.length - 1];
+ return last ? last.getAttribute('data-astryx-media') : null;
+}
+
+// Fire the transition-end that ToastViewport listens for to unmount an
+// exiting toast (jsdom does not run CSS transitions) — mirrors
+// ToastViewport.test.tsx's completeExit helper.
+function completeExit(toastId: string) {
+ const node = document.querySelector<HTMLElement>(
+ `[data-toast-id="${toastId}"]`,
+ );
+ if (node) {
+ fireEvent.transitionEnd(node, {propertyName: 'grid-template-rows'});
+ }
+}
+
+// Dismisses every toast still mounted in the fallback viewport so none of
+// them remain subscribed to useTheme's shared MutationObserver by the time
+// RTL's own cleanup unmounts this test's <Theme> — that unmount would
+// otherwise notify a lingering subscriber outside any act scope.
+async function dismissAllFallbackToasts(): Promise<void> {
+ const fallback = document.querySelector('[data-astryx-toast-fallback]');
+ const ids = Array.from(
+ fallback?.querySelectorAll<HTMLElement>('[data-toast-id]') ?? [],
+ ).map(node => node.getAttribute('data-toast-id')!);
+
+ await act(async () => {
+ for (const id of ids) {
+ fallback
+ ?.querySelector<HTMLElement>(
+ `[data-toast-id="${id}"] button[aria-label="Dismiss notification"]`,
+ )
+ ?.click();
+ }
+ });
+
+ await act(async () => {
+ for (const id of ids) {
+ completeExit(id);
+ }
+ });
+}
+
+describe('useToast fallback viewport theme mode', () => {
+ afterEach(async () => {
+ mockMatchMedia(false);
+ await dismissAllFallbackToasts();
+ });
+
+ it('resolves the app mode (light) instead of OS preference (dark) with no LayerProvider', async () => {
+ mockMatchMedia(true); // OS prefers dark
+
+ render(
+ <Theme theme={testTheme} mode="light">
+ <ShowToastButton />
+ </Theme>,
+ );
+
+ // This is the very first click in the whole file, so it's the one that
+ // finds the fallback proxy still pending: addToast queues the entry and
+ // kicks off the ctxReady.then(...) microtask that later delivers it to
+ // the real context. Awaiting an async act() here flushes that chain
+ // instead of letting it resolve outside any act scope.
+ await act(async () => {
+ fireEvent.click(screen.getByText('Trigger'));
+ });
+
+ await waitFor(() => {
+ expect(
+ document.querySelector(
+ '[data-astryx-toast-fallback] [data-astryx-media]',
+ ),
+ ).not.toBeNull();
+ });
+
+ // App mode is light, so the toast's inverted surface must be dark — if
+ // the fallback fell back to OS preference (dark) instead, this would be
+ // 'light' and the toast's text/icon would compute the same color as its
+ // own background (the invisible-toast bug).
+ expect(
+ newestMediaAttr(document.querySelector('[data-astryx-toast-fallback]')!),
+ ).toBe('dark');
+ });
+
+ it('keeps the OS-preference fallback for mode="system" with no LayerProvider', async () => {
+ mockMatchMedia(true); // OS prefers dark
+
+ render(
+ <Theme theme={testTheme} mode="system">
+ <ShowToastButton label="Trigger System" />
+ </Theme>,
+ );
+
+ // The fallback viewport is a persistent module singleton (see file
+ // header), so earlier tests may have already added toasts to it — count
+ // beforehand instead of assuming a fixed prior count, so this test
+ // survives running alone (.only, -t, shuffle) as well as in sequence.
+ const countBefore = document.querySelectorAll(
+ '[data-astryx-toast-fallback] [data-astryx-media]',
+ ).length;
+
+ act(() => {
+ fireEvent.click(screen.getByText('Trigger System'));
+ });
+
+ await waitFor(() => {
+ const nodes = document.querySelectorAll(
+ '[data-astryx-toast-fallback] [data-astryx-media]',
+ );
+ expect(nodes.length).toBeGreaterThan(countBefore);
+ });
+
+ // mode="system" means #1587 removes data-theme from <html> — useTheme's
+ // <html data-theme> fallback then has nothing to read, leaving its own
+ // OS-preference resolution (dark here) in place, same as before this fix.
+ expect(
+ newestMediaAttr(document.querySelector('[data-astryx-toast-fallback]')!),
+ ).toBe('light');
+ });
+
+ it('mirrors <html data-theme> and data-astryx-theme onto the fallback container', async () => {
+ mockMatchMedia(false);
+
+ const {rerender} = render(
+ <Theme theme={testTheme} mode="dark">
+ <ShowToastButton label="Trigger Mirror" />
+ </Theme>,
+ );
+
+ act(() => {
+ fireEvent.click(screen.getByText('Trigger Mirror'));
+ });
+
+ await waitFor(() => {
+ const fallback = document.querySelector(
+ '[data-astryx-toast-fallback]',
+ ) as HTMLElement;
+ expect(fallback.getAttribute('data-theme')).toBe('dark');
+ expect(fallback.getAttribute('data-astryx-theme')).toBe('test');
+ // Inline color-scheme must follow the mirrored mode, not <html>'s own
+ // (possibly #3658-pinned) theme CSS — see useToast.tsx's syncRootThemeAttrs.
+ expect(fallback.style.colorScheme).toBe('dark');
+ });
+
+ // Flip the app mode: the shared MutationObserver re-syncs the container,
+ // so the inline color-scheme must follow it live.
+ rerender(
+ <Theme theme={testTheme} mode="light">
+ <ShowToastButton label="Trigger Mirror" />
+ </Theme>,
+ );
+
+ await waitFor(() => {
+ const fallback = document.querySelector(
+ '[data-astryx-toast-fallback]',
+ ) as HTMLElement;
+ expect(fallback.getAttribute('data-theme')).toBe('light');
+ expect(fallback.style.colorScheme).toBe('light');
+ });
+
+ // mode="system" removes <html data-theme> entirely — the inline property
+ // must be removed too, reverting to whatever the CSS otherwise resolves.
+ rerender(
+ <Theme theme={testTheme} mode="system">
+ <ShowToastButton label="Trigger Mirror" />
+ </Theme>,
+ );
+
+ await waitFor(() => {
+ const fallback = document.querySelector(
+ '[data-astryx-toast-fallback]',
+ ) as HTMLElement;
+ expect(fallback.getAttribute('data-theme')).toBeNull();
+ expect(fallback.style.colorScheme).toBe('');
+ });
+ });
+});
+
+describe('useToast LayerProvider path', () => {
+ afterEach(() => {
+ mockMatchMedia(false);
+ });
+
+ it('resolves mode via real context, unaffected by the fallback provider', () => {
+ mockMatchMedia(true); // OS prefers dark; should be irrelevant here
+
+ const {container} = render(
+ <Theme theme={testTheme} mode="light">
+ <ToastViewport isTopLayer={false}>
+ <ShowToastButton label="Trigger Provider" />
+ </ToastViewport>
+ </Theme>,
+ );
+
+ act(() => {
+ fireEvent.click(screen.getByText('Trigger Provider'));
+ });
+
+ expect(newestMediaAttr(container)).toBe('dark');
+ });
+});
diff --git a/packages/core/src/Toast/useToast.tsx b/packages/core/src/Toast/useToast.tsx
index 48fcd22ca5..2d03ec994f 100644
--- a/packages/core/src/Toast/useToast.tsx
+++ b/packages/core/src/Toast/useToast.tsx
@@ -4,6 +4,7 @@
import {useCallback, use, useEffect, useRef} from 'react';
import {createRoot} from 'react-dom/client';
+import {dataAttr} from '../naming';
import {ToastContext, type ToastContextValue} from './ToastContext';
import {ToastViewport} from './ToastViewport';
import type {
@@ -18,6 +19,45 @@ let fallbackContext: ToastContextValue | null = null;
let fallbackRoot: ReturnType<typeof createRoot> | null = null;
let fallbackWarned = false;
+const ROOT_THEME_ATTRS = ['data-theme', dataAttr('theme')] as const;
+
+// The fallback container is a detached tree with no ThemeContext, so this
+// mirrors <html>'s theme attributes onto it directly (live via
+// MutationObserver) for the theme's @scope'd CSS to reach it. It's a
+// lifetime-of-app singleton that's never torn down, so there's nothing to
+// disconnect — this returns void.
+function syncRootThemeAttrs(container: HTMLElement): void {
+ const sync = () => {
+ let mirroredMode: string | null = null;
+ for (const attr of ROOT_THEME_ATTRS) {
+ const value = document.documentElement.getAttribute(attr);
+ if (value == null) {
+ container.removeAttribute(attr);
+ } else {
+ container.setAttribute(attr, value);
+ if (attr === 'data-theme') {
+ mirroredMode = value;
+ }
+ }
+ }
+ // Pages whose built theme CSS pins color-scheme unconditionally (#3658)
+ // would otherwise resolve light-dark() tokens by OS preference while the
+ // mirrored mode above follows the app theme; the inline style wins over
+ // that CSS.
+ if (mirroredMode === 'light' || mirroredMode === 'dark') {
+ container.style.colorScheme = mirroredMode;
+ } else {
+ container.style.removeProperty('color-scheme');
+ }
+ };
+ sync();
+ const observer = new MutationObserver(sync);
+ observer.observe(document.documentElement, {
+ attributes: true,
+ attributeFilter: [...ROOT_THEME_ATTRS],
+ });
+}
+
function getFallbackContext(): ToastContextValue {
if (fallbackContext) {
return fallbackContext;
@@ -41,6 +81,7 @@ function getFallbackContext(): ToastContextValue {
const container = document.createElement('div');
container.setAttribute('data-astryx-toast-fallback', '');
document.body.appendChild(container);
+ syncRootThemeAttrs(container);
let resolveCtx: ((ctx: ToastContextValue) => void) | undefined;
const ctxReady = new Promise<ToastContextValue>(r => {
diff --git a/packages/core/src/theme/useTheme.test.tsx b/packages/core/src/theme/useTheme.test.tsx
index 6674f82443..5aa9fc892c 100644
--- a/packages/core/src/theme/useTheme.test.tsx
+++ b/packages/core/src/theme/useTheme.test.tsx
@@ -1,7 +1,7 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-import {describe, it, expect, vi} from 'vitest';
-import {renderHook} from '@testing-library/react';
+import {describe, it, expect, vi, afterEach} from 'vitest';
+import {render, renderHook, act, waitFor} from '@testing-library/react';
import React from 'react';
import {Theme} from './Theme';
import {defineTheme} from './defineTheme';
@@ -143,3 +143,107 @@ describe('useTheme', () => {
);
});
});
+
+// Covers the fallback used when a component calls useTheme() with no
+// ThemeContext ancestor reachable — e.g. a detached tree (useToast's
+// fallback viewport, other portals appended straight to document.body).
+// Root Theme instances sync their mode to <html data-theme> specifically so
+// this fallback can resolve the app's actual mode instead of jumping
+// straight to OS preference (see Theme.tsx's useRootThemeSync).
+describe('useTheme mode resolution without a ThemeContext ancestor', () => {
+ afterEach(async () => {
+ // The hook from each `it` below is still mounted and subscribed to the
+ // shared MutationObserver when this runs (RTL's own cleanup — which
+ // unmounts it — is registered after this file's afterEach), so removing
+ // the attribute here triggers a live state update; flush it inside act
+ // so React doesn't warn about an update outside one.
+ await act(async () => {
+ document.documentElement.removeAttribute('data-theme');
+ });
+ });
+
+ it('resolves mode from <html data-theme> when set', () => {
+ document.documentElement.setAttribute('data-theme', 'dark');
+ const {result} = renderHook(() => useTheme());
+ expect(result.current.mode).toBe('dark');
+ });
+
+ it('falls back to OS preference when <html data-theme> is absent', () => {
+ // useMediaQuery is mocked to false (light) at the top of this file.
+ const {result} = renderHook(() => useTheme());
+ expect(result.current.mode).toBe('light');
+ });
+
+ it('stays live when <html data-theme> changes after mount', async () => {
+ const {result} = renderHook(() => useTheme());
+ expect(result.current.mode).toBe('light');
+
+ act(() => {
+ document.documentElement.setAttribute('data-theme', 'dark');
+ });
+
+ await waitFor(() => expect(result.current.mode).toBe('dark'));
+ });
+});
+
+// Covers the singleton MutationObserver + no-op gating in useRootThemeModeAttr:
+// provider-path consumers (a ThemeContext ancestor is reachable) must not
+// create an observer or react to <html data-theme> at all, and every
+// no-context consumer must share exactly one observer, refcounted down to
+// zero as they unmount.
+describe('useTheme root-attribute observer lifecycle', () => {
+ afterEach(() => {
+ document.documentElement.removeAttribute('data-theme');
+ // vi.stubGlobal'd MutationObserver stubs below are torn down here even if
+ // a test fails partway through, instead of relying on a manual restore
+ // line at the end of each test that a mid-test throw would skip.
+ vi.unstubAllGlobals();
+ });
+
+ it('creates no observer and does not re-render provider-path consumers when <html data-theme> changes', () => {
+ const ObserverSpy = vi.fn();
+ vi.stubGlobal('MutationObserver', ObserverSpy);
+
+ const renders = {count: 0};
+ function Consumer() {
+ useTheme();
+ renders.count++;
+ return null;
+ }
+
+ render(
+ <Theme theme={testTheme} mode="light">
+ <Consumer />
+ </Theme>,
+ );
+
+ expect(ObserverSpy).not.toHaveBeenCalled();
+
+ const before = renders.count;
+ act(() => {
+ document.documentElement.setAttribute('data-theme', 'dark');
+ });
+ expect(renders.count).toBe(before);
+ });
+
+ it('shares one observer across multiple no-context consumers and disconnects once all unmount', () => {
+ const observe = vi.fn();
+ const disconnect = vi.fn();
+ const ObserverSpy = vi
+ .fn()
+ .mockImplementation(() => ({observe, disconnect}));
+ vi.stubGlobal('MutationObserver', ObserverSpy);
+
+ const first = renderHook(() => useTheme());
+ const second = renderHook(() => useTheme());
+
+ expect(ObserverSpy).toHaveBeenCalledTimes(1);
+ expect(observe).toHaveBeenCalledTimes(1);
+
+ first.unmount();
+ expect(disconnect).not.toHaveBeenCalled();
+
+ second.unmount();
+ expect(disconnect).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/core/src/theme/useTheme.ts b/packages/core/src/theme/useTheme.ts
index 66ee5886db..3feae38f96 100644
--- a/packages/core/src/theme/useTheme.ts
+++ b/packages/core/src/theme/useTheme.ts
@@ -9,14 +9,19 @@
* @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. Token resolution
- * is shared with the server-safe helpers in ./tokens.ts.
+ * current color mode — no DOM reads on the provider path, no double render.
+ * Without a reachable ThemeContext it consults `<html data-theme>` (kept in
+ * sync by Theme) via a single shared, refcounted MutationObserver before
+ * assuming OS preference; provider-path consumers subscribe to a no-op
+ * store instead (the same args-switch technique useMediaQuery uses), so
+ * mounting under a Theme never creates an observer. Token resolution is
+ * shared with the server-safe helpers in ./tokens.ts.
*
* SYNC: When modified, update:
* - /packages/core/src/theme/index.ts
*/
-import {createContext, use, useMemo} from 'react';
+import {createContext, use, useMemo, useSyncExternalStore} from 'react';
import type {ThemeMode} from './types';
import type {DefinedTheme} from './defineTheme';
import {resolveThemeTokens} from './tokens';
@@ -87,6 +92,76 @@ export interface UseThemeReturn {
// Hook
// =============================================================================
+function getRootThemeAttrSnapshot(): 'light' | 'dark' | null {
+ if (typeof document === 'undefined') {
+ return null;
+ }
+ const attr = document.documentElement.getAttribute('data-theme');
+ return attr === 'light' || attr === 'dark' ? attr : null;
+}
+
+function getRootThemeAttrServerSnapshot(): 'light' | 'dark' | null {
+ return null;
+}
+
+function getNullThemeMode(): null {
+ return null;
+}
+
+// Every no-context consumer wants the same <html data-theme> attribute, so
+// one MutationObserver — refcounted via this listener set — serves all of
+// them instead of one per consumer.
+const rootThemeAttrListeners = new Set<() => void>();
+let rootThemeAttrObserver: MutationObserver | null = null;
+
+function notifyRootThemeAttrListeners(): void {
+ for (const listener of rootThemeAttrListeners) {
+ listener();
+ }
+}
+
+function subscribeRootThemeAttr(onStoreChange: () => void): () => void {
+ rootThemeAttrListeners.add(onStoreChange);
+
+ if (
+ rootThemeAttrListeners.size === 1 &&
+ typeof MutationObserver !== 'undefined'
+ ) {
+ rootThemeAttrObserver = new MutationObserver(notifyRootThemeAttrListeners);
+ rootThemeAttrObserver.observe(document.documentElement, {
+ attributes: true,
+ attributeFilter: ['data-theme'],
+ });
+ }
+
+ return () => {
+ rootThemeAttrListeners.delete(onStoreChange);
+ if (rootThemeAttrListeners.size === 0 && rootThemeAttrObserver) {
+ rootThemeAttrObserver.disconnect();
+ rootThemeAttrObserver = null;
+ }
+ };
+}
+
+function subscribeNoop(): () => void {
+ return () => {};
+}
+
+/**
+ * Reads the root Theme's mode off `<html data-theme>`, live via the shared
+ * MutationObserver. Null means no root Theme has synced it (none present,
+ * or mode is 'system'). `hasCtx` switches which store this subscribes to —
+ * a no-op store when a ThemeContext exists — instead of skipping the hook
+ * call, so provider-path consumers never touch the DOM or the observer.
+ */
+function useRootThemeModeAttr(hasCtx: boolean): 'light' | 'dark' | null {
+ return useSyncExternalStore(
+ hasCtx ? subscribeNoop : subscribeRootThemeAttr,
+ hasCtx ? getNullThemeMode : getRootThemeAttrSnapshot,
+ getRootThemeAttrServerSnapshot,
+ );
+}
+
/**
* Access the current Astryx theme's token values, resolved for the active color mode.
*
@@ -95,8 +170,9 @@ export interface UseThemeReturn {
* (e.g. Vega, D3, Chart.js) that need concrete values rather than
* CSS custom property references.
*
- * When called outside an <Theme> provider, returns the default theme
- * tokens resolved against the current system color mode.
+ * When called outside a <Theme> provider, resolves mode from the root
+ * Theme's `<html data-theme>` when one is present, falling back to the
+ * current system color mode otherwise.
*
* @example
* ```
@@ -114,10 +190,15 @@ export interface UseThemeReturn {
export function useTheme(): UseThemeReturn {
const ctx = use(ThemeContext);
+ // Falls back to the root Theme's mode via <html data-theme> when there's
+ // no ThemeContext ancestor (e.g. useToast's detached fallback viewport).
+ // Resolves to null when `ctx` is present, so it has no effect there.
+ const rootAttrMode = useRootThemeModeAttr(ctx != null);
+
// Resolve 'system' to 'light' | 'dark' using the OS preference
const prefersDark = useMediaQuery('(prefers-color-scheme: dark)');
- const mode = ctx?.mode ?? 'system';
+ const mode = ctx?.mode ?? rootAttrMode ?? 'system';
const theme = ctx?.theme ?? null;
const effectiveMode: 'light' | 'dark' =