Skip to content

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

TypeScript

feat(theme): auto-sync data-theme to <html> for browser chrome theming (#1170)

Cindy Zhangcffb228d1aa7
diff --git a/packages/core/src/reset.css b/packages/core/src/reset.css
index c631d26698..0fbd5ff3fb 100644
--- a/packages/core/src/reset.css
+++ b/packages/core/src/reset.css
@@ -354,4 +354,35 @@
outline: none;
}
}
+
+ /* ===========================================================================
+ Color Scheme
+ =========================================================================== */
+
+ /*
+ * Map data-theme attribute to CSS color-scheme.
+ *
+ * Setting data-theme on <html> tells the browser which color scheme
+ * to use for native UI elements (scrollbars, form controls, date
+ * pickers) and enables CSS light-dark() to resolve correctly.
+ *
+ * XDSTheme auto-detects when it's the root provider and syncs this
+ * attribute on the client. For RSC / SSR, set it on <html> in your
+ * root layout to avoid a flash of wrong theme:
+ *
+ * <html lang="en" data-theme="dark">
+ *
+ * Values: "light" | "dark" | omitted (defaults to light dark = system)
+ */
+ :where(html[data-theme="light"]) {
+ color-scheme: light;
+ }
+
+ :where(html[data-theme="dark"]) {
+ color-scheme: dark;
+ }
+
+ :where(html:not([data-theme])) {
+ color-scheme: light dark;
+ }
}
diff --git a/packages/core/src/theme/XDSTheme.test.tsx b/packages/core/src/theme/XDSTheme.test.tsx
new file mode 100644
index 0000000000..8402a7ec40
--- /dev/null
+++ b/packages/core/src/theme/XDSTheme.test.tsx
@@ -0,0 +1,123 @@
+import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
+import {render, cleanup} from '@testing-library/react';
+import React from 'react';
+import {XDSTheme} from './XDSTheme';
+import {defineTheme} from './defineTheme';
+
+const testTheme = defineTheme({
+ name: 'test',
+ tokens: {
+ '--color-accent': ['#AA0000', '#FF5555'],
+ },
+});
+
+const altTheme = defineTheme({
+ name: 'alt',
+ tokens: {
+ '--color-accent': ['#00AA00', '#55FF55'],
+ },
+});
+
+describe('XDSTheme', () => {
+ beforeEach(() => {
+ // Clean up documentElement state before each test
+ document.documentElement.removeAttribute('data-theme');
+ });
+
+ afterEach(() => {
+ cleanup();
+ document.documentElement.removeAttribute('data-theme');
+ });
+
+ it('renders children', () => {
+ const {getByText} = render(
+ <XDSTheme theme={testTheme}>
+ <span>hello</span>
+ </XDSTheme>,
+ );
+ expect(getByText('hello')).toBeTruthy();
+ });
+
+ it('sets data-xds-theme on wrapper div', () => {
+ const {container} = render(
+ <XDSTheme theme={testTheme}>
+ <span>child</span>
+ </XDSTheme>,
+ );
+ const wrapper = container.querySelector('[data-xds-theme="test"]');
+ expect(wrapper).toBeTruthy();
+ });
+
+ // =========================================================================
+ // Root detection — data-theme on <html>
+ // =========================================================================
+
+ it('syncs data-theme to <html> for root provider in dark mode', () => {
+ render(
+ <XDSTheme theme={testTheme} mode="dark">
+ <span>child</span>
+ </XDSTheme>,
+ );
+ expect(document.documentElement.getAttribute('data-theme')).toBe('dark');
+ });
+
+ it('syncs data-theme to <html> for root provider in light mode', () => {
+ render(
+ <XDSTheme theme={testTheme} mode="light">
+ <span>child</span>
+ </XDSTheme>,
+ );
+ expect(document.documentElement.getAttribute('data-theme')).toBe('light');
+ });
+
+ it('removes data-theme from <html> for root provider in system mode', () => {
+ document.documentElement.setAttribute('data-theme', 'dark');
+ render(
+ <XDSTheme theme={testTheme} mode="system">
+ <span>child</span>
+ </XDSTheme>,
+ );
+ expect(document.documentElement.hasAttribute('data-theme')).toBe(false);
+ });
+
+ it('removes data-theme from <html> when root provider unmounts', () => {
+ const {unmount} = render(
+ <XDSTheme theme={testTheme} mode="dark">
+ <span>child</span>
+ </XDSTheme>,
+ );
+ expect(document.documentElement.getAttribute('data-theme')).toBe('dark');
+ unmount();
+ expect(document.documentElement.hasAttribute('data-theme')).toBe(false);
+ });
+
+ // =========================================================================
+ // Nested themes — should NOT sync to <html>
+ // =========================================================================
+
+ it('does not let nested XDSTheme override <html> data-theme', () => {
+ render(
+ <XDSTheme theme={testTheme} mode="dark">
+ <XDSTheme theme={altTheme} mode="light">
+ <span>nested</span>
+ </XDSTheme>
+ </XDSTheme>,
+ );
+ // Root is dark — nested light should NOT override
+ expect(document.documentElement.getAttribute('data-theme')).toBe('dark');
+ });
+
+ it('nested XDSTheme still sets data-theme on its own wrapper div', () => {
+ const {container} = render(
+ <XDSTheme theme={testTheme} mode="dark">
+ <XDSTheme theme={altTheme} mode="light">
+ <span>nested</span>
+ </XDSTheme>
+ </XDSTheme>,
+ );
+ // The nested wrapper should have data-theme="light" on its own div
+ const nestedWrapper = container.querySelector('[data-xds-theme="alt"]');
+ expect(nestedWrapper).toBeTruthy();
+ expect(nestedWrapper?.getAttribute('data-theme')).toBe('light');
+ });
+});
diff --git a/packages/core/src/theme/XDSTheme.tsx b/packages/core/src/theme/XDSTheme.tsx
index 6dd91137c5..1af1fdecc7 100644
--- a/packages/core/src/theme/XDSTheme.tsx
+++ b/packages/core/src/theme/XDSTheme.tsx
@@ -8,6 +8,16 @@
* - Token overrides set as CSS custom properties on [data-xds-theme]
* - Component overrides scoped via @scope'd CSS selectors on .xds-* classes
*
+ * Root detection: The first XDSTheme in the tree (no parent XDSTheme)
+ * automatically syncs `data-theme` to `document.documentElement`, which
+ * drives `color-scheme` via reset.css rules. This ensures browser chrome
+ * (scrollbars, native form controls, date pickers) reflects the active mode.
+ *
+ * For RSC / SSR, set `data-theme` on `<html>` in your root server layout
+ * to avoid a flash of wrong theme before hydration:
+ *
+ * <html lang="en" data-theme="dark">
+ *
* @example
* ```
* const ocean = defineTheme({
@@ -66,6 +76,17 @@ const wrapperStyles = stylex.create({
},
});
+// =============================================================================
+// Nesting context — detect root vs nested XDSTheme
+// =============================================================================
+
+/**
+ * Context to detect whether this XDSTheme is nested inside another.
+ * The root provider (no parent context) syncs data-theme to <html>.
+ * @internal
+ */
+const XDSThemeNestingContext = React.createContext(false);
+
// =============================================================================
// Style injection for unbuilt themes
// =============================================================================
@@ -194,6 +215,38 @@ function useThemeFontLoading(theme: XDSDefinedTheme): void {
}, [theme.fonts, theme.name]);
}
+// =============================================================================
+// Root color-scheme sync
+// =============================================================================
+
+/**
+ * Hook to sync data-theme to document.documentElement for the root provider.
+ * Skipped for nested XDSTheme instances.
+ *
+ * reset.css maps [data-theme] to color-scheme, which controls browser chrome
+ * (scrollbars, native form controls, date pickers).
+ *
+ * - 'light' | 'dark' → sets data-theme="light" | "dark"
+ * - 'system' → removes data-theme (reset.css defaults to color-scheme: light dark)
+ */
+function useRootColorSchemeSync(isNested: boolean, mode: ThemeMode): void {
+ useLayoutEffect(() => {
+ if (isNested) return;
+ if (typeof document === 'undefined') return;
+
+ if (mode === 'light' || mode === 'dark') {
+ document.documentElement.setAttribute('data-theme', mode);
+ } else {
+ // system — remove attribute, let reset.css default apply
+ document.documentElement.removeAttribute('data-theme');
+ }
+
+ return () => {
+ document.documentElement.removeAttribute('data-theme');
+ };
+ }, [isNested, mode]);
+}
+
// =============================================================================
// Component
// =============================================================================
@@ -204,14 +257,22 @@ function useThemeFontLoading(theme: XDSDefinedTheme): void {
* Sets data-xds-theme attribute so @scope'd CSS takes effect.
* Component overrides are pure CSS scoped under the theme attribute —
* components render with their .xds-* class and don't need context.
+ *
+ * When this is the root XDSTheme (no parent XDSTheme in the tree),
+ * it syncs `data-theme` to `<html>` so browser chrome elements
+ * (scrollbars, form controls, date pickers) reflect the active mode.
+ * Nested XDSTheme instances skip the sync.
*/
export function XDSTheme({
theme,
mode = 'system',
children,
}: XDSThemeProps): React.ReactElement {
+ const isNested = React.useContext(XDSThemeNestingContext);
+
useThemeStyleInjection(theme);
useThemeFontLoading(theme);
+ useRootColorSchemeSync(isNested, mode);
// Get color-scheme style
const colorSchemeStyle =
@@ -232,12 +293,14 @@ export function XDSTheme({
return (
<XDSThemeContext.Provider value={ctxValue}>
- <div
- {...stylex.props(wrapperStyles.base, colorSchemeStyle)}
- data-xds-theme={theme.name}
- data-theme={mode === 'system' ? undefined : mode}>
- {children}
- </div>
+ <XDSThemeNestingContext.Provider value={true}>
+ <div
+ {...stylex.props(wrapperStyles.base, colorSchemeStyle)}
+ data-xds-theme={theme.name}
+ data-theme={mode === 'system' ? undefined : mode}>
+ {children}
+ </div>
+ </XDSThemeNestingContext.Provider>
</XDSThemeContext.Provider>
);
}