Skip to content

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

TypeScript

feat(theme): a theme lists its icon variant names once (#8756)

Xinzi Zhoudae17473034c
diff --git a/.changeset/ast-087-icon-variant-list.md b/.changeset/ast-087-icon-variant-list.md
new file mode 100644
index 0000000000..0453b9b5e8
--- /dev/null
+++ b/.changeset/ast-087-icon-variant-list.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+'@astryxdesign/cli': patch
+---
+
+[feat] A theme lists the icon variant names it supports once with `defineTheme({iconVariants})`, and reads them back from `theme.iconVariants`. A child theme that sets the list replaces the inherited one; a child that omits it inherits it. `astryx theme build` keeps the list in the built theme, so a theme extending a built theme inherits it too. Inside `defineTheme`, icon entry functions receive `variant` typed as the theme's listed names. `@astryxdesign/core/Icon` exports the augmentable `IconVariantMap` and its `IconVariant` names, which type `variant` in `registerIcons()` entries. Themes without `iconVariants` are unchanged.
+@imdreamrunner
diff --git a/packages/cli/api/theme/build/build.adaptation-enrollment.test.mjs b/packages/cli/api/theme/build/build.adaptation-enrollment.test.mjs
index c3afbf67cb..adfa0a537d 100644
--- a/packages/cli/api/theme/build/build.adaptation-enrollment.test.mjs
+++ b/packages/cli/api/theme/build/build.adaptation-enrollment.test.mjs
@@ -86,6 +86,10 @@ describe('values the root accepts without enrollment are accepted rule-only', ()
// case. It must NOT be an adaptation-specific exception; it is simply
// whatever root does.
['an unresolved domain', 'avatar-group', 'size:not-a-real-avatar-size'],
+ // `IconVariantMap` is public and augmentable, but `Icon.variant` selects
+ // artwork and has no component styling map (component-theming-surface
+ // INV14), so a styling key on it never enrolls a value.
+ ['an artwork-request axis', 'icon', 'variant:filled'],
])('accepts %s on both surfaces', async (_label, component, key) => {
const rootReceipt = await buildWithRootValue('root-ok', component, key);
expect(rootReceipt?.type).toBe('theme.build');
diff --git a/packages/cli/api/theme/build/build.icon-variants.test.mjs b/packages/cli/api/theme/build/build.icon-variants.test.mjs
new file mode 100644
index 0000000000..1b5ec8a6e2
--- /dev/null
+++ b/packages/cli/api/theme/build/build.icon-variants.test.mjs
@@ -0,0 +1,105 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file A built theme keeps its `iconVariants` list.
+ *
+ * `architecture:theme-compilation` (System model item 7): a built theme carries
+ * its `iconVariants` list in its JavaScript, so the built theme, and a theme
+ * that `extends` it, read the same list as the runtime theme
+ * (`spec:AST-087` FR2, FR18).
+ *
+ * `themeBuild` compiles via @astryxdesign/core, so it needs a built core — the
+ * `node` project's globalSetup builds it once before workers fork.
+ */
+
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import {pathToFileURL} from 'node:url';
+import {defineTheme} from '@astryxdesign/core/theme';
+import {themeBuild} from './build.mjs';
+
+vi.setConfig({testTimeout: 30000});
+
+let tmpDir;
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-icon-variants-'));
+});
+afterEach(() => {
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+/**
+ * Build a raw theme source and import the generated module's theme.
+ * @param {Record<string, unknown>} source
+ */
+async function buildAndImport(source) {
+ const name = String(source.name);
+ fs.writeFileSync(
+ path.join(tmpDir, `${name}.mjs`),
+ `export default ${JSON.stringify({tokens: {}, ...source})};\n`,
+ );
+ await themeBuild(`${name}.mjs`, {}, {cwd: tmpDir});
+ const mod = await import(pathToFileURL(path.join(tmpDir, `${name}.js`)).href);
+ const [theme] = Object.values(mod);
+ return /** @type {any} */ (theme);
+}
+
+describe('theme build keeps the iconVariants list', () => {
+ it('writes the list a theme sets, as the runtime theme reads it', async () => {
+ const source = {name: 'listed-icons', iconVariants: ['outline', 'filled']};
+ const built = await buildAndImport(source);
+
+ expect(built.__built).toBe(true);
+ expect(built.iconVariants).toEqual(['outline', 'filled']);
+ expect(built.iconVariants).toEqual(defineTheme(source).iconVariants);
+ });
+
+ it('lets a child of the built theme inherit or replace the list, as at runtime', async () => {
+ const source = {name: 'base-icons', iconVariants: ['outline', 'filled']};
+ const built = await buildAndImport(source);
+ const runtime = defineTheme(source);
+
+ const inherits = defineTheme({name: 'inherits', extends: built});
+ const replaces = defineTheme({
+ name: 'replaces',
+ extends: built,
+ iconVariants: ['bold'],
+ });
+
+ expect(inherits.iconVariants).toEqual(['outline', 'filled']);
+ expect(replaces.iconVariants).toEqual(['bold']);
+ expect(inherits.iconVariants).toEqual(
+ defineTheme({name: 'inherits-runtime', extends: runtime}).iconVariants,
+ );
+ expect(replaces.iconVariants).toEqual(
+ defineTheme({
+ name: 'replaces-runtime',
+ extends: runtime,
+ iconVariants: ['bold'],
+ }).iconVariants,
+ );
+ });
+
+ it('keeps an explicit empty list, which replaces an inherited one', async () => {
+ const built = await buildAndImport({
+ name: 'emptied-icons',
+ iconVariants: [],
+ });
+
+ expect(built.iconVariants).toEqual([]);
+ expect(
+ defineTheme({name: 'emptied-child', extends: built}).iconVariants,
+ ).toEqual([]);
+ });
+
+ it('writes no list for a theme without one', async () => {
+ const built = await buildAndImport({name: 'unlisted-icons'});
+
+ expect('iconVariants' in built).toBe(false);
+ expect(
+ defineTheme({name: 'unlisted-child', extends: built}).iconVariants,
+ ).toBeUndefined();
+ });
+});
diff --git a/packages/cli/api/theme/build/build.mjs b/packages/cli/api/theme/build/build.mjs
index 8c0f2af656..28a9082952 100644
--- a/packages/cli/api/theme/build/build.mjs
+++ b/packages/cli/api/theme/build/build.mjs
@@ -1103,6 +1103,28 @@ function componentHasAugmentableInterface(pascalName, interfaceName) {
return re.test(decl);
}
+/**
+ * Public augmentable maps whose axis requests artwork instead of styling.
+ * `Icon.variant` selects a theme's icon artwork, so it has no component styling
+ * map (architecture:component-theming-surface INV14): a `components` key on it
+ * never enrolls a value or generates an augmentation of its map.
+ */
+const ARTWORK_REQUEST_MAPS = new Set(['IconVariantMap']);
+
+/**
+ * Whether a theme's component styling keys may enroll values in `interfaceName`
+ * on `@astryxdesign/core/<Component>`.
+ * @param {string} pascalName
+ * @param {string} interfaceName
+ * @returns {boolean}
+ */
+function isComponentValueAugmentationPoint(pascalName, interfaceName) {
+ return (
+ !ARTWORK_REQUEST_MAPS.has(interfaceName) &&
+ componentHasAugmentableInterface(pascalName, interfaceName)
+ );
+}
+
/**
* Adaptation values from resolved runtime rules, raw input, or normalized built
* metadata. Built modules intentionally omit `__adaptationRules`, so every CLI
@@ -1410,7 +1432,7 @@ async function classifyComponentValue(component, prop, value) {
const propPascal = prop.charAt(0).toUpperCase() + prop.slice(1);
const target = (await resolveAugmentationTargetCandidates(component)).find(
candidate =>
- componentHasAugmentableInterface(
+ isComponentValueAugmentationPoint(
candidate.moduleName,
`${candidate.interfacePrefix}${propPascal}Map`,
),
@@ -1567,7 +1589,7 @@ async function generateVariantDeclarationsAsync(themeDef) {
const target = (
await resolveAugmentationTargetCandidates(component)
).find(candidate =>
- componentHasAugmentableInterface(
+ isComponentValueAugmentationPoint(
candidate.moduleName,
`${candidate.interfacePrefix}${propPascal}Map`,
),
@@ -2151,7 +2173,9 @@ function generateBuiltModule(
serializeField('__onDark', themeDef.__onDark) +
serializeField('__onLight', themeDef.__onLight) +
serializeField('__adaptations', themeDef.__adaptations) +
- serializeField('__axes', themeDef.__axes ?? {}, true);
+ serializeField('__axes', themeDef.__axes ?? {}, true) +
+ // An explicit empty list replaces an inherited one, so keep `[]`.
+ serializeField('iconVariants', themeDef.iconVariants, true);
return `${iconImport}${iconDeclaration}/**
* ${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 4d0eb5daff..7592b1872b 100644
--- a/packages/cli/assets/docs/author-a-theme.doc.mjs
+++ b/packages/cli/assets/docs/author-a-theme.doc.mjs
@@ -55,6 +55,7 @@ export const docs = {
['tokens', 'Base tokens are copied first, then child tokens override on top.'],
['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.'],
['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."],
diff --git a/packages/cli/assets/docs/icons.doc.mjs b/packages/cli/assets/docs/icons.doc.mjs
index 8ce3939357..8b906e410a 100644
--- a/packages/cli/assets/docs/icons.doc.mjs
+++ b/packages/cli/assets/docs/icons.doc.mjs
@@ -126,6 +126,53 @@ export const brandTheme = defineTheme({
},
],
},
+ {
+ title: 'Icon Variants',
+ category: 'foundations',
+ content: [
+ {
+ type: 'prose',
+ text: "A theme lists the icon variant names it supports once, with `iconVariants` in `defineTheme()`. The list belongs to the whole theme, never to one icon, and Astryx defines no names of its own. Inside `defineTheme`, an entry function receives `variant` typed as the listed names, or `undefined`, so a misspelled name is a type error. An entry that receives `undefined` draws its normal artwork.",
+ },
+ {
+ type: 'code',
+ lang: 'tsx',
+ label: 'Listing variants and mapping them to artwork',
+ code: `import {defineTheme} from '@astryxdesign/core/theme';
+import {InfoFilledIcon, InfoIcon} from './brand-icons';
+
+export const brandTheme = defineTheme({
+ name: 'brand',
+ iconVariants: ['outline', 'filled'],
+ icons: {
+ info: ({size, variant}) =>
+ variant === 'filled' ? <InfoFilledIcon /> : <InfoIcon bold={size === 'sm'} />,
+ },
+});
+
+brandTheme.iconVariants; // ['outline', 'filled']`,
+ },
+ {
+ type: 'prose',
+ text: 'A theme that `extends` another inherits its list unless it sets its own; a list it sets replaces the inherited one instead of merging with it.',
+ },
+ {
+ type: 'prose',
+ text: 'An application declares the variant names it uses by augmenting `IconVariantMap` from `@astryxdesign/core/Icon`. `IconVariant` is those names, and an entry passed to `registerIcons()` receives `variant` typed as `IconVariant`.',
+ },
+ {
+ type: 'code',
+ lang: 'ts',
+ label: 'Declaring the variant names an application uses',
+ code: `declare module '@astryxdesign/core/Icon' {
+ interface IconVariantMap {
+ outline: true;
+ filled: true;
+ }
+}`,
+ },
+ ],
+ },
{
title: 'Component and Library Icons',
category: 'foundations',
diff --git a/packages/cli/assets/theme.template.ts b/packages/cli/assets/theme.template.ts
index 6f5f2b78f5..dfa1aeaa76 100644
--- a/packages/cli/assets/theme.template.ts
+++ b/packages/cli/assets/theme.template.ts
@@ -321,6 +321,15 @@ export const myTheme = defineTheme({
*/
// icons: {check: <MyCheck />, info: ({size}) => <MyInfo bold={size === 'sm'} />},
+ /**
+ * The icon variant names this theme supports, listed once for the whole
+ * theme. An icon entry function receives `variant` typed as these names.
+ * A theme that sets the list replaces the one it would inherit; omit it to
+ * inherit the base's list.
+ * Reference: `astryx docs icons`.
+ */
+ // iconVariants: ['outline', 'filled'],
+
/**
* 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/test/__golden__/no-icon-set/docs-topics.json b/packages/cli/test/__golden__/no-icon-set/docs-topics.json
index dc1658e90b..4e2566d15f 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": "eff6b78c23d611da7d40a9534e421236f5e6fc1f6367d47d6ee02ef76c5a3229",
+ "skeleton": "74ad4592579fdeb35ec1e46f2788da77d6087c2fb852607680db1d88e3a809b6",
"mentions": []
},
"browser-support": {
@@ -160,9 +160,10 @@
"available-names",
"custom-icons",
"theme-overrides",
+ "icon-variants",
"component-and-library-icons"
],
- "skeleton": "5d8a54e271cc1aa84302b2b101820eba3ae1b674f3ef87767fb356939464e097",
+ "skeleton": "93430a3f9039a2f8bcf20d0873a6d6a3679096f399bfa493a81083fba92ee908",
"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 973dbe84a4..718f0f660f 100644
--- a/packages/cli/test/__golden__/no-icon-set/docs-tree.json
+++ b/packages/cli/test/__golden__/no-icon-set/docs-tree.json
@@ -904,6 +904,7 @@
"available-names",
"custom-icons",
"theme-overrides",
+ "icon-variants",
"component-and-library-icons"
],
"mentions": [
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 996e30d2e0..c862b58236 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": 369,
+ "matchCount": 370,
"results": [
{
"domain": "doc",
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 d7c74d2679..a888cb11f6 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 369)
+Results for "icon set" (20 of 370)
name: authoring/building-blocks/templates/build-the-template/template-assets/template-icons
section: use-astryx-icon
domain: doc
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 67a674f40e..cc9a6d0eb9 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": 222,
+ "matchCount": 223,
"results": [
{
"domain": "component",
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 aa160626ff..ecaabe65ac 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 222)
+Results for "icon" (20 of 223)
name: Icon
domain: component
package: @astryxdesign/core
diff --git a/packages/core/src/Icon/globalIconRegistry.test.tsx b/packages/core/src/Icon/globalIconRegistry.test.tsx
index 16ac5409be..1eb303ea88 100644
--- a/packages/core/src/Icon/globalIconRegistry.test.tsx
+++ b/packages/core/src/Icon/globalIconRegistry.test.tsx
@@ -29,8 +29,18 @@ import {
} from './globalIconRegistry';
import {Icon} from './Icon';
import type {IconSize} from './IconSize.stylex';
+import type {IconVariant, IconVariantMap} from './index';
import {useIcon} from './useIcon';
+// An application augments the public map with the variant names it requests
+// (spec:AST-087 FR3).
+declare module './index' {
+ interface IconVariantMap {
+ outline: true;
+ filled: true;
+ }
+}
+
describe('iconRegistry (global, RSC-compatible)', () => {
beforeEach(() => {
resetIcons();
@@ -464,7 +474,7 @@ describe('iconRegistry (global, RSC-compatible)', () => {
NonNullable<DefinedTheme['icons']>['info']
>().toEqualTypeOf<ReactNode>();
expectTypeOf<IconRequest>().toEqualTypeOf<
- Readonly<{size: IconSize; variant?: undefined}>
+ Readonly<{size: IconSize; variant?: IconVariant}>
>();
expectTypeOf<IconEntry>().toEqualTypeOf<
ReactNode | ((request: IconRequest) => ReactNode)
@@ -489,5 +499,46 @@ describe('iconRegistry (global, RSC-compatible)', () => {
});
});
});
+
+ describe('variant names', () => {
+ it('types a process-wide entry by the augmentable IconVariantMap', () => {
+ expectTypeOf<IconVariant>().toEqualTypeOf<
+ keyof IconVariantMap & string
+ >();
+ expectTypeOf<IconVariant>().toEqualTypeOf<'outline' | 'filled'>();
+
+ registerIcons({
+ info: ({variant}) => {
+ expectTypeOf(variant).toEqualTypeOf<
+ 'outline' | 'filled' | undefined
+ >();
+ return variant === 'filled' ? 'global-info-filled' : 'global-info';
+ },
+ close: ({variant}) =>
+ // @ts-expect-error — 'bold' is not an augmented variant name.
+ variant === 'bold' ? 'bold-close' : 'close',
+ });
+ });
+
+ it('passes no variant to an entry, so it draws its normal artwork', () => {
+ const info = vi.fn(({variant}: IconRequest) =>
+ variant === 'filled' ? 'filled-info' : 'normal-info',
+ );
+ registerIcons({info});
+ const theme = defineTheme({
+ name: 'fn-listed',
+ iconVariants: ['outline', 'filled'],
+ icons: {close: info},
+ });
+
+ expect(resolveIcon('info', theme, {size: 'sm'})).toBe('normal-info');
+ expect(resolveIcon('close', theme, {size: 'sm'})).toBe('normal-info');
+ expect(getIcon('close', theme)).toBe('normal-info');
+ expect(info).toHaveBeenCalled();
+ for (const [request] of info.mock.calls) {
+ expect(request.variant).toBeUndefined();
+ }
+ });
+ });
});
});
diff --git a/packages/core/src/Icon/globalIconRegistry.tsx b/packages/core/src/Icon/globalIconRegistry.tsx
index 273661d375..1bf89fe458 100644
--- a/packages/core/src/Icon/globalIconRegistry.tsx
+++ b/packages/core/src/Icon/globalIconRegistry.tsx
@@ -22,6 +22,7 @@
import type {ReactNode} from 'react';
import {defaultIcons} from './defaultIcons';
import type {IconSize} from './IconSize.stylex';
+import type {IconVariant} from './index';
import type {DefinedTheme} from '../theme/defineTheme';
import {getRegisteredTheme} from '../theme/themeRegistry';
import {warnOnce} from '../utils/devWarning';
@@ -100,13 +101,15 @@ 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'`.
+ * explicit `size` → owning component's default → `'md'`, and a variant name
+ * or `undefined`.
*
- * `variant` is always `undefined` here.
+ * Inside `defineTheme`, `Variant` is the theme's listed `iconVariants`; a
+ * process-wide registration receives {@link IconVariant}.
*/
-export type IconRequest = Readonly<{
+export type IconRequest<Variant extends string = IconVariant> = Readonly<{
size: IconSize;
- variant?: undefined;
+ variant?: Variant;
}>;
/**
@@ -128,18 +131,25 @@ export type IconRequest = Readonly<{
* });
* ```
*/
-export type IconEntry = ReactNode | ((request: IconRequest) => ReactNode);
+export type IconEntry<Variant extends string = IconVariant> =
+ ReactNode | ((request: IconRequest<Variant>) => ReactNode);
+
+/**
+ * How resolution holds any entry: an entry typed for some variant names
+ * accepts a request with none of them.
+ */
+type StoredIconEntry = IconEntry<never>;
export type IconRegistrySource = DefinedTheme | string | null | undefined;
/** The request every public, one-argument read uses. */
-const PUBLIC_READ_REQUEST: IconRequest = {size: 'md'};
+const PUBLIC_READ_REQUEST: IconRequest<never> = {size: 'md'};
// =============================================================================
// Global Registry
// =============================================================================
-let globalRegistry: Record<string, IconEntry> = {};
+let globalRegistry: Record<string, StoredIconEntry> = {};
/**
* A key is namespaced when it carries a `<namespace>:` prefix — the runtime
@@ -158,7 +168,7 @@ function isNamespacedKey(name: string): boolean {
*/
function getThemeIconEntries(
source: IconRegistrySource,
-): Readonly<Record<string, IconEntry>> | null {
+): Readonly<Record<string, StoredIconEntry>> | null {
const theme =
typeof source === 'string' ? getRegisteredTheme(source) : source;
if (theme == null) {
@@ -177,7 +187,7 @@ function selectIconEntry(
name: string,
source: IconRegistrySource,
fallback?: ReactNode,
-): IconEntry {
+): StoredIconEntry {
return (
getThemeIconEntries(source)?.[name] ??
globalRegistry[name] ??
@@ -187,7 +197,10 @@ function selectIconEntry(
}
/** Read an entry for a request: call a function, return a node as-is. */
-function readIconEntry(entry: IconEntry, request: IconRequest): ReactNode {
+function readIconEntry(
+ entry: StoredIconEntry,
+ request: IconRequest<never>,
+): ReactNode {
return typeof entry === 'function' ? entry(request) : entry;
}
@@ -199,7 +212,7 @@ function readIconEntry(entry: IconEntry, request: IconRequest): ReactNode {
export function resolveIcon(
name: ExtendedIconName,
source: IconRegistrySource,
- request: IconRequest,
+ request: IconRequest<never>,
): ReactNode {
return readIconEntry(selectIconEntry(name, source), request);
}
diff --git a/packages/core/src/Icon/index.ts b/packages/core/src/Icon/index.ts
index 0059ce36c8..08f823dfca 100644
--- a/packages/core/src/Icon/index.ts
+++ b/packages/core/src/Icon/index.ts
@@ -6,12 +6,37 @@
* @file index.ts
* @input Imports Icon component/types, icon registry, and global registration
* @output Exports Icon, icon registry helpers, registerIcons, getIconRegistry, getIcon,
- * and the IconEntry/IconRequest types for theme and registered entries
+ * the IconEntry/IconRequest types for theme and registered entries, and the
+ * augmentable IconVariantMap with its IconVariant names
* @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
*/
+/**
+ * Icon variant names an application uses. Astryx defines none: a theme lists
+ * the names it supports in `defineTheme({iconVariants})`, and an application
+ * augments this map with the names it requests.
+ *
+ * A theme icon entry receives a requested variant only when the active theme
+ * lists it; any other request renders the entry's normal artwork.
+ *
+ * @example
+ * ```
+ * declare module '@astryxdesign/core/Icon' {
+ * interface IconVariantMap {
+ * outline: true;
+ * filled: true;
+ * }
+ * }
+ * ```
+ */
+// eslint-disable-next-line @typescript-eslint/no-empty-object-type -- augmentation point
+export interface IconVariantMap {}
+
+/** A variant name from the augmentable {@link IconVariantMap}. */
+export type IconVariant = keyof IconVariantMap & string;
+
export {Icon, renderIconSlot} from './Icon';
export {useIcon} from './useIcon';
export type {IconProps, IconColor, IconSize, IconType} from './Icon';
diff --git a/packages/core/src/theme/defineTheme.test.ts b/packages/core/src/theme/defineTheme.test.ts
index b59751f38e..a657b6e7a6 100644
--- a/packages/core/src/theme/defineTheme.test.ts
+++ b/packages/core/src/theme/defineTheme.test.ts
@@ -1,8 +1,12 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-import {describe, it, expect, vi} from 'vitest';
+import {describe, it, expect, expectTypeOf, vi} from 'vitest';
import type {IconRegistry} from '../Icon/globalIconRegistry';
-import type {DefinedTheme} from './defineTheme';
+import type {
+ DefinedTheme,
+ DefineThemeInput,
+ ResolvedDefinedTheme,
+} from './defineTheme';
import {
defineTheme,
generateThemeCSS,
@@ -1668,6 +1672,180 @@ describe('defineTheme extends', () => {
expect(child.icons?.close).toBe('X');
});
+ // spec:AST-087 FR2, FR3, FR18 — one theme-level list; a child that sets it
+ // replaces the inherited list, one that omits it inherits; entry functions
+ // receive `variant` typed as the theme's listed names.
+ describe('iconVariants', () => {
+ it('keeps the listed names on the defined theme', () => {
+ const list = ['outline', 'filled'];
+ const theme = defineTheme({name: 'variants', iconVariants: list});
+
+ expect(theme.iconVariants).toEqual(['outline', 'filled']);
+ list.push('bold');
+ expect(theme.iconVariants).toEqual(['outline', 'filled']);
+ });
+
+ it('has no list when no theme in the lineage sets one', () => {
+ const base = defineTheme({name: 'no-variants'});
+ const child = defineTheme({name: 'no-variants-child', extends: base});
+
+ expect(base.iconVariants).toBeUndefined();
+ expect('iconVariants' in base).toBe(false);
+ expect(child.iconVariants).toBeUndefined();
+ });
+
+ it('inherits the base list when a child omits it', () => {
+ const base = defineTheme({
+ name: 'variants-base',
+ iconVariants: ['outline', 'filled'],
+ });
+ const child = defineTheme({name: 'variants-inherit', extends: base});
+
+ expect(child.iconVariants).toEqual(['outline', 'filled']);
+ });
+
+ it('replaces the base list, without merging, when a child sets it', () => {
+ const base = defineTheme({
+ name: 'variants-base',
+ iconVariants: ['outline', 'filled'],
+ });
+ const child = defineTheme({
+ name: 'variants-replace',
+ extends: base,
+ iconVariants: ['bold'],
+ });
+ const emptied = defineTheme({
+ name: 'variants-empty',
+ extends: base,
+ iconVariants: [],
+ });
+
+ expect(child.iconVariants).toEqual(['bold']);
+ expect(emptied.iconVariants).toEqual([]);
+ expect(base.iconVariants).toEqual(['outline', 'filled']);
+ });
+
+ it('types entry functions by the listed names', () => {
+ const base = defineTheme({
+ name: 'variants-typed',
+ iconVariants: ['outline', 'filled'],
+ icons: {
+ info: ({size, variant}) => {
+ expectTypeOf(variant).toEqualTypeOf<
+ 'outline' | 'filled' | undefined
+ >();
+ return `${size}-${variant ?? 'normal'}`;
+ },
+ close: ({variant}) =>
+ // @ts-expect-error — 'bold' is not a name this theme lists.
+ variant === 'bold' ? 'bold-close' : 'close',
+ },
+ });
+ expectTypeOf(base).toEqualTypeOf<
+ ResolvedDefinedTheme<'outline' | 'filled'>
+ >();
+
+ defineTheme({
+ name: 'variants-typed-inherit',
+ extends: base,
+ icons: {
+ info: ({variant}) => {
+ expectTypeOf(variant).toEqualTypeOf<
+ 'outline' | 'filled' | undefined
+ >();
+ return null;
+ },
+ },
+ });
+
+ defineTheme({
+ name: 'variants-typed-replace',
+ extends: base,
+ iconVariants: ['bold'],
+ icons: {
+ info: ({variant}) => {
+ expectTypeOf(variant).toEqualTypeOf<'bold' | undefined>();
+ return null;
+ },
+ close: ({variant}) =>
+ // @ts-expect-error — the child replaced the list; 'filled' is gone.
+ variant === 'filled' ? 'filled-close' : 'close',
+ },
+ });
+
+ defineTheme({
+ name: 'variants-typed-none',
+ icons: {
+ info: ({variant}) => {
+ expectTypeOf(variant).toEqualTypeOf<undefined>();
+ return null;
+ },
+ },
+ });
+
+ const plainBase: DefinedTheme = base;
+ defineTheme({
+ name: 'variants-typed-plain-base',
+ extends: plainBase,
+ icons: {
+ info: ({variant}) => {
+ expectTypeOf(variant).toEqualTypeOf<string | undefined>();
+ return null;
+ },
+ },
+ });
+
+ expectTypeOf<DefinedTheme['iconVariants']>().toEqualTypeOf<
+ ReadonlyArray<string> | undefined
+ >();
+ });
+
+ it('keeps resolved themes with and without lists assignable to each other', () => {
+ const shared: DefineThemeInput = {name: 'variants-shared'};
+ const unlisted = defineTheme({name: 'variants-active'});
+ // Each annotation is the check: these assignments compiled before
+ // iconVariants existed and must keep compiling.
+ const fromShared: typeof unlisted = defineTheme(shared);
+ const fromListed: typeof unlisted = defineTheme({
+ name: 'variants-listed-active',
+ iconVariants: ['outline'],
+ });
+ const listed = defineTheme({
+ name: 'variants-listed',
+ iconVariants: ['outline', 'filled'],
+ });
+ const fromUnlisted: typeof listed = defineTheme({
+ name: 'variants-unlisted',
+ });
+ const resolved: ResolvedDefinedTheme = fromUnlisted;
+
+ expect(
+ [unlisted, fromShared, fromListed, listed, resolved].map(t => t.name),
+ ).toEqual([
+ 'variants-active',
+ 'variants-shared',
+ 'variants-listed-active',
+ 'variants-listed',
+ 'variants-unlisted',
+ ]);
+ });
+
+ it('passes no variant to entry functions', () => {
+ const info = vi.fn(
+ ({size, variant}: {size: string; variant?: string}) =>
+ `${size}-${variant ?? 'normal'}`,
+ );
+ const theme = defineTheme({
+ name: 'variants-no-request',
+ iconVariants: ['outline', 'filled'],
+ icons: {info},
+ });
+
+ expect(theme.icons?.info).toBe('md-normal');
+ expect(info).toHaveBeenCalledWith({size: 'md'});
+ });
+ });
+
it('merges function icon entries by key and reads them at md', () => {
const base = defineTheme({
name: 'base',
diff --git a/packages/core/src/theme/defineTheme.ts b/packages/core/src/theme/defineTheme.ts
index fc1fbafa17..32e6dcbf40 100644
--- a/packages/core/src/theme/defineTheme.ts
+++ b/packages/core/src/theme/defineTheme.ts
@@ -49,12 +49,48 @@ import type {
/**
* Icon overrides a theme may declare: any built-in semantic name, plus the
* namespaced keys components and libraries own (`'richtext:bold'`). Each entry
- * is a React node or a pure synchronous function of `{size, variant}`.
+ * is a React node or a pure synchronous function of `{size, variant}`, where
+ * `variant` is one of `Variant` or `undefined`.
*/
-type ThemeIconEntries = Partial<
- Record<IconName | NamespacedIconName, IconEntry>
+type ThemeIconEntries<Variant extends string> = Partial<
+ Record<IconName | NamespacedIconName, IconEntry<Variant>>
>;
+/**
+ * The variant names a base theme lists: exact for a theme from `defineTheme`,
+ * any string for another `DefinedTheme`, none without a base.
+ */
+type BaseThemeIconVariant<Base> = Base extends DefinedTheme
+ ? '__iconVariant' extends keyof Base
+ ? Base extends {name: string; __iconVariant?(variant: infer Variant): void}
+ ? Extract<Variant, string>
+ : string
+ : string
+ : never;
+
+/**
+ * The variant names a theme lists: its own `iconVariants` when it sets the
+ * field, otherwise the list it inherits from `extends`.
+ */
+type ThemeIconVariant<
+ IconVariants extends ReadonlyArray<string> | undefined,
+ Base,
+> = [IconVariants] extends [ReadonlyArray<infer Variant extends string>]
+ ? Variant
+ : BaseThemeIconVariant<Base>;
+
+/**
+ * The same names, as a type `defineTheme` does not infer from: only
+ * `iconVariants` and `extends` decide a theme's names, never the parameter
+ * types of its icon entry functions.
+ */
+type ThemeIconEntryVariant<
+ IconVariants extends ReadonlyArray<string> | undefined,
+ Base,
+> = [ThemeIconVariant<IconVariants, Base>][IconVariants extends unknown
+ ? 0
+ : never];
+
/** The node-valued view of a theme's icons that public reads return. */
type ThemeIconOverrides = Partial<
Record<IconName | NamespacedIconName, ReactNode>
@@ -192,8 +228,18 @@ export type StyleOverrides = Record<string, string | Record<string, string>>;
*/
export type ComponentStyleMap = Record<string, Record<string, StyleOverrides>>;
-/** Input to defineTheme */
-export interface DefineThemeInput {
+/**
+ * Input to defineTheme.
+ *
+ * `IconVariants` is the theme's own `iconVariants` list and `Base` its
+ * `extends` theme; together they type the `variant` an icon entry function
+ * receives. `defineTheme` infers both.
+ */
+export interface DefineThemeInput<
+ IconVariants extends ReadonlyArray<string> | undefined =
+ ReadonlyArray<string> | undefined,
+ Base extends DefinedTheme | undefined = DefinedTheme | undefined,
+> {
/** Theme name — used for data-astryx-theme attribute and identification */
name: string;
@@ -222,7 +268,7 @@ export interface DefineThemeInput {
* });
* ```
*/
- extends?: DefinedTheme;
+ extends?: Base;
/**
* Unified typography configuration — fonts, scale, and weights.
*
@@ -366,8 +412,27 @@ export interface DefineThemeInput {
* info: ({size}) => <InfoIcon weight={size === 'sm' ? 'bold' : 'regular'} />,
* }
* ```
+ *
+ * `variant` is typed as the names in `iconVariants` (or the inherited list).
+ */
+ icons?: ThemeIconEntries<ThemeIconEntryVariant<IconVariants, Base>>;
+ /**
+ * The icon variant names this theme supports, listed once for the whole
+ * theme — never per icon. Icon entry functions receive `variant` typed as
+ * these names.
+ *
+ * A theme that sets `iconVariants` replaces the list it would inherit from
+ * `extends`; a theme that omits it inherits the base's list.
+ *
+ * @example
+ * ```
+ * iconVariants: ['outline', 'filled'],
+ * icons: {
+ * info: ({variant}) => (variant === 'filled' ? <InfoFilled /> : <InfoOutline />),
+ * },
+ * ```
*/
- icons?: ThemeIconEntries;
+ iconVariants?: IconVariants;
/**
* Indicator overrides — replaces the components that draw stateful control
* visuals with the theme's own, by name.
@@ -467,7 +532,12 @@ export interface DefinedTheme {
* Only Astryx icon resolution reads it.
* @internal
*/
- __icons?: ThemeIconEntries;
+ __icons?: ThemeIconEntries<never>;
+ /**
+ * The icon variant names this theme supports: its own `iconVariants`, or
+ * the list it inherited. Absent when no theme in its lineage lists any.
+ */
+ iconVariants?: ReadonlyArray<string>;
/** Indicator overrides for stateful control visuals, keyed by name */
indicators?: IndicatorRegistry;
/** Whether this theme has been pre-compiled by theme build CLI */
@@ -507,11 +577,23 @@ export interface DefinedTheme {
__axes?: ThemeGenerativeAxes;
}
-/** A theme produced by the current defineTheme implementation. */
-export type ResolvedDefinedTheme = DefinedTheme & {
- __adaptations: NormalizedThemeAdaptations;
- __axes: ThemeGenerativeAxes;
-};
+/**
+ * A theme produced by the current defineTheme implementation. `IconVariant`
+ * is the names in its `iconVariants` list.
+ */
+export type ResolvedDefinedTheme<IconVariant extends string = string> =
+ DefinedTheme & {
+ __adaptations: NormalizedThemeAdaptations;
+ __axes: ThemeGenerativeAxes;
+ /**
+ * Type-only: the names in `iconVariants`, so a theme that `extends` this
+ * one types its icon entries by the list it inherits. Never set. Method
+ * syntax keeps resolved themes with different lists assignable to each
+ * other, as they were before the list existed.
+ * @internal
+ */
+ __iconVariant?(variant: IconVariant): void;
+ };
// =============================================================================
// All defaults merged into a single flat map
@@ -567,7 +649,12 @@ function describeBadBase(value: unknown): string {
* that are merged into the token map. Explicit `tokens` entries take
* precedence over generated values.
*/
-export function defineTheme(input: DefineThemeInput): ResolvedDefinedTheme {
+export function defineTheme<
+ const IconVariants extends ReadonlyArray<string> | undefined = undefined,
+ Base extends DefinedTheme | undefined = undefined,
+>(
+ input: DefineThemeInput<IconVariants, Base>,
+): ResolvedDefinedTheme<ThemeIconVariant<IconVariants, Base>> {
// Pre-seed from the base theme when `extends` is provided (lowest precedence).
// A base that is not a theme is refused rather than ignored: `extends` used
// to inherit nothing when its value was undefined, which is what a named
@@ -647,6 +734,13 @@ export function defineTheme(input: DefineThemeInput): ResolvedDefinedTheme {
: (input.icons ?? baseIcons);
const icons = readThemeIconNodes(iconEntries);
+ // The variant list is theme-level: a list this theme sets replaces the
+ // inherited one; an omitted list is inherited.
+ const iconVariants: ReadonlyArray<string> | undefined =
+ input.iconVariants !== undefined
+ ? [...input.iconVariants]
+ : base?.iconVariants;
+
// Indicator overrides merge by name, like icons: a child theme replacing one
// indicator keeps the ones its base replaced.
const indicators =
@@ -667,6 +761,7 @@ export function defineTheme(input: DefineThemeInput): ResolvedDefinedTheme {
components,
icons,
...(icons !== iconEntries ? {__icons: iconEntries} : {}),
+ ...(iconVariants !== undefined ? {iconVariants} : {}),
indicators,
__inputTokens:
base?.__inputTokens || input.tokens
@@ -688,7 +783,7 @@ export function defineTheme(input: DefineThemeInput): ResolvedDefinedTheme {
* `{size: 'md'}`. Entries without a function are returned as the same object.
*/
function readThemeIconNodes(
- entries: ThemeIconEntries | undefined,
+ entries: ThemeIconEntries<never> | undefined,
): ThemeIconOverrides | undefined {
if (
entries == null ||
diff --git a/scripts/check-theme-template.test.mjs b/scripts/check-theme-template.test.mjs
index 4ed8df58d2..56e2a77b0b 100644
--- a/scripts/check-theme-template.test.mjs
+++ b/scripts/check-theme-template.test.mjs
@@ -97,7 +97,7 @@ const tokensSrc = fs.readFileSync(
/** Field names declared on `DefineThemeInput`. */
function defineThemeFields() {
const body = defineThemeSrc.match(
- /export interface DefineThemeInput \{([\s\S]*?)\n\}/,
+ /export interface DefineThemeInput(?:<[\s\S]*?>)? \{([\s\S]*?)\n\}/,
);
if (!body) throw new Error('DefineThemeInput not found in defineTheme.ts');
return [...body[1].matchAll(/^ {2}(\w+)\??:/gm)].map(m => m[1]);