Skip to content

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

TypeScript

feat(Icon): a theme icon entry can be a function of the requested size (#8753)

Xinzi Zhou05ead02aa4ec
diff --git a/.changeset/ast-087-icon-function-entries.md b/.changeset/ast-087-icon-function-entries.md
new file mode 100644
index 0000000000..b369b7d56d
--- /dev/null
+++ b/.changeset/ast-087-icon-function-entries.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+'@astryxdesign/cli': patch
+---
+
+[feat] A theme icon entry in `defineTheme({icons})` or `registerIcons()` can be a pure, synchronous function of `{size, variant}`; `Icon` calls it with the size it renders at, so a theme can match its icon library's artwork or props to each Icon size. A selected function's result is final: `null` draws no glyph instead of falling back. `getIcon`, `getExtendedIcon`, `getIconRegistry`, `useIcon`, and a theme's `icons` field stay node-valued and read a function entry at `{size: 'md'}`. Existing node entries are unchanged.
+@imdreamrunner
diff --git a/packages/cli/assets/docs/icons.doc.mjs b/packages/cli/assets/docs/icons.doc.mjs
index d93088cc60..8ce3939357 100644
--- a/packages/cli/assets/docs/icons.doc.mjs
+++ b/packages/cli/assets/docs/icons.doc.mjs
@@ -101,11 +101,34 @@ export const brandTheme = defineTheme({
},
});`,
},
+ {
+ type: 'prose',
+ text: "An entry can also be a function of the request, so the theme maps Icon's size to its icon library's own props or artwork. `Icon` calls it with `{size, variant}`, where `size` is the size it renders at (`xsm`, `sm`, `md`, or `lg`: an explicit `size`, else the owning component's default, else `md`). Reads that return one node — `getIcon()`, `useIcon()`, `getIconRegistry()`, and the theme's `icons` field — call it with `{size: 'md'}`. The same entry shape works in `registerIcons()`.",
+ },
+ {
+ type: 'code',
+ lang: 'tsx',
+ label: 'A size-aware icon entry',
+ code: `import {defineTheme} from '@astryxdesign/core/theme';
+import {Info} from 'lucide-react';
+
+export const brandTheme = defineTheme({
+ name: 'brand',
+ icons: {
+ // A heavier stroke keeps the small size legible.
+ info: ({size}) => <Info strokeWidth={size === 'sm' || size === 'xsm' ? 2.5 : 2} />,
+ },
+});`,
+ },
+ {
+ type: 'prose',
+ text: 'Keep the function pure and synchronous: it computes its result from the request only, with no hooks, DOM or SVG measurement, browser globals, network access, mutable module state, or side effects. Its result is final. Returning `null` draws no glyph instead of falling back to a registered or built-in icon, while a `null` or `undefined` node entry still falls back. A child theme that sets an entry for a key replaces the inherited entry for that key.',
+ },
],
},
{
title: 'Component and Library Icons',
- category: 'foundations',
+ category: 'foundations',
content: [
{
type: 'prose',
diff --git a/packages/cli/assets/theme.template.ts b/packages/cli/assets/theme.template.ts
index 781204ec00..6f5f2b78f5 100644
--- a/packages/cli/assets/theme.template.ts
+++ b/packages/cli/assets/theme.template.ts
@@ -314,10 +314,12 @@ export const myTheme = defineTheme({
/**
* Swap the artwork behind semantic icon names — every component that asks
- * for `check`, `close`, `chevron-down` gets yours.
+ * for `check`, `close`, `chevron-down` gets yours. An entry may also be a
+ * pure function of `{size, variant}` that picks artwork for the size Icon
+ * renders at.
* Reference: `astryx docs icons` lists the names.
*/
- // icons: {check: <MyCheck />, close: <MyClose />},
+ // icons: {check: <MyCheck />, info: ({size}) => <MyInfo bold={size === 'sm'} />},
/**
* Replace the small components that DRAW control state — the checkbox box,
diff --git a/packages/cli/test/__golden__/no-icon-set/docs-topics.json b/packages/cli/test/__golden__/no-icon-set/docs-topics.json
index dd9fe6f0fb..1e3c320ea5 100644
--- a/packages/cli/test/__golden__/no-icon-set/docs-topics.json
+++ b/packages/cli/test/__golden__/no-icon-set/docs-topics.json
@@ -162,7 +162,7 @@
"theme-overrides",
"component-and-library-icons"
],
- "skeleton": "e64c5b38eb3c598a4e2d35f4301fe72a59497fee2f48a32e1faf270fc5fd41f1",
+ "skeleton": "5d8a54e271cc1aa84302b2b101820eba3ae1b674f3ef87767fb356939464e097",
"mentions": [
"This lets you swap the icon set (e.g."
]
diff --git a/packages/cli/test/__golden__/no-icon-set/search-icon-set.json b/packages/cli/test/__golden__/no-icon-set/search-icon-set.json
index c931a71b43..21d9a87cb7 100644
--- a/packages/cli/test/__golden__/no-icon-set/search-icon-set.json
+++ b/packages/cli/test/__golden__/no-icon-set/search-icon-set.json
@@ -18,18 +18,6 @@
"parent": "astryx docs authoring/building-blocks/templates/build-the-template/template-assets/template-icons --index",
"mentions": []
},
- {
- "domain": "template",
- "name": "ToolbarTableFilter",
- "package": "@astryxdesign/core",
- "score": "<text>",
- "reason": "<text>",
- "description": "<text>",
- "displayName": "<text>",
- "kind": "block",
- "command": "astryx template ToolbarTableFilter --type block",
- "mentions": []
- },
{
"domain": "doc",
"name": "icons",
@@ -45,6 +33,18 @@
"This lets you swap the icon set (e.g."
]
},
+ {
+ "domain": "template",
+ "name": "ToolbarTableFilter",
+ "package": "@astryxdesign/core",
+ "score": "<text>",
+ "reason": "<text>",
+ "description": "<text>",
+ "displayName": "<text>",
+ "kind": "block",
+ "command": "astryx template ToolbarTableFilter --type block",
+ "mentions": []
+ },
{
"domain": "component",
"name": "Icon",
diff --git a/packages/cli/test/__golden__/no-icon-set/search-icon-set.txt b/packages/cli/test/__golden__/no-icon-set/search-icon-set.txt
index 6e222060b3..3806e4d19f 100644
--- a/packages/cli/test/__golden__/no-icon-set/search-icon-set.txt
+++ b/packages/cli/test/__golden__/no-icon-set/search-icon-set.txt
@@ -5,16 +5,16 @@ domain: doc
package: @astryxdesign/cli
command: pnpm exec astryx docs authoring/building-blocks/templates/build-the-template/template-assets/template-icons use-astryx-icon
parent: pnpm exec astryx docs authoring/building-blocks/templates/build-the-template/template-assets/template-icons --index
-name: ToolbarTableFilter
-domain: template
-package: @astryxdesign/core
-command: pnpm exec astryx template ToolbarTableFilter --type block
name: icons
section: theme-overrides
domain: doc
package: @astryxdesign/cli
command: pnpm exec astryx docs icons theme-overrides
parent: pnpm exec astryx docs icons --index
+name: ToolbarTableFilter
+domain: template
+package: @astryxdesign/core
+command: pnpm exec astryx template ToolbarTableFilter --type block
name: Icon
domain: component
package: @astryxdesign/core
diff --git a/packages/cli/test/__golden__/no-icon-set/search-icon.json b/packages/cli/test/__golden__/no-icon-set/search-icon.json
index 64511715e5..2033da1df8 100644
--- a/packages/cli/test/__golden__/no-icon-set/search-icon.json
+++ b/packages/cli/test/__golden__/no-icon-set/search-icon.json
@@ -61,6 +61,21 @@
"command": "astryx hook useInputStatusIcon",
"mentions": []
},
+ {
+ "domain": "doc",
+ "name": "icons",
+ "package": "@astryxdesign/cli",
+ "score": "<text>",
+ "reason": "<text>",
+ "description": "<text>",
+ "section": "<text>",
+ "title": "<text>",
+ "command": "astryx docs icons theme-overrides",
+ "parent": "astryx docs icons --index",
+ "mentions": [
+ "This lets you swap the icon set (e.g."
+ ]
+ },
{
"domain": "template",
"name": "BaseTypeaheadCustomSearch",
@@ -228,18 +243,6 @@
"kind": "block",
"command": "astryx template ChatMessageBubbleMetadata --type block",
"mentions": []
- },
- {
- "domain": "template",
- "name": "ChatMessageMetadataFooter",
- "package": "@astryxdesign/core",
- "score": "<text>",
- "reason": "<text>",
- "description": "<text>",
- "displayName": "<text>",
- "kind": "block",
- "command": "astryx template ChatMessageMetadataFooter --type block",
- "mentions": []
}
]
},
diff --git a/packages/cli/test/__golden__/no-icon-set/search-icon.txt b/packages/cli/test/__golden__/no-icon-set/search-icon.txt
index 510f85d2b8..77f45f34fc 100644
--- a/packages/cli/test/__golden__/no-icon-set/search-icon.txt
+++ b/packages/cli/test/__golden__/no-icon-set/search-icon.txt
@@ -24,6 +24,12 @@ domain: hook
package: @astryxdesign/core
import: @astryxdesign/core/hooks
command: pnpm exec astryx hook useInputStatusIcon
+name: icons
+section: theme-overrides
+domain: doc
+package: @astryxdesign/cli
+command: pnpm exec astryx docs icons theme-overrides
+parent: pnpm exec astryx docs icons --index
name: BaseTypeaheadCustomSearch
domain: template
package: @astryxdesign/core
@@ -79,8 +85,4 @@ command: pnpm exec astryx template ChatComposerFullFeatured --type block
name: ChatMessageBubbleMetadata
domain: template
package: @astryxdesign/core
-command: pnpm exec astryx template ChatMessageBubbleMetadata --type block
-name: ChatMessageMetadataFooter
-domain: template
-package: @astryxdesign/core
-command: pnpm exec astryx template ChatMessageMetadataFooter --type block
\ No newline at end of file
+command: pnpm exec astryx template ChatMessageBubbleMetadata --type block
\ No newline at end of file
diff --git a/packages/core/src/Icon/Icon.doc.mjs b/packages/core/src/Icon/Icon.doc.mjs
index f579342caf..38f084e29f 100644
--- a/packages/core/src/Icon/Icon.doc.mjs
+++ b/packages/core/src/Icon/Icon.doc.mjs
@@ -120,6 +120,11 @@ export const docs = {
description:
"Override icons through the theme, not globally: defineTheme({icons: {close: <XMarkIcon />}}) scopes the swap to the active <Theme>, and extends shallow-merges it into derived themes. registerIcons() mutates a process-wide registry and warns in dev, so keep it for app bootstrap rather than making it a library's theming seam.",
},
+ {
+ guidance: true,
+ description:
+ "To match artwork to the rendered size, make a theme or registered icon entry a pure, synchronous function of {size, variant}: defineTheme({icons: {info: ({size}) => <InfoIcon weight={size === 'sm' ? 'bold' : 'regular'} />}}). Icon passes the size it renders at; getIcon(), useIcon(), getIconRegistry() and theme.icons read the function at size md. A function that returns null draws nothing instead of falling back to the default icon. Do not use hooks, measure the DOM, or read browser or mutable state inside it.",
+ },
{
guidance: true,
description:
@@ -282,6 +287,11 @@ export const docsDense = {
description:
'Override icons via theme, not globally: defineTheme({icons: {close: <XMarkIcon />}}) scopes the swap to the active <Theme>; extends shallow-merges into derived themes. registerIcons() mutates a global registry and warns in dev: app bootstrap only, not a library theming seam.',
},
+ {
+ guidance: true,
+ description:
+ "Size-aware artwork: a theme/registered entry may be a pure sync function of {size, variant}, e.g. info: ({size}) => <InfoIcon weight={size === 'sm' ? 'bold' : 'regular'} />. Icon passes its rendered size; getIcon/useIcon/getIconRegistry/theme.icons read it at md. A null result draws nothing (no fallback). No hooks, DOM measurement, or browser/mutable state.",
+ },
{
guidance: true,
description:
diff --git a/packages/core/src/Icon/Icon.test.tsx b/packages/core/src/Icon/Icon.test.tsx
index d08f9e512e..18e63e29fc 100644
--- a/packages/core/src/Icon/Icon.test.tsx
+++ b/packages/core/src/Icon/Icon.test.tsx
@@ -17,7 +17,12 @@ import {Theme} from '../theme/Theme';
import {defineTheme} from '../theme/defineTheme';
import {resetThemes} from '../theme/themeRegistry';
import {Icon} from './Icon';
-import {registerIcons, resetIcons} from './globalIconRegistry';
+import {IconDefaultSizeProvider} from './IconDefaultSizeContext';
+import {
+ registerIcons,
+ resetIcons,
+ type IconRequest,
+} from './globalIconRegistry';
describe('Icon', () => {
it('renders the icon component', () => {
@@ -198,6 +203,143 @@ describe('Icon', () => {
expect(screen.getByTestId('inner')).toHaveTextContent('inner-check');
});
+ // spec:AST-087 FR1, FR6, FR9 — a function registry entry receives the size
+ // resolved by component:Icon ORD1, and its result is final.
+ describe('function registry entries', () => {
+ const sized = (label: string) => (request: IconRequest) =>
+ `${label}-${request.size}`;
+
+ it('passes each explicit size to a theme function entry', () => {
+ resetIcons();
+ resetThemes();
+ const info = vi.fn(sized('theme-info'));
+ const theme = defineTheme({name: 'fn-sizes', icons: {info}});
+
+ render(
+ <Theme theme={theme}>
+ {(['xsm', 'sm', 'md', 'lg'] as const).map(size => (
+ <Icon key={size} icon="info" size={size} data-testid={size} />
+ ))}
+ </Theme>,
+ );
+
+ for (const size of ['xsm', 'sm', 'md', 'lg'] as const) {
+ const icon = screen.getByTestId(size);
+ expect(icon).toHaveTextContent(`theme-info-${size}`);
+ expect(icon).toHaveAttribute('data-size', size);
+ expect(info).toHaveBeenCalledWith({size});
+ }
+ });
+
+ it('passes the standalone md fallback when no size is set', () => {
+ resetIcons();
+ resetThemes();
+ const theme = defineTheme({
+ name: 'fn-standalone',
+ icons: {info: sized('theme-info')},
+ });
+
+ render(
+ <Theme theme={theme}>
+ <Icon icon="info" data-testid="icon" />
+ </Theme>,
+ );
+
+ expect(screen.getByTestId('icon')).toHaveTextContent('theme-info-md');
+ });
+
+ it('passes the owning component default, and an explicit size over it', () => {
+ resetIcons();
+ resetThemes();
+ const theme = defineTheme({
+ name: 'fn-contextual',
+ icons: {info: sized('theme-info')},
+ });
+
+ render(
+ <Theme theme={theme}>
+ <IconDefaultSizeProvider value="sm">
+ <Icon icon="info" data-testid="contextual" />
+ <Icon icon="info" size="lg" data-testid="explicit" />
+ </IconDefaultSizeProvider>
+ </Theme>,
+ );
+
+ expect(screen.getByTestId('contextual')).toHaveTextContent(
+ 'theme-info-sm',
+ );
+ expect(screen.getByTestId('explicit')).toHaveTextContent('theme-info-lg');
+ });
+
+ it('passes the resolved size to a process-wide function entry', () => {
+ resetIcons();
+ resetThemes();
+ registerIcons({info: sized('global-info')});
+
+ render(<Icon icon="info" size="xsm" data-testid="icon" />);
+
+ expect(screen.getByTestId('icon')).toHaveTextContent('global-info-xsm');
+ });
+
+ it('resolves function entries from the nearest Theme', () => {
+ resetIcons();
+ resetThemes();
+ const outer = defineTheme({
+ name: 'fn-outer',
+ icons: {info: sized('outer-info')},
+ });
+ const inner = defineTheme({
+ name: 'fn-inner',
+ icons: {info: sized('inner-info')},
+ });
+
+ render(
+ <Theme theme={outer}>
+ <Icon icon="info" size="sm" data-testid="outer" />
+ <Theme theme={inner}>
+ <Icon icon="info" size="lg" data-testid="inner" />
+ </Theme>
+ </Theme>,
+ );
+
+ expect(screen.getByTestId('outer')).toHaveTextContent('outer-info-sm');
+ expect(screen.getByTestId('inner')).toHaveTextContent('inner-info-lg');
+ });
+
+ it('renders no glyph when the selected function returns null', () => {
+ resetIcons();
+ resetThemes();
+ registerIcons({info: 'global-info'});
+ const theme = defineTheme({name: 'fn-null', icons: {info: () => null}});
+
+ const {container} = render(
+ <Theme theme={theme}>
+ <Icon icon="info" data-testid="icon" />
+ </Theme>,
+ );
+
+ expect(screen.queryByTestId('icon')).not.toBeInTheDocument();
+ expect(container.querySelector('.astryx-icon')).toBeNull();
+ });
+
+ it('renders a supplied icon component as given', () => {
+ resetIcons();
+ resetThemes();
+ const info = vi.fn(sized('theme-info'));
+ const theme = defineTheme({name: 'fn-direct', icons: {info}});
+ info.mockClear();
+
+ render(
+ <Theme theme={theme}>
+ <Icon icon={TestIcon} size="sm" data-testid="icon" />
+ </Theme>,
+ );
+
+ expect(screen.getByTestId('icon').tagName.toLowerCase()).toBe('svg');
+ expect(info).not.toHaveBeenCalled();
+ });
+ });
+
describe('namespaced extension keys', () => {
it('renders a theme-registered namespaced key with size and color applied', () => {
resetIcons();
diff --git a/packages/core/src/Icon/Icon.tsx b/packages/core/src/Icon/Icon.tsx
index ef1137c97d..c1228df1aa 100644
--- a/packages/core/src/Icon/Icon.tsx
+++ b/packages/core/src/Icon/Icon.tsx
@@ -13,6 +13,7 @@
* directly with and spread SVG props.
* - String mode: Pass a semantic name (e.g. 'close', 'chevronDown') — resolved from the
* theme's icon registry (or built-in fallback SVGs) and wrapped in a styled span.
+ * A function registry entry receives `{size}`, the size resolved by ORD1.
*
* SYNC: When modified, update these files to stay in sync:
* - /packages/core/src/Icon/Icon.doc.mjs (props table, features, implementation notes)
@@ -27,7 +28,7 @@ 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 {resolveIcon} from './globalIconRegistry';
import type {IconName, NamespacedIconName} from './globalIconRegistry';
import {mergeProps} from '../utils';
import {themeProps} from '../utils/themeProps';
@@ -315,8 +316,8 @@ Icon.displayName = 'Icon';
* Internal component that resolves a semantic icon name from the registry
* and renders it in a styled span with proper sizing.
*
- * Extracted as a separate component so getIcon is only called
- * when the icon prop is a string.
+ * Extracted as a separate component so the registry is only read when the
+ * icon prop is a string. A function entry receives the resolved size.
*/
function IconFromRegistry({
name,
@@ -338,7 +339,7 @@ function IconFromRegistry({
spanProps?: Omit<SVGProps<SVGSVGElement>, 'ref' | 'color'>;
}) {
const themeName = useThemeName();
- const resolvedIcon = getIcon(name, themeName);
+ const resolvedIcon = resolveIcon(name, themeName, {size});
if (resolvedIcon == null) {
return null;
diff --git a/packages/core/src/Icon/globalIconRegistry.test.tsx b/packages/core/src/Icon/globalIconRegistry.test.tsx
index 2a21710352..16ac5409be 100644
--- a/packages/core/src/Icon/globalIconRegistry.test.tsx
+++ b/packages/core/src/Icon/globalIconRegistry.test.tsx
@@ -1,8 +1,18 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
-import {render} from '@testing-library/react';
-import {defineTheme} from '../theme/defineTheme';
+import {
+ describe,
+ it,
+ expect,
+ expectTypeOf,
+ beforeEach,
+ afterEach,
+ vi,
+} from 'vitest';
+import type {ReactNode} from 'react';
+import {render, screen} from '@testing-library/react';
+import {Theme} from '../theme/Theme';
+import {defineTheme, type DefinedTheme} from '../theme/defineTheme';
import {resetThemes} from '../theme/themeRegistry';
import {__resetDevWarnings} from '../utils/devWarning';
import {defaultIcons} from './defaultIcons';
@@ -12,9 +22,14 @@ import {
getIcon,
getExtendedIcon,
resetIcons,
+ resolveIcon,
+ type IconEntry,
type IconRegistry,
+ type IconRequest,
} from './globalIconRegistry';
import {Icon} from './Icon';
+import type {IconSize} from './IconSize.stylex';
+import {useIcon} from './useIcon';
describe('iconRegistry (global, RSC-compatible)', () => {
beforeEach(() => {
@@ -218,4 +233,261 @@ describe('iconRegistry (global, RSC-compatible)', () => {
expect(getExtendedIcon('richtext:bold', 'fallback')).toBe('fallback');
});
});
+
+ // spec:AST-087 FR1, FR6, FR7, FR9, FR18 — an entry is a node or a pure
+ // function of the request; sources resolve before the request; public reads
+ // stay node-valued and read a function at {size: 'md'}.
+ describe('function entries', () => {
+ const sized = (label: string) => (request: IconRequest) =>
+ `${label}-${request.size}`;
+
+ it('calls a theme function entry with the requested size', () => {
+ const info = vi.fn(sized('theme-info'));
+ const theme = defineTheme({name: 'fn-theme', icons: {info}});
+
+ for (const size of ['xsm', 'sm', 'md', 'lg'] as const) {
+ expect(resolveIcon('info', theme, {size})).toBe(`theme-info-${size}`);
+ expect(info).toHaveBeenLastCalledWith({size});
+ }
+ });
+
+ it('calls a process-wide function entry with the requested size', () => {
+ const info = vi.fn(sized('global-info'));
+ registerIcons({info});
+
+ expect(resolveIcon('info', null, {size: 'lg'})).toBe('global-info-lg');
+ expect(info).toHaveBeenLastCalledWith({size: 'lg'});
+ });
+
+ it('resolves a function entry for a namespaced key', () => {
+ const theme = defineTheme({
+ name: 'fn-namespaced',
+ icons: {'numberInput:stepperDown': sized('stepper')},
+ });
+
+ expect(resolveIcon('numberInput:stepperDown', theme, {size: 'xsm'})).toBe(
+ 'stepper-xsm',
+ );
+ });
+
+ it('resolves through a registered theme name', () => {
+ defineTheme({name: 'fn-by-name', icons: {info: sized('named-info')}});
+
+ expect(resolveIcon('info', 'fn-by-name', {size: 'sm'})).toBe(
+ 'named-info-sm',
+ );
+ expect(getIcon('info', 'fn-by-name')).toBe('named-info-md');
+ });
+
+ describe('source precedence', () => {
+ it('prefers a theme entry over a process-wide registration and the default', () => {
+ const global = vi.fn(sized('global-info'));
+ registerIcons({info: global});
+ const theme = defineTheme({
+ name: 'fn-precedence',
+ icons: {info: sized('theme-info')},
+ });
+
+ expect(resolveIcon('info', theme, {size: 'sm'})).toBe('theme-info-sm');
+ expect(global).not.toHaveBeenCalled();
+ });
+
+ it('prefers a process-wide registration over the built-in default', () => {
+ registerIcons({info: sized('global-info')});
+
+ expect(resolveIcon('info', null, {size: 'sm'})).toBe('global-info-sm');
+ expect(getIcon('info')).toBe('global-info-md');
+ });
+
+ it('uses the built-in default when neither source has an entry', () => {
+ const theme = defineTheme({
+ name: 'fn-default',
+ icons: {close: sized('theme-close')},
+ });
+
+ expect(resolveIcon('info', theme, {size: 'sm'})).toBe(
+ defaultIcons.info,
+ );
+ });
+
+ it('lets a nullish static theme entry fall through to the next source', () => {
+ registerIcons({info: sized('global-info')});
+ const theme = defineTheme({
+ name: 'fn-nullish-static',
+ icons: {info: null, close: undefined},
+ });
+
+ expect(resolveIcon('info', theme, {size: 'sm'})).toBe('global-info-sm');
+ expect(resolveIcon('close', theme, {size: 'sm'})).toBe(
+ defaultIcons.close,
+ );
+ });
+
+ it('treats a selected function result as final, even when nullish', () => {
+ registerIcons({info: 'global-info', close: 'global-close'});
+ const theme = defineTheme({
+ name: 'fn-final',
+ icons: {info: () => null, close: () => undefined},
+ });
+
+ expect(resolveIcon('info', theme, {size: 'sm'})).toBeNull();
+ expect(resolveIcon('close', theme, {size: 'sm'})).toBeUndefined();
+ expect(getIcon('info', theme)).toBeNull();
+ expect(getIconRegistry(theme).info).toBeNull();
+ expect(getExtendedIcon('info', 'fallback', theme)).toBeNull();
+ });
+
+ it('treats a process-wide function result as final', () => {
+ registerIcons({info: () => null});
+
+ expect(resolveIcon('info', null, {size: 'sm'})).toBeNull();
+ expect(getIcon('info')).toBeNull();
+ expect(getExtendedIcon('info', 'fallback')).toBeNull();
+ });
+
+ it('returns a function result per request, never mixing sources', () => {
+ // The theme draws only `sm`; every other size draws nothing rather than
+ // borrowing the default's artwork.
+ const theme = defineTheme({
+ name: 'fn-partial',
+ icons: {info: ({size}) => (size === 'sm' ? 'theme-info-sm' : null)},
+ });
+
+ expect(resolveIcon('info', theme, {size: 'sm'})).toBe('theme-info-sm');
+ expect(resolveIcon('info', theme, {size: 'lg'})).toBeNull();
+ });
+ });
+
+ describe('extends', () => {
+ it('inherits a base function entry and keeps calling it per request', () => {
+ const base = defineTheme({
+ name: 'fn-base',
+ icons: {info: sized('base-info')},
+ });
+ const child = defineTheme({name: 'fn-child', extends: base});
+
+ expect(resolveIcon('info', child, {size: 'lg'})).toBe('base-info-lg');
+ expect(child.icons?.info).toBe('base-info-md');
+ });
+
+ it("replaces the inherited entry whole with the child's entry for the same key", () => {
+ const base = defineTheme({
+ name: 'fn-base-replace',
+ icons: {info: sized('base-info'), close: 'base-close'},
+ });
+ const child = defineTheme({
+ name: 'fn-child-replace',
+ extends: base,
+ icons: {info: 'child-info', close: sized('child-close')},
+ });
+
+ expect(resolveIcon('info', child, {size: 'lg'})).toBe('child-info');
+ expect(resolveIcon('close', child, {size: 'lg'})).toBe(
+ 'child-close-lg',
+ );
+ expect(child.icons).toEqual({
+ info: 'child-info',
+ close: 'child-close-md',
+ });
+ });
+ });
+
+ describe('public reads stay node-valued', () => {
+ it('getIcon reads a theme function entry at md', () => {
+ const info = vi.fn(sized('theme-info'));
+ const theme = defineTheme({name: 'fn-read', icons: {info}});
+ info.mockClear();
+
+ expect(getIcon('info', theme)).toBe('theme-info-md');
+ expect(info).toHaveBeenCalledWith({size: 'md'});
+ });
+
+ it('getIconRegistry reads every function entry at md', () => {
+ registerIcons({close: sized('global-close')});
+ const theme = defineTheme({
+ name: 'fn-snapshot',
+ icons: {info: sized('theme-info')},
+ });
+
+ const registry = getIconRegistry(theme);
+ expect(registry.info).toBe('theme-info-md');
+ expect(registry.close).toBe('global-close-md');
+ expect(registry.check).toBe(defaultIcons.check);
+ expect(
+ Object.values(registry).some(value => typeof value === 'function'),
+ ).toBe(false);
+ });
+
+ it('getExtendedIcon reads a function entry at md', () => {
+ registerIcons({'richtext:bold': sized('bold')});
+
+ expect(getExtendedIcon('richtext:bold', 'fallback')).toBe('bold-md');
+ });
+
+ it("DefinedTheme['icons'] holds the md node for a function entry", () => {
+ const theme = defineTheme({
+ name: 'fn-public-icons',
+ icons: {info: sized('theme-info'), close: 'theme-close'},
+ });
+
+ expect(theme.icons).toEqual({
+ info: 'theme-info-md',
+ close: 'theme-close',
+ });
+ });
+
+ it('useIcon reads a function entry at md from the nearest Theme', () => {
+ const theme = defineTheme({
+ name: 'fn-hook',
+ icons: {info: sized('theme-info')},
+ });
+ function Probe() {
+ return <span data-testid="probe">{useIcon('info')}</span>;
+ }
+
+ render(
+ <Theme theme={theme}>
+ <Probe />
+ </Theme>,
+ );
+
+ expect(screen.getByTestId('probe')).toHaveTextContent('theme-info-md');
+ });
+
+ it('keeps public read types node-valued while entries accept functions', () => {
+ expectTypeOf<IconRegistry['info']>().toEqualTypeOf<ReactNode>();
+ expectTypeOf(getIcon).returns.toEqualTypeOf<ReactNode>();
+ expectTypeOf(getIconRegistry).returns.toEqualTypeOf<
+ Readonly<Record<keyof IconRegistry, ReactNode>>
+ >();
+ expectTypeOf<
+ NonNullable<DefinedTheme['icons']>['info']
+ >().toEqualTypeOf<ReactNode>();
+ expectTypeOf<IconRequest>().toEqualTypeOf<
+ Readonly<{size: IconSize; variant?: undefined}>
+ >();
+ expectTypeOf<IconEntry>().toEqualTypeOf<
+ ReactNode | ((request: IconRequest) => ReactNode)
+ >();
+
+ defineTheme({
+ name: 'fn-types',
+ icons: {
+ info: ({size, variant}) => {
+ expectTypeOf(size).toEqualTypeOf<IconSize>();
+ expectTypeOf(variant).toEqualTypeOf<undefined>();
+ return null;
+ },
+ // @ts-expect-error — an entry returns artwork, not a props object.
+ close: () => ({weight: 'bold'}),
+ },
+ });
+ registerIcons({
+ info: ({size}) => `global-${size}`,
+ // @ts-expect-error — the request has no `name`.
+ close: ({name}) => String(name),
+ });
+ });
+ });
+ });
});
diff --git a/packages/core/src/Icon/globalIconRegistry.tsx b/packages/core/src/Icon/globalIconRegistry.tsx
index 55f9e8fce9..273661d375 100644
--- a/packages/core/src/Icon/globalIconRegistry.tsx
+++ b/packages/core/src/Icon/globalIconRegistry.tsx
@@ -2,16 +2,26 @@
/**
* @file globalIconRegistry.tsx
- * @input None (pure module-level state)
- * @output Exports registerIcons, getIconRegistry, getIcon, resetIcons, IconName, IconRegistry
+ * @input Theme icon entries (a DefinedTheme or a registered theme name), the
+ * process-wide registry, and built-in defaults
+ * @output Exports registerIcons, getIconRegistry, getIcon, getExtendedIcon,
+ * resetIcons, resolveIcon (internal), IconName, IconRegistry, IconEntry,
+ * IconRequest
* @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.
* Components resolve semantic icons through getIcon() or the client useIcon() hook.
+ *
+ * An entry is a React node or a pure synchronous function of an
+ * {@link IconRequest}. Resolution picks one source — theme entry, then
+ * process-wide registration, then built-in default; a nullish static entry
+ * falls through — and a selected function's result is final. `Icon` passes
+ * its resolved size; the public reads below pass `{size: 'md'}`.
*/
import type {ReactNode} from 'react';
import {defaultIcons} from './defaultIcons';
+import type {IconSize} from './IconSize.stylex';
import type {DefinedTheme} from '../theme/defineTheme';
import {getRegisteredTheme} from '../theme/themeRegistry';
import {warnOnce} from '../utils/devWarning';
@@ -88,13 +98,48 @@ export type ExtendedIconName = IconName | (string & {});
*/
export type IconRegistry = Record<IconName, ReactNode>;
+/**
+ * What `Icon` asks a function icon entry for: the final Icon size, resolved
+ * explicit `size` → owning component's default → `'md'`.
+ *
+ * `variant` is always `undefined` here.
+ */
+export type IconRequest = Readonly<{
+ size: IconSize;
+ variant?: undefined;
+}>;
+
+/**
+ * A theme or process-wide icon entry: a React node, or a pure synchronous
+ * function of the {@link IconRequest} that returns one.
+ *
+ * A function computes its result from the request only — no hooks, DOM or
+ * SVG measurement, browser globals, network access, mutable module state, or
+ * side effects. Once selected, its result is final: returning `null` or
+ * `undefined` renders no glyph instead of falling through to another source.
+ *
+ * @example
+ * ```
+ * defineTheme({
+ * name: 'brand',
+ * icons: {
+ * info: ({size}) => <InfoIcon weight={size === 'sm' ? 'bold' : 'regular'} />,
+ * },
+ * });
+ * ```
+ */
+export type IconEntry = ReactNode | ((request: IconRequest) => ReactNode);
+
export type IconRegistrySource = DefinedTheme | string | null | undefined;
+/** The request every public, one-argument read uses. */
+const PUBLIC_READ_REQUEST: IconRequest = {size: 'md'};
+
// =============================================================================
// Global Registry
// =============================================================================
-let globalRegistry: Record<string, ReactNode> = {};
+let globalRegistry: Record<string, IconEntry> = {};
/**
* A key is namespaced when it carries a `<namespace>:` prefix — the runtime
@@ -106,18 +151,57 @@ function isNamespacedKey(name: string): boolean {
return name.includes(':');
}
-function getThemeIconOverrides(
+/**
+ * The theme's icon entries, functions included. A theme from `defineTheme`
+ * keeps them in `__icons` when any entry is a function (its public `icons`
+ * is the node view); otherwise `icons` already holds them.
+ */
+function getThemeIconEntries(
source: IconRegistrySource,
-): Partial<Record<IconName | NamespacedIconName, ReactNode>> | null {
- if (source == null) {
+): Readonly<Record<string, IconEntry>> | null {
+ const theme =
+ typeof source === 'string' ? getRegisteredTheme(source) : source;
+ if (theme == null) {
return null;
}
+ return theme.__icons ?? theme.icons ?? null;
+}
- if (typeof source === 'string') {
- return getRegisteredTheme(source)?.icons ?? null;
- }
+/**
+ * Pick the one source that answers `name`: the theme entry, then the
+ * process-wide registration, then the built-in default, then `fallback`. A
+ * nullish static entry falls through; a function is returned as-is, because
+ * its result is final.
+ */
+function selectIconEntry(
+ name: string,
+ source: IconRegistrySource,
+ fallback?: ReactNode,
+): IconEntry {
+ return (
+ getThemeIconEntries(source)?.[name] ??
+ globalRegistry[name] ??
+ defaultIcons[name as IconName] ??
+ fallback
+ );
+}
- return source.icons ?? null;
+/** Read an entry for a request: call a function, return a node as-is. */
+function readIconEntry(entry: IconEntry, request: IconRequest): ReactNode {
+ return typeof entry === 'function' ? entry(request) : entry;
+}
+
+/**
+ * Resolve a key for an Icon request. `Icon` is the caller: it passes the size
+ * it resolved. Public reads use {@link getIcon} instead.
+ * @internal
+ */
+export function resolveIcon(
+ name: ExtendedIconName,
+ source: IconRegistrySource,
+ request: IconRequest,
+): ReactNode {
+ return readIconEntry(selectIconEntry(name, source), request);
}
/**
@@ -142,9 +226,16 @@ function getThemeIconOverrides(
* ```
* registerIcons({ 'richtext:bold': <MyBoldIcon /> });
* ```
+ *
+ * An entry may also be a pure synchronous function of `{size, variant}`
+ * ({@link IconEntry}); `Icon` passes it the size it renders at.
+ * @example
+ * ```
+ * registerIcons({ info: ({size}) => <InfoIcon weight={size === 'sm' ? 'bold' : 'regular'} /> });
+ * ```
*/
export function registerIcons(
- icons: Partial<Record<ExtendedIconName, ReactNode>>,
+ icons: Partial<Record<ExtendedIconName, IconEntry>>,
): void {
warnOnce(
'icon-registry:global-register-icons',
@@ -161,6 +252,9 @@ export function registerIcons(
* Works in both server and client environments. Useful for tooling that needs
* to derive valid semantic icon-name options from the same registry Icon
* resolves against.
+ *
+ * Every value is a React node: a function entry is read at `{size: 'md'}`,
+ * exactly as {@link getIcon} reads it.
*/
export function getIconRegistry(
source?: IconRegistrySource,
@@ -171,21 +265,18 @@ export function getIconRegistry(
// contributed by a library or shipped as a component's own default, are
// resolved via getIcon/getExtendedIcon and intentionally kept out of the
// typed IconRegistry snapshot.
- for (const name of Object.keys(defaultIcons) as IconName[]) {
+ const names = new Set(Object.keys(defaultIcons));
+ for (const name of Object.keys(getThemeIconEntries(source) ?? {})) {
+ names.add(name);
+ }
+ for (const name of names) {
if (isNamespacedKey(name)) {
continue;
}
- registry[name] = globalRegistry[name] ?? defaultIcons[name];
- }
-
- const themeIcons = getThemeIconOverrides(source);
- if (themeIcons != null) {
- for (const name of Object.keys(themeIcons) as IconName[]) {
- if (isNamespacedKey(name)) {
- continue;
- }
- registry[name] = themeIcons[name] ?? registry[name];
- }
+ registry[name] = readIconEntry(
+ selectIconEntry(name, source),
+ PUBLIC_READ_REQUEST,
+ );
}
return registry as Record<IconName, ReactNode>;
@@ -201,17 +292,15 @@ export function getIconRegistry(
* {@link IconName}s — useful for library-contributed icons. For a
* caller-supplied fallback when a key isn't registered, use
* {@link getExtendedIcon}.
+ *
+ * Returns a React node: a function entry is read at `{size: 'md'}`. Render
+ * `<Icon icon={name} />` to request another size.
*/
export function getIcon(
name: ExtendedIconName,
source?: IconRegistrySource,
): ReactNode {
- const themeIcons = getThemeIconOverrides(source);
- return (
- themeIcons?.[name as IconName] ??
- globalRegistry[name] ??
- defaultIcons[name as IconName]
- );
+ return readIconEntry(selectIconEntry(name, source), PUBLIC_READ_REQUEST);
}
/**
@@ -224,7 +313,9 @@ export function getIcon(
* widen the core {@link IconName} union.
*
* The `fallback` is the library default, overridable by a theme registering the
- * same key (for example `'richtext:bold'`).
+ * same key (for example `'richtext:bold'`). A function entry is read at
+ * `{size: 'md'}`, and its result is final: a nullish result does not fall
+ * back.
* @example
* ```
* getExtendedIcon('richtext:bold', <BoldGlyph />)
@@ -235,12 +326,9 @@ export function getExtendedIcon(
fallback?: ReactNode,
source?: IconRegistrySource,
): ReactNode {
- const themeIcons = getThemeIconOverrides(source);
- return (
- themeIcons?.[name as IconName] ??
- globalRegistry[name] ??
- defaultIcons[name as IconName] ??
- fallback
+ return readIconEntry(
+ selectIconEntry(name, source, fallback),
+ PUBLIC_READ_REQUEST,
);
}
diff --git a/packages/core/src/Icon/index.ts b/packages/core/src/Icon/index.ts
index cb63bdaafd..0059ce36c8 100644
--- a/packages/core/src/Icon/index.ts
+++ b/packages/core/src/Icon/index.ts
@@ -5,7 +5,8 @@
/**
* @file index.ts
* @input Imports Icon component/types, icon registry, and global registration
- * @output Exports Icon, icon registry helpers, registerIcons, getIconRegistry, getIcon
+ * @output Exports Icon, icon registry helpers, registerIcons, getIconRegistry, getIcon,
+ * and the IconEntry/IconRequest types for theme and registered entries
* @position Component entry point; re-exported by /packages/core/src/index.ts
*
* SYNC: When modified, update this header and /packages/core/src/Icon/Icon.doc.mjs
@@ -29,4 +30,6 @@ export type {
NamespacedIconName,
IconRegistry,
IconRegistrySource,
+ IconEntry,
+ IconRequest,
} from './globalIconRegistry';
diff --git a/packages/core/src/Icon/useIcon.ts b/packages/core/src/Icon/useIcon.ts
index 8993ebd566..668dde032c 100644
--- a/packages/core/src/Icon/useIcon.ts
+++ b/packages/core/src/Icon/useIcon.ts
@@ -5,7 +5,8 @@
/**
* @file useIcon.ts
* @input Semantic icon name
- * @output Exports useIcon hook for theme-aware icon lookup
+ * @output Exports useIcon hook for theme-aware icon lookup (node-valued; a
+ * function entry is read at `{size: 'md'}`)
* @position Client hook for components that render registry icons directly
*/
@@ -23,6 +24,9 @@ import {
*
* Accepts a namespaced extension key (`'richtext:bold'`) as well as a built-in
* name; both resolve through the same registry.
+ *
+ * Returns a React node: a function entry is read at `{size: 'md'}`. Render
+ * `<Icon icon={name} />` to resolve the entry at another size.
*/
export function useIcon(name: IconName | NamespacedIconName): ReactNode {
const themeName = useThemeName();
diff --git a/packages/core/src/theme/defineTheme.test.ts b/packages/core/src/theme/defineTheme.test.ts
index 015ce2cfc1..b59751f38e 100644
--- a/packages/core/src/theme/defineTheme.test.ts
+++ b/packages/core/src/theme/defineTheme.test.ts
@@ -498,6 +498,18 @@ describe('defineTheme', () => {
expect(theme.icons).toBe(icons);
});
+ it('reads function icon entries at md in the public icons view', () => {
+ const info = vi.fn(({size}: {size: string}) => `info-${size}`);
+ const theme = defineTheme({
+ name: 'fn-icons',
+ icons: {info, close: 'X', menu: null},
+ });
+
+ expect(theme.icons).toEqual({info: 'info-md', close: 'X', menu: null});
+ expect(info).toHaveBeenCalledTimes(1);
+ expect(info).toHaveBeenCalledWith({size: 'md'});
+ });
+
it('works with no tokens', () => {
const theme = defineTheme({name: 'bare'});
expect(Object.keys(theme.tokens)).toHaveLength(0);
@@ -1656,6 +1668,23 @@ describe('defineTheme extends', () => {
expect(child.icons?.close).toBe('X');
});
+ it('merges function icon entries by key and reads them at md', () => {
+ const base = defineTheme({
+ name: 'base',
+ icons: {close: ({size}) => `base-close-${size}`, menu: 'M'},
+ });
+ const child = defineTheme({
+ name: 'child',
+ extends: base,
+ icons: {menu: ({size}) => `child-menu-${size}`},
+ });
+
+ expect(child.icons).toEqual({
+ close: 'base-close-md',
+ menu: 'child-menu-md',
+ });
+ });
+
it('uses child name, not base name', () => {
const base = defineTheme({name: 'base'});
const child = defineTheme({name: 'my-brand', extends: base});
diff --git a/packages/core/src/theme/defineTheme.ts b/packages/core/src/theme/defineTheme.ts
index dd28d50900..fc1fbafa17 100644
--- a/packages/core/src/theme/defineTheme.ts
+++ b/packages/core/src/theme/defineTheme.ts
@@ -40,12 +40,22 @@
*/
import type {ReactNode} from 'react';
-import type {IconName, NamespacedIconName} from '../Icon/globalIconRegistry';
+import type {
+ IconEntry,
+ IconName,
+ NamespacedIconName,
+} from '../Icon/globalIconRegistry';
/**
* Icon overrides a theme may declare: any built-in semantic name, plus the
- * namespaced keys components and libraries own (`'richtext:bold'`).
+ * namespaced keys components and libraries own (`'richtext:bold'`). Each entry
+ * is a React node or a pure synchronous function of `{size, variant}`.
*/
+type ThemeIconEntries = Partial<
+ Record<IconName | NamespacedIconName, IconEntry>
+>;
+
+/** The node-valued view of a theme's icons that public reads return. */
type ThemeIconOverrides = Partial<
Record<IconName | NamespacedIconName, ReactNode>
>;
@@ -338,8 +348,26 @@ export interface DefineThemeInput {
* ```
*/
components?: ComponentStyleMap;
- /** Icon registry — maps semantic icon names to React nodes */
- icons?: ThemeIconOverrides;
+ /**
+ * Icon registry — maps semantic icon names and namespaced keys to artwork.
+ *
+ * An entry is a React node, or a pure synchronous function of
+ * `{size, variant}` that returns one. `Icon` passes the size it renders at
+ * (`'xsm' | 'sm' | 'md' | 'lg'`), so the theme can map it to its icon
+ * library's own props. A function must not use hooks, measure the DOM, read
+ * browser globals or mutable state, or have side effects. Its result is
+ * final: returning `null` draws nothing instead of falling back to a
+ * registered or built-in icon. A `null` or `undefined` node entry falls back.
+ *
+ * @example
+ * ```
+ * icons: {
+ * close: <XMarkIcon />,
+ * info: ({size}) => <InfoIcon weight={size === 'sm' ? 'bold' : 'regular'} />,
+ * }
+ * ```
+ */
+ icons?: ThemeIconEntries;
/**
* Indicator overrides — replaces the components that draw stateful control
* visuals with the theme's own, by name.
@@ -429,8 +457,17 @@ export interface DefinedTheme {
localTokens?: Record<string, string>;
/** Component style overrides */
components?: ComponentStyleMap;
- /** Icon registry */
+ /**
+ * Icon registry as React nodes. A function entry is read at
+ * `{size: 'md'}`; `Icon` resolves the entry at the size it renders.
+ */
icons?: ThemeIconOverrides;
+ /**
+ * Icon entries with their functions, present when any entry is a function.
+ * Only Astryx icon resolution reads it.
+ * @internal
+ */
+ __icons?: ThemeIconEntries;
/** Indicator overrides for stateful control visuals, keyed by name */
indicators?: IndicatorRegistry;
/** Whether this theme has been pre-compiled by theme build CLI */
@@ -601,11 +638,14 @@ export function defineTheme(input: DefineThemeInput): ResolvedDefinedTheme {
components,
);
- // Icons — input icons override base icons
- const icons =
- input.icons && base?.icons
- ? {...base.icons, ...input.icons}
- : (input.icons ?? base?.icons);
+ // Icons — input entries override base entries by key. The base's entries
+ // include its function entries, which its node-valued `icons` does not.
+ const baseIcons = base?.__icons ?? base?.icons;
+ const iconEntries =
+ input.icons && baseIcons
+ ? {...baseIcons, ...input.icons}
+ : (input.icons ?? baseIcons);
+ const icons = readThemeIconNodes(iconEntries);
// Indicator overrides merge by name, like icons: a child theme replacing one
// indicator keeps the ones its base replaced.
@@ -626,6 +666,7 @@ export function defineTheme(input: DefineThemeInput): ResolvedDefinedTheme {
: {}),
components,
icons,
+ ...(icons !== iconEntries ? {__icons: iconEntries} : {}),
indicators,
__inputTokens:
base?.__inputTokens || input.tokens
@@ -642,6 +683,26 @@ export function defineTheme(input: DefineThemeInput): ResolvedDefinedTheme {
return theme;
}
+/**
+ * The node-valued view of a theme's icon entries: each function entry read at
+ * `{size: 'md'}`. Entries without a function are returned as the same object.
+ */
+function readThemeIconNodes(
+ entries: ThemeIconEntries | undefined,
+): ThemeIconOverrides | undefined {
+ if (
+ entries == null ||
+ !Object.values(entries).some(entry => typeof entry === 'function')
+ ) {
+ return entries as ThemeIconOverrides | undefined;
+ }
+ const nodes: Record<string, ReactNode> = {};
+ for (const [name, entry] of Object.entries(entries)) {
+ nodes[name] = typeof entry === 'function' ? entry({size: 'md'}) : entry;
+ }
+ return nodes as ThemeIconOverrides;
+}
+
// =============================================================================
// CSS generation — re-exported from ./generateThemeRules.ts
// =============================================================================
diff --git a/packages/lab/src/Comments/icons.test.tsx b/packages/lab/src/Comments/icons.test.tsx
new file mode 100644
index 0000000000..67ad744e61
--- /dev/null
+++ b/packages/lab/src/Comments/icons.test.tsx
@@ -0,0 +1,76 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file icons.test.tsx
+ * @input Uses vitest, @testing-library/react, Theme, defineTheme, CommentIcon
+ * @output Tests which source draws a Comments glyph
+ * @position Testing; validates icons.tsx
+ */
+
+import {afterEach, describe, expect, it} from 'vitest';
+import {render, screen} from '@testing-library/react';
+import {resetIcons} from '@astryxdesign/core/Icon';
+import {defineTheme, Theme} from '@astryxdesign/core/theme';
+import {CommentIcon} from './icons';
+
+describe('CommentIcon', () => {
+ afterEach(() => {
+ resetIcons();
+ });
+
+ it('draws the bundled glyph when no theme entry answers the key', () => {
+ const {container} = render(<CommentIcon name="reply" />);
+
+ expect(container.querySelector('svg')).not.toBeNull();
+ });
+
+ it("draws a theme's node entry for the key", () => {
+ const theme = defineTheme({
+ name: 'comment-icons-node',
+ icons: {'comment:reply': <span data-testid="themed">reply</span>},
+ });
+
+ render(
+ <Theme theme={theme}>
+ <CommentIcon name="reply" />
+ </Theme>,
+ );
+
+ expect(screen.getByTestId('themed')).toBeInTheDocument();
+ });
+
+ it("calls a theme's function entry at the glyph's size", () => {
+ const theme = defineTheme({
+ name: 'comment-icons-function',
+ icons: {
+ 'comment:reply': ({size}) => <span data-testid="themed">{size}</span>,
+ },
+ });
+
+ render(
+ <Theme theme={theme}>
+ <CommentIcon name="reply" size="xsm" />
+ </Theme>,
+ );
+
+ expect(screen.getByTestId('themed')).toHaveTextContent('xsm');
+ });
+
+ it('draws nothing when the selected function entry returns null', () => {
+ // spec:AST-087 FR6: a selected function's result is final, so the bundled
+ // glyph does not stand in for it.
+ const theme = defineTheme({
+ name: 'comment-icons-null',
+ icons: {'comment:reply': () => null},
+ });
+
+ const {container} = render(
+ <Theme theme={theme}>
+ <CommentIcon name="reply" />
+ </Theme>,
+ );
+
+ expect(container.querySelector('svg')).toBeNull();
+ expect(container.querySelector('.astryx-icon')).toBeNull();
+ });
+});
diff --git a/packages/lab/src/Comments/icons.tsx b/packages/lab/src/Comments/icons.tsx
index 7fad42ee94..58b94bba8b 100644
--- a/packages/lab/src/Comments/icons.tsx
+++ b/packages/lab/src/Comments/icons.tsx
@@ -13,7 +13,7 @@
* defineTheme({icons: {'comment:reply': <MyReplyIcon />}})
*/
-import type {SVGProps} from 'react';
+import type {ReactNode, SVGProps} from 'react';
import {getExtendedIcon, Icon, type IconColor} from '@astryxdesign/core/Icon';
import {useThemeName} from '@astryxdesign/core/theme';
@@ -105,6 +105,13 @@ const FALLBACK_GLYPHS: Record<
]),
};
+/**
+ * The fallback `getExtendedIcon` returns only when no theme, registered, or
+ * built-in entry answers a key. A function entry that returns `null` still
+ * answers it: its result is final, so the glyph draws nothing.
+ */
+const NO_ENTRY: ReactNode = <></>;
+
/**
* A comment glyph at the icon slot's size: the active theme's icon for its
* `comment:*` key when one is registered, else the bundled default.
@@ -120,7 +127,7 @@ export function CommentIcon({
}) {
const themeName = useThemeName();
const key = COMMENT_ICON_KEYS[name];
- const hasOverride = getExtendedIcon(key, undefined, themeName) != null;
+ const hasOverride = getExtendedIcon(key, NO_ENTRY, themeName) !== NO_ENTRY;
const fallback =
name in REGISTRY_FALLBACKS
? REGISTRY_FALLBACKS[name as keyof typeof REGISTRY_FALLBACKS]