Skip to content

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

TypeScript

feat(Icon): a theme maps a component's own icon role by slot, starting with CodeBlock's copy button (#9828)

Xinzi Zhou98efdf1839c9
diff --git a/.changeset/component-icon-slots-code-block-copy.md b/.changeset/component-icon-slots-code-block-copy.md
new file mode 100644
index 0000000000..e5adbfde34
--- /dev/null
+++ b/.changeset/component-icon-slots-code-block-copy.md
@@ -0,0 +1,8 @@
+---
+'@astryxdesign/core': patch
+'@astryxdesign/cli': patch
+---
+
+[feat] A theme chooses which shared icon a component's own icon role uses, by slot, with `defineTheme({componentIcons})`. The first slot is `code-block-copy`: CodeBlock's copy button passes `{copied}` and, with no theme entry, draws `copy`, then `check` while copied. A slot value is a shared icon name, `null` to hide the icon, a partial `{icon, variant, size}` request, or a pure function of the slot's state that returns one; a field the request leaves out keeps the component's own value. For the copy button, `null` hides only the glyph. `theme.componentIcons` reads back the static values. `ComponentIconSlotMap` and the slot value types are exported from `@astryxdesign/core/Icon`. `astryx theme build` carries static slot values into built themes and fails on a slot function, and `astryx component` lists a component's slots.
+
+@imdreamrunner
diff --git a/apps/docsite/scripts/generate-data.mjs b/apps/docsite/scripts/generate-data.mjs
index 41bdd2d265..7efec30c25 100644
--- a/apps/docsite/scripts/generate-data.mjs
+++ b/apps/docsite/scripts/generate-data.mjs
@@ -1191,11 +1191,26 @@ export interface DerivedVar {
replaces?: boolean;
}
+export interface ComponentIconSlotState {
+ name: string;
+ type: string;
+ description: string;
+}
+
+export interface ComponentIconSlot {
+ slot: string;
+ description: string;
+ fallback: string;
+ state?: ComponentIconSlotState[];
+ whenNull: string;
+}
+
export interface ThemingDoc {
container?: boolean;
targets: ThemingTarget[];
vars?: ComponentVar[];
derived?: DerivedVar[];
+ componentIcons?: ComponentIconSlot[];
}
export interface HookParamDoc {
@@ -1638,9 +1653,15 @@ async function generateBlockRegistry() {
package: entry.package,
cwd: DOCSITE_ROOT,
});
- const dirName = `${entry.package}-${entry.id}`.replace(/[^a-zA-Z0-9_-]/g, '-');
+ const dirName = `${entry.package}-${entry.id}`.replace(
+ /[^a-zA-Z0-9_-]/g,
+ '-',
+ );
const authored = discovered.find(
- t => t.type === 'block' && t.dirName === entry.id && pkgOf(t) === entry.package,
+ t =>
+ t.type === 'block' &&
+ t.dirName === entry.id &&
+ pkgOf(t) === entry.package,
);
if (!authored) throw new Error(`No authored file for ${dirName}`);
integrationBlockFiles.set(dirName, authored.filePath);
diff --git a/apps/docsite/scripts/lib/theming-doc.mjs b/apps/docsite/scripts/lib/theming-doc.mjs
index ee2fc77e45..8fb49681bc 100644
--- a/apps/docsite/scripts/lib/theming-doc.mjs
+++ b/apps/docsite/scripts/lib/theming-doc.mjs
@@ -28,8 +28,26 @@ export const COMPONENT_VAR_FIELDS = [
/** Fields of the emitted `DerivedVar` interface. */
export const DERIVED_VAR_FIELDS = ['property', 'vars', 'expand', 'replaces'];
+/** Fields of the emitted `ComponentIconSlot` interface. */
+export const COMPONENT_ICON_SLOT_FIELDS = [
+ 'slot',
+ 'description',
+ 'fallback',
+ 'state',
+ 'whenNull',
+];
+
+/** Fields of the emitted `ComponentIconSlotState` interface. */
+export const COMPONENT_ICON_SLOT_STATE_FIELDS = ['name', 'type', 'description'];
+
/** Fields of the emitted `ThemingDoc` interface. */
-export const THEMING_DOC_FIELDS = ['container', 'targets', 'vars', 'derived'];
+export const THEMING_DOC_FIELDS = [
+ 'container',
+ 'targets',
+ 'vars',
+ 'derived',
+ 'componentIcons',
+];
/**
* @template {Record<string, unknown>} T
@@ -105,5 +123,25 @@ export function projectThemingDoc(theming) {
: entry,
);
}
+ if (Array.isArray(out.componentIcons)) {
+ out.componentIcons = out.componentIcons.map(entry => {
+ if (entry == null || typeof entry !== 'object') return entry;
+ const slot = pick(
+ /** @type {Record<string, unknown>} */ (entry),
+ COMPONENT_ICON_SLOT_FIELDS,
+ );
+ if (Array.isArray(slot.state)) {
+ slot.state = slot.state.map(field =>
+ field != null && typeof field === 'object'
+ ? pick(
+ /** @type {Record<string, unknown>} */ (field),
+ COMPONENT_ICON_SLOT_STATE_FIELDS,
+ )
+ : field,
+ );
+ }
+ return slot;
+ });
+ }
return out;
}
diff --git a/apps/docsite/src/__tests__/theming-doc-projection.test.ts b/apps/docsite/src/__tests__/theming-doc-projection.test.ts
index 77fd001cee..d5a825f5e5 100644
--- a/apps/docsite/src/__tests__/theming-doc-projection.test.ts
+++ b/apps/docsite/src/__tests__/theming-doc-projection.test.ts
@@ -4,6 +4,8 @@ import fs from 'node:fs';
import path from 'node:path';
import {describe, expect, it} from 'vitest';
import {
+ COMPONENT_ICON_SLOT_FIELDS,
+ COMPONENT_ICON_SLOT_STATE_FIELDS,
COMPONENT_VAR_FIELDS,
DERIVED_VAR_FIELDS,
THEMING_DOC_FIELDS,
@@ -19,7 +21,9 @@ function emittedInterfaceFields(name: string): string[] {
const match = new RegExp(
`export interface ${name} \\{([\\s\\S]*?)\\n\\}`,
).exec(source);
- if (!match) {throw new Error(`generate-data.mjs emits no interface ${name}`);}
+ if (!match) {
+ throw new Error(`generate-data.mjs emits no interface ${name}`);
+ }
return [...match[1].matchAll(/^\s{2}([A-Za-z]+)\??:/gm)].map(m => m[1]);
}
@@ -32,6 +36,8 @@ describe('generated theming docs typecheck against the emitted interfaces', () =
['ThemingTarget', THEMING_TARGET_FIELDS],
['ComponentVar', COMPONENT_VAR_FIELDS],
['DerivedVar', DERIVED_VAR_FIELDS],
+ ['ComponentIconSlot', COMPONENT_ICON_SLOT_FIELDS],
+ ['ComponentIconSlotState', COMPONENT_ICON_SLOT_STATE_FIELDS],
['ThemingDoc', THEMING_DOC_FIELDS],
])('%s: the projection keeps exactly the emitted fields', (name, fields) => {
expect([...fields].sort()).toEqual(emittedInterfaceFields(name).sort());
@@ -57,6 +63,18 @@ describe('generated theming docs typecheck against the emitted interfaces', () =
},
],
derived: [{property: 'padding', vars: ['--p'], note: 'legacy'}],
+ componentIcons: [
+ {
+ slot: 'button-icon',
+ description: 'Icon',
+ fallback: 'none',
+ whenNull: 'Hides it.',
+ since: '0.8',
+ state: [
+ {name: 'busy', type: 'boolean', description: 'Busy', note: 'x'},
+ ],
+ },
+ ],
legacyTargets: [],
};
expect(projectThemingDoc(published)).toEqual({
@@ -66,6 +84,15 @@ describe('generated theming docs typecheck against the emitted interfaces', () =
],
vars: [{name: '--button-gap', description: 'Gap', default: '4px'}],
derived: [{property: 'padding', vars: ['--p']}],
+ componentIcons: [
+ {
+ slot: 'button-icon',
+ description: 'Icon',
+ fallback: 'none',
+ whenNull: 'Hides it.',
+ state: [{name: 'busy', type: 'boolean', description: 'Busy'}],
+ },
+ ],
});
});
@@ -83,6 +110,15 @@ describe('generated theming docs typecheck against the emitted interfaces', () =
},
],
derived: [{property: 'padding', expand: 'container', replaces: true}],
+ componentIcons: [
+ {
+ slot: 'card-dismiss',
+ description: 'Dismiss',
+ fallback: '`close`',
+ state: [{name: 'open', type: 'boolean', description: 'Open'}],
+ whenNull: 'Hides the glyph.',
+ },
+ ],
};
expect(projectThemingDoc(current)).toEqual(current);
expect(projectThemingDoc(null)).toBeNull();
diff --git a/packages/cli/api/theme/build/build.component-icons.test.mjs b/packages/cli/api/theme/build/build.component-icons.test.mjs
new file mode 100644
index 0000000000..ae7c5f9cc9
--- /dev/null
+++ b/packages/cli/api/theme/build/build.component-icons.test.mjs
@@ -0,0 +1,236 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Built themes carry static component icon slots and resolve them as
+ * runtime.
+ * @input Real themeBuild and themeBuildFamily calls on source themes whose
+ * `componentIcons` hold names, `null`, and requests, and on a theme with a
+ * slot function.
+ * @output Native ESM loads that resolve each slot under the built and the
+ * runtime theme and read the `componentIcons` view; a rejected build.
+ * @position Theme build parity for component icon slots. The node project's
+ * global setup supplies the compiled core package.
+ */
+
+import {afterEach, beforeEach, describe, expect, it} from 'vitest';
+import {execFileSync} from 'node:child_process';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {themeBuild, themeBuildFamily} from './build.mjs';
+
+let tmpDir;
+beforeEach(() => {
+ // Under the CLI package, so core and React resolve both in the theme loader
+ // and in the native artifact checks.
+ tmpDir = fs.mkdtempSync(
+ path.resolve(import.meta.dirname, '../../..', '.tmp-component-icons-'),
+ );
+});
+afterEach(() => {
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+/** @param {string} file @param {string} source */
+function write(file, source) {
+ fs.mkdirSync(path.dirname(path.join(tmpDir, file)), {recursive: true});
+ fs.writeFileSync(path.join(tmpDir, file), source);
+}
+
+/** @param {string} file */
+async function buildAndCheck(file) {
+ const built = await themeBuild(file, {}, {cwd: tmpDir});
+ expect(built?.type).toBe('theme.build');
+ const checked = await themeBuild(file, {check: true}, {cwd: tmpDir});
+ expect(checked?.data.upToDate).toBe(true);
+}
+
+const SLOTS = ['code-block-copy', 'parity-panel-dismiss', 'parity-tab-close'];
+
+/**
+ * Load built and runtime themes with native Node and report, for each pair,
+ * how each slot resolves for the copy button's states and what
+ * `componentIcons` reads back.
+ *
+ * @param {Array<{label: string, built: string, runtime: string}>} pairs -
+ * Module specifiers with `#export` suffixes, relative to the fixture root.
+ */
+function inspect(pairs) {
+ const load = specifier => {
+ const [file, name] = specifier.split('#');
+ return `(await import(${JSON.stringify(file)}))[${JSON.stringify(name)}]`;
+ };
+ const output = execFileSync(
+ process.execPath,
+ [
+ '--input-type=module',
+ '--eval',
+ `const {resolveComponentIcon} = await import(
+ import.meta.resolve('@astryxdesign/core/Icon').replace(/index\\.js$/, 'globalIconRegistry.js')
+);
+const describe = theme => ({
+ resolved: Object.fromEntries(
+ ${JSON.stringify(SLOTS)}.flatMap(slot =>
+ [false, true].map(copied => [
+ slot + '|' + copied,
+ resolveComponentIcon(slot, {copied}, {icon: copied ? 'check' : 'copy', size: 'sm'}, theme),
+ ]),
+ ),
+ ),
+ componentIcons: theme.componentIcons ?? null,
+});
+const result = {};
+${pairs
+ .map(
+ ({label, built, runtime}) => `{
+ const built = ${load(built)};
+ const runtime = ${load(runtime)};
+ result[${JSON.stringify(label)}] = {built: describe(built), runtime: describe(runtime)};
+}`,
+ )
+ .join('\n')}
+process.stdout.write(JSON.stringify(result));`,
+ ],
+ {cwd: tmpDir, encoding: 'utf8', timeout: 60000},
+ );
+ return JSON.parse(output);
+}
+
+function writeLineage() {
+ write(
+ 'base/source.mjs',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+export const baseTheme = defineTheme({
+ name: 'slots-base', tokens: {},
+ componentIcons: {'code-block-copy': 'clock', 'parity-panel-dismiss': {icon: 'close', size: 'sm'}},
+});
+export default baseTheme;
+`,
+ );
+ write(
+ 'child/source.mjs',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {baseTheme} from '../base/source.mjs';
+export const childTheme = defineTheme({
+ name: 'slots-child', extends: baseTheme, tokens: {},
+ componentIcons: {'parity-panel-dismiss': null, 'parity-tab-close': {size: 'xsm'}, 'code-block-copy': undefined},
+});
+export default childTheme;
+`,
+ );
+}
+
+describe('built themes keep static component icon slots', () => {
+ it('resolve every slot as the runtime theme does, through a built base', async () => {
+ writeLineage();
+ await buildAndCheck('base/source.mjs');
+ // A child extends the BUILT base module.
+ write(
+ 'built-child/source.mjs',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {slotsBaseTheme} from '../base/slots-base.js';
+export default defineTheme({
+ name: 'slots-built-child', extends: slotsBaseTheme, tokens: {},
+ componentIcons: {'parity-tab-close': 'menu'},
+});
+`,
+ );
+ await buildAndCheck('child/source.mjs');
+ await buildAndCheck('built-child/source.mjs');
+
+ const module = fs.readFileSync(
+ path.join(tmpDir, 'base/slots-base.js'),
+ 'utf8',
+ );
+ expect(module).not.toMatch(/^import /m);
+
+ const result = inspect([
+ {
+ label: 'base',
+ built: './base/slots-base.js#slotsBaseTheme',
+ runtime: './base/source.mjs#default',
+ },
+ {
+ label: 'child',
+ built: './child/slots-child.js#slotsChildTheme',
+ runtime: './child/source.mjs#default',
+ },
+ {
+ label: 'builtChild',
+ built: './built-child/slots-built-child.js#slotsBuiltChildTheme',
+ runtime: './built-child/source.mjs#default',
+ },
+ ]);
+ for (const {built, runtime} of Object.values(result)) {
+ expect(built).toEqual(runtime);
+ }
+ expect(result.child.built.componentIcons).toEqual({
+ 'code-block-copy': 'clock',
+ 'parity-panel-dismiss': null,
+ 'parity-tab-close': {size: 'xsm'},
+ });
+ expect(result.builtChild.built.resolved).toMatchObject({
+ 'code-block-copy|true': {icon: 'clock', size: 'sm'},
+ 'parity-panel-dismiss|false': {icon: 'close', size: 'sm'},
+ 'parity-tab-close|false': {icon: 'menu', size: 'sm'},
+ });
+ });
+
+ it('keeps static slots in a family build', async () => {
+ writeLineage();
+ const receipt = await themeBuildFamily(
+ ['base/source.mjs', 'child/source.mjs'],
+ {familyKey: 'slots-family'},
+ {cwd: tmpDir},
+ );
+ expect(receipt?.type).toBe('theme.build');
+ const familyModule = `./${receipt.data.outputs.js}`;
+
+ const result = inspect([
+ {
+ label: 'base',
+ built: `${familyModule}#slotsBaseTheme`,
+ runtime: './base/source.mjs#default',
+ },
+ {
+ label: 'child',
+ built: `${familyModule}#slotsChildTheme`,
+ runtime: './child/source.mjs#default',
+ },
+ ]);
+ expect(result.base.built).toEqual(result.base.runtime);
+ expect(result.child.built).toEqual(result.child.runtime);
+ });
+});
+
+describe('a slot function fails the build', () => {
+ it.each([
+ [
+ 'an inline slot function',
+ `componentIcons: {'code-block-copy': ({copied}) => ({icon: copied ? 'check' : 'copy'})}`,
+ ],
+ [
+ 'an imported slot function',
+ `componentIcons: {'code-block-copy': copySlot}`,
+ ],
+ ])('rejects %s before writing', async (_label, field) => {
+ write('slots.mjs', `export const copySlot = () => ({icon: 'clock'});\n`);
+ write(
+ 'functions.mjs',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {copySlot} from './slots.mjs';
+export default defineTheme({name: 'slot-functions', tokens: {}, ${field}});
+`,
+ );
+
+ await expect(
+ themeBuild('functions.mjs', {}, {cwd: tmpDir}),
+ ).rejects.toMatchObject({
+ code: 'ERR_THEME_INVALID',
+ message: expect.stringContaining('componentIcons["code-block-copy"]'),
+ });
+ expect(fs.readdirSync(tmpDir).sort()).toEqual([
+ 'functions.mjs',
+ 'slots.mjs',
+ ]);
+ });
+});
diff --git a/packages/cli/api/theme/build/build.mjs b/packages/cli/api/theme/build/build.mjs
index 0c034d7a3b..0bd3c80200 100644
--- a/packages/cli/api/theme/build/build.mjs
+++ b/packages/cli/api/theme/build/build.mjs
@@ -2198,6 +2198,17 @@ function iconNodesExpression(entries, entriesName, nodesName) {
})()`;
}
+/**
+ * A theme's component icon slot values: a theme from defineTheme keeps them
+ * in `__componentIcons` when any is a function (its `componentIcons` is the
+ * static view); otherwise `componentIcons` holds them.
+ * @param {any} theme
+ * @returns {Record<string, unknown> | undefined}
+ */
+function themeComponentIcons(theme) {
+ return theme?.__componentIcons ?? theme?.componentIcons;
+}
+
/**
* Generate a minimal JS module for a built theme.
* Includes the theme name, marker, and re-exports the icon registry.
@@ -2224,6 +2235,9 @@ function iconNodesExpression(entries, entriesName, nodesName) {
* renders, and the theme's `icons` and the re-exported registry are the node
* view, each function read at `{size: 'md'}` as `DefinedTheme['icons']` is.
*
+ * Component icon slot values are names, `null`, and requests, written as
+ * JSON. A slot function cannot be serialized, so it fails the build.
+ *
* @param {any} themeDef
* @param {import('./icon-imports.mjs').IconImports | null} iconInfo
* @param {string} [iconsSpecifier] - Overrides the selected registry specifier.
@@ -2295,6 +2309,19 @@ function generateBuiltModule(
: `\nexport { ${iconInfo.exportName} };\n`
: '';
+ const componentIcons = themeComponentIcons(themeDef);
+ const slotFunction = Object.entries(componentIcons ?? {}).find(
+ ([, value]) => typeof value === 'function',
+ );
+ if (slotFunction) {
+ throw new AstryxError(
+ `Theme "${themeDef.name}" sets componentIcons["${slotFunction[0]}"] to a slot function, which a built theme cannot carry. ` +
+ 'A built theme keeps names, null, and requests. Use one of those, or apply the source theme at runtime.',
+ undefined,
+ ERROR_CODES.ERR_THEME_INVALID,
+ );
+ }
+
// Resolve token values — tuples become light-dark() strings
/** @type {Record<string, unknown>} */
const resolvedTokens = {};
@@ -2365,7 +2392,8 @@ function generateBuiltModule(
list ?? [],
]),
),
- );
+ ) +
+ serializeField('componentIcons', componentIcons, true);
return `${iconImport}${iconDeclaration}${iconNodesDeclaration}/**
* ${themeDef.name} theme — built by \`${getCliInvocation()} theme build\`
diff --git a/packages/cli/assets/docs/author-a-theme.doc.mjs b/packages/cli/assets/docs/author-a-theme.doc.mjs
index 43479a9454..e335e426df 100644
--- a/packages/cli/assets/docs/author-a-theme.doc.mjs
+++ b/packages/cli/assets/docs/author-a-theme.doc.mjs
@@ -56,6 +56,7 @@ export const docs = {
['components', 'Deep-merged: child component rules override matching keys from the base.'],
['icons', 'Shallow-merged: child icons override matching names from the base.'],
['iconVariants', 'Replaced, never merged: a child that sets iconVariants replaces the base list; a child that omits it inherits the list.'],
+ ['componentIcons', 'Merged by slot: a child entry replaces the base entry for that slot whole; an omitted or undefined entry keeps the inherited one.'],
['indicators', 'Shallow-merged: child indicators override matching names from the base.'],
['onDark, onLight', "Deep-merged per surface: the base's resolved surface first, then the child's overrides."],
['motion', "Field by field: the child's `fast`, `medium` and `ratio` regenerate the fast and medium duration tokens; `slow` and `easing` left unset keep the base theme's tokens, so an inherited slow band stays at the base's ratio. Each knob (`tempo`, `character`) the child leaves unset keeps the base's."],
@@ -138,6 +139,7 @@ export const docs = {
{type: 'prose', text: 'Keep `react` and the icon library external so the registry does not bundle its own copies of those dependencies.'},
{type: 'prose', text: "A registry entry can be a function of `{size, variant}`. The built theme keeps the function, so `Icon` asks it for the size and variant it renders, as the runtime theme does, including for entries inherited from a built or package theme. The built theme's `icons` field and the registry its module re-exports are React nodes, with each function read at size `md`. A function written in the theme file itself cannot be carried, so the build fails; move it into the registry module."},
{type: 'prose', text: "A theme that lists `iconVariants` also writes an `IconVariantMap` augmentation into `<theme>.variants.d.ts`, so `Icon`'s `variant` accepts those names wherever the theme's types load. Its declaration carries the list too, so a theme that extends the built theme types `variant` in its icon entries by that list."},
+ {type: 'prose', text: "A built theme keeps its `componentIcons` names, `null` values, and static requests, so component slots resolve the same for the built theme as for the runtime theme. A slot function cannot be written into the module, so a theme with one fails the build: use a static value, or apply the source theme at runtime."},
],
},
{
diff --git a/packages/cli/assets/docs/icons.doc.mjs b/packages/cli/assets/docs/icons.doc.mjs
index 7000fe3d72..338bd4173a 100644
--- a/packages/cli/assets/docs/icons.doc.mjs
+++ b/packages/cli/assets/docs/icons.doc.mjs
@@ -214,5 +214,34 @@ export const brandTheme = defineTheme({
},
],
},
+ {
+ title: 'Component Icon Slots',
+ category: 'foundations',
+ content: [
+ {
+ type: 'prose',
+ text: "A component icon slot names why an icon appears in one component, such as `code-block-copy` for CodeBlock's copy button. `defineTheme({componentIcons})` maps a slot to one of the shared icon names. A theme can then change the icon one component uses without changing that name's artwork everywhere; `icons` still chooses the artwork for each name. Each component's docs list its slots, their state, and their fallbacks (`astryx component CodeBlock`).",
+ },
+ {
+ type: 'code',
+ lang: 'tsx',
+ label: 'Mapping a slot, with its state',
+ code: `export const brandTheme = defineTheme({
+ name: 'brand',
+ componentIcons: {
+ 'code-block-copy': ({copied}) => ({icon: copied ? 'checkDouble' : 'copy'}),
+ },
+});`,
+ },
+ {
+ type: 'prose',
+ text: "A slot value is a shared icon name, `null` to hide the icon, or a partial request of `icon`, `variant`, and `size`. A field the request leaves out keeps the component's own value. A slot with state also accepts a pure, synchronous function of that state that returns a request: returning `null` hides the icon, and returning `undefined` changes nothing. A request `size` changes only the icon, never the control around it. Icon content a component's caller passes wins over the slot.",
+ },
+ {
+ type: 'prose',
+ text: "An unknown icon name, a variant the theme does not list, or a size other than `xsm`, `sm`, `md`, or `lg` is ignored for that field, with one development warning. A theme that extends another merges `componentIcons` by slot ({@link generic:author-a-theme}). `theme.componentIcons` reads back names, `null` values, and static requests, and leaves out the slots a function resolves.",
+ },
+ ],
+ },
],
};
diff --git a/packages/cli/assets/theme.template.ts b/packages/cli/assets/theme.template.ts
index 58b771ced4..82253d80c9 100644
--- a/packages/cli/assets/theme.template.ts
+++ b/packages/cli/assets/theme.template.ts
@@ -346,6 +346,15 @@ export const myTheme = defineTheme({
*/
// iconVariants: ['outline', 'filled'],
+ /**
+ * Choose which shared icon a component's own icon role uses, by slot, such
+ * as `code-block-copy` for CodeBlock's copy button. A value is an icon name,
+ * `null` to hide the icon, a partial `{icon, variant, size}` request, or a
+ * pure function of the slot's state that returns one.
+ * Reference: `astryx docs icons`; each component's docs list its slots.
+ */
+ // componentIcons: {'code-block-copy': 'clock'},
+
/**
* Replace the small components that DRAW control state — the checkbox box,
* the radio dot, the mark on a chosen option — by indicator name rather than
diff --git a/packages/cli/authoring/doctypes/base/type.ts b/packages/cli/authoring/doctypes/base/type.ts
index 1e0d210c28..f940a2dfdc 100644
--- a/packages/cli/authoring/doctypes/base/type.ts
+++ b/packages/cli/authoring/doctypes/base/type.ts
@@ -549,6 +549,47 @@ export interface ComponentThemingVar {
private?: boolean;
}
+/**
+ * A component icon slot: a themeable icon role the component owns, which a
+ * theme maps to a shared icon name through `defineTheme({componentIcons})`.
+ * Each entry corresponds to a slot in `ComponentIconSlotMap`.
+ *
+ * @example
+ * ```
+ * {
+ * slot: 'code-block-copy',
+ * description: 'The copy button icon.',
+ * fallback: '`copy`; `check` while copied',
+ * state: [{name: 'copied', type: 'boolean', description: 'True while the copied feedback shows.'}],
+ * whenNull: 'Hides the glyph. The button keeps its size, name, and tooltip.',
+ * }
+ * ```
+ */
+// SYNC: When adding a field here, add it to the docsite's generated-registry
+// copy too — apps/docsite/scripts/generate-data.mjs (interface ComponentIconSlot).
+export interface ComponentIconSlotDoc {
+ /** The slot name, `<component-kebab>-<semantic-role>`. */
+ slot: string;
+ /** The icon's role in the component. */
+ description: string;
+ /** The icon the component renders when the theme maps nothing, per state. */
+ fallback: string;
+ /** The state a slot function receives. Omit for a stateless slot. */
+ state?: ComponentIconSlotStateDoc[];
+ /** What a slot value of `null` does for this component. */
+ whenNull: string;
+}
+
+/** One field of the state a component passes to a slot function. */
+export interface ComponentIconSlotStateDoc {
+ /** The field name. */
+ name: string;
+ /** The field's TypeScript type. */
+ type: string;
+ /** When the field has each value. */
+ description: string;
+}
+
/**
* Documents a hook parameter/option. Similar to ComponentPropDoc but for hook
* arguments and options object fields.
diff --git a/packages/cli/authoring/doctypes/component/component.doc.mjs b/packages/cli/authoring/doctypes/component/component.doc.mjs
index 2c5fc63226..e718149f00 100644
--- a/packages/cli/authoring/doctypes/component/component.doc.mjs
+++ b/packages/cli/authoring/doctypes/component/component.doc.mjs
@@ -102,7 +102,7 @@ export const doc = {
},
{
name: 'theming',
- type: '{ container?: boolean; targets: ComponentThemingTarget[]; vars?: ComponentThemingVar[]; derived?: ComponentThemingDerivedVar[] }',
+ type: '{ container?: boolean; targets: ComponentThemingTarget[]; vars?: ComponentThemingVar[]; derived?: ComponentThemingDerivedVar[]; componentIcons?: ComponentIconSlotDoc[] }',
description:
'Theming configuration: the stable selector surface (astryx-* classes + data-attribute reflections) that themes target via @scope selectors in defineTheme.',
fields: [
@@ -130,6 +130,12 @@ export const doc = {
description:
"Maps standard CSS properties to internal vars for theme-pipeline expansion. Ordered by priority: earlier entries emit first. The pipeline reads only Core components' entries, so an integration's have no effect.",
},
+ {
+ name: 'theming.componentIcons',
+ type: 'ComponentIconSlotDoc[]',
+ description:
+ "The component's icon slots, which a theme maps through `defineTheme({componentIcons})`: each slot's name, role, fallback per state, the state a slot function receives, and what `null` does. Each entry corresponds to a slot in `ComponentIconSlotMap`.",
+ },
],
},
{
diff --git a/packages/cli/authoring/doctypes/component/type.ts b/packages/cli/authoring/doctypes/component/type.ts
index 14893c1b6e..5f21141d83 100644
--- a/packages/cli/authoring/doctypes/component/type.ts
+++ b/packages/cli/authoring/doctypes/component/type.ts
@@ -10,6 +10,7 @@ import type {
ComponentAnatomyElement,
ComponentBestPractice,
ComponentExampleDoc,
+ ComponentIconSlotDoc,
ComponentPlaygroundConfig,
ComponentPropDoc,
ComponentThemingDerivedVar,
@@ -162,6 +163,10 @@ export interface ComponentBaseDoc extends AuthoredDocGraphFields {
* on this component, also emit the internal var.
* @see ComponentThemingDerivedVar */
derived?: ComponentThemingDerivedVar[];
+ /** Component icon slots this component resolves through the theme's
+ * `componentIcons`. Each entry corresponds to a slot in
+ * `ComponentIconSlotMap`. */
+ componentIcons?: ComponentIconSlotDoc[];
};
/** Component usage documentation — concise summary, best practices,
* and optional visual anatomy. */
diff --git a/packages/cli/authoring/index.d.ts b/packages/cli/authoring/index.d.ts
index fd44355713..30563239ca 100644
--- a/packages/cli/authoring/index.d.ts
+++ b/packages/cli/authoring/index.d.ts
@@ -138,6 +138,8 @@ export type {
ComponentThemingTarget,
ComponentThemingVar,
ComponentThemingDerivedVar,
+ ComponentIconSlotDoc,
+ ComponentIconSlotStateDoc,
UsageDoc,
// hook
HookParamDoc,
diff --git a/packages/cli/clients/cli/lib/component-format.mjs b/packages/cli/clients/cli/lib/component-format.mjs
index 2460d4598b..fde678ee9d 100644
--- a/packages/cli/clients/cli/lib/component-format.mjs
+++ b/packages/cli/clients/cli/lib/component-format.mjs
@@ -163,6 +163,34 @@ function getTargetStates(target) {
return target.states || [];
}
+/**
+ * Format a component's icon slots: the `componentIcons` keys a theme sets,
+ * with each slot's state, fallback, and what `null` does.
+ * @param {any[]} slots - `theming.componentIcons` entries.
+ * @returns {string}
+ */
+function formatComponentIconSlots(slots) {
+ const lines = [
+ '**Component icon slots** - set in `defineTheme({componentIcons})` to a shared icon name, `null`, a partial `{icon, variant, size}` request, or a function of the slot state.\n',
+ '| Slot | State | Fallback | Role | `null` |',
+ '|------|-------|----------|------|--------|',
+ ];
+ for (const slot of slots) {
+ const state = slot.state?.length
+ ? slot.state
+ .map(
+ (/** @type {any} */ field) =>
+ `\`${mdCell(field.name)}: ${mdCell(field.type)}\` ${mdCell(field.description)}`,
+ )
+ .join('<br>')
+ : 'none';
+ lines.push(
+ `| \`${mdCell(slot.slot)}\` | ${state} | ${mdCell(slot.fallback)} | ${mdCell(slot.description)} | ${mdCell(slot.whenNull)} |`,
+ );
+ }
+ return lines.join('\n') + '\n';
+}
+
/**
* Format the theming targets table, merging in theme variants if available.
*
@@ -351,6 +379,10 @@ export function formatFull(docs, options = {}) {
}
}
+ if (docs.theming.componentIcons?.length) {
+ sections.push(formatComponentIconSlots(docs.theming.componentIcons));
+ }
+
// Legacy componentKey (for backward compatibility)
if (docs.theming.componentKey) {
sections.push(`Component key: \`${docs.theming.componentKey}\`\n`);
@@ -507,6 +539,11 @@ export function formatCompact(docs, componentName, importHint) {
sections.push(propLines.join('\n') + '\n');
}
+ if (docs.theming?.componentIcons?.length) {
+ sections.push('## Component Icon Slots\n');
+ sections.push(formatComponentIconSlots(docs.theming.componentIcons));
+ }
+
return sections.join('\n');
}
@@ -626,6 +663,18 @@ export function formatBrief(docs, componentName, importHint, options = {}) {
output.push(` Derived: ${derivedNames}`);
}
+ // Component icon slots, with the state each slot function receives
+ if (docs.theming?.componentIcons?.length) {
+ const slots = docs.theming.componentIcons
+ .map((/** @type {any} */ slot) =>
+ slot.state?.length
+ ? `${slot.slot} {${slot.state.map((/** @type {any} */ field) => `${field.name}: ${field.type}`).join(', ')}}`
+ : slot.slot,
+ )
+ .join('; ');
+ output.push(` Icon slots: ${slots}`);
+ }
+
// Theme targets (component class, preferred data attrs, props, states) with theme variant merging
if (docs.theming?.targets?.length) {
const {themeData = null} = options;
diff --git a/packages/cli/clients/cli/lib/component-format.test.mjs b/packages/cli/clients/cli/lib/component-format.test.mjs
index bf4b940c75..679193360f 100644
--- a/packages/cli/clients/cli/lib/component-format.test.mjs
+++ b/packages/cli/clients/cli/lib/component-format.test.mjs
@@ -244,3 +244,62 @@ describe('formatBrief signature stays terse', () => {
expect(formatBrief(docs, 'HStack', '')).toContain('gap');
});
});
+
+describe('component icon slots', () => {
+ const docs = {
+ name: 'CodeBlock',
+ description: 'Code.',
+ props: [],
+ theming: {
+ targets: [{className: 'astryx-code-block'}],
+ componentIcons: [
+ {
+ slot: 'code-block-copy',
+ description: 'The copy button icon.',
+ fallback: '`copy`; `check` while copied',
+ state: [
+ {
+ name: 'copied',
+ type: 'boolean',
+ description: 'True while copied.',
+ },
+ ],
+ whenNull: 'Hides the glyph.',
+ },
+ {
+ slot: 'code-block-example',
+ description: 'A stateless slot.',
+ fallback: '`info`',
+ whenNull: 'Hides the icon.',
+ },
+ ],
+ },
+ };
+
+ it('lists each slot with its state, fallback, role, and null behavior in full output', () => {
+ const out = formatFull(docs);
+ expect(out).toContain('**Component icon slots**');
+ expect(out).toContain(
+ '| `code-block-copy` | `copied: boolean` True while copied. | `copy`; `check` while copied | The copy button icon. | Hides the glyph. |',
+ );
+ expect(out).toContain(
+ '| `code-block-example` | none | `info` | A stateless slot. | Hides the icon. |',
+ );
+ });
+
+ it('keeps the slots in compact and brief output', () => {
+ expect(formatCompact(docs, 'CodeBlock')).toContain(
+ '## Component Icon Slots',
+ );
+ expect(formatBrief(docs, 'CodeBlock')).toContain(
+ 'Icon slots: code-block-copy {copied: boolean}; code-block-example',
+ );
+ });
+
+ it('prints no slot section for a component without slots', () => {
+ const {componentIcons: _omitted, ...theming} = docs.theming;
+ expect(formatFull({...docs, theming})).not.toContain(
+ 'Component icon slots',
+ );
+ });
+});
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 40cbd19c11..2879e923d9 100644
--- a/packages/cli/test/__golden__/no-icon-set/docs-topics.json
+++ b/packages/cli/test/__golden__/no-icon-set/docs-topics.json
@@ -103,7 +103,7 @@
"token-utilities",
"usetheme-hook"
],
- "skeleton": "67521830da2f078f4335b843b78812e05919c7f7b976f089bfcf8c3d1552c496",
+ "skeleton": "9d5b6d6c228d6f569726bc06c61eaac8fbe073ff28d1d8b2d33ad4c5644188b8",
"mentions": []
},
"browser-support": {
@@ -162,9 +162,10 @@
"custom-icons",
"theme-overrides",
"icon-variants",
- "component-and-library-icons"
+ "component-and-library-icons",
+ "component-icon-slots"
],
- "skeleton": "b58107977247069a83428bd5c6af3c28edef4c4754cb12e6b8bbfa9dca6ab052",
+ "skeleton": "206b12fc6081d11de22b5e9aa8c2cbf3755acf167da9442cab0f89c3080ca101",
"mentions": [
"This lets you swap the icon set (e.g."
]
diff --git a/packages/cli/test/__golden__/no-icon-set/docs-tree.json b/packages/cli/test/__golden__/no-icon-set/docs-tree.json
index b00e686f52..7d6760c88b 100644
--- a/packages/cli/test/__golden__/no-icon-set/docs-tree.json
+++ b/packages/cli/test/__golden__/no-icon-set/docs-tree.json
@@ -924,7 +924,8 @@
"custom-icons",
"theme-overrides",
"icon-variants",
- "component-and-library-icons"
+ "component-and-library-icons",
+ "component-icon-slots"
],
"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 550ae1e9fa..192899d178 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
@@ -3,7 +3,7 @@
"type": "search",
"data": {
"query": "icon set",
- "matchCount": 383,
+ "matchCount": 384,
"results": [
{
"domain": "doc",
@@ -150,99 +150,97 @@
"mentions": []
},
{
- "domain": "template",
- "name": "BaseTypeaheadCustomSearch",
- "package": "@astryxdesign/core",
+ "domain": "doc",
+ "name": "icons",
+ "package": "@astryxdesign/cli",
"score": "<text>",
"reason": "<text>",
"description": "<text>",
- "displayName": "<text>",
- "kind": "block",
- "command": "astryx template BaseTypeaheadCustomSearch --type block",
+ "section": "<text>",
+ "title": "<text>",
+ "command": "astryx docs icons component-icon-slots",
+ "parent": "astryx docs icons --index",
"mentions": []
},
{
- "domain": "template",
- "name": "BottomSheetSnapPoints",
+ "domain": "component",
+ "name": "NavIcon",
"package": "@astryxdesign/core",
"score": "<text>",
"reason": "<text>",
"description": "<text>",
- "displayName": "<text>",
- "kind": "block",
- "command": "astryx template BottomSheetSnapPoints --type block",
+ "import": "@astryxdesign/core/NavIcon",
+ "command": "astryx component NavIcon",
"mentions": []
},
{
- "domain": "template",
- "name": "BreadcrumbsDeepHierarchy",
+ "domain": "component",
+ "name": "BottomSheet",
"package": "@astryxdesign/core",
"score": "<text>",
"reason": "<text>",
"description": "<text>",
- "displayName": "<text>",
- "kind": "block",
- "command": "astryx template BreadcrumbsDeepHierarchy --type block",
+ "import": "@astryxdesign/core/BottomSheet",
+ "command": "astryx component BottomSheet",
"mentions": []
},
{
- "domain": "template",
- "name": "BreadcrumbsWithIcons",
+ "domain": "component",
+ "name": "BottomSheetSwitcher",
"package": "@astryxdesign/core",
"score": "<text>",
"reason": "<text>",
"description": "<text>",
- "displayName": "<text>",
- "kind": "block",
- "command": "astryx template BreadcrumbsWithIcons --type block",
+ "import": "@astryxdesign/core/BottomSheet",
+ "command": "astryx component BottomSheetSwitcher",
+ "deprecated": {
+ "replacement": "<text>",
+ "description": "<text>"
+ },
"mentions": []
},
{
- "domain": "template",
- "name": "ButtonFloating",
+ "domain": "component",
+ "name": "Carousel",
"package": "@astryxdesign/core",
"score": "<text>",
"reason": "<text>",
"description": "<text>",
- "displayName": "<text>",
- "kind": "block",
- "command": "astryx template ButtonFloating --type block",
+ "import": "@astryxdesign/core/Carousel",
+ "command": "astryx component Carousel",
"mentions": []
},
{
- "domain": "template",
- "name": "ButtonGroupShowcase",
+ "domain": "component",
+ "name": "ChatLayout",
"package": "@astryxdesign/core",
"score": "<text>",
"reason": "<text>",
"description": "<text>",
- "displayName": "<text>",
- "kind": "block",
- "command": "astryx template ButtonGroupShowcase --type block",
+ "import": "@astryxdesign/core/Chat",
+ "command": "astryx component ChatLayout",
"mentions": []
},
{
- "domain": "template",
- "name": "ButtonWithIcon",
+ "domain": "component",
+ "name": "ChatMessageList",
"package": "@astryxdesign/core",
"score": "<text>",
"reason": "<text>",
"description": "<text>",
- "displayName": "<text>",
- "kind": "block",
- "command": "astryx template ButtonWithIcon --type block",
+ "import": "@astryxdesign/core/Chat",
+ "command": "astryx component ChatMessageList",
"mentions": []
},
{
- "domain": "template",
- "name": "CenterHorizontal",
+ "domain": "component",
+ "name": "InternationalizationProvider",
"package": "@astryxdesign/core",
"score": "<text>",
"reason": "<text>",
"description": "<text>",
- "displayName": "<text>",
- "kind": "block",
- "command": "astryx template CenterHorizontal --type block",
+ "import": "@astryxdesign/core/i18n",
+ "command": "astryx component InternationalizationProvider",
"mentions": []
}
]
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 a0ab293428..8c9e898e31 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
@@ -1,4 +1,4 @@
-Results for "icon set" (20 of 383)
+Results for "icon set" (20 of 384)
name: authoring/building-blocks/templates/build-the-template/template-assets/template-icons
section: use-astryx-icon
domain: doc
@@ -62,35 +62,44 @@ domain: hook
package: @astryxdesign/core
import: @astryxdesign/core/hooks
command: pnpm exec astryx hook useInputStatusIcon
-name: BaseTypeaheadCustomSearch
-domain: template
-package: @astryxdesign/core
-command: pnpm exec astryx template BaseTypeaheadCustomSearch --type block
-name: BottomSheetSnapPoints
-domain: template
+name: icons
+section: component-icon-slots
+domain: doc
+package: @astryxdesign/cli
+command: pnpm exec astryx docs icons component-icon-slots
+parent: pnpm exec astryx docs icons --index
+name: NavIcon
+domain: component
package: @astryxdesign/core
-command: pnpm exec astryx template BottomSheetSnapPoints --type block
-name: BreadcrumbsDeepHierarchy
-domain: template
+import: @astryxdesign/core/NavIcon
+command: pnpm exec astryx component NavIcon
+name: BottomSheet
+domain: component
package: @astryxdesign/core
-command: pnpm exec astryx template BreadcrumbsDeepHierarchy --type block
-name: BreadcrumbsWithIcons
-domain: template
+import: @astryxdesign/core/BottomSheet
+command: pnpm exec astryx component BottomSheet
+name: BottomSheetSwitcher
+domain: component
package: @astryxdesign/core
-command: pnpm exec astryx template BreadcrumbsWithIcons --type block
-name: ButtonFloating
-domain: template
+import: @astryxdesign/core/BottomSheet
+command: pnpm exec astryx component BottomSheetSwitcher
+name: Carousel
+domain: component
package: @astryxdesign/core
-command: pnpm exec astryx template ButtonFloating --type block
-name: ButtonGroupShowcase
-domain: template
+import: @astryxdesign/core/Carousel
+command: pnpm exec astryx component Carousel
+name: ChatLayout
+domain: component
package: @astryxdesign/core
-command: pnpm exec astryx template ButtonGroupShowcase --type block
-name: ButtonWithIcon
-domain: template
+import: @astryxdesign/core/Chat
+command: pnpm exec astryx component ChatLayout
+name: ChatMessageList
+domain: component
package: @astryxdesign/core
-command: pnpm exec astryx template ButtonWithIcon --type block
-name: CenterHorizontal
-domain: template
+import: @astryxdesign/core/Chat
+command: pnpm exec astryx component ChatMessageList
+name: InternationalizationProvider
+domain: component
package: @astryxdesign/core
-command: pnpm exec astryx template CenterHorizontal --type block
\ No newline at end of file
+import: @astryxdesign/core/i18n
+command: pnpm exec astryx component InternationalizationProvider
\ No newline at end of file
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 79c33af0d8..5cd94a5cb7 100644
--- a/packages/cli/test/__golden__/no-icon-set/search-icon.json
+++ b/packages/cli/test/__golden__/no-icon-set/search-icon.json
@@ -3,7 +3,7 @@
"type": "search",
"data": {
"query": "icon",
- "matchCount": 228,
+ "matchCount": 230,
"results": [
{
"domain": "component",
@@ -111,6 +111,19 @@
"parent": "astryx docs icons --index",
"mentions": []
},
+ {
+ "domain": "doc",
+ "name": "icons",
+ "package": "@astryxdesign/cli",
+ "score": "<text>",
+ "reason": "<text>",
+ "description": "<text>",
+ "section": "<text>",
+ "title": "<text>",
+ "command": "astryx docs icons component-icon-slots",
+ "parent": "astryx docs icons --index",
+ "mentions": []
+ },
{
"domain": "template",
"name": "BaseTypeaheadCustomSearch",
@@ -230,18 +243,6 @@
"kind": "block",
"command": "astryx template ChatComposerDrawerShowcase --type block",
"mentions": []
- },
- {
- "domain": "template",
- "name": "ChatComposerDrawerWithProgress",
- "package": "@astryxdesign/core",
- "score": "<text>",
- "reason": "<text>",
- "description": "<text>",
- "displayName": "<text>",
- "kind": "block",
- "command": "astryx template ChatComposerDrawerWithProgress --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 450ff3f74c..a7c3af3cc3 100644
--- a/packages/cli/test/__golden__/no-icon-set/search-icon.txt
+++ b/packages/cli/test/__golden__/no-icon-set/search-icon.txt
@@ -1,4 +1,4 @@
-Results for "icon" (20 of 228)
+Results for "icon" (20 of 230)
name: Icon
domain: component
package: @astryxdesign/core
@@ -46,6 +46,12 @@ domain: doc
package: @astryxdesign/cli
command: pnpm exec astryx docs icons icon-variants
parent: pnpm exec astryx docs icons --index
+name: icons
+section: component-icon-slots
+domain: doc
+package: @astryxdesign/cli
+command: pnpm exec astryx docs icons component-icon-slots
+parent: pnpm exec astryx docs icons --index
name: BaseTypeaheadCustomSearch
domain: template
package: @astryxdesign/core
@@ -85,8 +91,4 @@ command: pnpm exec astryx template CenterInsideACard --type block
name: ChatComposerDrawerShowcase
domain: template
package: @astryxdesign/core
-command: pnpm exec astryx template ChatComposerDrawerShowcase --type block
-name: ChatComposerDrawerWithProgress
-domain: template
-package: @astryxdesign/core
-command: pnpm exec astryx template ChatComposerDrawerWithProgress --type block
\ No newline at end of file
+command: pnpm exec astryx template ChatComposerDrawerShowcase --type block
\ No newline at end of file
diff --git a/packages/core/src/CodeBlock/CodeBlock.doc.mjs b/packages/core/src/CodeBlock/CodeBlock.doc.mjs
index 05de6ecefe..20d6f1851a 100644
--- a/packages/core/src/CodeBlock/CodeBlock.doc.mjs
+++ b/packages/core/src/CodeBlock/CodeBlock.doc.mjs
@@ -219,6 +219,23 @@ export const docs = {
private: true,
},
],
+ componentIcons: [
+ {
+ slot: 'code-block-copy',
+ description: 'The copy button icon.',
+ fallback: '`copy`; `check` while copied',
+ state: [
+ {
+ name: 'copied',
+ type: 'boolean',
+ description:
+ 'True while the copied feedback shows after a successful copy.',
+ },
+ ],
+ whenNull:
+ 'Hides the glyph. The button keeps its size, name, tooltip, and copy action.',
+ },
+ ],
},
usage: {
description:
diff --git a/packages/core/src/CodeBlock/CodeBlock.test.tsx b/packages/core/src/CodeBlock/CodeBlock.test.tsx
index 1b35808862..e7168c6b96 100644
--- a/packages/core/src/CodeBlock/CodeBlock.test.tsx
+++ b/packages/core/src/CodeBlock/CodeBlock.test.tsx
@@ -21,6 +21,9 @@ import {dracula} from '../theme/syntax';
import {InternationalizationProvider} from '../i18n';
import {defineTheme} from '../theme/defineTheme';
import {generateThemeCSS} from '../theme/generateThemeRules';
+import {Theme} from '../theme/Theme';
+import {resetThemes} from '../theme/themeRegistry';
+import {__resetDevWarnings} from '../utils/devWarning';
function generateThemeTestCSS(theme: Parameters<typeof generateThemeCSS>[0]) {
const {prose, component} = generateThemeCSS(theme);
@@ -785,3 +788,157 @@ describe('CodeBlock theme target names', () => {
expect(css).toContain('.astryx-code-block-title');
});
});
+
+describe('CodeBlock copy icon slot', () => {
+ // Label each shared icon's artwork, so a test reads which name rendered.
+ const icons = {
+ copy: <span data-icon="copy" />,
+ check: <span data-icon="check" />,
+ clock: <span data-icon="clock" />,
+ checkDouble: <span data-icon="checkDouble" />,
+ };
+
+ beforeEach(() => {
+ // An earlier user-event test can leave a getter-only clipboard behind.
+ Object.defineProperty(navigator, 'clipboard', {
+ configurable: true,
+ value: {writeText: vi.fn().mockResolvedValue(undefined)},
+ });
+ resetThemes();
+ __resetDevWarnings();
+ });
+
+ afterEach(() => {
+ __resetLiveRegionsForTest();
+ vi.restoreAllMocks();
+ });
+
+ function renderInTheme(theme: Parameters<typeof Theme>[0]['theme']) {
+ render(
+ <Theme theme={theme}>
+ <CodeBlock code="const x = 1;" />
+ </Theme>,
+ );
+ }
+
+ function glyphOf(name: string) {
+ const button = screen.getByRole('button', {name});
+ return button.querySelector('[data-icon]')?.getAttribute('data-icon');
+ }
+
+ async function copy() {
+ fireEvent.click(screen.getByRole('button', {name: 'Copy code'}));
+ await screen.findByRole('button', {name: 'Copied'});
+ }
+
+ it('draws copy, then check while copied, when the theme maps nothing', async () => {
+ renderInTheme(defineTheme({name: 'copy-slot-fallback', icons}));
+
+ expect(glyphOf('Copy code')).toBe('copy');
+ await copy();
+ expect(glyphOf('Copied')).toBe('check');
+ });
+
+ it('passes `copied` to a slot function and draws the name it returns', async () => {
+ const slot = vi.fn(({copied}: {copied: boolean}) => ({
+ icon: copied ? ('checkDouble' as const) : ('clock' as const),
+ }));
+ renderInTheme(
+ defineTheme({
+ name: 'copy-slot-function',
+ icons,
+ componentIcons: {'code-block-copy': slot},
+ }),
+ );
+
+ expect(glyphOf('Copy code')).toBe('clock');
+ expect(slot).toHaveBeenLastCalledWith({copied: false});
+ await copy();
+ expect(glyphOf('Copied')).toBe('checkDouble');
+ expect(slot).toHaveBeenLastCalledWith({copied: true});
+ });
+
+ it('keeps the copied fallback when a slot function returns undefined for that state', async () => {
+ renderInTheme(
+ defineTheme({
+ name: 'copy-slot-partial',
+ icons,
+ componentIcons: {
+ 'code-block-copy': ({copied}) =>
+ copied ? undefined : {icon: 'clock'},
+ },
+ }),
+ );
+
+ expect(glyphOf('Copy code')).toBe('clock');
+ await copy();
+ expect(glyphOf('Copied')).toBe('check');
+ });
+
+ it('draws a mapped name in both states', async () => {
+ renderInTheme(
+ defineTheme({
+ name: 'copy-slot-name',
+ icons,
+ componentIcons: {'code-block-copy': 'clock'},
+ }),
+ );
+
+ expect(glyphOf('Copy code')).toBe('clock');
+ await copy();
+ expect(glyphOf('Copied')).toBe('clock');
+ });
+
+ it('hides only the glyph for null; the button keeps its name and copy action', async () => {
+ renderInTheme(
+ defineTheme({
+ name: 'copy-slot-null',
+ icons,
+ componentIcons: {'code-block-copy': null},
+ }),
+ );
+
+ const button = screen.getByRole('button', {name: 'Copy code'});
+ expect(button.querySelector('.astryx-icon')).toBeNull();
+ expect(button).toHaveClass('astryx-code-block-copy-button');
+ await copy();
+ expect(navigator.clipboard.writeText).toHaveBeenCalledWith('const x = 1;');
+ });
+
+ it('changes only the icon size for a size request, not the button', () => {
+ renderInTheme(
+ defineTheme({
+ name: 'copy-slot-size',
+ icons,
+ componentIcons: {'code-block-copy': {size: 'lg'}},
+ }),
+ );
+
+ const button = screen.getByRole('button', {name: 'Copy code'});
+ expect(button.querySelector('.astryx-icon')).toHaveAttribute(
+ 'data-size',
+ 'lg',
+ );
+ expect(glyphOf('Copy code')).toBe('copy');
+ expect(button).toHaveAttribute('data-size', 'sm');
+ });
+
+ it('keeps the fallback and warns once for an unknown icon name', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const theme = defineTheme({
+ name: 'copy-slot-unknown',
+ icons,
+ componentIcons: {
+ // @ts-expect-error -- not a shared icon name.
+ 'code-block-copy': 'clipboard',
+ },
+ });
+
+ renderInTheme(theme);
+ expect(glyphOf('Copy code')).toBe('copy');
+ const slotWarnings = warn.mock.calls.filter(([message]) =>
+ String(message).includes('componentIcons["code-block-copy"]'),
+ );
+ expect(slotWarnings).toHaveLength(1);
+ });
+});
diff --git a/packages/core/src/CodeBlock/CodeBlock.tsx b/packages/core/src/CodeBlock/CodeBlock.tsx
index 36644d4397..18dd72a99e 100644
--- a/packages/core/src/CodeBlock/CodeBlock.tsx
+++ b/packages/core/src/CodeBlock/CodeBlock.tsx
@@ -3,7 +3,8 @@
'use client';
/**
* @file CodeBlock.tsx
- * @input Uses React, StyleX, theme tokens, CSS Custom Highlight API, SyntaxTheme provider
+ * @input Uses React, StyleX, theme tokens, CSS Custom Highlight API, SyntaxTheme
+ * provider, and the theme's `code-block-copy` icon slot
* @output Exports CodeBlock component and CodeBlockProps
* @position Core implementation; read-only syntax-highlighted code display
*/
@@ -36,6 +37,7 @@ import {isRenderable, mergeProps, rtlStyles} from '../utils';
import {useClipboard} from '../hooks/useClipboard';
import {useScrollableArea} from '../hooks/useScrollableArea';
import {Icon} from '../Icon';
+import {ComponentIcon} from '../Icon/ComponentIcon';
import {IconButton} from '../IconButton';
import type {DiffLineKind} from './tokenizer';
import {
@@ -1137,7 +1139,14 @@ export function CodeBlock({
<IconButton
variant="ghost"
size="sm"
- icon={<Icon icon={copied ? 'check' : 'copy'} size="sm" color="inherit" />}
+ icon={
+ <ComponentIcon
+ slot="code-block-copy"
+ state={{copied}}
+ fallback={{icon: copied ? 'check' : 'copy', size: 'sm'}}
+ color="inherit"
+ />
+ }
// A visible "Copy" hover/focus hint via Button's built-in tooltip. It
// stays "Copy" after copying — the copy → check icon flip is the
// confirmation, not a tooltip change. The aria-label still swaps to the
diff --git a/packages/core/src/Icon/ComponentIcon.tsx b/packages/core/src/Icon/ComponentIcon.tsx
new file mode 100644
index 0000000000..55ea15b037
--- /dev/null
+++ b/packages/core/src/Icon/ComponentIcon.tsx
@@ -0,0 +1,71 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file ComponentIcon.tsx
+ * @input A component icon slot, its state, the component's fallback, and
+ * optional caller-supplied icon content
+ * @output Exports the internal ComponentIcon renderer
+ * @position Shared renderer that components use for a themeable icon slot:
+ * caller content, then the theme's slot, then the component's fallback
+ */
+
+import type {ReactNode} from 'react';
+import {Icon, type IconColor} from './Icon';
+import type {
+ ComponentIconFallback,
+ ComponentIconSlotState,
+} from './globalIconRegistry';
+import type {ComponentIconSlotName, IconVariant} from './index';
+import {useComponentIcon} from './useIcon';
+
+type ComponentIconProps<Slot extends ComponentIconSlotName> = {
+ slot: Slot;
+ state: ComponentIconSlotState<Slot>;
+ fallback: ComponentIconFallback;
+ color?: IconColor;
+ /**
+ * Icon content the component's caller supplied. When set (`null`
+ * included), it renders instead of the slot.
+ */
+ content?: ReactNode;
+};
+
+/**
+ * Render a component's themeable icon. Caller content wins. Otherwise the
+ * active theme's `componentIcons[slot]` adjusts the component's fallback,
+ * and the result renders through `Icon`, so shared icon resolution chooses
+ * the artwork. A resolved `null` renders nothing.
+ * @internal
+ */
+export function ComponentIcon<Slot extends ComponentIconSlotName>({
+ content,
+ ...props
+}: ComponentIconProps<Slot>): ReactNode {
+ if (content !== undefined) {
+ return content;
+ }
+ return <SlotIcon {...props} />;
+}
+
+function SlotIcon<Slot extends ComponentIconSlotName>({
+ slot,
+ state,
+ fallback,
+ color,
+}: Omit<ComponentIconProps<Slot>, 'content'>): ReactNode {
+ const {icon, variant, size} = useComponentIcon(slot, state, fallback);
+ if (icon == null) {
+ return null;
+ }
+ return (
+ <Icon
+ icon={icon}
+ // Resolution keeps only a variant the active theme lists.
+ variant={variant as IconVariant | undefined}
+ size={size}
+ color={color}
+ />
+ );
+}
diff --git a/packages/core/src/Icon/componentIconSlots.test.ts b/packages/core/src/Icon/componentIconSlots.test.ts
new file mode 100644
index 0000000000..828b140370
--- /dev/null
+++ b/packages/core/src/Icon/componentIconSlots.test.ts
@@ -0,0 +1,130 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/* eslint-disable @typescript-eslint/no-require-imports */
+/**
+ * @file componentIconSlots.test.ts
+ * @input The `ComponentIconSlotMap` declaration in Icon/index.ts, the Core
+ * sources that render a slot, and every Core `*.doc.mjs`
+ * @output Vitest failures naming each slot that is declared, rendered, or
+ * documented without the other two, or named outside its component
+ * @position Guards the component icon slot inventory: a declared slot has one
+ * owning component, which renders it and lists it in its doc's
+ * `theming.componentIcons`
+ */
+
+import {describe, expect, it} from 'vitest';
+import {readdirSync, readFileSync} from 'node:fs';
+import {basename, dirname, join, relative} from 'node:path';
+
+const CORE_SRC_DIR = join(__dirname, '..');
+
+function walk(dir: string, accept: (file: string) => boolean): string[] {
+ return readdirSync(dir, {withFileTypes: true}).flatMap(entry => {
+ const path = join(dir, entry.name);
+ if (entry.isDirectory()) {
+ return entry.name === '__tests__' ? [] : walk(path, accept);
+ }
+ return accept(path) ? [path] : [];
+ });
+}
+
+/** The slot names `ComponentIconSlotMap` declares in the public module. */
+function declaredSlots(): string[] {
+ const source = readFileSync(join(__dirname, 'index.ts'), 'utf8');
+ const body = /export interface ComponentIconSlotMap \{([\s\S]*?)\n\}/.exec(
+ source,
+ )?.[1];
+ return [...(body ?? '').matchAll(/^ {2}'([^']+)'\??:/gm)].map(m => m[1]);
+}
+
+/**
+ * The files that render each slot: a `slot` attribute on `ComponentIcon`, or
+ * the first argument of `useComponentIcon` or `resolveComponentIcon`.
+ */
+function renderedSlots(): Map<string, string[]> {
+ const sites = new Map<string, string[]>();
+ const sources = walk(
+ CORE_SRC_DIR,
+ file =>
+ /\.tsx?$/.test(file) &&
+ !/\.(test|stories)\.tsx?$/.test(file) &&
+ dirname(file) !== __dirname,
+ );
+ for (const file of sources) {
+ const text = readFileSync(file, 'utf8');
+ const pattern =
+ /<ComponentIcon\b[^>]*?\bslot="([^"]+)"|\b(?:useComponentIcon|resolveComponentIcon)\(\s*'([^']+)'/g;
+ for (const match of text.matchAll(pattern)) {
+ const slot = match[1] ?? match[2];
+ sites.set(slot, [...(sites.get(slot) ?? []), file]);
+ }
+ }
+ return sites;
+}
+
+interface SlotDoc {
+ slot: string;
+ description?: string;
+ fallback?: string;
+ whenNull?: string;
+}
+
+/** Each documented slot, with the doc file that lists it. */
+function documentedSlots(): {doc: string; entry: SlotDoc}[] {
+ return walk(CORE_SRC_DIR, file => file.endsWith('.doc.mjs')).flatMap(doc => {
+ const mod = require(doc) as {
+ docs?: {theming?: {componentIcons?: SlotDoc[]}};
+ };
+ return (mod.docs?.theming?.componentIcons ?? []).map(entry => ({
+ doc,
+ entry,
+ }));
+ });
+}
+
+function kebab(name: string): string {
+ return name.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
+}
+
+describe('component icon slot inventory', () => {
+ const declared = declaredSlots();
+ const rendered = renderedSlots();
+ const documented = documentedSlots();
+
+ it('declares at least one slot', () => {
+ expect(declared.length).toBeGreaterThan(0);
+ });
+
+ it.each(declared)(
+ '%s is rendered by one component and documented by it',
+ slot => {
+ const sites = rendered.get(slot) ?? [];
+ expect(sites, `${slot} has no render site`).not.toEqual([]);
+ const docs = documented.filter(({entry}) => entry.slot === slot);
+ expect(
+ docs.map(({doc}) => relative(CORE_SRC_DIR, doc)),
+ `${slot} must be listed in exactly one theming.componentIcons`,
+ ).toHaveLength(1);
+ const [{doc, entry}] = docs;
+ for (const site of sites) {
+ expect(
+ relative(dirname(doc), site).startsWith('..'),
+ `${relative(CORE_SRC_DIR, site)} renders ${slot}, which ${relative(CORE_SRC_DIR, doc)} owns`,
+ ).toBe(false);
+ }
+ // `<component-kebab>-<semantic-role>`, by the owning component folder.
+ expect(slot.startsWith(`${kebab(basename(dirname(doc)))}-`)).toBe(true);
+ expect([entry.description, entry.fallback, entry.whenNull]).not.toContain(
+ undefined,
+ );
+ },
+ );
+
+ it('documents and renders only declared slots', () => {
+ const undeclared = [
+ ...documented.map(({entry}) => entry.slot),
+ ...rendered.keys(),
+ ].filter(slot => !declared.includes(slot));
+ expect(undeclared).toEqual([]);
+ });
+});
diff --git a/packages/core/src/Icon/componentIcons.test.tsx b/packages/core/src/Icon/componentIcons.test.tsx
new file mode 100644
index 0000000000..e3c7031a2c
--- /dev/null
+++ b/packages/core/src/Icon/componentIcons.test.tsx
@@ -0,0 +1,395 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file componentIcons.test.tsx
+ * @input Uses vitest, @testing-library/react, defineTheme, Theme, and the
+ * component icon slot resolver and renderer
+ * @output Tests slot precedence, partial requests, malformed requests, slot
+ * functions, static public reads, inheritance, and the public slot types
+ * @position Testing; validates resolveComponentIcon, useComponentIcon,
+ * ComponentIcon, and defineTheme({componentIcons})
+ */
+
+import {
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ expectTypeOf,
+ it,
+ 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 {ComponentIcon} from './ComponentIcon';
+import {
+ getIcon,
+ getIconRegistry,
+ resolveComponentIcon,
+ type ComponentIconFallback,
+} from './globalIconRegistry';
+import type {
+ ComponentIconMap,
+ ComponentIconRequest,
+ ComponentIconSlotMap,
+ ComponentIconSlotName,
+ ComponentIconStaticMap,
+ IconName,
+} from './index';
+
+// A package adds its own component's slots by augmenting the public map.
+declare module './index' {
+ interface ComponentIconSlotMap {
+ 'example-panel-dismiss': true;
+ 'example-nav-item-leading': {selected: boolean; disabled: boolean};
+ }
+}
+
+const COPY = 'code-block-copy';
+const FALLBACK = {icon: 'copy', size: 'sm'} as const;
+
+let themeCount = 0;
+/** Resolve the copy slot under a theme that sets `value` for it. */
+function resolveCopy(
+ value: unknown,
+ {
+ copied = false,
+ fallback = FALLBACK,
+ iconVariants,
+ }: {
+ copied?: boolean;
+ fallback?: ComponentIconFallback;
+ iconVariants?: string[];
+ } = {},
+) {
+ const theme = defineTheme({
+ name: `slots-${themeCount++}`,
+ iconVariants,
+ componentIcons: {[COPY]: value} as ComponentIconMap<string>,
+ });
+ return resolveComponentIcon(COPY, {copied}, fallback, theme);
+}
+
+describe('component icon slot resolution', () => {
+ let warn: {mock: {calls: unknown[][]}};
+ const warnings = () =>
+ warn.mock.calls
+ .map(([message]) => String(message))
+ .filter(message => message.includes('componentIcons['));
+
+ beforeEach(() => {
+ resetThemes();
+ __resetDevWarnings();
+ warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('returns the component fallback without a theme or a slot entry', () => {
+ expect(resolveComponentIcon(COPY, {copied: false}, 'copy', null)).toEqual({
+ icon: 'copy',
+ });
+ expect(resolveCopy(undefined)).toEqual(FALLBACK);
+ });
+
+ it.each([
+ ['a shared name replaces the icon', 'clock', {icon: 'clock', size: 'sm'}],
+ ['null hides the icon', null, {icon: null, size: 'sm'}],
+ ['icon: null hides the icon', {icon: null}, {icon: null, size: 'sm'}],
+ ['a null result hides the icon', () => null, {icon: null, size: 'sm'}],
+ ['an undefined result changes nothing', () => undefined, FALLBACK],
+ ['a size keeps the icon', {size: 'lg'}, {icon: 'copy', size: 'lg'}],
+ ])('%s', (_label, value, expected) => {
+ expect(resolveCopy(value)).toEqual(expected);
+ });
+
+ it('keeps every field a request leaves out, variant included', () => {
+ const fallback = {icon: 'copy', size: 'sm', variant: 'outline'} as const;
+ expect(resolveCopy({size: 'lg'}, {fallback})).toEqual({
+ ...fallback,
+ size: 'lg',
+ });
+ expect(
+ resolveCopy({variant: 'filled'}, {fallback, iconVariants: ['filled']}),
+ ).toEqual({...fallback, variant: 'filled'});
+ });
+
+ it('passes the slot state to a slot function and uses its request', () => {
+ const slot = vi.fn(({copied}: {copied: boolean}) => ({
+ icon: copied ? ('checkDouble' as const) : ('copy' as const),
+ }));
+
+ expect(resolveCopy(slot, {copied: true}).icon).toBe('checkDouble');
+ expect(slot).toHaveBeenLastCalledWith({copied: true});
+ expect(resolveCopy(slot).icon).toBe('copy');
+ });
+
+ it('resolves through a registered theme name', () => {
+ defineTheme({name: 'slots-by-name', componentIcons: {[COPY]: 'clock'}});
+
+ expect(
+ resolveComponentIcon(COPY, {copied: false}, 'copy', 'slots-by-name').icon,
+ ).toBe('clock');
+ });
+
+ it.each([
+ [
+ 'an unknown icon',
+ {icon: 'clipboard', size: 'lg'},
+ {icon: 'copy', size: 'lg'},
+ ],
+ ['a namespaced key', 'numberInput:stepperDown', FALLBACK],
+ [
+ 'an unlisted variant',
+ {icon: 'clock', variant: 'bold'},
+ {icon: 'clock', size: 'sm'},
+ ],
+ [
+ 'an unsupported size',
+ {icon: 'clock', size: 'xl'},
+ {icon: 'clock', size: 'sm'},
+ ],
+ ['a result that is not a request', () => 'clock', FALLBACK],
+ ])('ignores %s with one warning', (_label, value, expected) => {
+ for (let i = 0; i < 3; i++) {
+ expect(
+ resolveComponentIcon(
+ COPY,
+ {copied: false},
+ FALLBACK,
+ defineTheme({
+ name: 'slots-malformed',
+ iconVariants: ['outline'] as ReadonlyArray<string>,
+ componentIcons: {[COPY]: value} as ComponentIconMap<string>,
+ }),
+ ),
+ ).toEqual(expected);
+ }
+ expect(warnings()).toHaveLength(1);
+ });
+
+ it('does not warn in production', async () => {
+ vi.resetModules();
+ vi.stubEnv('NODE_ENV', 'production');
+ try {
+ const registry = await import('./globalIconRegistry');
+ const themes = await import('../theme/defineTheme');
+ const theme = themes.defineTheme({
+ name: 'slots-production',
+ componentIcons: {
+ // @ts-expect-error -- not a shared icon name.
+ [COPY]: 'clipboard',
+ },
+ });
+ expect(
+ registry.resolveComponentIcon(COPY, {copied: false}, 'copy', theme)
+ .icon,
+ ).toBe('copy');
+ expect(warnings()).toEqual([]);
+ } finally {
+ vi.unstubAllEnvs();
+ vi.resetModules();
+ }
+ });
+});
+
+describe('defineTheme({componentIcons})', () => {
+ beforeEach(() => {
+ resetThemes();
+ });
+
+ it('reads slot values back as a static view without slot functions', () => {
+ const slot = vi.fn(() => ({icon: 'clock' as const}));
+ const theme = defineTheme({
+ name: 'slots-static-view',
+ componentIcons: {
+ [COPY]: slot,
+ 'example-panel-dismiss': {icon: 'close', size: 'sm'},
+ 'example-nav-item-leading': null,
+ },
+ });
+
+ expect(theme.componentIcons).toEqual({
+ 'example-panel-dismiss': {icon: 'close', size: 'sm'},
+ 'example-nav-item-leading': null,
+ });
+ // Public reads never call a slot function.
+ expect(getIcon('copy', theme)).toBeTruthy();
+ expect(getIconRegistry(theme).copy).toBeTruthy();
+ expect(slot).not.toHaveBeenCalled();
+ });
+
+ it('keeps a map without functions as the static view', () => {
+ const theme = defineTheme({
+ name: 'slots-identity',
+ componentIcons: {[COPY]: 'clock'},
+ });
+
+ expect(theme.componentIcons).toEqual({[COPY]: 'clock'});
+ expect(theme.__componentIcons).toBeUndefined();
+ expect('componentIcons' in defineTheme({name: 'slots-absent'})).toBe(false);
+ });
+
+ it('inherits slot values, functions included, and replaces a slot whole', () => {
+ const base = defineTheme({
+ name: 'slots-base',
+ componentIcons: {
+ [COPY]: ({copied}) => ({icon: copied ? 'checkDouble' : 'clock'}),
+ 'example-panel-dismiss': {icon: 'close', size: 'sm'},
+ 'example-nav-item-leading': 'menu',
+ },
+ });
+ const inherits = defineTheme({name: 'slots-inherits', extends: base});
+ const child = defineTheme({
+ name: 'slots-replaces',
+ extends: base,
+ componentIcons: {
+ 'example-panel-dismiss': {size: 'lg'},
+ [COPY]: undefined,
+ 'example-nav-item-leading': null,
+ },
+ });
+
+ expect(
+ resolveComponentIcon(COPY, {copied: true}, 'check', inherits).icon,
+ ).toBe('checkDouble');
+ // An undefined entry inherits the base's slot function.
+ expect(
+ resolveComponentIcon(COPY, {copied: false}, 'copy', child).icon,
+ ).toBe('clock');
+ // The child's request replaces the base's whole: its icon is not merged.
+ expect(
+ resolveComponentIcon(
+ 'example-panel-dismiss',
+ undefined,
+ 'chevronDown',
+ child,
+ ),
+ ).toEqual({icon: 'chevronDown', size: 'lg'});
+ // A child hides an inherited slot with null.
+ expect(child.componentIcons).toEqual({
+ 'example-panel-dismiss': {size: 'lg'},
+ 'example-nav-item-leading': null,
+ });
+ });
+});
+
+describe('ComponentIcon', () => {
+ beforeEach(() => {
+ resetThemes();
+ });
+
+ function renderSlot(
+ componentIcons: ComponentIconMap<never>,
+ content?: ReactNode,
+ ) {
+ const theme = defineTheme({
+ name: `slots-render-${themeCount++}`,
+ icons: {
+ copy: <span data-icon="copy" />,
+ clock: <span data-icon="clock" />,
+ },
+ componentIcons,
+ });
+ render(
+ <Theme theme={theme}>
+ <span data-testid="slot">
+ <ComponentIcon
+ slot={COPY}
+ state={{copied: false}}
+ fallback={FALLBACK}
+ content={content}
+ />
+ </span>
+ </Theme>,
+ );
+ return screen.getByTestId('slot');
+ }
+
+ it('renders caller content instead of the slot, null included', () => {
+ const slot = vi.fn(() => ({icon: 'clock' as const}));
+
+ expect(
+ renderSlot({[COPY]: slot}, <b data-icon="caller" />).querySelector(
+ '[data-icon]',
+ ),
+ ).toHaveAttribute('data-icon', 'caller');
+ expect(slot).not.toHaveBeenCalled();
+ });
+
+ it('renders nothing for caller content null', () => {
+ expect(renderSlot({[COPY]: 'clock'}, null)).toBeEmptyDOMElement();
+ });
+
+ it('renders the resolved name through the theme icon registry', () => {
+ const icon = renderSlot({
+ [COPY]: {icon: 'clock', size: 'lg'},
+ }).querySelector('.astryx-icon');
+
+ expect(icon).toHaveAttribute('data-size', 'lg');
+ expect(icon?.querySelector('[data-icon]')).toHaveAttribute(
+ 'data-icon',
+ 'clock',
+ );
+ });
+
+ it('renders nothing for a resolved null', () => {
+ expect(renderSlot({[COPY]: null})).toBeEmptyDOMElement();
+ });
+});
+
+describe('component icon slot types', () => {
+ it('types slot names, values, and the static view', () => {
+ expectTypeOf<ComponentIconSlotName>().toEqualTypeOf<
+ 'code-block-copy' | 'example-panel-dismiss' | 'example-nav-item-leading'
+ >();
+ expectTypeOf<ComponentIconSlotMap[typeof COPY]>().toEqualTypeOf<{
+ readonly copied: boolean;
+ }>();
+ expectTypeOf<ComponentIconMap['example-panel-dismiss']>().toEqualTypeOf<
+ IconName | null | ComponentIconRequest | undefined
+ >();
+ expectTypeOf<
+ NonNullable<DefinedTheme['componentIcons']>
+ >().toEqualTypeOf<ComponentIconStaticMap>();
+
+ defineTheme({
+ name: 'slots-types',
+ iconVariants: ['outline', 'filled'],
+ componentIcons: {
+ 'example-nav-item-leading': ({selected, disabled}) => {
+ expectTypeOf(selected).toEqualTypeOf<boolean>();
+ expectTypeOf(disabled).toEqualTypeOf<boolean>();
+ return {variant: selected ? 'filled' : 'outline'};
+ },
+ // @ts-expect-error -- a stateless slot takes no function.
+ 'example-panel-dismiss': () => ({icon: 'close'}),
+ },
+ });
+
+ defineTheme({
+ name: 'slots-types-variant',
+ iconVariants: ['outline'],
+ componentIcons: {
+ // @ts-expect-error -- 'filled' is not a name this theme lists.
+ 'example-nav-item-leading': {variant: 'filled'},
+ // @ts-expect-error -- not a shared icon name.
+ [COPY]: 'clipboard',
+ },
+ });
+
+ defineTheme({
+ name: 'slots-types-unknown',
+ componentIcons: {
+ // @ts-expect-error -- not a declared slot.
+ 'code-block-paste': 'copy',
+ },
+ });
+ });
+});
diff --git a/packages/core/src/Icon/globalIconRegistry.tsx b/packages/core/src/Icon/globalIconRegistry.tsx
index 1e496ce796..f15b486896 100644
--- a/packages/core/src/Icon/globalIconRegistry.tsx
+++ b/packages/core/src/Icon/globalIconRegistry.tsx
@@ -5,9 +5,10 @@
* @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
+ * resetIcons, resolveIcon and resolveComponentIcon (internal), IconName,
+ * IconRegistry, IconEntry, IconRequest
+ * @position Global and theme-scoped icon registry and component icon slot
+ * resolution; 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.
@@ -19,12 +20,21 @@
* its resolved size and a variant the entry can receive (listed by the active
* theme and, for a theme entry, by the theme that defined it), otherwise
* `undefined`; the public reads below pass `{size: 'md'}`.
+ *
+ * `resolveComponentIcon` is the only caller of a theme's `componentIcons`
+ * slot functions. It turns a slot, its state, and the component's own
+ * fallback into the request the component renders through `Icon`.
*/
import type {ReactNode} from 'react';
import {defaultIcons} from './defaultIcons';
import type {IconSize} from './IconSize.stylex';
-import type {IconVariant} from './index';
+import type {
+ ComponentIconRequest,
+ ComponentIconSlotMap,
+ ComponentIconSlotName,
+ IconVariant,
+} from './index';
import type {DefinedTheme} from '../theme/defineTheme';
import {getRegisteredTheme} from '../theme/themeRegistry';
import {warnOnce} from '../utils/devWarning';
@@ -392,6 +402,173 @@ export function getExtendedIcon(
);
}
+// =============================================================================
+// Component icon slots
+// =============================================================================
+
+/**
+ * A theme's stored value for a slot, function included. A function was typed
+ * for its slot's state; resolution passes it the state of that slot only.
+ */
+export type StoredComponentIconValue =
+ | IconName
+ | null
+ | ComponentIconRequest<string>
+ | ((state: never) => ComponentIconRequest<string> | null | undefined);
+
+/** The state a slot's component passes: `undefined` for a stateless slot. */
+export type ComponentIconSlotState<Slot extends ComponentIconSlotName> =
+ ComponentIconSlotMap[Slot] extends true
+ ? undefined
+ : Readonly<ComponentIconSlotMap[Slot]>;
+
+/**
+ * What a component renders for a slot when the theme maps nothing: its own
+ * icon name (or `null` for none), and optionally its own variant and size.
+ */
+export type ComponentIconFallback =
+ | IconName
+ | null
+ | Readonly<{icon: IconName | null; variant?: IconVariant; size?: IconSize}>;
+
+/** A slot resolved to what the component renders through `Icon`. */
+export type ResolvedComponentIcon = Readonly<{
+ icon: IconName | null;
+ variant?: string;
+ size?: IconSize;
+}>;
+
+const ICON_SIZES: ReadonlySet<unknown> = new Set(['xsm', 'sm', 'md', 'lg']);
+
+function isIconName(value: unknown): value is IconName {
+ return (
+ typeof value === 'string' &&
+ !isNamespacedKey(value) &&
+ Object.hasOwn(defaultIcons, value)
+ );
+}
+
+/**
+ * The theme's slot values, functions included. A theme from `defineTheme`
+ * keeps them in `__componentIcons` when any value is a function (its public
+ * `componentIcons` is the static view); otherwise `componentIcons` holds them.
+ */
+function getThemeComponentIcons(
+ theme: DefinedTheme | null,
+): Readonly<Record<string, StoredComponentIconValue | undefined>> | null {
+ if (theme == null) {
+ return null;
+ }
+ return theme.__componentIcons ?? theme.componentIcons ?? null;
+}
+
+function warnMalformedRequest(slot: string, problem: string): void {
+ warnOnce(
+ `component-icons:${slot}:${problem}`,
+ 'Icon',
+ `componentIcons["${slot}"] ${problem}. The component keeps its own value for that field.`,
+ );
+}
+
+/**
+ * Apply a theme's request to the component's fallback, field by field. A
+ * missing field keeps the fallback. An unknown icon, a variant the active
+ * theme does not list, or an unsupported size is ignored with one
+ * development-only warning.
+ */
+function applyComponentIconRequest(
+ slot: string,
+ fallback: ResolvedComponentIcon,
+ request: unknown,
+ theme: DefinedTheme | null,
+): ResolvedComponentIcon {
+ if (request === undefined) {
+ return fallback;
+ }
+ if (request === null) {
+ return {...fallback, icon: null};
+ }
+ if (typeof request !== 'object' || Array.isArray(request)) {
+ warnMalformedRequest(
+ slot,
+ `returned ${JSON.stringify(request)}, which is not a request`,
+ );
+ return fallback;
+ }
+ const {icon, variant, size} = request as Record<string, unknown>;
+ let resolved = fallback;
+ if (icon === null || isIconName(icon)) {
+ resolved = {...resolved, icon};
+ } else if (icon !== undefined) {
+ warnMalformedRequest(
+ slot,
+ `requests the unknown icon ${JSON.stringify(icon)}`,
+ );
+ }
+ if (typeof variant === 'string' && theme?.iconVariants?.includes(variant)) {
+ resolved = {...resolved, variant};
+ } else if (variant !== undefined) {
+ warnMalformedRequest(
+ slot,
+ `requests the variant ${JSON.stringify(variant)}, which the theme does not list`,
+ );
+ }
+ if (ICON_SIZES.has(size)) {
+ resolved = {...resolved, size: size as IconSize};
+ } else if (size !== undefined) {
+ warnMalformedRequest(
+ slot,
+ `requests the unsupported size ${JSON.stringify(size)}`,
+ );
+ }
+ return resolved;
+}
+
+/**
+ * Resolve a component's icon slot. The component passes its slot state and
+ * its own fallback; the active theme's `componentIcons[slot]` adjusts that
+ * fallback. A shared icon name replaces the fallback icon, `null` hides the
+ * icon, a request applies field by field, and a slot function receives the
+ * state and returns a request whose result is final: `null` hides the icon,
+ * `undefined` changes nothing.
+ *
+ * This is the only caller of a theme's slot functions. Caller-supplied icon
+ * content wins before resolution, so a component does not resolve the slot
+ * when its caller passed content.
+ * @internal
+ */
+export function resolveComponentIcon<Slot extends ComponentIconSlotName>(
+ slot: Slot,
+ state: ComponentIconSlotState<Slot>,
+ fallback: ComponentIconFallback,
+ source: IconRegistrySource,
+): ResolvedComponentIcon {
+ const own: ResolvedComponentIcon =
+ fallback === null || typeof fallback === 'string'
+ ? {icon: fallback}
+ : fallback;
+ const theme = getTheme(source);
+ const value = getThemeComponentIcons(theme)?.[slot];
+ if (value === undefined) {
+ return own;
+ }
+ if (typeof value === 'function') {
+ const result: unknown = (value as (state: unknown) => unknown)(state);
+ if (typeof result === 'string') {
+ warnMalformedRequest(
+ slot,
+ `returned ${JSON.stringify(result)}, which is not a request`,
+ );
+ return own;
+ }
+ return applyComponentIconRequest(slot, own, result, theme);
+ }
+ if (typeof value === 'string') {
+ return applyComponentIconRequest(slot, own, {icon: value}, theme);
+ }
+ return applyComponentIconRequest(slot, own, value, theme);
+}
+
/**
* Reset the global registry. For testing only.
* @internal
diff --git a/packages/core/src/Icon/index.ts b/packages/core/src/Icon/index.ts
index 08f823dfca..cd3d4aa6e2 100644
--- a/packages/core/src/Icon/index.ts
+++ b/packages/core/src/Icon/index.ts
@@ -6,13 +6,17 @@
* @file index.ts
* @input Imports Icon component/types, icon registry, and global registration
* @output Exports Icon, icon registry helpers, registerIcons, getIconRegistry, getIcon,
- * the IconEntry/IconRequest types for theme and registered entries, and the
- * augmentable IconVariantMap with its IconVariant names
+ * the IconEntry/IconRequest types for theme and registered entries, the
+ * augmentable IconVariantMap with its IconVariant names, and the augmentable
+ * ComponentIconSlotMap with the types of a theme's `componentIcons`
* @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
*/
+import type {IconName} from './globalIconRegistry';
+import type {IconSize} from './IconSize.stylex';
+
/**
* Icon variant names an application uses. Astryx defines none: a theme lists
* the names it supports in `defineTheme({iconVariants})`, and an application
@@ -37,6 +41,77 @@ export interface IconVariantMap {}
/** A variant name from the augmentable {@link IconVariantMap}. */
export type IconVariant = keyof IconVariantMap & string;
+/**
+ * The themeable icons that components own, by slot. A slot names why an icon
+ * is in one component (`<component-kebab>-<semantic-role>`), not its artwork.
+ * A theme maps a slot to a shared icon name through
+ * `defineTheme({componentIcons})`.
+ *
+ * The value is `true` for a stateless slot, or the readonly state the component
+ * passes to a theme's slot function. A package adds its own component's slots
+ * by augmenting this interface.
+ *
+ * @example
+ * ```
+ * declare module '@astryxdesign/core/Icon' {
+ * interface ComponentIconSlotMap {
+ * 'example-panel-dismiss': true;
+ * 'example-nav-item-leading': {selected: boolean};
+ * }
+ * }
+ * ```
+ */
+export interface ComponentIconSlotMap {
+ /** CodeBlock's copy button. `copied` is true while the copied feedback shows. */
+ 'code-block-copy': {readonly copied: boolean};
+}
+
+/** A slot name from the augmentable {@link ComponentIconSlotMap}. */
+export type ComponentIconSlotName = keyof ComponentIconSlotMap & string;
+
+/**
+ * A partial request for a slot's icon. A missing field keeps what the
+ * component would otherwise render: its own icon name, variant, and size.
+ * `icon: null` hides the icon. `size` changes only the icon, never the
+ * control around it.
+ */
+export type ComponentIconRequest<Variant extends string = IconVariant> =
+ Readonly<{
+ icon?: IconName | null;
+ variant?: Variant;
+ size?: IconSize;
+ }>;
+
+/**
+ * A theme's value for a slot: a shared icon name, `null` to hide the icon, a
+ * partial request, or, for a stateful slot, a pure synchronous function of the
+ * slot's state that returns a partial request. A function that returns `null`
+ * hides the icon; one that returns `undefined` changes nothing.
+ */
+export type ComponentIconValue<State, Variant extends string = IconVariant> =
+ | IconName
+ | null
+ | ComponentIconRequest<Variant>
+ | ((
+ state: Readonly<State>,
+ ) => ComponentIconRequest<Variant> | null | undefined);
+
+/** A theme's `componentIcons`: a value for any slot, keyed by slot name. */
+export type ComponentIconMap<Variant extends string = IconVariant> = {
+ [Slot in ComponentIconSlotName]?: ComponentIconSlotMap[Slot] extends true
+ ? IconName | null | ComponentIconRequest<Variant>
+ : ComponentIconValue<ComponentIconSlotMap[Slot], Variant>;
+};
+
+/**
+ * The static view of a theme's `componentIcons` that public reads return:
+ * names, `null`, and static requests. Slots a theme resolves with a function
+ * are left out.
+ */
+export type ComponentIconStaticMap = Partial<
+ Record<ComponentIconSlotName, IconName | null | ComponentIconRequest<string>>
+>;
+
export {Icon, renderIconSlot} from './Icon';
export {useIcon} from './useIcon';
export type {IconProps, IconColor, IconSize, IconType} from './Icon';
diff --git a/packages/core/src/Icon/useIcon.ts b/packages/core/src/Icon/useIcon.ts
index 668dde032c..5db6254fd6 100644
--- a/packages/core/src/Icon/useIcon.ts
+++ b/packages/core/src/Icon/useIcon.ts
@@ -4,19 +4,26 @@
/**
* @file useIcon.ts
- * @input Semantic icon name
+ * @input Semantic icon name, or a component icon slot with its state and
+ * fallback
* @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
+ * function entry is read at `{size: 'md'}`) and the internal
+ * useComponentIcon hook that resolves a slot from the nearest Theme
+ * @position Client hooks for components that render registry icons directly
*/
import type {ReactNode} from 'react';
import {useThemeName} from '../theme/useTheme';
import {
getIcon,
+ resolveComponentIcon,
+ type ComponentIconFallback,
+ type ComponentIconSlotState,
type IconName,
type NamespacedIconName,
+ type ResolvedComponentIcon,
} from './globalIconRegistry';
+import type {ComponentIconSlotName} from './index';
/**
* Resolve a semantic icon name from the nearest Theme, falling back through
@@ -32,3 +39,17 @@ export function useIcon(name: IconName | NamespacedIconName): ReactNode {
const themeName = useThemeName();
return getIcon(name, themeName);
}
+
+/**
+ * Resolve a component icon slot from the nearest Theme: the theme's
+ * `componentIcons[slot]` applied to the component's own fallback.
+ * @internal
+ */
+export function useComponentIcon<Slot extends ComponentIconSlotName>(
+ slot: Slot,
+ state: ComponentIconSlotState<Slot>,
+ fallback: ComponentIconFallback,
+): ResolvedComponentIcon {
+ const themeName = useThemeName();
+ return resolveComponentIcon(slot, state, fallback, themeName);
+}
diff --git a/packages/core/src/theme/defineTheme.ts b/packages/core/src/theme/defineTheme.ts
index f5e8db526d..d2e4546f9c 100644
--- a/packages/core/src/theme/defineTheme.ts
+++ b/packages/core/src/theme/defineTheme.ts
@@ -44,7 +44,9 @@ import type {
IconEntry,
IconName,
NamespacedIconName,
+ StoredComponentIconValue,
} from '../Icon/globalIconRegistry';
+import type {ComponentIconMap, ComponentIconStaticMap} from '../Icon/index';
/**
* Icon overrides a theme may declare: any built-in semantic name, plus the
@@ -448,6 +450,32 @@ export interface DefineThemeInput<
* ```
*/
iconVariants?: IconVariants;
+ /**
+ * Component icon slots — which shared icon a component's own icon role
+ * uses, separate from `icons`, which chooses the artwork for each shared
+ * name. Keys are the slots in `ComponentIconSlotMap`, such as
+ * `code-block-copy`.
+ *
+ * A value is a shared icon name, `null` to hide the icon, a partial request
+ * of `icon`, `variant`, and `size`, or, for a slot with state, a pure
+ * synchronous function of that state that returns a request. A missing
+ * request field keeps the component's own value; a function that returns
+ * `null` hides the icon and one that returns `undefined` changes nothing.
+ * A request `size` changes only the icon, never the control around it.
+ * `variant` is typed as the names in `iconVariants` (or the inherited
+ * list).
+ *
+ * An entry replaces the inherited entry for the same slot whole; an omitted
+ * or `undefined` entry is inherited.
+ *
+ * @example
+ * ```
+ * componentIcons: {
+ * 'code-block-copy': ({copied}) => ({icon: copied ? 'checkDouble' : 'copy'}),
+ * },
+ * ```
+ */
+ componentIcons?: ComponentIconMap<ThemeIconEntryVariant<IconVariants, Base>>;
/**
* Indicator overrides — replaces the components that draw stateful control
* visuals with the theme's own, by name.
@@ -560,6 +588,18 @@ export interface DefinedTheme {
* @internal
*/
__iconEntryVariants?: Record<string, ReadonlyArray<string> | undefined>;
+ /**
+ * Component icon slots as a static view: names, `null`, and static
+ * requests. Slots the theme resolves with a function are left out; the
+ * component's slot resolution calls them with its state.
+ */
+ componentIcons?: ComponentIconStaticMap;
+ /**
+ * Component icon slot values with their functions, present when any value
+ * is a function. Only component slot resolution reads it.
+ * @internal
+ */
+ __componentIcons?: Partial<Record<string, StoredComponentIconValue>>;
/** Indicator overrides for stateful control visuals, keyed by name */
indicators?: IndicatorRegistry;
/** Whether this theme has been pre-compiled by theme build CLI */
@@ -868,6 +908,14 @@ export function defineTheme<
iconVariants,
);
+ // The base's static `componentIcons` view omits its slot functions, so read
+ // its `__componentIcons` first.
+ const componentIconValues = mergeComponentIcons(
+ base?.__componentIcons ?? base?.componentIcons,
+ input.componentIcons,
+ );
+ const componentIcons = staticComponentIcons(componentIconValues);
+
// Indicator overrides merge by name, like icons: a child theme replacing one
// indicator keeps the ones its base replaced.
const indicators =
@@ -892,6 +940,10 @@ export function defineTheme<
...(iconEntryVariants !== undefined
? {__iconEntryVariants: iconEntryVariants}
: {}),
+ ...(componentIcons !== undefined ? {componentIcons} : {}),
+ ...(componentIcons !== componentIconValues
+ ? {__componentIcons: componentIconValues}
+ : {}),
indicators,
__inputTokens:
base?.__inputTokens || input.tokens
@@ -943,6 +995,51 @@ function resolveIconEntryVariants(
return record;
}
+/**
+ * A theme's slot values: the base's, then this theme's own, by slot. An own
+ * entry replaces the inherited one whole; an `undefined` entry is omitted, so
+ * the inherited one stays.
+ */
+function mergeComponentIcons(
+ inherited: Partial<Record<string, StoredComponentIconValue>> | undefined,
+ own: object | undefined,
+): Partial<Record<string, StoredComponentIconValue>> | undefined {
+ if (own == null) {
+ return inherited;
+ }
+ const merged: Partial<Record<string, StoredComponentIconValue>> = {
+ ...inherited,
+ };
+ for (const [slot, value] of Object.entries(own)) {
+ if (value !== undefined) {
+ merged[slot] = value as StoredComponentIconValue;
+ }
+ }
+ return merged;
+}
+
+/**
+ * The static view of a theme's slot values, without its slot functions.
+ * Values without a function are returned as the same object.
+ */
+function staticComponentIcons(
+ values: Partial<Record<string, StoredComponentIconValue>> | undefined,
+): ComponentIconStaticMap | undefined {
+ if (
+ values == null ||
+ !Object.values(values).some(value => typeof value === 'function')
+ ) {
+ return values;
+ }
+ const view: Partial<Record<string, StoredComponentIconValue>> = {};
+ for (const [slot, value] of Object.entries(values)) {
+ if (typeof value !== 'function') {
+ view[slot] = value;
+ }
+ }
+ return view;
+}
+
/**
* 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.