Skip to content

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

TypeScript

feat(theme): add ssr-friendly icon registry resolution (#4643)

Cindy Zhang4e594e18473e
diff --git a/.changeset/ssr-theme-icon-registry.md b/.changeset/ssr-theme-icon-registry.md
new file mode 100644
index 0000000000..3fbb75dc11
--- /dev/null
+++ b/.changeset/ssr-theme-icon-registry.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feature] Add SSR-friendly theme and icon registry resolution so semantic icons can resolve from a registered theme name without relying on React context.
+
+@cixzhang
diff --git a/packages/cli/assets/docs/icons.doc.mjs b/packages/cli/assets/docs/icons.doc.mjs
index 59ff8e725d..35e2e7e09e 100644
--- a/packages/cli/assets/docs/icons.doc.mjs
+++ b/packages/cli/assets/docs/icons.doc.mjs
@@ -81,19 +81,21 @@ import { HeartIcon } from 'lucide-react';
content: [
{
type: 'prose',
- text: 'Themes can replace the default SVGs for any semantic name using registerIcons(). This lets you swap the entire icon set (e.g. heroicons \u2192 lucide) without touching component code.',
+ text: 'Themes can replace the default SVGs for any semantic name with the `icons` field in `defineTheme()`. This lets you swap the icon set (e.g. heroicons → lucide) without touching component code, and keeps lookup scoped to the active theme instead of mutating global defaults.',
},
{
type: 'code',
lang: 'tsx',
- label: 'Registering theme icons',
- code: `import { registerIcons } from '@astryxdesign/core/Icon';
-import { XMarkIcon, ChevronDownIcon } from '@heroicons/react/24/outline';
+ label: 'Theme-scoped icons',
+ code: `import {defineTheme} from '@astryxdesign/core/theme';
+import {XMarkIcon, ChevronDownIcon} from '@heroicons/react/24/outline';
-registerIcons({
- close: <XMarkIcon />,
- chevronDown: <ChevronDownIcon />,
- // ... override as many as needed
+export const brandTheme = defineTheme({
+ name: 'brand',
+ icons: {
+ close: <XMarkIcon />,
+ chevronDown: <ChevronDownIcon />,
+ },
});`,
},
],
diff --git a/packages/cli/assets/docs/theme.doc.mjs b/packages/cli/assets/docs/theme.doc.mjs
index 0a4dd4a2b1..753e546f00 100644
--- a/packages/cli/assets/docs/theme.doc.mjs
+++ b/packages/cli/assets/docs/theme.doc.mjs
@@ -536,7 +536,7 @@ import './themes/ocean.css';
content: [
{
type: 'prose',
- text: 'Use `tokenVar()` when a non-StyleX styling library wants a CSS variable reference, and `resolveThemeTokens()` when JavaScript needs token values for a specific theme and mode without React context.',
+ text: 'Use `tokenVar()` when a non-StyleX styling library wants a CSS variable reference, and `resolveThemeTokens()` when JavaScript needs token values for a specific theme and mode without React context. Themes are also registered by name when created with `defineTheme()`; call `registerTheme(theme)` for prebuilt or object-literal themes that need name-based SSR lookup.',
},
{
type: 'code',
diff --git a/packages/core/src/Breadcrumbs/BreadcrumbItem.tsx b/packages/core/src/Breadcrumbs/BreadcrumbItem.tsx
index 645a707f76..e18917c294 100644
--- a/packages/core/src/Breadcrumbs/BreadcrumbItem.tsx
+++ b/packages/core/src/Breadcrumbs/BreadcrumbItem.tsx
@@ -45,7 +45,7 @@ import type {LinkComponentType} from '../Link/types';
import {mergeProps, mergeRefs} from '../utils';
import type {BaseProps} from '../BaseProps';
import {themeProps} from '../utils/themeProps';
-import {getIcon} from '../Icon/globalIconRegistry';
+import {useIcon} from '../Icon';
import {usePopover} from '../Popover/usePopover';
import {useListFocus} from '../hooks/useListFocus';
import {useTypeahead} from '../hooks/useTypeahead';
@@ -507,6 +507,8 @@ function BreadcrumbMenuTrigger({
role: 'none',
});
+ const chevronDownIcon = useIcon('chevronDown');
+
const closeMenu = useCallback(() => {
popover.hide();
}, [popover]);
@@ -623,7 +625,7 @@ function BreadcrumbMenuTrigger({
)}>
{children}
<span aria-hidden="true" {...stylex.props(itemStyles.chevron)}>
- {getIcon('chevronDown')}
+ {chevronDownIcon}
</span>
</button>
diff --git a/packages/core/src/Chat/ChatSendButton.tsx b/packages/core/src/Chat/ChatSendButton.tsx
index d51b656eaf..b72e5c29a7 100644
--- a/packages/core/src/Chat/ChatSendButton.tsx
+++ b/packages/core/src/Chat/ChatSendButton.tsx
@@ -20,7 +20,7 @@
import React, {type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {Button} from '../Button';
-import {getIcon} from '../Icon/globalIconRegistry';
+import {useIcon} from '../Icon';
import {useChatComposerContext} from './ChatContext';
import type {BaseProps} from '../BaseProps';
@@ -95,6 +95,8 @@ export function ChatSendButton(props: ChatSendButtonProps): ReactNode {
} = props;
const handleSend = onSend ?? (() => context?.onSubmit(''));
+ const defaultStopIcon = useIcon('stop');
+ const defaultSendIcon = useIcon('arrowUp');
return (
<Button
@@ -108,8 +110,8 @@ export function ChatSendButton(props: ChatSendButtonProps): ReactNode {
size={size}
icon={
isStopShown
- ? (stopIcon ?? getIcon('stop'))
- : (sendIcon ?? getIcon('arrowUp'))
+ ? (stopIcon ?? defaultStopIcon)
+ : (sendIcon ?? defaultSendIcon)
}
isIconOnly
isDisabled={!isStopShown && isDisabled}
diff --git a/packages/core/src/Collapsible/Collapsible.tsx b/packages/core/src/Collapsible/Collapsible.tsx
index 3ab7be7556..145a67eba6 100644
--- a/packages/core/src/Collapsible/Collapsible.tsx
+++ b/packages/core/src/Collapsible/Collapsible.tsx
@@ -42,7 +42,7 @@ import {
import {useCollapsible} from './useCollapsible';
import {CollapsibleGroupPresentationContext} from './CollapsibleGroupContext';
-import {getIcon} from '../Icon/globalIconRegistry';
+import {useIcon} from '../Icon';
import {mergeProps} from '../utils';
import type {BaseProps} from '../BaseProps';
import {themeProps} from '../utils/themeProps';
@@ -293,7 +293,7 @@ export function Collapsible({
const isDivided = presentation?.hasDividers ?? false;
const density = presentation?.density ?? null;
- const chevronIcon = getIcon('chevronDown');
+ const chevronIcon = useIcon('chevronDown');
// Links the trigger to the region it shows/hides so assistive tech can move
// from the button to its controlled content (disclosure pattern).
diff --git a/packages/core/src/Icon/Icon.test.tsx b/packages/core/src/Icon/Icon.test.tsx
index 87190ed86b..0e79619eec 100644
--- a/packages/core/src/Icon/Icon.test.tsx
+++ b/packages/core/src/Icon/Icon.test.tsx
@@ -13,7 +13,11 @@ import {describe, it, expect, vi} from 'vitest';
import {render, screen} from '@testing-library/react';
import * as stylex from '@stylexjs/stylex';
import {TestIcon} from '../__tests__/TestIcon';
+import {Theme} from '../theme/Theme';
+import {defineTheme} from '../theme/defineTheme';
+import {resetThemes} from '../theme/themeRegistry';
import {Icon} from './Icon';
+import {resetIcons} from './globalIconRegistry';
describe('Icon', () => {
it('renders the icon component', () => {
@@ -169,6 +173,25 @@ describe('Icon', () => {
expect(screen.getByTestId('icon')).toHaveAttribute('aria-hidden', 'true');
});
+ it('resolves string-mode icons from the nearest Theme without leaking globally', () => {
+ resetIcons();
+ resetThemes();
+ const outer = defineTheme({name: 'outer', icons: {check: 'outer-check'}});
+ const inner = defineTheme({name: 'inner', icons: {check: 'inner-check'}});
+
+ render(
+ <Theme theme={outer}>
+ <Icon icon="check" data-testid="outer" />
+ <Theme theme={inner}>
+ <Icon icon="check" data-testid="inner" />
+ </Theme>
+ </Theme>,
+ );
+
+ expect(screen.getByTestId('outer')).toHaveTextContent('outer-check');
+ expect(screen.getByTestId('inner')).toHaveTextContent('inner-check');
+ });
+
it('lets a string-mode icon be made meaningful by overriding aria-hidden', () => {
render(
<Icon
diff --git a/packages/core/src/Icon/Icon.tsx b/packages/core/src/Icon/Icon.tsx
index 707b748e14..9390ed7108 100644
--- a/packages/core/src/Icon/Icon.tsx
+++ b/packages/core/src/Icon/Icon.tsx
@@ -26,6 +26,7 @@ import React, {type ComponentType, type SVGProps} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
import {colorVars} from '../theme/tokens.stylex';
+import {useThemeName} from '../theme/useTheme';
import {getIcon} from './globalIconRegistry';
import type {IconName} from './globalIconRegistry';
import {mergeProps} from '../utils';
@@ -379,7 +380,8 @@ function IconFromRegistry({
xstyle?: StyleXStyles;
spanProps?: Omit<SVGProps<SVGSVGElement>, 'ref' | 'color'>;
}) {
- const resolvedIcon = getIcon(name);
+ const themeName = useThemeName();
+ const resolvedIcon = getIcon(name, themeName);
if (resolvedIcon == null) {
return null;
diff --git a/packages/core/src/Icon/globalIconRegistry.test.tsx b/packages/core/src/Icon/globalIconRegistry.test.tsx
index dec9084d98..c51ba59ac2 100644
--- a/packages/core/src/Icon/globalIconRegistry.test.tsx
+++ b/packages/core/src/Icon/globalIconRegistry.test.tsx
@@ -1,6 +1,9 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-import {describe, it, expect, beforeEach} from 'vitest';
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import {defineTheme} from '../theme/defineTheme';
+import {resetThemes} from '../theme/themeRegistry';
+import {__resetDevWarnings} from '../utils/devWarning';
import {defaultIcons} from './defaultIcons';
import {
registerIcons,
@@ -12,6 +15,13 @@ import {
describe('iconRegistry (global, RSC-compatible)', () => {
beforeEach(() => {
resetIcons();
+ resetThemes();
+ __resetDevWarnings();
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
});
it('returns a default icon registry snapshot', () => {
@@ -28,6 +38,18 @@ describe('iconRegistry (global, RSC-compatible)', () => {
expect(icon).not.toBeNull();
});
+ it('warns once that registerIcons applies global overrides', () => {
+ const warnSpy = vi.mocked(console.warn);
+
+ registerIcons({close: 'custom-close'});
+ registerIcons({check: 'custom-check'});
+
+ expect(warnSpy).toHaveBeenCalledTimes(1);
+ expect(warnSpy.mock.calls[0]?.[0]).toContain(
+ '`registerIcons()` applies icon overrides globally',
+ );
+ });
+
it('returns registered icons over defaults', () => {
const customClose = 'custom-close-icon';
registerIcons({close: customClose});
@@ -65,6 +87,35 @@ describe('iconRegistry (global, RSC-compatible)', () => {
expect(getIcon('close')).toBe('close-v2');
});
+ it('resolves icons from an explicit theme object over global registrations', () => {
+ registerIcons({close: 'global-close'});
+ const theme = defineTheme({
+ name: 'brand',
+ icons: {close: 'theme-close'},
+ });
+
+ expect(getIcon('close', theme)).toBe('theme-close');
+ expect(getIconRegistry(theme).close).toBe('theme-close');
+ });
+
+ it('resolves icons from a registered theme name for SSR-friendly lookups', () => {
+ defineTheme({
+ name: 'brand',
+ icons: {close: 'theme-close'},
+ });
+
+ expect(getIcon('close', 'brand')).toBe('theme-close');
+ expect(getIconRegistry('brand').close).toBe('theme-close');
+ });
+
+ it('falls back through global registrations when a theme omits a name', () => {
+ registerIcons({close: 'global-close'});
+ const theme = defineTheme({name: 'brand', icons: {check: 'theme-check'}});
+
+ expect(getIcon('close', theme)).toBe('global-close');
+ expect(getIcon('check', theme)).toBe('theme-check');
+ });
+
it('resetIcons clears the global registry', () => {
registerIcons({close: 'custom'});
expect(getIcon('close')).toBe('custom');
diff --git a/packages/core/src/Icon/globalIconRegistry.tsx b/packages/core/src/Icon/globalIconRegistry.tsx
index aa0f0c83fe..7a59ede6d4 100644
--- a/packages/core/src/Icon/globalIconRegistry.tsx
+++ b/packages/core/src/Icon/globalIconRegistry.tsx
@@ -4,14 +4,17 @@
* @file globalIconRegistry.tsx
* @input None (pure module-level state)
* @output Exports registerIcons, getIconRegistry, getIcon, resetIcons, IconName, IconRegistry
- * @position Global icon registry; works in both server and client environments
+ * @position Global and theme-scoped icon registry; works in server and client environments
*
* This module has NO 'use client' directive — it's importable from RSC.
- * All components use getIcon() to resolve icons from this global registry.
+ * Components resolve semantic icons through getIcon() or the client useIcon() hook.
*/
import type {ReactNode} from 'react';
import {defaultIcons} from './defaultIcons';
+import type {DefinedTheme} from '../theme/defineTheme';
+import {getRegisteredTheme} from '../theme/themeRegistry';
+import {warnOnce} from '../utils/devWarning';
// =============================================================================
// Types
@@ -57,12 +60,28 @@ export type IconName =
*/
export type IconRegistry = Record<IconName, ReactNode>;
+export type IconRegistrySource = DefinedTheme | string | null | undefined;
+
// =============================================================================
// Global Registry
// =============================================================================
let globalRegistry: Partial<IconRegistry> = {};
+function getThemeIconOverrides(
+ source: IconRegistrySource,
+): Partial<IconRegistry> | null {
+ if (source == null) {
+ return null;
+ }
+
+ if (typeof source === 'string') {
+ return getRegisteredTheme(source)?.icons ?? null;
+ }
+
+ return source.icons ?? null;
+}
+
/**
* Register icons at the module level. Works in both server and client
* environments. Call once at app initialization (e.g. root layout).
@@ -78,6 +97,11 @@ let globalRegistry: Partial<IconRegistry> = {};
* ```
*/
export function registerIcons(icons: Partial<IconRegistry>): void {
+ warnOnce(
+ 'icon-registry:global-register-icons',
+ 'Icon',
+ '`registerIcons()` applies icon overrides globally. Prefer `defineTheme({ icons })` for theme-scoped icon overrides.',
+ );
globalRegistry = {...globalRegistry, ...icons};
}
@@ -89,13 +113,22 @@ export function registerIcons(icons: Partial<IconRegistry>): void {
* to derive valid semantic icon-name options from the same registry Icon
* resolves against.
*/
-export function getIconRegistry(): Readonly<IconRegistry> {
+export function getIconRegistry(
+ source?: IconRegistrySource,
+): Readonly<IconRegistry> {
const registry = {...defaultIcons};
for (const name of Object.keys(globalRegistry) as IconName[]) {
registry[name] = globalRegistry[name] ?? defaultIcons[name];
}
+ const themeIcons = getThemeIconOverrides(source);
+ if (themeIcons != null) {
+ for (const name of Object.keys(themeIcons) as IconName[]) {
+ registry[name] = themeIcons[name] ?? registry[name];
+ }
+ }
+
return registry;
}
@@ -105,8 +138,12 @@ export function getIconRegistry(): Readonly<IconRegistry> {
* Works in both server and client environments.
* Falls back to built-in default icons when no override is registered.
*/
-export function getIcon(name: IconName): ReactNode {
- return globalRegistry[name] ?? defaultIcons[name];
+export function getIcon(
+ name: IconName,
+ source?: IconRegistrySource,
+): ReactNode {
+ const themeIcons = getThemeIconOverrides(source);
+ return themeIcons?.[name] ?? globalRegistry[name] ?? defaultIcons[name];
}
/**
diff --git a/packages/core/src/Icon/index.ts b/packages/core/src/Icon/index.ts
index 992dc4b097..b09300d314 100644
--- a/packages/core/src/Icon/index.ts
+++ b/packages/core/src/Icon/index.ts
@@ -12,12 +12,8 @@
*/
export {Icon, renderIconSlot} from './Icon';
-export type {
- IconProps,
- IconColor,
- IconSize,
- IconType,
-} from './Icon';
+export {useIcon} from './useIcon';
+export type {IconProps, IconColor, IconSize, IconType} from './Icon';
// Global registry (RSC-compatible, no 'use client')
export {
@@ -26,4 +22,8 @@ export {
getIcon,
resetIcons,
} from './globalIconRegistry';
-export type {IconName, IconRegistry} from './globalIconRegistry';
+export type {
+ IconName,
+ IconRegistry,
+ IconRegistrySource,
+} from './globalIconRegistry';
diff --git a/packages/core/src/Icon/useIcon.ts b/packages/core/src/Icon/useIcon.ts
new file mode 100644
index 0000000000..e3302dadb7
--- /dev/null
+++ b/packages/core/src/Icon/useIcon.ts
@@ -0,0 +1,23 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useIcon.ts
+ * @input Semantic icon name
+ * @output Exports useIcon hook for theme-aware icon lookup
+ * @position Client hook for components that render registry icons directly
+ */
+
+import type {ReactNode} from 'react';
+import {useThemeName} from '../theme/useTheme';
+import {getIcon, type IconName} from './globalIconRegistry';
+
+/**
+ * Resolve a semantic icon name from the nearest Theme, falling back through
+ * root theme registration, global icon overrides, and built-in defaults.
+ */
+export function useIcon(name: IconName): ReactNode {
+ const themeName = useThemeName();
+ return getIcon(name, themeName);
+}
diff --git a/packages/core/src/MoreMenu/MoreMenu.tsx b/packages/core/src/MoreMenu/MoreMenu.tsx
index 568988d004..965f3c3e1a 100644
--- a/packages/core/src/MoreMenu/MoreMenu.tsx
+++ b/packages/core/src/MoreMenu/MoreMenu.tsx
@@ -19,7 +19,7 @@
*/
import type {ReactNode} from 'react';
-import {getIcon} from '../Icon/globalIconRegistry';
+import {useIcon} from '../Icon';
import {DropdownMenu} from '../DropdownMenu/DropdownMenu';
import {useSize} from '../SizeContext/SizeContext';
import type {DropdownMenuOption} from '../DropdownMenu';
@@ -119,7 +119,7 @@ export function MoreMenu({
const t = useTranslator();
const label = labelFromProps ?? t('@astryx.moreMenu.label');
const size = useSize(sizeProp, 'md');
- const moreIcon = getIcon('moreHorizontal');
+ const moreIcon = useIcon('moreHorizontal');
return (
<DropdownMenu
diff --git a/packages/core/src/SideNav/SideNavCollapseButton.tsx b/packages/core/src/SideNav/SideNavCollapseButton.tsx
index fd39f8369d..df170416ea 100644
--- a/packages/core/src/SideNav/SideNavCollapseButton.tsx
+++ b/packages/core/src/SideNav/SideNavCollapseButton.tsx
@@ -20,7 +20,7 @@
import React, {type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {durationVars, easeVars} from '../theme/tokens.stylex';
-import {getIcon} from '../Icon/globalIconRegistry';
+import {useIcon} from '../Icon';
import {Button} from '../Button';
import type {BaseProps} from '../BaseProps';
import {composeEventHandlers, rtlStyles} from '../utils';
@@ -107,6 +107,7 @@ export function SideNavCollapseButton({
...props
}: SideNavCollapseButtonProps) {
const t = useTranslator();
+ const chevronLeftIcon = useIcon('chevronLeft');
const {isCollapsed, toggle, isCollapsible} =
useSideNavCollapseState(handleRef);
const {isMobile} = useAppShellMobile();
@@ -137,7 +138,7 @@ export function SideNavCollapseButton({
styles.chevron,
isCollapsed && styles.chevronCollapsed,
)}>
- {getIcon('chevronLeft')}
+ {chevronLeftIcon}
</span>
</span>
)
diff --git a/packages/core/src/SideNav/SideNavHeading.tsx b/packages/core/src/SideNav/SideNavHeading.tsx
index 91f9270434..eb963fd4d5 100644
--- a/packages/core/src/SideNav/SideNavHeading.tsx
+++ b/packages/core/src/SideNav/SideNavHeading.tsx
@@ -33,7 +33,7 @@ import {
// of lazy loading layer resources.
import {usePopover} from '../Popover/usePopover';
import {Link} from '../Link';
-import {getIcon} from '../Icon/globalIconRegistry';
+import {useIcon} from '../Icon';
import {Tooltip} from '../Tooltip';
import {navItemStyles} from '../NavItem/navItemStyles.stylex';
import {useSideNavCollapse} from './SideNavCollapseContext';
@@ -344,6 +344,7 @@ export function SideNavHeading({
...props
}: SideNavHeadingProps) {
const t = useTranslator();
+ const chevronDownIcon = useIcon('chevronDown');
const LinkComponent = useLinkComponent(as);
const {isCollapsed} = useSideNavCollapse();
const rootRef = useRef<HTMLDivElement>(null);
@@ -454,7 +455,7 @@ export function SideNavHeading({
{heading}
</span>
<span {...stylex.props(styles.popoverChevron)}>
- {getIcon('chevronDown')}
+ {chevronDownIcon}
</span>
</span>
{subheading && (
@@ -550,7 +551,7 @@ export function SideNavHeading({
);
const chevronElement = showChevron && (
- <span {...stylex.props(styles.chevron)}>{getIcon('chevronDown')}</span>
+ <span {...stylex.props(styles.chevron)}>{chevronDownIcon}</span>
);
const headerEndContentElement = headerEndContent && (
@@ -566,9 +567,7 @@ export function SideNavHeading({
onClick={triggerProps.onClick}>
{icon && <span {...stylex.props(styles.icon)}>{icon}</span>}
{renderTextContent(
- <span {...stylex.props(styles.popoverChevron)}>
- {getIcon('chevronDown')}
- </span>,
+ <span {...stylex.props(styles.popoverChevron)}>{chevronDownIcon}</span>,
)}
</button>
);
@@ -620,7 +619,7 @@ export function SideNavHeading({
}}
{...popover.triggerProps}
{...stylex.props(styles.chevron, styles.interactive)}>
- {getIcon('chevronDown')}
+ {chevronDownIcon}
</button>,
)}
{headerEndContentElement}
@@ -686,7 +685,7 @@ export function SideNavHeading({
}}
{...popover.triggerProps}
{...stylex.props(styles.chevron, styles.interactive)}>
- {getIcon('chevronDown')}
+ {chevronDownIcon}
</button>
) : undefined,
)}
diff --git a/packages/core/src/SideNav/SideNavItem.tsx b/packages/core/src/SideNav/SideNavItem.tsx
index 14a0d10f5d..fcd044238f 100644
--- a/packages/core/src/SideNav/SideNavItem.tsx
+++ b/packages/core/src/SideNav/SideNavItem.tsx
@@ -38,7 +38,7 @@ import {
borderVars,
radiusVars,
} from '../theme/tokens.stylex';
-import {renderIconSlot, type IconType} from '../Icon';
+import {renderIconSlot, useIcon, type IconType} from '../Icon';
import {useLinkComponent} from '../Link/useLinkComponent';
import type {LinkComponentType} from '../Link/types';
import {usePopover} from '../Popover/usePopover';
@@ -50,7 +50,6 @@ import {
useSideNavCollapse,
SideNavCollapseContext,
} from './SideNavCollapseContext';
-import {getIcon} from '../Icon/globalIconRegistry';
import {useSideNavRenderMode} from './SideNavRenderContext';
import {useAppShellMobile} from '../AppShell/AppShellMobileContext';
import {themeProps} from '../utils/themeProps';
@@ -357,9 +356,9 @@ export function SideNavItem({
'data-testid': testId,
ref,
xstyle,
- ...rest
}: SideNavItemProps) {
const t = useTranslator();
+ const chevronDownIcon = useIcon('chevronDown');
const {isCollapsed} = useSideNavCollapse();
const renderMode = useSideNavRenderMode();
const {closeMobileNav} = useAppShellMobile();
@@ -580,7 +579,7 @@ export function SideNavItem({
styles.expandChevron,
!isItemCollapsed && styles.expandChevronExpanded,
)}>
- {getIcon('chevronDown')}
+ {chevronDownIcon}
</span>
)}
</>
@@ -643,7 +642,7 @@ export function SideNavItem({
styles.expandChevron,
!isItemCollapsed && styles.expandChevronExpanded,
)}>
- {getIcon('chevronDown')}
+ {chevronDownIcon}
</span>
</button>
</div>
diff --git a/packages/core/src/TopNav/TopNavHeading.tsx b/packages/core/src/TopNav/TopNavHeading.tsx
index 36a1ffef5d..d97e88c24c 100644
--- a/packages/core/src/TopNav/TopNavHeading.tsx
+++ b/packages/core/src/TopNav/TopNavHeading.tsx
@@ -31,7 +31,7 @@ import {
} from '../theme/tokens.stylex';
import {usePopover} from '../Popover/usePopover';
import {Link} from '../Link';
-import {getIcon} from '../Icon/globalIconRegistry';
+import {useIcon} from '../Icon';
import {useLinkComponent} from '../Link/useLinkComponent';
import type {LinkComponentType} from '../Link/types';
import {mergeProps, mergeRefs} from '../utils';
@@ -320,6 +320,7 @@ export function TopNavHeading({
...props
}: TopNavHeadingProps) {
const t = useTranslator();
+ const chevronDownIcon = useIcon('chevronDown');
const LinkComponent = useLinkComponent(as);
// Support both headingHref and legacy href
const headingHref = headingHrefProp ?? href;
@@ -412,7 +413,7 @@ export function TopNavHeading({
);
const chevronElement = showChevron && (
- <span {...stylex.props(styles.chevron)}>{getIcon('chevronDown')}</span>
+ <span {...stylex.props(styles.chevron)}>{chevronDownIcon}</span>
);
const headerEndContentElement = headerEndContent && (
@@ -428,9 +429,7 @@ export function TopNavHeading({
onClick={triggerProps.onClick}>
{logo && <span {...stylex.props(styles.logo)}>{logo}</span>}
{renderTextContent(
- <span {...stylex.props(styles.popoverChevron)}>
- {getIcon('chevronDown')}
- </span>,
+ <span {...stylex.props(styles.popoverChevron)}>{chevronDownIcon}</span>,
)}
</button>
);
@@ -507,7 +506,7 @@ export function TopNavHeading({
}}
{...popover.triggerProps}
{...stylex.props(styles.chevron, styles.interactive)}>
- {getIcon('chevronDown')}
+ {chevronDownIcon}
</button>,
)}
{headerEndContentElement}
@@ -576,7 +575,7 @@ export function TopNavHeading({
}}
{...popover.triggerProps}
{...stylex.props(styles.chevron, styles.interactive)}>
- {getIcon('chevronDown')}
+ {chevronDownIcon}
</button>
) : undefined,
)}
diff --git a/packages/core/src/TopNav/TopNavMegaMenu.tsx b/packages/core/src/TopNav/TopNavMegaMenu.tsx
index d8a7536899..92d7a78206 100644
--- a/packages/core/src/TopNav/TopNavMegaMenu.tsx
+++ b/packages/core/src/TopNav/TopNavMegaMenu.tsx
@@ -44,7 +44,7 @@ import {
} from '../theme/tokens.stylex';
import {usePopover} from '../Popover/usePopover';
import {Grid} from '../Grid/Grid';
-import {getIcon} from '../Icon/globalIconRegistry';
+import {useIcon} from '../Icon';
import {mergeProps, mergeRefs} from '../utils';
import type {BaseProps} from '../BaseProps';
import {navItemStyles} from '../NavItem/navItemStyles.stylex';
@@ -364,6 +364,7 @@ function DefaultMegaMenu({
onOpenChange,
}: TopNavMegaMenuProps) {
const slot = useTopNavSlot();
+ const chevronDownIcon = useIcon('chevronDown');
const showTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const hideTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const triggerButtonRef = useRef<HTMLButtonElement | null>(null);
@@ -476,7 +477,7 @@ function DefaultMegaMenu({
styles.chevron,
popover.isOpen && styles.chevronOpen,
)}>
- {getIcon('chevronDown')}
+ {chevronDownIcon}
</span>
</button>
{popover.render(
@@ -525,6 +526,7 @@ function DrawerMegaMenu({
featured,
}: Pick<TopNavMegaMenuProps, 'label' | 'items' | 'featured'>) {
const [isExpanded, setIsExpanded] = useState(false);
+ const chevronDownIcon = useIcon('chevronDown');
const menuId = `mega-menu-${label.toLowerCase().replace(/\s+/g, '-')}`;
return (
@@ -545,7 +547,7 @@ function DrawerMegaMenu({
styles.drawerChevron,
isExpanded && styles.drawerChevronExpanded,
)}>
- {getIcon('chevronDown')}
+ {chevronDownIcon}
</span>
</button>
diff --git a/packages/core/src/TopNav/TopNavMenu.tsx b/packages/core/src/TopNav/TopNavMenu.tsx
index e8e3c5b539..7221981293 100644
--- a/packages/core/src/TopNav/TopNavMenu.tsx
+++ b/packages/core/src/TopNav/TopNavMenu.tsx
@@ -28,7 +28,7 @@ import {usePopover} from '../Popover/usePopover';
import {useMenuHover} from '../hooks/useMenuHover';
import {useListFocus} from '../hooks/useListFocus';
import {useTypeahead} from '../hooks/useTypeahead';
-import {getIcon} from '../Icon/globalIconRegistry';
+import {useIcon} from '../Icon';
import {mergeProps, mergeRefs} from '../utils';
import type {BaseProps} from '../BaseProps';
import {navItemStyles} from '../NavItem/navItemStyles.stylex';
@@ -332,6 +332,7 @@ export function TopNavMenu({
hideDelay = 200,
}: TopNavMenuProps) {
const renderMode = useTopNavRenderMode();
+ const chevronDownIcon = useIcon('chevronDown');
const {closeMobileNav} = useAppShellMobile();
const LinkComponent = useLinkComponent();
const [drawerExpanded, setDrawerExpanded] = useState(false);
@@ -445,7 +446,7 @@ export function TopNavMenu({
drawerStyles.chevron,
drawerExpanded && drawerStyles.chevronExpanded,
)}>
- {getIcon('chevronDown')}
+ {chevronDownIcon}
</span>
</button>
<div
@@ -503,7 +504,7 @@ export function TopNavMenu({
styles.chevron,
popover.isOpen && styles.chevronOpen,
)}>
- {getIcon('chevronDown')}
+ {chevronDownIcon}
</span>
</button>
{popover.render(
diff --git a/packages/core/src/TreeList/TreeListItem.tsx b/packages/core/src/TreeList/TreeListItem.tsx
index 761d809eee..1432f35f91 100644
--- a/packages/core/src/TreeList/TreeListItem.tsx
+++ b/packages/core/src/TreeList/TreeListItem.tsx
@@ -24,7 +24,7 @@ import {
easeVars,
typeScaleVars,
} from '../theme/tokens.stylex';
-import {getIcon} from '../Icon/globalIconRegistry';
+import {useIcon} from '../Icon';
import {mergeProps, rtlStyles} from '../utils';
import {useLinkComponent} from '../Link/useLinkComponent';
import {TreeListBranches} from './TreeListBranches';
@@ -328,6 +328,7 @@ export function TreeListItem({
isTabbable,
}: TreeListItemInternalProps) {
const t = useTranslator();
+ const chevronRightIcon = useIcon('chevronRight');
const labelId = useId();
const descriptionId = useId();
const LinkComponent = useLinkComponent();
@@ -412,7 +413,7 @@ export function TreeListItem({
styles.chevronSvg,
isExpanded ? styles.chevronExpanded : styles.chevronCollapsed,
)}>
- {getIcon('chevronRight')}
+ {chevronRightIcon}
</span>
</span>
);
diff --git a/packages/core/src/theme/Theme.tsx b/packages/core/src/theme/Theme.tsx
index 885305a7f9..547762ef8e 100644
--- a/packages/core/src/theme/Theme.tsx
+++ b/packages/core/src/theme/Theme.tsx
@@ -41,8 +41,8 @@ import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
import * as stylex from '@stylexjs/stylex';
import type {ThemeMode} from './types';
import {colorVars, typographyVars} from './tokens.stylex';
-import {registerIcons} from '../Icon/globalIconRegistry';
import {generateThemeCSS, type DefinedTheme} from './defineTheme';
+import {registerTheme} from './themeRegistry';
import {dataAttr} from '../naming';
import {ThemeContext} from './useTheme';
import {warnOnce} from '../utils/devWarning';
@@ -243,6 +243,8 @@ export function Theme({
}: ThemeProps): React.ReactElement {
const isNested = use(ThemeNestingContext);
+ registerTheme(theme);
+
useThemeStyleInjection(theme);
useRootThemeSync(isNested, mode, theme.name);
@@ -254,12 +256,6 @@ export function Theme({
? wrapperStyles.light
: wrapperStyles.system;
- // Icons — register globally (works in both server and client environments)
- const icons = theme.icons;
- if (icons != null) {
- registerIcons(icons);
- }
-
// Memoize the context value to prevent unnecessary re-renders
const ctxValue = useMemo(() => ({theme, mode}), [theme, mode]);
diff --git a/packages/core/src/theme/defineTheme.ts b/packages/core/src/theme/defineTheme.ts
index e28c67cc18..f0c713c329 100644
--- a/packages/core/src/theme/defineTheme.ts
+++ b/packages/core/src/theme/defineTheme.ts
@@ -63,6 +63,7 @@ import {expandColorScale, type ColorScaleConfig} from './expandColorScale';
import type {DomainTokenName} from './domainTokens';
import {domainTokenDefaults} from './domainTokens';
import type {SyntaxThemeDefinition} from './syntax';
+import {registerTheme} from './themeRegistry';
// =============================================================================
// Types
@@ -624,7 +625,7 @@ export function defineTheme(input: DefineThemeInput): DefinedTheme {
? {...base.icons, ...input.icons}
: (input.icons ?? base?.icons);
- return {
+ const theme: DefinedTheme = {
name: input.name,
tokens,
components,
@@ -633,6 +634,9 @@ export function defineTheme(input: DefineThemeInput): DefinedTheme {
__onDark,
__onLight,
};
+
+ registerTheme(theme);
+ return theme;
}
// =============================================================================
diff --git a/packages/core/src/theme/index.ts b/packages/core/src/theme/index.ts
index 230b86a6ea..e2230431f0 100644
--- a/packages/core/src/theme/index.ts
+++ b/packages/core/src/theme/index.ts
@@ -30,6 +30,12 @@ export {
isDefinedTheme,
tokenDefaults,
} from './defineTheme';
+export {
+ registerTheme,
+ getRegisteredTheme,
+ getRegisteredThemes,
+ resetThemes,
+} from './themeRegistry';
export type {
DefineThemeInput,
DefinedTheme,
@@ -126,7 +132,7 @@ export type {
TypeScaleVarName,
} from './tokens.stylex';
-export {useTheme, ThemeContext} from './useTheme';
+export {useTheme, useThemeName, ThemeContext} from './useTheme';
export type {UseThemeReturn, ThemeContextValue} from './useTheme';
export {
resolveThemeToken,
diff --git a/packages/core/src/theme/themeRegistry.test.ts b/packages/core/src/theme/themeRegistry.test.ts
new file mode 100644
index 0000000000..29995921d6
--- /dev/null
+++ b/packages/core/src/theme/themeRegistry.test.ts
@@ -0,0 +1,59 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, it, expect, beforeEach} from 'vitest';
+import {defineTheme} from './defineTheme';
+import {
+ getRegisteredTheme,
+ getRegisteredThemes,
+ registerTheme,
+ resetThemes,
+} from './themeRegistry';
+
+describe('themeRegistry', () => {
+ beforeEach(() => {
+ resetThemes();
+ });
+
+ it('registers and resolves themes by name', () => {
+ const theme = defineTheme({
+ name: 'brand',
+ tokens: {'--color-accent': '#123456'},
+ });
+
+ expect(getRegisteredTheme('brand')).toBe(theme);
+ });
+
+ it('returns null for empty or unknown names', () => {
+ expect(getRegisteredTheme(null)).toBeNull();
+ expect(getRegisteredTheme('')).toBeNull();
+ expect(getRegisteredTheme('missing')).toBeNull();
+ });
+
+ it('replaces an existing theme with the same name', () => {
+ const first = defineTheme({name: 'brand'});
+ const second = defineTheme({
+ name: 'brand',
+ tokens: {'--color-accent': '#654321'},
+ });
+
+ expect(getRegisteredTheme('brand')).not.toBe(first);
+ expect(getRegisteredTheme('brand')).toBe(second);
+ });
+
+ it('returns a defensive snapshot of registered themes', () => {
+ const theme = defineTheme({name: 'brand'});
+ const snapshot = getRegisteredThemes();
+
+ expect(snapshot.get('brand')).toBe(theme);
+ expect(snapshot).not.toBe(getRegisteredThemes());
+ });
+
+ it('allows explicit registration of built theme objects', () => {
+ const theme = defineTheme({name: 'built'});
+ resetThemes();
+
+ registerTheme(theme);
+
+ expect(getRegisteredTheme('built')).toBe(theme);
+ });
+});
diff --git a/packages/core/src/theme/themeRegistry.ts b/packages/core/src/theme/themeRegistry.ts
new file mode 100644
index 0000000000..78658a9a26
--- /dev/null
+++ b/packages/core/src/theme/themeRegistry.ts
@@ -0,0 +1,53 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file themeRegistry.ts
+ * @input DefinedTheme objects from defineTheme() or built theme packages
+ * @output Exports registerTheme, getRegisteredTheme, getRegisteredThemes, resetThemes
+ * @position Server-safe theme registry for theme-name-based SSR resolution
+ *
+ * This module has NO 'use client' directive. It is importable from SSR/RSC and
+ * lets code resolve theme data by stable theme name without React context.
+ */
+
+import type {DefinedTheme} from './defineTheme';
+
+const themeRegistry = new Map<string, DefinedTheme>();
+
+/**
+ * Register a defined theme under its `name`.
+ *
+ * Registration is idempotent and replaces any previous theme with the same
+ * name. Call from app initialization, theme packages, or <Theme> to make the
+ * theme available to SSR-safe resolvers by name.
+ */
+export function registerTheme(theme: DefinedTheme): void {
+ themeRegistry.set(theme.name, theme);
+}
+
+/**
+ * Return a previously registered theme by name.
+ */
+export function getRegisteredTheme(
+ name: string | null | undefined,
+): DefinedTheme | null {
+ if (name == null || name === '') {
+ return null;
+ }
+ return themeRegistry.get(name) ?? null;
+}
+
+/**
+ * Return all registered themes keyed by theme name.
+ */
+export function getRegisteredThemes(): ReadonlyMap<string, DefinedTheme> {
+ return new Map(themeRegistry);
+}
+
+/**
+ * Reset the theme registry. For testing only.
+ * @internal
+ */
+export function resetThemes(): void {
+ themeRegistry.clear();
+}
diff --git a/packages/core/src/theme/useTheme.test.tsx b/packages/core/src/theme/useTheme.test.tsx
index 04acc56d50..461b534962 100644
--- a/packages/core/src/theme/useTheme.test.tsx
+++ b/packages/core/src/theme/useTheme.test.tsx
@@ -5,6 +5,7 @@ import {render, renderHook, act, waitFor} from '@testing-library/react';
import React from 'react';
import {Theme} from './Theme';
import {defineTheme} from './defineTheme';
+import {resetThemes} from './themeRegistry';
import {useTheme} from './useTheme';
import {resolveThemeTokens} from './tokens';
@@ -152,6 +153,8 @@ describe('useTheme', () => {
// straight to OS preference (see Theme.tsx's useRootThemeSync).
describe('useTheme mode resolution without a ThemeContext ancestor', () => {
afterEach(async () => {
+ resetThemes();
+ document.documentElement.removeAttribute('data-astryx-theme');
// 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
@@ -184,6 +187,46 @@ describe('useTheme mode resolution without a ThemeContext ancestor', () => {
await waitFor(() => expect(result.current.mode).toBe('dark'));
});
+
+ it('resolves registered theme tokens from <html data-astryx-theme> when set', () => {
+ defineTheme({
+ name: 'root-brand',
+ tokens: {'--color-accent': ['#010203', '#AABBCC']},
+ });
+ document.documentElement.setAttribute('data-astryx-theme', 'root-brand');
+ document.documentElement.setAttribute('data-theme', 'dark');
+
+ const {result} = renderHook(() => useTheme());
+
+ expect(result.current.name).toBe('root-brand');
+ expect(result.current.token('--color-accent')).toBe('#AABBCC');
+ });
+
+ it('stays live when <html data-astryx-theme> changes after mount', async () => {
+ defineTheme({
+ name: 'first-brand',
+ tokens: {'--color-accent': '#111111'},
+ });
+ defineTheme({
+ name: 'second-brand',
+ tokens: {'--color-accent': '#222222'},
+ });
+ document.documentElement.setAttribute('data-astryx-theme', 'first-brand');
+
+ const {result} = renderHook(() => useTheme());
+ expect(result.current.name).toBe('first-brand');
+ expect(result.current.token('--color-accent')).toBe('#111111');
+
+ act(() => {
+ document.documentElement.setAttribute(
+ 'data-astryx-theme',
+ 'second-brand',
+ );
+ });
+
+ await waitFor(() => expect(result.current.name).toBe('second-brand'));
+ expect(result.current.token('--color-accent')).toBe('#222222');
+ });
});
// Covers the singleton MutationObserver + no-op gating in useRootThemeModeAttr:
@@ -193,7 +236,9 @@ describe('useTheme mode resolution without a ThemeContext ancestor', () => {
// zero as they unmount.
describe('useTheme root-attribute observer lifecycle', () => {
afterEach(() => {
+ resetThemes();
document.documentElement.removeAttribute('data-theme');
+ document.documentElement.removeAttribute('data-astryx-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.
@@ -237,13 +282,13 @@ describe('useTheme root-attribute observer lifecycle', () => {
const first = renderHook(() => useTheme());
const second = renderHook(() => useTheme());
- expect(ObserverSpy).toHaveBeenCalledTimes(1);
- expect(observe).toHaveBeenCalledTimes(1);
+ expect(ObserverSpy).toHaveBeenCalledTimes(2);
+ expect(observe).toHaveBeenCalledTimes(2);
first.unmount();
expect(disconnect).not.toHaveBeenCalled();
second.unmount();
- expect(disconnect).toHaveBeenCalledTimes(1);
+ expect(disconnect).toHaveBeenCalledTimes(2);
});
});
diff --git a/packages/core/src/theme/useTheme.ts b/packages/core/src/theme/useTheme.ts
index 3feae38f96..d1a7bfb2bf 100644
--- a/packages/core/src/theme/useTheme.ts
+++ b/packages/core/src/theme/useTheme.ts
@@ -5,17 +5,17 @@
/**
* @file useTheme.ts
* @input ThemeContext provided by Theme
- * @output Exports useTheme hook for programmatic access to resolved theme tokens
+ * @output Exports useTheme and useThemeName hooks for programmatic theme access
* @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 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.
+ * Without a reachable ThemeContext it consults `<html data-theme>` and
+ * `<html data-astryx-theme>` (kept in sync by Theme) via shared, refcounted
+ * MutationObservers before assuming OS preference/default tokens. Provider-path
+ * consumers subscribe to no-op stores instead, 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
@@ -25,6 +25,8 @@ import {createContext, use, useMemo, useSyncExternalStore} from 'react';
import type {ThemeMode} from './types';
import type {DefinedTheme} from './defineTheme';
import {resolveThemeTokens} from './tokens';
+import {getRegisteredTheme} from './themeRegistry';
+import {dataAttr} from '../naming';
import {useMediaQuery} from '../hooks/useMediaQuery';
// =============================================================================
@@ -92,7 +94,7 @@ export interface UseThemeReturn {
// Hook
// =============================================================================
-function getRootThemeAttrSnapshot(): 'light' | 'dark' | null {
+function getRootModeAttrSnapshot(): 'light' | 'dark' | null {
if (typeof document === 'undefined') {
return null;
}
@@ -100,45 +102,88 @@ function getRootThemeAttrSnapshot(): 'light' | 'dark' | null {
return attr === 'light' || attr === 'dark' ? attr : null;
}
-function getRootThemeAttrServerSnapshot(): 'light' | 'dark' | null {
+function getRootModeAttrServerSnapshot(): 'light' | 'dark' | null {
return null;
}
-function getNullThemeMode(): null {
+function getRootNameAttrSnapshot(): string | null {
+ if (typeof document === 'undefined') {
+ return null;
+ }
+ return document.documentElement.getAttribute(dataAttr('theme'));
+}
+
+function getRootNameAttrServerSnapshot(): string | null {
+ return null;
+}
+
+function getNullThemeSnapshot(): 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;
+const rootModeAttrListeners = new Set<() => void>();
+let rootModeAttrObserver: MutationObserver | null = null;
-function notifyRootThemeAttrListeners(): void {
- for (const listener of rootThemeAttrListeners) {
+const rootNameAttrListeners = new Set<() => void>();
+let rootNameAttrObserver: MutationObserver | null = null;
+
+function notifyRootModeAttrListeners(): void {
+ for (const listener of rootModeAttrListeners) {
listener();
}
}
-function subscribeRootThemeAttr(onStoreChange: () => void): () => void {
- rootThemeAttrListeners.add(onStoreChange);
+function subscribeRootModeAttr(onStoreChange: () => void): () => void {
+ rootModeAttrListeners.add(onStoreChange);
if (
- rootThemeAttrListeners.size === 1 &&
+ rootModeAttrListeners.size === 1 &&
typeof MutationObserver !== 'undefined'
) {
- rootThemeAttrObserver = new MutationObserver(notifyRootThemeAttrListeners);
- rootThemeAttrObserver.observe(document.documentElement, {
+ rootModeAttrObserver = new MutationObserver(notifyRootModeAttrListeners);
+ rootModeAttrObserver.observe(document.documentElement, {
attributes: true,
attributeFilter: ['data-theme'],
});
}
return () => {
- rootThemeAttrListeners.delete(onStoreChange);
- if (rootThemeAttrListeners.size === 0 && rootThemeAttrObserver) {
- rootThemeAttrObserver.disconnect();
- rootThemeAttrObserver = null;
+ rootModeAttrListeners.delete(onStoreChange);
+ if (rootModeAttrListeners.size === 0 && rootModeAttrObserver) {
+ rootModeAttrObserver.disconnect();
+ rootModeAttrObserver = null;
+ }
+ };
+}
+
+function notifyRootNameAttrListeners(): void {
+ for (const listener of rootNameAttrListeners) {
+ listener();
+ }
+}
+
+function subscribeRootNameAttr(onStoreChange: () => void): () => void {
+ rootNameAttrListeners.add(onStoreChange);
+
+ if (
+ rootNameAttrListeners.size === 1 &&
+ typeof MutationObserver !== 'undefined'
+ ) {
+ rootNameAttrObserver = new MutationObserver(notifyRootNameAttrListeners);
+ rootNameAttrObserver.observe(document.documentElement, {
+ attributes: true,
+ attributeFilter: [dataAttr('theme')],
+ });
+ }
+
+ return () => {
+ rootNameAttrListeners.delete(onStoreChange);
+ if (rootNameAttrListeners.size === 0 && rootNameAttrObserver) {
+ rootNameAttrObserver.disconnect();
+ rootNameAttrObserver = null;
}
};
}
@@ -154,14 +199,38 @@ function subscribeNoop(): () => void {
* 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 {
+function useRootModeAttr(hasCtx: boolean): 'light' | 'dark' | null {
+ return useSyncExternalStore(
+ hasCtx ? subscribeNoop : subscribeRootModeAttr,
+ hasCtx ? getNullThemeSnapshot : getRootModeAttrSnapshot,
+ getRootModeAttrServerSnapshot,
+ );
+}
+
+function useRootThemeNameAttr(hasCtx: boolean): string | null {
return useSyncExternalStore(
- hasCtx ? subscribeNoop : subscribeRootThemeAttr,
- hasCtx ? getNullThemeMode : getRootThemeAttrSnapshot,
- getRootThemeAttrServerSnapshot,
+ hasCtx ? subscribeNoop : subscribeRootNameAttr,
+ hasCtx ? getNullThemeSnapshot : getRootNameAttrSnapshot,
+ getRootNameAttrServerSnapshot,
);
}
+/**
+ * Return the nearest active Astryx theme name.
+ *
+ * Uses ThemeContext when present and otherwise follows the root Theme's
+ * <html data-astryx-theme> attribute. This is intentionally lighter than
+ * useTheme() for consumers that only need theme identity, such as semantic
+ * icon resolution.
+ */
+export function useThemeName(): string | null {
+ const ctx = use(ThemeContext);
+ const hasCtx = ctx != null;
+ const rootThemeName = useRootThemeNameAttr(hasCtx);
+
+ return ctx?.theme.name ?? rootThemeName;
+}
+
/**
* Access the current Astryx theme's token values, resolved for the active color mode.
*
@@ -193,13 +262,15 @@ export function useTheme(): UseThemeReturn {
// 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);
+ const hasCtx = ctx != null;
+ const rootAttrMode = useRootModeAttr(hasCtx);
+ const rootThemeName = useRootThemeNameAttr(hasCtx);
// Resolve 'system' to 'light' | 'dark' using the OS preference
const prefersDark = useMediaQuery('(prefers-color-scheme: dark)');
const mode = ctx?.mode ?? rootAttrMode ?? 'system';
- const theme = ctx?.theme ?? null;
+ const theme = ctx?.theme ?? getRegisteredTheme(rootThemeName);
const effectiveMode: 'light' | 'dark' =
mode === 'system' ? (prefersDark ? 'dark' : 'light') : mode;