Skip to content

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

TypeScript

feat(cli): built themes keep function icon entries and type their icon variants (#8785)

Xinzi Zhoueb3e53943c40
diff --git a/.changeset/ast-087-built-icon-functions.md b/.changeset/ast-087-built-icon-functions.md
new file mode 100644
index 0000000000..46517e7324
--- /dev/null
+++ b/.changeset/ast-087-built-icon-functions.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+'@astryxdesign/core': patch
+---
+
+[feat] `astryx theme build` keeps function icon entries, so a built theme answers each `<Icon>` request with the size and variant it renders, exactly as the runtime theme does. This includes entries inherited from a built or package theme, and family builds. A built theme's `icons` field and the registry its module re-exports are React nodes, each function read at `{size: 'md'}`. A theme that lists `iconVariants` writes an `IconVariantMap` augmentation into `<theme>.variants.d.ts`, and its declaration carries the list, so a theme that extends the built theme types `variant` by those names. A function written in the theme file itself fails the build, as an inline registry always has. Themes without function entries or an icon variant list build the same output as before.
+@imdreamrunner
diff --git a/packages/cli/api/theme/build/build.icon-function-entries.test.mjs b/packages/cli/api/theme/build/build.icon-function-entries.test.mjs
new file mode 100644
index 0000000000..a8ac19d725
--- /dev/null
+++ b/packages/cli/api/theme/build/build.icon-function-entries.test.mjs
@@ -0,0 +1,499 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Built themes carry function icon entries and resolve them as runtime.
+ * @input Real themeBuild and themeBuildFamily calls on source themes whose icon
+ * registries hold functions of `{size, variant}` and that list icon variants:
+ * a child under a replaced list, a theme extending a built module, a theme
+ * extending a package theme, and a family.
+ * @output Native ESM loads that render `<Icon>` for every request a theme's
+ * entries can receive under the built and the runtime theme, read the public
+ * icon views, and a TypeScript program that extends a built theme.
+ * @position `architecture:theme-compilation` INV15 and `spec:AST-087` FR3,
+ * FR18, and FR19 for theme build. 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 ts from 'typescript';
+import {themeBuild, themeBuildFamily} from './build.mjs';
+
+const SIZES = ['xsm', 'sm', 'md', 'lg'];
+
+let tmpDir;
+beforeEach(() => {
+ // Under the CLI package, so core, React, and TypeScript resolve both in the
+ // theme loader and in the native artifact checks.
+ tmpDir = fs.mkdtempSync(
+ path.resolve(import.meta.dirname, '../../..', '.tmp-icon-functions-'),
+ );
+});
+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);
+}
+
+/** A registry module whose function entries label what they were asked for. */
+function writeRegistry(file, exportName, entries) {
+ write(
+ file,
+ `import {createElement} from 'react';
+const draw = label => ({size, variant}) =>
+ createElement('svg', {'data-icon': label + ':' + size + ':' + (variant ?? 'normal')});
+export const ${exportName} = {
+${Object.entries(entries)
+ .map(([key, label]) =>
+ label.startsWith('node:')
+ ? ` ${JSON.stringify(key)}: createElement('svg', {'data-icon': ${JSON.stringify(label.slice(5))}}),`
+ : ` ${JSON.stringify(key)}: draw(${JSON.stringify(label)}),`,
+ )
+ .join('\n')}
+};
+`,
+ );
+}
+
+/** The base, its child under a replaced list, and their registries. */
+function writeLineage() {
+ writeRegistry('base/icons.mjs', 'baseIcons', {
+ info: 'base-info',
+ close: 'base-close',
+ check: 'node:base-check',
+ 'parity:mark': 'base-mark',
+ });
+ write(
+ 'base/source.mjs',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {baseIcons} from './icons.mjs';
+export const baseTheme = defineTheme({
+ name: 'parity-base', tokens: {}, iconVariants: ['outline', 'filled'], icons: baseIcons,
+});
+export default baseTheme;
+`,
+ );
+ writeRegistry('child/icons.mjs', 'childIcons', {
+ close: 'child-close',
+ menu: 'child-menu',
+ });
+ write(
+ 'child/source.mjs',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {baseTheme} from '../base/source.mjs';
+import {childIcons} from './icons.mjs';
+export const childTheme = defineTheme({
+ name: 'parity-child', extends: baseTheme, tokens: {},
+ iconVariants: ['filled', 'bold'], icons: childIcons,
+});
+export default childTheme;
+`,
+ );
+}
+
+/** @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);
+ return built;
+}
+
+/**
+ * Load built and runtime themes with native Node and report, for each pair,
+ * what `<Icon>` renders for every request and what the public reads return.
+ * The requests are every key a theme draws × the four sizes × no variant and
+ * each name any theme here lists, so unlisted names are covered too.
+ *
+ * @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',
+ `import {createElement, isValidElement} from 'react';
+import {renderToStaticMarkup} from 'react-dom/server';
+import {Icon, getIcon, getIconRegistry} from '@astryxdesign/core/Icon';
+import {Theme} from '@astryxdesign/core/theme';
+const SIZES = ${JSON.stringify(SIZES)};
+const VARIANTS = [undefined, 'outline', 'filled', 'bold'];
+const label = node => {
+ if (node == null) return null;
+ if (!isValidElement(node)) return 'not-a-node:' + typeof node;
+ return node.props['data-icon'];
+};
+const rendered = (theme, icon, size, variant) => {
+ const html = renderToStaticMarkup(
+ createElement(Theme, {theme}, createElement(Icon, {icon, size, variant})),
+ );
+ return /data-icon="([^"]+)"/.exec(html)?.[1] ?? null;
+};
+const describe = theme => {
+ const keys = Object.keys(theme.icons ?? {}).sort();
+ const requests = {};
+ for (const key of keys) {
+ for (const size of SIZES) {
+ for (const variant of VARIANTS) {
+ requests[key + '|' + size + '|' + (variant ?? '-')] = rendered(theme, key, size, variant);
+ }
+ }
+ }
+ return {
+ keys,
+ requests,
+ icons: Object.fromEntries(keys.map(key => [key, label(theme.icons[key])])),
+ getIcon: Object.fromEntries(keys.map(key => [key, label(getIcon(key, theme))])),
+ registry: Object.fromEntries(
+ Object.entries(getIconRegistry(theme))
+ .filter(([key]) => keys.includes(key))
+ .map(([key, node]) => [key, label(node)]),
+ ),
+ iconVariants: theme.iconVariants ?? null,
+ };
+};
+const result = {};
+${pairs
+ .map(
+ ({label, built, runtime}) => `{
+ const built = ${load(built)};
+ const runtime = ${load(runtime)};
+ const mod = await import(${JSON.stringify(built.split('#')[0])});
+ const reexports = Object.entries(mod).filter(([name]) => name !== ${JSON.stringify(built.split('#')[1])});
+ result[${JSON.stringify(label)}] = {
+ built: describe(built),
+ runtime: describe(runtime),
+ reexportIsNodeView: reexports.length === 0 ? null : reexports.every(([, value]) => value === built.icons),
+ };
+}`,
+ )
+ .join('\n')}
+process.stdout.write(JSON.stringify(result));`,
+ ],
+ {cwd: tmpDir, encoding: 'utf8', timeout: 60000},
+ );
+ return JSON.parse(output);
+}
+
+describe('built themes keep function icon entries', () => {
+ it('resolve every request as the runtime theme does, including an inherited entry under a replaced list', async () => {
+ writeLineage();
+ await buildAndCheck('base/source.mjs');
+ await buildAndCheck('child/source.mjs');
+ // A grandchild extends the BUILT child module.
+ write(
+ 'grandchild/source.mjs',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {parityChildTheme} from '../child/parity-child.js';
+export default defineTheme({name: 'parity-grandchild', extends: parityChildTheme, tokens: {}});
+`,
+ );
+ await buildAndCheck('grandchild/source.mjs');
+
+ const result = inspect([
+ {
+ label: 'base',
+ built: './base/parity-base.js#parityBaseTheme',
+ runtime: './base/source.mjs#default',
+ },
+ {
+ label: 'child',
+ built: './child/parity-child.js#parityChildTheme',
+ runtime: './child/source.mjs#default',
+ },
+ {
+ label: 'grandchild',
+ built: './grandchild/parity-grandchild.js#parityGrandchildTheme',
+ runtime: './grandchild/source.mjs#default',
+ },
+ ]);
+
+ for (const {built, runtime, reexportIsNodeView} of Object.values(result)) {
+ // INV15: built resolution and public views match runtime.
+ expect(built).toEqual(runtime);
+ expect(reexportIsNodeView).not.toBe(false);
+ }
+
+ const child = result.child.built;
+ expect(child.keys).toEqual([
+ 'check',
+ 'close',
+ 'info',
+ 'menu',
+ 'parity:mark',
+ ]);
+ for (const size of SIZES) {
+ // The child's own entry receives the names the child lists.
+ expect(child.requests[`close|${size}|bold`]).toBe(
+ `child-close:${size}:bold`,
+ );
+ expect(child.requests[`close|${size}|filled`]).toBe(
+ `child-close:${size}:filled`,
+ );
+ expect(child.requests[`close|${size}|outline`]).toBe(
+ `child-close:${size}:normal`,
+ );
+ // The inherited entry keeps its defining theme's list: 'outline' is no
+ // longer listed by the child, and the base never listed 'bold'.
+ expect(child.requests[`info|${size}|filled`]).toBe(
+ `base-info:${size}:filled`,
+ );
+ expect(child.requests[`info|${size}|outline`]).toBe(
+ `base-info:${size}:normal`,
+ );
+ expect(child.requests[`info|${size}|bold`]).toBe(
+ `base-info:${size}:normal`,
+ );
+ expect(child.requests[`info|${size}|-`]).toBe(`base-info:${size}:normal`);
+ // A node entry renders the same node for every request.
+ expect(child.requests[`check|${size}|filled`]).toBe('base-check');
+ }
+ expect(result.grandchild.built.requests).toEqual(child.requests);
+
+ // FR18: public reads are React nodes, each function read at md.
+ expect(child.icons).toEqual({
+ check: 'base-check',
+ close: 'child-close:md:normal',
+ info: 'base-info:md:normal',
+ menu: 'child-menu:md:normal',
+ 'parity:mark': 'base-mark:md:normal',
+ });
+ expect(child.getIcon).toEqual(child.icons);
+ expect(child.registry).toEqual({
+ check: 'base-check',
+ close: 'child-close:md:normal',
+ info: 'base-info:md:normal',
+ menu: 'child-menu:md:normal',
+ });
+ expect(result.base.reexportIsNodeView).toBe(true);
+ expect(result.child.reexportIsNodeView).toBe(true);
+ });
+
+ it('keeps the function entries of a package theme it extends', async () => {
+ const pkg = 'node_modules/@fixture/function-icons';
+ write(
+ `${pkg}/package.json`,
+ JSON.stringify({
+ name: '@fixture/function-icons',
+ type: 'module',
+ exports: './index.mjs',
+ }),
+ );
+ writeRegistry(`${pkg}/icons.mjs`, 'packageIcons', {info: 'package-info'});
+ write(
+ `${pkg}/index.mjs`,
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {packageIcons} from './icons.mjs';
+export const packageTheme = defineTheme({
+ name: 'parity-package', tokens: {}, iconVariants: ['filled'], icons: packageIcons,
+});
+`,
+ );
+ write(
+ 'package-child.mjs',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {packageTheme} from '@fixture/function-icons';
+export default defineTheme({name: 'parity-package-child', extends: packageTheme, tokens: {}});
+`,
+ );
+ await buildAndCheck('package-child.mjs');
+
+ const {packageChild} = inspect([
+ {
+ label: 'packageChild',
+ built: './parity-package-child.js#parityPackageChildTheme',
+ runtime: './package-child.mjs#default',
+ },
+ ]);
+
+ expect(packageChild.built).toEqual(packageChild.runtime);
+ for (const size of SIZES) {
+ expect(packageChild.built.requests[`info|${size}|filled`]).toBe(
+ `package-info:${size}:filled`,
+ );
+ }
+ expect(packageChild.built.icons).toEqual({info: 'package-info:md:normal'});
+ });
+
+ it('keeps function entries in a family build', async () => {
+ writeLineage();
+ // A member that sets no icons of its own inherits the child's entries.
+ write(
+ 'inherit/source.mjs',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {childTheme} from '../child/source.mjs';
+export default defineTheme({name: 'parity-inherit', extends: childTheme, tokens: {}});
+`,
+ );
+ const receipt = await themeBuildFamily(
+ ['base/source.mjs', 'child/source.mjs', 'inherit/source.mjs'],
+ {familyKey: 'parity-family'},
+ {cwd: tmpDir},
+ );
+ expect(receipt?.type).toBe('theme.build');
+ const familyModule = `./${receipt.data.outputs.js}`;
+
+ const result = inspect([
+ {
+ label: 'base',
+ built: `${familyModule}#parityBaseTheme`,
+ runtime: './base/source.mjs#default',
+ },
+ {
+ label: 'child',
+ built: `${familyModule}#parityChildTheme`,
+ runtime: './child/source.mjs#default',
+ },
+ {
+ label: 'inherit',
+ built: `${familyModule}#parityInheritTheme`,
+ runtime: './inherit/source.mjs#default',
+ },
+ ]);
+
+ expect(result.base.built).toEqual(result.base.runtime);
+ expect(result.child.built).toEqual(result.child.runtime);
+ expect(result.inherit.built).toEqual(result.inherit.runtime);
+ expect(result.inherit.built.requests).toEqual(result.child.built.requests);
+ expect(result.child.built.requests['info|sm|filled']).toBe(
+ 'base-info:sm:filled',
+ );
+ expect(result.child.built.requests['info|sm|outline']).toBe(
+ 'base-info:sm:normal',
+ );
+ });
+});
+
+describe('the node view never captures a registry binding', () => {
+ it.each(['entries', 'nodes', 'name', 'entry', 'Object'])(
+ 'loads a built theme whose registry is imported as `%s`',
+ async binding => {
+ writeRegistry('icons.mjs', 'registry', {info: 'bound-info'});
+ write(
+ 'bound.mjs',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {registry as ${binding}} from './icons.mjs';
+export default defineTheme({
+ name: 'bound', tokens: {}, iconVariants: ['filled'], icons: ${binding},
+});
+`,
+ );
+ await buildAndCheck('bound.mjs');
+
+ const {bound} = inspect([
+ {
+ label: 'bound',
+ built: './bound.js#boundTheme',
+ runtime: './bound.mjs#default',
+ },
+ ]);
+ expect(bound.built).toEqual(bound.runtime);
+ expect(bound.built.icons).toEqual({info: 'bound-info:md:normal'});
+ expect(bound.built.requests['info|lg|filled']).toBe(
+ 'bound-info:lg:filled',
+ );
+ expect(bound.reexportIsNodeView).toBe(true);
+ },
+ );
+});
+
+describe('a built theme types its icon variants', () => {
+ it('lets a theme extending the built module type `variant` by its list', async () => {
+ writeLineage();
+ await buildAndCheck('base/source.mjs');
+
+ const variants = fs.readFileSync(
+ path.join(tmpDir, 'base/parity-base.variants.d.ts'),
+ 'utf8',
+ );
+ expect(variants).toContain("declare module '@astryxdesign/core/Icon'");
+ expect(variants).toContain("'outline': true;");
+ expect(variants).toContain("'filled': true;");
+
+ write(
+ 'consumer.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import type {IconVariant} from '@astryxdesign/core/Icon';
+import {parityBaseTheme} from './base/parity-base.js';
+
+type Equal<A, B> =
+ (<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2 ? true : false;
+
+defineTheme({
+ name: 'consumer',
+ extends: parityBaseTheme,
+ icons: {
+ info: ({variant}) => {
+ const exact: Equal<typeof variant, 'outline' | 'filled' | undefined> = true;
+ return exact ? null : null;
+ },
+ // @ts-expect-error -- 'bold' is not a name the built theme lists.
+ close: ({variant}) => (variant === 'bold' ? null : null),
+ },
+});
+
+// The built theme's augmentation adds its names to IconVariant.
+export const listed: IconVariant = 'filled';
+// @ts-expect-error -- no theme here lists 'bold'.
+export const unlisted: IconVariant = 'bold';
+`,
+ );
+ const program = ts.createProgram([path.join(tmpDir, 'consumer.ts')], {
+ strict: true,
+ noEmit: true,
+ skipLibCheck: true,
+ target: ts.ScriptTarget.ES2022,
+ module: ts.ModuleKind.ESNext,
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
+ types: [],
+ });
+ const diagnostics = ts
+ .getPreEmitDiagnostics(program)
+ .filter(diagnostic => diagnostic.file?.fileName.endsWith('consumer.ts'))
+ .map(diagnostic =>
+ ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'),
+ );
+ expect(diagnostics).toEqual([]);
+ });
+});
+
+describe('a function the build cannot carry fails the build', () => {
+ it.each([
+ [
+ 'an inline function entry',
+ `icons: {info: ({size}) => createElement('svg', {'data-size': size})}`,
+ ],
+ [
+ 'a function beside a spread registry',
+ `icons: {...baseIcons, info: () => null}`,
+ ],
+ ])('rejects %s before writing', async (_label, iconsField) => {
+ writeRegistry('icons.mjs', 'baseIcons', {close: 'base-close'});
+ write(
+ 'inline.mjs',
+ `import {createElement} from 'react';
+import {defineTheme} from '@astryxdesign/core/theme';
+import {baseIcons} from './icons.mjs';
+export default defineTheme({name: 'inline-functions', tokens: {}, ${iconsField}});
+`,
+ );
+
+ await expect(
+ themeBuild('inline.mjs', {}, {cwd: tmpDir}),
+ ).rejects.toMatchObject({code: 'ERR_THEME_INVALID'});
+ expect(fs.readdirSync(tmpDir).sort()).toEqual(['icons.mjs', 'inline.mjs']);
+ });
+});
diff --git a/packages/cli/api/theme/build/build.mjs b/packages/cli/api/theme/build/build.mjs
index abdde9e57d..7d4b9ac46d 100644
--- a/packages/cli/api/theme/build/build.mjs
+++ b/packages/cli/api/theme/build/build.mjs
@@ -12,8 +12,10 @@
* build emits the exact CSS the `<Theme>` runtime does), writes:
* - A CSS file with token overrides and component styles
* - A CSS declaration module for strict side-effect imports
- * - A JS module that re-exports the built theme (+ icon registry)
- * - A .d.ts (plus an optional .variants.d.ts for custom prop values)
+ * - A JS module that re-exports the built theme (+ icon registry); function
+ * icon entries stay functions for `Icon`, beside a node view of the registry
+ * - A .d.ts (plus an optional .variants.d.ts for custom prop values and the
+ * theme's icon variant names)
*
* It performs the writes and returns a `theme.build` receipt — its `warnings`
* carry override problems and every declaration core's generator dropped
@@ -1577,12 +1579,21 @@ async function validateAdaptationEnrollment(themeDef) {
* generating a `declare module` block for them would be dead code — those are
* skipped.
*
- * @param {{components?: Record<string, Record<string, Record<string, unknown>>>}} themeDef - Theme definition (resolved by defineTheme)
+ * A theme that lists `iconVariants` also augments `IconVariantMap` in
+ * `@astryxdesign/core/Icon` with those names, when the installed core declares
+ * it, so `<Icon variant>` accepts them (spec:AST-087 FR3).
+ *
+ * @param {{components?: Record<string, Record<string, Record<string, unknown>>>, iconVariants?: readonly string[]}} themeDef - Theme definition (resolved by defineTheme)
* @returns {Promise<string|null>} TypeScript declaration content, or null if no augmentations needed
*/
async function generateVariantDeclarationsAsync(themeDef) {
const componentLayers = getThemeComponentLayers(themeDef);
- if (componentLayers.length === 0) {
+ const iconVariantNames =
+ Array.isArray(themeDef.iconVariants) &&
+ componentHasAugmentableInterface('Icon', 'IconVariantMap')
+ ? [...new Set(themeDef.iconVariants)]
+ : [];
+ if (componentLayers.length === 0 && iconVariantNames.length === 0) {
return null;
}
@@ -1618,7 +1629,7 @@ async function generateVariantDeclarationsAsync(themeDef) {
const hasCustom = Object.values(customValues).some(props =>
Object.values(props).some(values => values.size > 0),
);
- if (!hasCustom) return null;
+ if (!hasCustom && iconVariantNames.length === 0) return null;
const sections = ['// Generated by astryx theme build', 'export {};', ''];
@@ -1658,6 +1669,17 @@ async function generateVariantDeclarationsAsync(themeDef) {
}
}
+ if (iconVariantNames.length > 0) {
+ sections.push(`declare module '@astryxdesign/core/Icon' {`);
+ sections.push(' interface IconVariantMap {');
+ for (const name of iconVariantNames) {
+ sections.push(` ${tsStringLiteral(name)}: true;`);
+ }
+ sections.push(' }');
+ sections.push('}');
+ sections.push('');
+ }
+
// If every custom value targeted a non-augmentable prop, there's nothing to
// emit beyond the header — return null so no `.variants.d.ts` is written.
const hasEmittedAugmentation = sections.some(line =>
@@ -2098,6 +2120,53 @@ function extractRegistryInfo(filePath, field) {
return null;
}
+/**
+ * Whether a theme's icon entries include a function of `{size, variant}`.
+ * @param {Record<string, unknown> | null | undefined} entries
+ * @returns {boolean}
+ */
+function hasFunctionIconEntry(entries) {
+ return Object.values(entries ?? {}).some(
+ entry => typeof entry === 'function',
+ );
+}
+
+/**
+ * A built theme's icon entries: a theme from defineTheme keeps them in
+ * `__icons` when any is a function (its `icons` is the node view); otherwise
+ * `icons` holds them.
+ * @param {any} theme
+ * @returns {Record<string, unknown> | undefined}
+ */
+function themeIconEntries(theme) {
+ return theme?.__icons ?? theme?.icons;
+}
+
+/**
+ * The generated code that reads a registry's entries as React nodes, each
+ * function entry read at `{size: 'md'}` like core's public reads. It never
+ * passes the registry to a call, so a theme extending the built module can
+ * still trace the registry through its `__icons` field, and it reads no
+ * global, which a registry import could shadow. The registry expression runs
+ * where only `entriesName` and `nodesName` are declared, both names the
+ * registry imports cannot use.
+ * @param {string} entries - Expression for the registry's entries.
+ * @param {string} entriesName - A reserved local name.
+ * @param {string} nodesName - A reserved local name.
+ * @returns {string}
+ */
+function iconNodesExpression(entries, entriesName, nodesName) {
+ return `(() => {
+ const ${entriesName} = ${entries};
+ const ${nodesName} = {};
+ for (const name in ${entriesName}) {
+ const entry = ${entriesName}[name];
+ ${nodesName}[name] = typeof entry === 'function' ? entry({size: 'md'}) : entry;
+ }
+ return ${nodesName};
+})()`;
+}
+
/**
* Generate a minimal JS module for a built theme.
* Includes the theme name, marker, and re-exports the icon registry.
@@ -2119,6 +2188,11 @@ function extractRegistryInfo(filePath, field) {
* not given, direct registry specifiers are preserved, and inherited relative
* imports are rebased from the base module to the theme entry's directory.
*
+ * When an icon entry is a function of `{size, variant}`, the module keeps the
+ * registry as `__icons`, which `Icon` resolves at the size and variant it
+ * 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.
+ *
* @param {any} themeDef
* @param {import('./icon-imports.mjs').IconImports | null} iconInfo
* @param {string} [iconsSpecifier] - Overrides the selected registry specifier.
@@ -2167,12 +2241,28 @@ function generateBuiltModule(
? `const ${iconInfo.exportName} = ${iconInfo.expression};\n`
: '';
const iconsExpression = moduleOptions.iconsExpression ?? iconInfo?.exportName;
- const iconsField = iconsExpression ? ` icons: ${iconsExpression},` : '';
+ const iconNodes =
+ iconsExpression && hasFunctionIconEntry(themeIconEntries(themeDef))
+ ? `${themeBinding}IconNodes`
+ : null;
+ const iconNodesDeclaration =
+ iconNodes && iconsExpression
+ ? `const ${iconNodes} = ${iconNodesExpression(iconsExpression, `${themeBinding}IconEntries`, iconNodes)};\n`
+ : '';
+ const iconsField = iconNodes
+ ? ` icons: ${iconNodes},\n __icons: ${iconsExpression},`
+ : iconsExpression
+ ? ` icons: ${iconsExpression},`
+ : '';
const indicatorsField = moduleOptions.indicatorsExpression
? `\n indicators: ${moduleOptions.indicatorsExpression},`
: '';
const iconReExport =
- iconInfo && exportIcons ? `\nexport { ${iconInfo.exportName} };\n` : '';
+ iconInfo && exportIcons
+ ? iconNodes
+ ? `\nexport { ${iconNodes} as ${iconInfo.exportName} };\n`
+ : `\nexport { ${iconInfo.exportName} };\n`
+ : '';
// Resolve token values — tuples become light-dark() strings
/** @type {Record<string, unknown>} */
@@ -2246,7 +2336,7 @@ function generateBuiltModule(
),
);
- return `${iconImport}${iconDeclaration}/**
+ return `${iconImport}${iconDeclaration}${iconNodesDeclaration}/**
* ${themeDef.name} theme — built by \`${getCliInvocation()} theme build\`
* Import the CSS file alongside this module:
*
@@ -2296,7 +2386,39 @@ export declare const ${iconInfo.exportName}: IconRegistry;
(typeOptions.includeThemeImport ?? true)
? `import type { DefinedTheme } from '@astryxdesign/core/theme';\n`
: '';
- return `${variantsRef}${themeImport}${iconType}export declare const ${themeBinding}: DefinedTheme;\n`;
+ return `${variantsRef}${themeImport}${iconType}export declare const ${themeBinding}: ${builtThemeType(themeDef)};\n`;
+}
+
+/**
+ * A TypeScript string literal type for `value`.
+ * @param {string} value
+ * @returns {string}
+ */
+function tsStringLiteral(value) {
+ const inner = JSON.stringify(value)
+ .slice(1, -1)
+ .replace(/\\"/g, '"')
+ .replace(/'/g, "\\'");
+ return `'${inner}'`;
+}
+
+/**
+ * The declared type of a built theme. A theme that lists icon variants
+ * carries core's type-only `__iconVariant` marker with those names, so a theme
+ * that extends the built one types its icon entries' `variant` by the list,
+ * exactly as it would extending the source theme.
+ * SYNC: packages/core/src/theme/defineTheme.ts (ResolvedDefinedTheme)
+ * @param {any} themeDef
+ * @returns {string}
+ */
+function builtThemeType(themeDef) {
+ const names = themeDef.iconVariants;
+ if (!Array.isArray(names)) return 'DefinedTheme';
+ const variant =
+ names.length > 0
+ ? [...new Set(names)].map(tsStringLiteral).join(' | ')
+ : 'never';
+ return `DefinedTheme & { __iconVariant?(variant: ${variant}): void }`;
}
// =============================================================================
@@ -2770,10 +2892,26 @@ async function themeBuildInternal(
// Family preparation keeps its own named-import registry contract, which
// themeBuildFamily checks against the selected members' graph.
const standaloneIcons = !options.__prepareFamily;
+ // Function icon entries stay functions in the built module, beside a node
+ // view bound to `<theme>IconNodes` and computed from `<theme>IconEntries`.
+ const functionEntries =
+ hasFunctionIconEntry(themeIconEntries(themeDef)) ||
+ hasFunctionIconEntry(themeIconEntries(themeDef.extends));
+ /** @param {boolean} reserveIconNodes */
+ const reservedNames = reserveIconNodes => [
+ `${toIdentifier(themeDef.name)}Theme`,
+ ...(reserveIconNodes
+ ? [
+ `${toIdentifier(themeDef.name)}ThemeIconNodes`,
+ `${toIdentifier(themeDef.name)}ThemeIconEntries`,
+ ]
+ : []),
+ ];
const iconResolution = {
readSource: (/** @type {string} */ file) => fs.readFileSync(file, 'utf8'),
resolveModule: resolveThemeModule,
- reservedNames: [`${toIdentifier(themeDef.name)}Theme`],
+ reservedNames: reservedNames(functionEntries),
+ functionEntries,
rawInput: 'extends' in themeDef,
hasIcons:
Object.keys(themeDef.icons ?? {}).length > 0 ||
@@ -2897,9 +3035,14 @@ async function themeBuildInternal(
!iconInfo &&
Object.keys(resolvedTheme.icons ?? {}).length > 0
) {
+ const resolvedFunctionEntries = hasFunctionIconEntry(
+ themeIconEntries(resolvedTheme),
+ );
iconInfo = await resolveIconImports(filePath, themeExportName, {
...iconResolution,
hasIcons: true,
+ functionEntries: resolvedFunctionEntries,
+ reservedNames: reservedNames(resolvedFunctionEntries),
});
}
// An opaque package base can legitimately have no icons. Its .icons
@@ -3162,7 +3305,7 @@ async function themeBuildInternal(
);
const dtsContent =
generatedHeader(sourceRelative, 'ts', buildCommand, versions) +
- generateBuiltTypes(themeDef, iconInfo, variantsFileName);
+ generateBuiltTypes(resolvedTheme || themeDef, iconInfo, variantsFileName);
const unloadedFonts = [
...new Set([
@@ -3609,8 +3752,16 @@ export async function themeBuildFamily(
['icons', member.iconInfo],
['indicators', member.indicatorInfo],
]) {
- const value = member.theme[field];
- const inherited = member.sourceParent?.[field];
+ // A theme with a function entry gets its own node view of `icons`, so
+ // an inherit-only member is recognized by its entries.
+ const value =
+ field === 'icons'
+ ? themeIconEntries(member.theme)
+ : member.theme[field];
+ const inherited =
+ field === 'icons'
+ ? themeIconEntries(member.sourceParent)
+ : member.sourceParent?.[field];
if (
value &&
Object.keys(value).length > 0 &&
@@ -3681,7 +3832,14 @@ export async function themeBuildFamily(
// prettier-ignore
for (const registry of [icon, indicator]) if (registry.info) registryImports.push({specifier: registry.specifier ?? registry.info.importPath, exportName: registry.info.exportName});
const ownIcons = icon.info ? `${themeBinding}Icons` : null;
- const inheritedIcons = parentBinding ? `${parentBinding}.icons` : null;
+ // A parent with function entries keeps them in `__icons`; its `icons`
+ // is the node view.
+ const parent = members.find(
+ other => other.theme.name === member.parentName,
+ );
+ const inheritedIcons = parentBinding
+ ? `${parentBinding}.${hasFunctionIconEntry(themeIconEntries(parent?.theme)) ? '__icons' : 'icons'}`
+ : null;
const ownIndicators = indicator.info ? `${themeBinding}Indicators` : null;
const inheritedIndicators = parentBinding
? `${parentBinding}.indicators`
diff --git a/packages/cli/api/theme/build/icon-imports.mjs b/packages/cli/api/theme/build/icon-imports.mjs
index 6d641d1553..1257e6be74 100644
--- a/packages/cli/api/theme/build/icon-imports.mjs
+++ b/packages/cli/api/theme/build/icon-imports.mjs
@@ -24,7 +24,11 @@ import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
*/
/** @typedef {{kind: 'reference', module: any, binding: any, members: string[]}} RegistryReference */
-/** @typedef {{kind: 'registry', ref: RegistryReference, preferredName: string, override?: boolean} | {kind: 'merge', base: RegistryPlan, own: RegistryPlan}} RegistryPlan */
+/**
+ * `entries` marks a package theme read for its icon entries: its node-valued
+ * `icons` merged with the `__icons` that hold its function entries, if any.
+ * @typedef {{kind: 'registry', ref: RegistryReference, preferredName: string, override?: boolean, entries?: boolean} | {kind: 'merge', base: RegistryPlan, own: RegistryPlan}} RegistryPlan
+ */
/** @param {any} node */
function unwrap(node) {
@@ -98,15 +102,26 @@ function invalidRegistry(name, reason = '') {
* Local base themes are traced to their registry imports. Package bases remain
* public theme imports, so their implementation and private files stay private.
*
+ * A theme whose resolved icon entries include a function keeps them: a package
+ * base is read for its entries (`__icons`) as well as its node-valued `icons`,
+ * and a built base module's `__icons` field is followed instead of `icons`.
+ *
* @param {string} filePath
* @param {string | undefined} exportName
- * @param {{hasIcons: boolean, readSource: (filename: string) => string, resolveModule: (specifier: string, fromFile: string) => string | Promise<string>, reservedNames?: string[], rawInput?: boolean}} options
+ * @param {{hasIcons: boolean, functionEntries?: boolean, readSource: (filename: string) => string, resolveModule: (specifier: string, fromFile: string) => string | Promise<string>, reservedNames?: string[], rawInput?: boolean}} options
* @returns {Promise<IconImports | null>}
*/
export async function resolveIconImports(
filePath,
exportName,
- {hasIcons, readSource, resolveModule, reservedNames = [], rawInput = false},
+ {
+ hasIcons,
+ functionEntries = false,
+ readSource,
+ resolveModule,
+ reservedNames = [],
+ rawInput = false,
+ },
) {
if (exportName === undefined) {
if (!hasIcons) return null;
@@ -391,11 +406,16 @@ export async function resolveIconImports(
/** @param {RegistryReference} ref @returns {RegistryPlan} */
function packageTheme(ref) {
- return {
- kind: 'registry',
- ref: {...ref, members: [...ref.members, 'icons']},
- preferredName: 'themeIcons',
- };
+ // A theme's `icons` is node-valued; its function entries live in
+ // `__icons`. Read both only when the built theme needs its functions, so
+ // a theme without them keeps its existing output.
+ return functionEntries
+ ? {kind: 'registry', ref, preferredName: 'themeIcons', entries: true}
+ : {
+ kind: 'registry',
+ ref: {...ref, members: [...ref.members, 'icons']},
+ preferredName: 'themeIcons',
+ };
}
/** @param {any} module @param {string} name @param {boolean} [rejectOpaque] @returns {Promise<RegistryPlan | null>} */
@@ -513,7 +533,7 @@ export async function resolveIconImports(
: propertyName(item.key);
if (key === null)
invalidRegistry(undefined, 'Computed theme keys cannot be resolved.');
- if (!['icons', 'extends'].includes(key)) continue;
+ if (!['icons', '__icons', 'extends'].includes(key)) continue;
if (
!['ObjectProperty', 'Property'].includes(item.type) ||
item.method ||
@@ -566,7 +586,9 @@ export async function resolveIconImports(
}
const config = await fields(module, node);
const baseField = config.get('extends');
- const iconField = config.get('icons');
+ // A built module keeps its function entries in `__icons` beside its
+ // node-valued `icons`; the entries are the registry to carry.
+ const iconField = config.get('__icons') ?? config.get('icons');
const base = baseField
? await theme(baseField.module, baseField.node)
: null;
@@ -655,10 +677,13 @@ export async function resolveIconImports(
localName,
});
}
- const expression = ref.members.reduce(
+ const target = ref.members.reduce(
(result, member) => `${result}[${JSON.stringify(member)}]`,
localName,
);
+ const expression = value.entries
+ ? `{...${target}["icons"], ...${target}["__icons"]}`
+ : target;
return {
expression,
preferredName:
diff --git a/packages/cli/assets/docs/author-a-theme.doc.mjs b/packages/cli/assets/docs/author-a-theme.doc.mjs
index 7592b1872b..23871d1880 100644
--- a/packages/cli/assets/docs/author-a-theme.doc.mjs
+++ b/packages/cli/assets/docs/author-a-theme.doc.mjs
@@ -136,6 +136,8 @@ export const docs = {
{type: 'prose', text: 'In the example above, the generated theme imports `./icons.mjs` from `dist`. If the second command is skipped, `theme build` can still succeed, but loading or bundling the generated module fails because `dist/icons.mjs` is missing. `--icons-specifier` changes the emitted import; it does not create or verify the target file. Match the specifier to a module that resolves from the generated JS file.'},
{type: 'prose', text: 'Without `--icons-specifier`, the detected source import specifier is emitted unchanged. In the default flow without `--out`, a bundler can resolve an extensionless `./icons` to the neighboring `icons.tsx` source, but Node ESM does not perform that lookup and reports `ERR_MODULE_NOT_FOUND`. Moving the output with `--out` also changes where relative imports resolve from.'},
{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."},
],
},
{
diff --git a/packages/cli/assets/docs/icons.doc.mjs b/packages/cli/assets/docs/icons.doc.mjs
index d0fd5b0f54..7000fe3d72 100644
--- a/packages/cli/assets/docs/icons.doc.mjs
+++ b/packages/cli/assets/docs/icons.doc.mjs
@@ -169,7 +169,7 @@ brandTheme.iconVariants; // ['outline', 'filled']`,
},
{
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`.',
+ 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`. `astryx theme build` writes this augmentation for a built theme\'s list.',
},
{
type: 'code',
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 ec2826ac37..4acf4cfaf2 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": "74ad4592579fdeb35ec1e46f2788da77d6087c2fb852607680db1d88e3a809b6",
+ "skeleton": "67521830da2f078f4335b843b78812e05919c7f7b976f089bfcf8c3d1552c496",
"mentions": []
},
"browser-support": {
diff --git a/packages/core/src/theme/defineTheme.ts b/packages/core/src/theme/defineTheme.ts
index f885ea7631..adf01d996d 100644
--- a/packages/core/src/theme/defineTheme.ts
+++ b/packages/core/src/theme/defineTheme.ts
@@ -596,7 +596,9 @@ export type ResolvedDefinedTheme<IconVariant extends string = string> =
* 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.
+ * other, as they were before the list existed. `astryx theme build` writes
+ * the same marker into a built theme's declaration.
+ * SYNC: packages/cli/api/theme/build/build.mjs (builtThemeType)
* @internal
*/
__iconVariant?(variant: IconVariant): void;