Skip to content

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

TypeScript

feat(cli): built themes keep componentIcons slot functions (#9829)

Xinzi Zhou7fb5cab36a9d
diff --git a/.changeset/component-icon-slot-functions-theme-build.md b/.changeset/component-icon-slot-functions-theme-build.md
new file mode 100644
index 0000000000..014e4e6b1c
--- /dev/null
+++ b/.changeset/component-icon-slot-functions-theme-build.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] `astryx theme build` keeps a theme's `componentIcons` slot functions. The built module imports each slot function from the module the theme source imports it from, writes static slot values beside it as JSON, and reads back the same static `componentIcons` view, so component icon slots resolve the same for the built theme as for the runtime theme. This includes slots inherited from a built, package, or family base. A slot function defined in the theme file still fails the build: move it to its own module and import it. In `--family` output, a member supplies its own slot functions through a named import of its whole `componentIcons` map. The module keeps each slot import as the theme source spells it (`--icons-specifier` rewrites only the icon registry import), so with `--out` in another directory, a module must answer to that specifier from the output directory.
+
+@imdreamrunner
diff --git a/packages/cli/api/theme/build/build.component-icons.test.mjs b/packages/cli/api/theme/build/build.component-icons.test.mjs
index ae7c5f9cc9..225eae6bb1 100644
--- a/packages/cli/api/theme/build/build.component-icons.test.mjs
+++ b/packages/cli/api/theme/build/build.component-icons.test.mjs
@@ -1,13 +1,14 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * @file Built themes carry static component icon slots and resolve them as
- * runtime.
+ * @file Built themes carry 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.
+ * `componentIcons` hold static values and slot functions: an imported map, a
+ * child with inline static slots and an imported slot function, a theme
+ * extending a built module, a theme extending a package theme, and a family.
+ * @output Native ESM loads that resolve every slot for each state under the
+ * built and the runtime theme, read the static `componentIcons` view, and
+ * render CodeBlock's copy button.
* @position Theme build parity for component icon slots. The node project's
* global setup supplies the compiled core package.
*/
@@ -36,20 +37,61 @@ function write(file, source) {
fs.writeFileSync(path.join(tmpDir, file), source);
}
+const SLOT_FUNCTIONS = `export const copySlot = ({copied}) =>
+ copied ? {icon: 'checkDouble', size: 'lg'} : {icon: 'clock'};
+export const baseSlots = {
+ 'code-block-copy': copySlot,
+ 'parity-panel-dismiss': {icon: 'close', size: 'sm'},
+ 'parity-nav-leading': ({selected}) => (selected ? null : undefined),
+ 'parity-unset': undefined,
+};
+`;
+
+/** A base with an imported slot map, and a child with inline slots. */
+function writeLineage() {
+ write('base/slots.mjs', SLOT_FUNCTIONS);
+ write(
+ 'base/source.mjs',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {baseSlots} from './slots.mjs';
+export const baseTheme = defineTheme({
+ name: 'slots-base', tokens: {}, componentIcons: baseSlots,
+});
+export default baseTheme;
+`,
+ );
+ write(
+ 'child/source.mjs',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {baseTheme} from '../base/source.mjs';
+import {copySlot} from '../base/slots.mjs';
+export const childTheme = defineTheme({
+ name: 'slots-child', extends: baseTheme, tokens: {},
+ componentIcons: {
+ 'parity-panel-dismiss': null,
+ 'parity-tab-close': {size: 'xsm'},
+ 'parity-copy-again': copySlot,
+ 'parity-nav-leading': undefined,
+ },
+});
+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;
}
-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.
+ * how every slot resolves for each state, the static view, and the glyph in
+ * CodeBlock's copy button.
*
* @param {Array<{label: string, built: string, runtime: string}>} pairs -
* Module specifiers with `#export` suffixes, relative to the fixture root.
@@ -64,19 +106,41 @@ function inspect(pairs) {
[
'--input-type=module',
'--eval',
- `const {resolveComponentIcon} = await import(
+ `import {createElement} from 'react';
+import {renderToStaticMarkup} from 'react-dom/server';
+import {CodeBlock} from '@astryxdesign/core/CodeBlock';
+import {Theme} from '@astryxdesign/core/theme';
+const {resolveComponentIcon} = await import(
import.meta.resolve('@astryxdesign/core/Icon').replace(/index\\.js$/, 'globalIconRegistry.js')
);
+const SLOTS = {
+ 'code-block-copy': [{copied: false}, {copied: true}],
+ 'parity-copy-again': [{copied: false}, {copied: true}],
+ 'parity-panel-dismiss': [undefined],
+ 'parity-tab-close': [undefined],
+ 'parity-nav-leading': [{selected: false}, {selected: true}],
+};
+const copyGlyph = theme => {
+ const html = renderToStaticMarkup(
+ createElement(Theme, {theme}, createElement(CodeBlock, {code: 'x'})),
+ );
+ return /astryx-code-block-copy-button[^>]*>(.*?)<\\/button>/s.exec(html)?.[1] ?? null;
+};
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),
+ Object.entries(SLOTS).flatMap(([slot, states]) =>
+ states.map(state => [
+ slot + '|' + JSON.stringify(state ?? null),
+ resolveComponentIcon(slot, state, {icon: 'copy', size: 'sm'}, theme),
]),
),
),
componentIcons: theme.componentIcons ?? null,
+ componentIconKeys: Object.keys(theme.componentIcons ?? {}).sort(),
+ staticViewHasFunction: Object.values(theme.componentIcons ?? {}).some(
+ value => typeof value === 'function',
+ ),
+ copyGlyph: copyGlyph(theme),
});
const result = {};
${pairs
@@ -95,53 +159,23 @@ process.stdout.write(JSON.stringify(result));`,
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 () => {
+describe('built themes keep component icon slots', () => {
+ it('resolve every slot and state as the runtime theme does', async () => {
writeLineage();
await buildAndCheck('base/source.mjs');
- // A child extends the BUILT base module.
+ await buildAndCheck('child/source.mjs');
+ // A grandchild extends the BUILT child module and adds a static slot.
write(
- 'built-child/source.mjs',
+ 'grandchild/source.mjs',
`import {defineTheme} from '@astryxdesign/core/theme';
-import {slotsBaseTheme} from '../base/slots-base.js';
+import {slotsChildTheme} from '../child/slots-child.js';
export default defineTheme({
- name: 'slots-built-child', extends: slotsBaseTheme, tokens: {},
+ name: 'slots-grandchild', extends: slotsChildTheme, 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);
+ await buildAndCheck('grandchild/source.mjs');
const result = inspect([
{
@@ -155,30 +189,164 @@ export default defineTheme({
runtime: './child/source.mjs#default',
},
{
- label: 'builtChild',
- built: './built-child/slots-built-child.js#slotsBuiltChildTheme',
- runtime: './built-child/source.mjs#default',
+ label: 'grandchild',
+ built: './grandchild/slots-grandchild.js#slotsGrandchildTheme',
+ runtime: './grandchild/source.mjs#default',
},
]);
+
for (const {built, runtime} of Object.values(result)) {
expect(built).toEqual(runtime);
+ expect(built.staticViewHasFunction).toBe(false);
}
- expect(result.child.built.componentIcons).toEqual({
- 'code-block-copy': 'clock',
+
+ const child = result.child.built;
+ expect(child.resolved).toEqual({
+ 'code-block-copy|{"copied":false}': {icon: 'clock', size: 'sm'},
+ 'code-block-copy|{"copied":true}': {icon: 'checkDouble', size: 'lg'},
+ 'parity-copy-again|{"copied":false}': {icon: 'clock', size: 'sm'},
+ 'parity-copy-again|{"copied":true}': {icon: 'checkDouble', size: 'lg'},
+ 'parity-panel-dismiss|null': {icon: null, size: 'sm'},
+ 'parity-tab-close|null': {icon: 'copy', size: 'xsm'},
+ // An undefined entry inherits the base's slot function.
+ 'parity-nav-leading|{"selected":false}': {icon: 'copy', size: 'sm'},
+ 'parity-nav-leading|{"selected":true}': {icon: null, size: 'sm'},
+ });
+ // The static view leaves out every slot function.
+ expect(child.componentIcons).toEqual({
'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'},
+ expect(result.grandchild.built.resolved['parity-tab-close|null']).toEqual({
+ icon: 'menu',
+ size: 'sm',
});
+ expect(child.copyGlyph).toContain('data-size="sm"');
+ });
+
+ it('writes static slots as JSON with no import', async () => {
+ write(
+ 'static.mjs',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+export default defineTheme({
+ name: 'slots-static', tokens: {},
+ componentIcons: {'code-block-copy': 'clock', 'parity-panel-dismiss': null},
+});
+`,
+ );
+ await buildAndCheck('static.mjs');
+
+ const module = fs.readFileSync(
+ path.join(tmpDir, 'slots-static.js'),
+ 'utf8',
+ );
+ expect(module).not.toMatch(/^import /m);
+ expect(module).not.toContain('__componentIcons');
+ const {staticSlots} = inspect([
+ {
+ label: 'staticSlots',
+ built: './slots-static.js#slotsStaticTheme',
+ runtime: './static.mjs#default',
+ },
+ ]);
+ expect(staticSlots.built).toEqual(staticSlots.runtime);
+ expect(staticSlots.built.componentIcons).toEqual({
+ 'code-block-copy': 'clock',
+ 'parity-panel-dismiss': null,
+ });
+ });
+
+ it('keeps the slot functions of a package theme it extends', async () => {
+ const pkg = 'node_modules/@fixture/slot-functions';
+ write(
+ `${pkg}/package.json`,
+ JSON.stringify({
+ name: '@fixture/slot-functions',
+ type: 'module',
+ exports: './index.mjs',
+ }),
+ );
+ write(`${pkg}/slots.mjs`, SLOT_FUNCTIONS);
+ write(
+ `${pkg}/index.mjs`,
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {baseSlots} from './slots.mjs';
+export const packageTheme = defineTheme({
+ name: 'slots-package', tokens: {}, componentIcons: baseSlots,
+});
+`,
+ );
+ write(
+ 'package-child.mjs',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {packageTheme} from '@fixture/slot-functions';
+export default defineTheme({
+ name: 'slots-package-child', extends: packageTheme, tokens: {},
+ componentIcons: {'parity-tab-close': 'menu'},
+});
+`,
+ );
+ await buildAndCheck('package-child.mjs');
+
+ const {packageChild} = inspect([
+ {
+ label: 'packageChild',
+ built: './slots-package-child.js#slotsPackageChildTheme',
+ runtime: './package-child.mjs#default',
+ },
+ ]);
+
+ expect(packageChild.built).toEqual(packageChild.runtime);
+ expect(
+ packageChild.built.resolved['code-block-copy|{"copied":true}'],
+ ).toEqual({icon: 'checkDouble', size: 'lg'});
});
- it('keeps static slots in a family build', async () => {
+ it('keeps slot functions in a family build', async () => {
writeLineage();
+ // A member that sets no slots of its own inherits the child's values.
+ write(
+ 'inherit/source.mjs',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {childTheme} from '../child/source.mjs';
+export default defineTheme({name: 'slots-inherit', extends: childTheme, tokens: {}});
+`,
+ );
+ // A family member supplies its own slot functions through a named import
+ // of its whole componentIcons map, so this child sets only static slots.
+ 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'}},
+});
+export default childTheme;
+`,
+ );
+ // A member whose imported map leaves a slot undefined keeps the parent's.
+ write(
+ 'imported/slots.mjs',
+ `export const importedSlots = {'code-block-copy': undefined, 'parity-tab-close': 'menu'};\n`,
+ );
+ write(
+ 'imported/source.mjs',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {childTheme} from '../child/source.mjs';
+import {importedSlots} from './slots.mjs';
+export default defineTheme({
+ name: 'slots-imported', extends: childTheme, tokens: {}, componentIcons: importedSlots,
+});
+`,
+ );
const receipt = await themeBuildFamily(
- ['base/source.mjs', 'child/source.mjs'],
+ [
+ 'base/source.mjs',
+ 'child/source.mjs',
+ 'inherit/source.mjs',
+ 'imported/source.mjs',
+ ],
{familyKey: 'slots-family'},
{cwd: tmpDir},
);
@@ -196,41 +364,277 @@ export default defineTheme({
built: `${familyModule}#slotsChildTheme`,
runtime: './child/source.mjs#default',
},
+ {
+ label: 'inherit',
+ built: `${familyModule}#slotsInheritTheme`,
+ runtime: './inherit/source.mjs#default',
+ },
+ {
+ label: 'imported',
+ built: `${familyModule}#slotsImportedTheme`,
+ runtime: './imported/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.imported.built).toEqual(result.imported.runtime);
+ // A runtime theme extending the family root reads what one extending the
+ // source root reads: the root's undefined slot is not listed.
+ write(
+ 'family-child.mjs',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {slotsBaseTheme} from '${familyModule}';
+import source from './base/source.mjs';
+export const fromBuilt = defineTheme({name: 'family-from-built', extends: slotsBaseTheme, tokens: {}});
+export const fromSource = defineTheme({name: 'family-from-source', extends: source, tokens: {}});
+`,
+ );
+ const {child} = inspect([
+ {
+ label: 'child',
+ built: './family-child.mjs#fromBuilt',
+ runtime: './family-child.mjs#fromSource',
+ },
+ ]);
+ expect(child.built).toEqual(child.runtime);
+ expect(child.built.componentIconKeys).not.toContain('parity-unset');
+ expect(
+ result.imported.built.resolved['code-block-copy|{"copied":true}'],
+ ).toEqual({icon: 'checkDouble', size: 'lg'});
+ expect(
+ result.child.built.resolved['code-block-copy|{"copied":true}'],
+ ).toEqual({icon: 'checkDouble', size: 'lg'});
+ });
+});
+
+describe('built slot values follow defineTheme', () => {
+ it('keeps an inherited slot under an undefined own slot, and reads static values through constants', async () => {
+ writeLineage();
+ write(
+ 'undefined-own/slots.mjs',
+ `export const childSlots = {'code-block-copy': undefined, 'parity-tab-close': 'menu'};\n`,
+ );
+ write(
+ 'undefined-own/source.mjs',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {baseTheme} from '../base/source.mjs';
+import {childSlots} from './slots.mjs';
+export default defineTheme({
+ name: 'slots-undefined-own', extends: baseTheme, tokens: {}, componentIcons: childSlots,
+});
+`,
+ );
+ write('constants/sizes.mjs', `export const COMPACT = 'xsm';\n`);
+ write(
+ 'constants/source.mjs',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {baseTheme} from '../base/source.mjs';
+import {copySlot} from '../base/slots.mjs';
+import {COMPACT} from './sizes.mjs';
+const SIZE = 'xsm';
+const SIZES = {compact: SIZE, icons: {dismiss: 'close'}};
+const DISMISS = {icon: SIZES.icons.dismiss, size: SIZE};
+export default defineTheme({
+ name: 'slots-constants', extends: baseTheme, tokens: {},
+ componentIcons: {
+ 'parity-panel-dismiss': DISMISS,
+ 'parity-tab-close': {size: SIZES.compact},
+ 'parity-nav-leading': {size: COMPACT},
+ 'parity-copy-again': copySlot,
+ },
+});
+`,
+ );
+ // Inside one object, a later undefined slot replaces a spread value, so the
+ // theme keeps no value for it.
+ write(
+ 'spread-undefined/source.mjs',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {baseSlots} from '../base/slots.mjs';
+export default defineTheme({
+ name: 'slots-spread-undefined', tokens: {},
+ componentIcons: {...baseSlots, 'code-block-copy': undefined},
+});
+`,
+ );
+ for (const file of [
+ 'undefined-own/source.mjs',
+ 'constants/source.mjs',
+ 'spread-undefined/source.mjs',
+ ]) {
+ await buildAndCheck(file);
+ }
+ // A runtime theme extends the built root and the source root alike.
+ write(
+ 'spread-undefined/child.mjs',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {slotsSpreadUndefinedTheme} from './slots-spread-undefined.js';
+import source from './source.mjs';
+export const fromBuilt = defineTheme({name: 'from-built', extends: slotsSpreadUndefinedTheme, tokens: {}});
+export const fromSource = defineTheme({name: 'from-source', extends: source, tokens: {}});
+`,
+ );
+
+ const result = inspect([
+ {
+ label: 'undefinedOwn',
+ built: './undefined-own/slots-undefined-own.js#slotsUndefinedOwnTheme',
+ runtime: './undefined-own/source.mjs#default',
+ },
+ {
+ label: 'constants',
+ built: './constants/slots-constants.js#slotsConstantsTheme',
+ runtime: './constants/source.mjs#default',
+ },
+ {
+ label: 'spreadUndefined',
+ built:
+ './spread-undefined/slots-spread-undefined.js#slotsSpreadUndefinedTheme',
+ runtime: './spread-undefined/source.mjs#default',
+ },
+ {
+ label: 'extendsBuiltRoot',
+ built: './spread-undefined/child.mjs#fromBuilt',
+ runtime: './spread-undefined/child.mjs#fromSource',
+ },
+ ]);
+ for (const {built, runtime} of Object.values(result)) {
+ expect(built).toEqual(runtime);
+ }
+ expect(
+ result.undefinedOwn.built.resolved['code-block-copy|{"copied":false}'],
+ ).toEqual({icon: 'clock', size: 'sm'});
+ expect(result.constants.built.componentIcons).toMatchObject({
+ 'parity-panel-dismiss': {icon: 'close', size: 'xsm'},
+ 'parity-tab-close': {size: 'xsm'},
+ 'parity-nav-leading': {size: 'xsm'},
+ });
+ expect(
+ Object.keys(result.extendsBuiltRoot.built.componentIcons ?? {}),
+ ).toEqual(
+ Object.keys(result.extendsBuiltRoot.runtime.componentIcons ?? {}),
+ );
+ expect(
+ result.spreadUndefined.built.resolved['code-block-copy|{"copied":true}'],
+ ).toEqual({icon: 'copy', size: 'sm'});
+ });
+});
+
+describe('a built theme written with --out', () => {
+ it('keeps the slot import as the source spells it, and loads where a module answers to it', async () => {
+ write('src/slots.mjs', SLOT_FUNCTIONS);
+ write(
+ 'src/theme.mjs',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {baseSlots} from './slots.mjs';
+export default defineTheme({name: 'slots-out', tokens: {}, componentIcons: baseSlots});
+`,
+ );
+ const built = await themeBuild(
+ 'src/theme.mjs',
+ {out: 'dist/theme.css'},
+ {cwd: tmpDir},
+ );
+ expect(built?.type).toBe('theme.build');
+ const module = fs.readFileSync(
+ path.join(tmpDir, 'dist/slots-out.js'),
+ 'utf8',
+ );
+ expect(module).toContain(`import { baseSlots } from './slots.mjs';`);
+
+ // The output directory supplies the module the specifier names.
+ write('dist/slots.mjs', SLOT_FUNCTIONS);
+ const {out} = inspect([
+ {
+ label: 'out',
+ built: './dist/slots-out.js#slotsOutTheme',
+ runtime: './src/theme.mjs#default',
+ },
+ ]);
+ expect(out.built).toEqual(out.runtime);
+ expect(out.built.resolved['code-block-copy|{"copied":true}']).toEqual({
+ icon: 'checkDouble',
+ size: 'lg',
+ });
});
});
-describe('a slot function fails the build', () => {
+describe('the static view never captures a slot binding', () => {
+ it.each(['slot', 'Object'])(
+ 'loads a built theme whose slot map is imported as `%s`',
+ async binding => {
+ write('slots.mjs', SLOT_FUNCTIONS);
+ write(
+ 'bound.mjs',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {baseSlots as ${binding}} from './slots.mjs';
+export default defineTheme({name: 'bound-slots', tokens: {}, componentIcons: ${binding}});
+`,
+ );
+ await buildAndCheck('bound.mjs');
+
+ const {bound} = inspect([
+ {
+ label: 'bound',
+ built: './bound-slots.js#boundSlotsTheme',
+ runtime: './bound.mjs#default',
+ },
+ ]);
+ expect(bound.built).toEqual(bound.runtime);
+ expect(bound.built.componentIcons).toEqual({
+ 'parity-panel-dismiss': {icon: 'close', size: 'sm'},
+ });
+ },
+ );
+});
+
+describe('a slot function the build cannot carry fails the build', () => {
+ it('names a value that is neither static nor imported', async () => {
+ write('slots.mjs', SLOT_FUNCTIONS);
+ write(
+ 'computed.mjs',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {baseSlots} from './slots.mjs';
+const big = Math.random() > 2;
+export default defineTheme({name: 'computed-slots', tokens: {},
+ componentIcons: {...baseSlots, 'parity-tab-close': {size: big ? 'lg' : 'sm'}}});
+`,
+ );
+
+ await expect(
+ themeBuild('computed.mjs', {}, {cwd: tmpDir}),
+ ).rejects.toMatchObject({
+ code: 'ERR_THEME_INVALID',
+ message: expect.stringContaining(
+ 'The value for "parity-tab-close" is neither a static value nor an imported binding.',
+ ),
+ });
+ });
+
it.each([
[
'an inline slot function',
`componentIcons: {'code-block-copy': ({copied}) => ({icon: copied ? 'check' : 'copy'})}`,
],
[
- 'an imported slot function',
- `componentIcons: {'code-block-copy': copySlot}`,
+ 'a slot function beside a spread map',
+ `componentIcons: {...baseSlots, 'code-block-copy': () => null}`,
],
])('rejects %s before writing', async (_label, field) => {
- write('slots.mjs', `export const copySlot = () => ({icon: 'clock'});\n`);
+ write('slots.mjs', SLOT_FUNCTIONS);
write(
- 'functions.mjs',
+ 'inline.mjs',
`import {defineTheme} from '@astryxdesign/core/theme';
-import {copySlot} from './slots.mjs';
-export default defineTheme({name: 'slot-functions', tokens: {}, ${field}});
+import {baseSlots} from './slots.mjs';
+export default defineTheme({name: 'inline-slots', 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',
- ]);
+ themeBuild('inline.mjs', {}, {cwd: tmpDir}),
+ ).rejects.toMatchObject({code: 'ERR_THEME_INVALID'});
+ expect(fs.readdirSync(tmpDir).sort()).toEqual(['inline.mjs', 'slots.mjs']);
});
});
diff --git a/packages/cli/api/theme/build/build.mjs b/packages/cli/api/theme/build/build.mjs
index 0bd3c80200..2564b4b3d0 100644
--- a/packages/cli/api/theme/build/build.mjs
+++ b/packages/cli/api/theme/build/build.mjs
@@ -2120,7 +2120,7 @@ export async function validateThemePrivateInputs(
* import { defaultIconRegistry } from './icons';
* icons: defaultIconRegistry,
* @param {string} filePath
- * @param {'icons' | 'indicators'} field
+ * @param {'icons' | 'indicators' | 'componentIcons'} field
* @returns {{exportName: string, importPath: string} | null}
*/
function extractRegistryInfo(filePath, field) {
@@ -2209,6 +2209,72 @@ function themeComponentIcons(theme) {
return theme?.__componentIcons ?? theme?.componentIcons;
}
+/**
+ * The generated function that merges a theme's own slot values over its
+ * base's, as `defineTheme` does: an own slot replaces the inherited one whole,
+ * and an `undefined` own slot leaves it in place. It reads no global.
+ * @param {string} name - A reserved function name.
+ * @returns {string}
+ */
+function componentIconMergeFunction(name) {
+ return `function ${name}(base, own) {
+ const merged = {...base};
+ for (const slot in own) {
+ if (own[slot] !== undefined) merged[slot] = own[slot];
+ }
+ return merged;
+}
+`;
+}
+
+/**
+ * The generated code that reads the static view of a theme's slot values:
+ * every slot without a function. Like the icon node view, it reads no global
+ * and declares only reserved local names.
+ * @param {string} valuesName - A reserved local name bound to the values.
+ * @param {string} viewName - A reserved local name.
+ * @returns {string}
+ */
+function componentIconViewExpression(valuesName, viewName) {
+ return `(() => {
+ const ${viewName} = {};
+ for (const slot in ${valuesName}) {
+ const value = ${valuesName}[slot];
+ if (value !== undefined && typeof value !== 'function') ${viewName}[slot] = value;
+ }
+ return ${viewName};
+})()`;
+}
+
+/**
+ * One import statement for a carried registry or slot binding. Ordinary named
+ * imports stay byte-compatible; paths with quotes or escapes are encoded, and
+ * default, namespace, and aliased bindings are kept.
+ * @param {{importPath: string, importedName: string, localName: string}} binding
+ * @param {string} [specifier] - Replaces the import path when given.
+ * @returns {string}
+ */
+function importStatement({importPath, importedName, localName}, specifier) {
+ const source =
+ specifier !== undefined
+ ? JSON.stringify(specifier)
+ : /['\\\r\n]/u.test(importPath)
+ ? JSON.stringify(importPath)
+ : `'${importPath}'`;
+ const imported = /^[$\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*$/u.test(
+ importedName,
+ )
+ ? importedName
+ : JSON.stringify(importedName);
+ const binding =
+ importedName === 'default'
+ ? localName
+ : importedName === '*'
+ ? `* as ${localName}`
+ : `{ ${imported}${importedName === localName ? '' : ` as ${localName}`} }`;
+ return `import ${binding} from ${source};\n`;
+}
+
/**
* Generate a minimal JS module for a built theme.
* Includes the theme name, marker, and re-exports the icon registry.
@@ -2235,13 +2301,15 @@ function themeComponentIcons(theme) {
* 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.
+ * Component icon slots without a function are written as JSON. When a slot
+ * value is a function, the module keeps the values, carried through
+ * `componentIconInfo`'s imports, as `__componentIcons`, and the theme's
+ * `componentIcons` is the static view, as `DefinedTheme['componentIcons']` is.
*
* @param {any} themeDef
* @param {import('./icon-imports.mjs').IconImports | null} iconInfo
* @param {string} [iconsSpecifier] - Overrides the selected registry specifier.
- * @param {{themeBinding?: string, iconsExpression?: string, indicatorsExpression?: string, artifactBaseName?: string, exportIcons?: boolean}} [moduleOptions]
+ * @param {{themeBinding?: string, iconsExpression?: string, indicatorsExpression?: string, artifactBaseName?: string, exportIcons?: boolean, componentIconInfo?: {imports: import('./icon-imports.mjs').IconImports['imports'], expression: string, mergeName?: string} | null}} [moduleOptions]
* @returns {string}
*/
function generateBuiltModule(
@@ -2254,32 +2322,17 @@ function generateBuiltModule(
moduleOptions.themeBinding ?? `${toIdentifier(themeDef.name)}Theme`;
const artifactBaseName = moduleOptions.artifactBaseName ?? themeDef.name;
const exportIcons = moduleOptions.exportIcons ?? true;
- // Keep ordinary direct named imports byte-compatible, while encoding paths
- // with quotes/escapes and retaining default, namespace, and aliased bindings.
const iconImport = (iconInfo?.imports ?? [])
- .map(({importPath, importedName, localName}) => {
- const overridden =
+ .map(binding =>
+ importStatement(
+ binding,
iconsSpecifier !== undefined &&
- importPath === iconInfo?.iconsSpecifierImportPath &&
- localName === iconInfo?.iconsSpecifierLocalName;
- const specifier = overridden
- ? JSON.stringify(iconsSpecifier)
- : /['\\\r\n]/u.test(importPath)
- ? JSON.stringify(importPath)
- : `'${importPath}'`;
- const imported = /^[$\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*$/u.test(
- importedName,
- )
- ? importedName
- : JSON.stringify(importedName);
- const binding =
- importedName === 'default'
- ? localName
- : importedName === '*'
- ? `* as ${localName}`
- : `{ ${imported}${importedName === localName ? '' : ` as ${localName}`} }`;
- return `import ${binding} from ${specifier};\n`;
- })
+ binding.importPath === iconInfo?.iconsSpecifierImportPath &&
+ binding.localName === iconInfo?.iconsSpecifierLocalName
+ ? iconsSpecifier
+ : undefined,
+ ),
+ )
.join('');
const iconDeclaration =
iconInfo && iconInfo.expression !== iconInfo.exportName
@@ -2309,18 +2362,28 @@ function generateBuiltModule(
: `\nexport { ${iconInfo.exportName} };\n`
: '';
- const componentIcons = themeComponentIcons(themeDef);
- const slotFunction = Object.entries(componentIcons ?? {}).find(
- ([, value]) => typeof value === 'function',
- );
- if (slotFunction) {
+ const componentIconValues = themeComponentIcons(themeDef);
+ const componentIconInfo = moduleOptions.componentIconInfo ?? null;
+ const carriesSlotFunctions = hasFunctionIconEntry(componentIconValues);
+ if (carriesSlotFunctions && !componentIconInfo) {
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.',
+ `Theme "${themeDef.name}" has componentIcons slot functions that the build cannot carry. ` +
+ 'Import the slot functions from their own module into the theme file.',
undefined,
ERROR_CODES.ERR_THEME_INVALID,
);
}
+ const componentIconValuesName = `${themeBinding}ComponentIconValues`;
+ const componentIconPrelude =
+ carriesSlotFunctions && componentIconInfo
+ ? componentIconInfo.imports
+ .map(binding => importStatement(binding))
+ .join('') +
+ (componentIconInfo.mergeName
+ ? componentIconMergeFunction(componentIconInfo.mergeName)
+ : '') +
+ `const ${componentIconValuesName} = ${componentIconInfo.expression};\n`
+ : '';
// Resolve token values — tuples become light-dark() strings
/** @type {Record<string, unknown>} */
@@ -2393,9 +2456,17 @@ function generateBuiltModule(
]),
),
) +
- serializeField('componentIcons', componentIcons, true);
+ (carriesSlotFunctions
+ ? ` componentIcons: ${componentIconViewExpression(
+ componentIconValuesName,
+ `${themeBinding}ComponentIconView`,
+ )
+ .split('\n')
+ .map((line, i) => (i === 0 ? line : ' ' + line))
+ .join('\n')},\n __componentIcons: ${componentIconValuesName},\n`
+ : serializeField('componentIcons', componentIconValues, true));
- return `${iconImport}${iconDeclaration}${iconNodesDeclaration}/**
+ return `${iconImport}${componentIconPrelude}${iconDeclaration}${iconNodesDeclaration}/**
* ${themeDef.name} theme — built by \`${getCliInvocation()} theme build\`
* Import the CSS file alongside this module:
*
@@ -2983,13 +3054,20 @@ async function themeBuildInternal(
]
: []),
];
+ // Names the slot values, their static view, and their merge function take
+ // in the built module.
+ const componentIconNames = [
+ `${toIdentifier(themeDef.name)}ThemeComponentIconValues`,
+ `${toIdentifier(themeDef.name)}ThemeComponentIconView`,
+ `${toIdentifier(themeDef.name)}ThemeMergeComponentIcons`,
+ ];
const iconResolution = {
readSource: (/** @type {string} */ file) =>
path.resolve(file) === path.resolve(filePath)
? themeSource
: fs.readFileSync(file, 'utf8'),
resolveModule: resolveThemeModule,
- reservedNames: reservedNames(functionEntries),
+ reservedNames: [...reservedNames(functionEntries), ...componentIconNames],
functionEntries,
rawInput: 'extends' in themeDef,
hasIcons:
@@ -2999,6 +3077,8 @@ async function themeBuildInternal(
let iconInfo = standaloneIcons
? await resolveIconImports(filePath, themeExportName, iconResolution)
: null;
+ /** @type {import('./icon-imports.mjs').IconImports | null} */
+ let componentIconInfo = null;
// Validate component overrides
const warnings = await validateComponentOverrides(themeDef);
@@ -3121,7 +3201,10 @@ async function themeBuildInternal(
...iconResolution,
hasIcons: true,
functionEntries: resolvedFunctionEntries,
- reservedNames: reservedNames(resolvedFunctionEntries),
+ reservedNames: [
+ ...reservedNames(resolvedFunctionEntries),
+ ...componentIconNames,
+ ],
});
}
// An opaque package base can legitimately have no icons. Its .icons
@@ -3146,6 +3229,27 @@ async function themeBuildInternal(
);
}
+ // A slot function cannot be serialized, so the module imports it from
+ // where the theme source does. Static slot values are written as JSON.
+ if (
+ standaloneIcons &&
+ hasFunctionIconEntry(themeComponentIcons(resolvedTheme))
+ ) {
+ componentIconInfo = await resolveIconImports(filePath, themeExportName, {
+ ...iconResolution,
+ field: 'componentIcons',
+ mergeName: `${toIdentifier(themeDef.name)}ThemeMergeComponentIcons`,
+ hasIcons: true,
+ functionEntries: true,
+ reservedNames: [
+ ...reservedNames(true),
+ ...componentIconNames,
+ ...(iconInfo?.imports.map(binding => binding.localName) ?? []),
+ ...(iconInfo ? [iconInfo.exportName] : []),
+ ],
+ });
+ }
+
// Cores that predate adaptations can still resolve typography, color,
// radius, and motion into root tokens, but they do not retain the raw axis
// inputs. Keep the effective metadata captured from the same defineTheme
@@ -3375,13 +3479,17 @@ async function themeBuildInternal(
const cssDtsContent =
generatedHeader(sourceRelative, 'ts', buildCommand, versions) +
'export {};\n';
- const jsContent =
- generatedHeader(sourceRelative, 'js', buildCommand, versions) +
- generateBuiltModule(
- resolvedTheme || themeDef,
- iconInfo,
- options.iconsSpecifier,
- );
+ // A family member's module is generated by themeBuildFamily, which carries
+ // its registries and slot functions through the family's own imports.
+ const jsContent = options.__prepareFamily
+ ? ''
+ : generatedHeader(sourceRelative, 'js', buildCommand, versions) +
+ generateBuiltModule(
+ resolvedTheme || themeDef,
+ iconInfo,
+ options.iconsSpecifier,
+ {componentIconInfo},
+ );
const dtsContent =
generatedHeader(sourceRelative, 'ts', buildCommand, versions) +
generateBuiltTypes(resolvedTheme || themeDef, iconInfo, variantsFileName);
@@ -3404,6 +3512,7 @@ async function themeBuildInternal(
sourceParent,
iconInfo: extractRegistryInfo(filePath, 'icons'),
indicatorInfo: extractRegistryInfo(filePath, 'indicators'),
+ componentIconInfo: extractRegistryInfo(filePath, 'componentIcons'),
variantDecl,
css: cssPlan,
versions,
@@ -3723,6 +3832,81 @@ function allocateFamilyBindings(members) {
const used = new Map();
return new Map(members.map(member => { const base = familyThemeBinding(member.theme.name), count = used.get(base) ?? 0; used.set(base, count + 1); return [member.theme.name, count === 0 ? base : `${base}${count + 1}`]; }));
}
+/**
+ * How a family member's module carries slot functions: its parent's values,
+ * then its own. A member supplies its own slot functions through a named
+ * import of its whole `componentIcons` map, merged as `defineTheme` merges;
+ * own static values are written as JSON. Null when the member has no slot
+ * function, so its static values are written as JSON alone.
+ * @param {any} member
+ * @param {any} parent - The member's parent in the family, if any.
+ * @param {{themeBinding: string | undefined, parentBinding: string | null | undefined, outDir: string, registryImports: Array<{specifier: string, exportName: string}>, expression: (own: string | null, inherited: string | null) => string | undefined}} context
+ * @returns {{imports: Array<{importPath: string, importedName: string, localName: string}>, expression: string, mergeName?: string} | null}
+ */
+function familyComponentIcons(member, parent, context) {
+ const values = themeComponentIcons(member.theme);
+ if (!hasFunctionIconEntry(values)) return null;
+ const inheritedValues = themeComponentIcons(parent?.theme);
+ const inherited =
+ context.parentBinding && inheritedValues
+ ? `${context.parentBinding}.${hasFunctionIconEntry(inheritedValues) ? '__componentIcons' : 'componentIcons'}`
+ : null;
+ /** @type {Array<{importPath: string, importedName: string, localName: string}>} */
+ const imports = [];
+ let own = null;
+ const binding =
+ context.themeBinding ?? `${toIdentifier(member.theme.name)}Theme`;
+ const info = member.componentIconInfo;
+ if (info) {
+ const input = familyRegistryInput(
+ info,
+ member.filePath,
+ context.outDir,
+ undefined,
+ );
+ const importPath = input.specifier ?? info.importPath;
+ own = `${binding}ComponentIconSource`;
+ imports.push({importPath, importedName: info.exportName, localName: own});
+ context.registryImports.push({
+ specifier: importPath,
+ exportName: info.exportName,
+ });
+ } else {
+ // Without an import, a member's own slots are the ones that differ from
+ // its parent's; they must all be static.
+ /** @type {Record<string, unknown>} */
+ const ownValues = {};
+ for (const [slot, value] of Object.entries(values ?? {})) {
+ if (
+ inheritedValues &&
+ Object.hasOwn(inheritedValues, slot) &&
+ inheritedValues[slot] === value
+ )
+ continue;
+ if (typeof value === 'function') {
+ throw new AstryxError(
+ `Theme "${member.theme.name}" must supply its componentIcons slot functions through a named import of its whole componentIcons map for family output.`,
+ undefined,
+ ERROR_CODES.ERR_THEME_INVALID,
+ );
+ }
+ ownValues[slot] = value;
+ }
+ if (Object.keys(ownValues).length > 0) own = JSON.stringify(ownValues);
+ }
+ if (info) {
+ // An imported map can hold an `undefined` slot: it keeps the parent's,
+ // and a root drops it, as `defineTheme` does.
+ const mergeName = `${binding}MergeComponentIcons`;
+ return {
+ imports,
+ expression: `${mergeName}(${inherited ?? '{}'}, ${own})`,
+ mergeName,
+ };
+ }
+ const expression = context.expression(own, inherited);
+ return expression ? {imports, expression} : null;
+}
/** Rebase a scraped relative registry import to the aggregate module. @param {any} info @param {string} filePath @param {string} outDir @param {string | undefined} override */
// prettier-ignore
function familyRegistryInput(info, filePath, outDir, override) {
@@ -3935,6 +4119,13 @@ export async function themeBuildFamily(
// rebased or overridden specifier replaces the scraped one.
// prettier-ignore
const iconImports = icon.info && ownIcons ? {imports: [{importPath: icon.info.importPath, importedName: icon.info.exportName, localName: ownIcons}], expression: ownIcons, exportName: ownIcons, iconsSpecifierImportPath: icon.info.importPath, iconsSpecifierLocalName: ownIcons} : null;
+ const componentIconInfo = familyComponentIcons(member, parent, {
+ themeBinding,
+ parentBinding,
+ outDir,
+ registryImports,
+ expression,
+ });
return (
indicatorImport +
generateBuiltModule(member.theme, iconImports, icon.specifier, {
@@ -3943,6 +4134,7 @@ export async function themeBuildFamily(
indicatorsExpression: expression(ownIndicators, inheritedIndicators),
artifactBaseName: baseName,
exportIcons: false,
+ componentIconInfo,
})
);
})
diff --git a/packages/cli/api/theme/build/icon-imports.mjs b/packages/cli/api/theme/build/icon-imports.mjs
index 1257e6be74..fcd37713bc 100644
--- a/packages/cli/api/theme/build/icon-imports.mjs
+++ b/packages/cli/api/theme/build/icon-imports.mjs
@@ -1,11 +1,13 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * Resolve importable icon registries for the selected theme export.
+ * Resolve importable icon registries, or component icon slot maps, for the
+ * selected theme export.
*
- * @input Loaded theme export identity, plus the caller's source reader and the
- * theme loader's resolver (this module performs no environment access).
- * @output Import bindings and an expression preserving inherited icon registries.
+ * @input Loaded theme export identity, the theme field to carry (`icons` or
+ * `componentIcons`), plus the caller's source reader and the theme loader's
+ * resolver (this module performs no environment access).
+ * @output Import bindings and an expression preserving inherited values.
* @position Private theme-build packaging helper; never evaluates authored source.
*/
@@ -21,15 +23,25 @@ import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
* @property {string} exportName
* @property {string} [iconsSpecifierImportPath]
* @property {string} [iconsSpecifierLocalName]
+ * @property {string} [mergeName] - Set when `expression` calls the slot merge
+ * function, which the module must declare under this name.
*/
/** @typedef {{kind: 'reference', module: any, binding: any, members: string[]}} RegistryReference */
/**
- * `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
+ * `entries` marks a package theme read for its entries: its public field
+ * (node-valued `icons`, or the static `componentIcons` view) merged with the
+ * `__` field that holds its functions, if any. `object` is an inline
+ * `componentIcons` object: each slot is a static value or an imported one.
+ * @typedef {{json: unknown} | {ref: RegistryReference} | {object: Array<[string, SlotData]>}} SlotData
+ * A `merge` with `theme` set merges a theme's own values over its base's;
+ * any other merge is a spread inside one object.
+ * @typedef {{kind: 'registry', ref: RegistryReference, preferredName: string, override?: boolean, entries?: boolean} | {kind: 'merge', base: RegistryPlan, own: RegistryPlan, theme?: boolean} | {kind: 'object', entries: Array<[string, SlotData]>}} RegistryPlan
*/
+/** Marks a node that is not a static JSON value. */
+const NOT_STATIC = Symbol('not static');
+
/** @param {any} node */
function unwrap(node) {
while (
@@ -83,8 +95,19 @@ function bindingNames(pattern) {
return [];
}
-/** @param {string} [name] @param {string} [reason] @returns {never} */
-function invalidRegistry(name, reason = '') {
+/** @param {string} [name] @param {string} [reason] @param {string} [field] @returns {never} */
+function registryError(name, reason = '', field = 'icons') {
+ if (field === 'componentIcons') {
+ const value = name ? `\`componentIcons: ${name}\`` : 'componentIcons';
+ throw new AstryxError(
+ `Theme sets ${value} but the build cannot carry it. ` +
+ (reason ? `${reason} ` : '') +
+ 'A built theme carries names, null, and requests made of static values, ' +
+ 'constants, or imported bindings, and slot functions imported from their own module.',
+ undefined,
+ ERROR_CODES.ERR_THEME_INVALID,
+ );
+ }
const registry = name ? `\`icons: ${name}\`` : 'an icon registry';
throw new AstryxError(
`Theme sets ${registry} but no import for the registry was found. ` +
@@ -106,9 +129,16 @@ function invalidRegistry(name, reason = '') {
* 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`.
*
+ * With `field: 'componentIcons'`, the same tracing carries a theme's slot
+ * values: a slot function must come from an import, and an inline object may
+ * also hold static values (names, `null`, requests), written as JSON. A built
+ * base module is read through its export, like a package theme. A theme's own
+ * slots merge over its base's through `mergeName`, which skips an
+ * `undefined` slot as `defineTheme` does.
+ *
* @param {string} filePath
* @param {string | undefined} exportName
- * @param {{hasIcons: boolean, functionEntries?: boolean, readSource: (filename: string) => string, resolveModule: (specifier: string, fromFile: string) => string | Promise<string>, reservedNames?: string[], rawInput?: boolean}} options
+ * @param {{hasIcons: boolean, functionEntries?: boolean, field?: 'icons' | 'componentIcons', mergeName?: string, 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(
@@ -117,12 +147,20 @@ export async function resolveIconImports(
{
hasIcons,
functionEntries = false,
+ field = 'icons',
+ mergeName = 'mergeComponentIcons',
readSource,
resolveModule,
reservedNames = [],
rawInput = false,
},
) {
+ const entriesField = `__${field}`;
+ const staticSlots = field === 'componentIcons';
+ const defaultName = staticSlots ? 'themeComponentIcons' : 'themeIcons';
+ /** @param {string} [name] @param {string} [reason] @returns {never} */
+ const invalidRegistry = (name, reason) => registryError(name, reason, field);
+
if (exportName === undefined) {
if (!hasIcons) return null;
invalidRegistry(
@@ -410,11 +448,11 @@ export async function resolveIconImports(
// `__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, preferredName: defaultName, entries: true}
: {
kind: 'registry',
- ref: {...ref, members: [...ref.members, 'icons']},
- preferredName: 'themeIcons',
+ ref: {...ref, members: [...ref.members, field]},
+ preferredName: defaultName,
};
}
@@ -431,9 +469,42 @@ export async function resolveIconImports(
});
}
+ /**
+ * Whether a node is a built theme module's theme object (`__built: true`).
+ * @param {any} module @param {any} node @param {Set<string>} [seen]
+ * @returns {boolean}
+ */
+ function isBuiltTheme(module, node, seen = new Set()) {
+ node = unwrap(node);
+ if (node?.type === 'Identifier') {
+ if (seen.has(node.name)) return false;
+ seen.add(node.name);
+ const binding = module.bindings.get(node.name);
+ return (
+ binding?.kind === 'const' && isBuiltTheme(module, binding.node, seen)
+ );
+ }
+ return (
+ node?.type === 'ObjectExpression' &&
+ node.properties.some(
+ (/** @type {any} */ item) =>
+ ['ObjectProperty', 'Property'].includes(item.type) &&
+ propertyName(item.key) === '__built' &&
+ unwrap(item.value)?.value === true,
+ )
+ );
+ }
+
/** @param {RegistryReference} ref @param {boolean} [rejectOpaque] @returns {Promise<RegistryPlan | null>} */
async function themeReference(ref, rejectOpaque = false) {
const target = await importedExport(ref);
+ if (target && staticSlots) {
+ // A built module's generated code is not traced: the module is imported
+ // and read through its export, like a package theme.
+ const selected = await selectedExport(target.module, target.name);
+ if (!selected.binding && isBuiltTheme(target.module, selected.node))
+ return packageTheme(ref);
+ }
if (target) return exportedTheme(target.module, target.name, rejectOpaque);
if (rejectOpaque)
invalidRegistry(
@@ -474,13 +545,15 @@ export async function resolveIconImports(
return {
kind: 'registry',
ref,
- preferredName: preferredName ?? 'themeIcons',
+ preferredName: preferredName ?? defaultName,
// A namespace's exported registry can be redirected to an icon module;
// a named theme's .icons cannot be imported from that sidecar.
override:
ref.binding.importedName === '*' && ref.members.length === 1,
};
}
+ if (staticSlots && node?.type === 'ObjectExpression')
+ return slotObject(module, node);
// Spreads merge in order. An object adding no entries, such as `{}`, is no
// local registry: a child keeps its inherited icons and a root emits none.
if (
@@ -501,6 +574,150 @@ export async function resolveIconImports(
invalidRegistry(preferredName ?? rootIdentifier(node) ?? undefined);
}
+ /** @param {any} item @returns {string | null} A plain property's static key. */
+ function plainKey(item) {
+ if (
+ !['ObjectProperty', 'Property'].includes(item.type) ||
+ item.method ||
+ (item.kind && item.kind !== 'init')
+ )
+ return null;
+ if (!item.computed) return propertyName(item.key);
+ return typeof item.key?.value === 'string' ? item.key.value : null;
+ }
+
+ /**
+ * A slot value as data the module can write: a JSON value, an imported
+ * binding (with any member reads), or an object of those. Unmutated `const`
+ * bindings and member reads on them are followed. Anything else, a function
+ * defined in the theme file included, is NOT_STATIC.
+ * @param {any} module @param {any} node @param {Set<string>} [path] - The
+ * `const` names on the current path, which a cycle would revisit.
+ * @returns {Promise<SlotData | typeof NOT_STATIC>}
+ */
+ async function slotData(module, node, path = new Set()) {
+ node = unwrap(node);
+ if (node?.type === 'NullLiteral') return {json: null};
+ if (
+ ['StringLiteral', 'NumericLiteral', 'BooleanLiteral', 'Literal'].includes(
+ node?.type,
+ ) &&
+ (node.value === null || typeof node.value !== 'object')
+ )
+ return {json: node.value};
+ if (node?.type === 'TemplateLiteral' && node.expressions.length === 0)
+ return {json: node.quasis[0].value.cooked};
+ if (
+ (node?.type === 'Identifier' &&
+ node.name === 'undefined' &&
+ !module.bindings.has(node.name)) ||
+ (node?.type === 'UnaryExpression' && node.operator === 'void')
+ )
+ return {json: undefined};
+ if (node?.type === 'Identifier') {
+ const binding = module.bindings.get(node.name);
+ if (!binding || module.mutated.has(node.name) || path.has(node.name))
+ return NOT_STATIC;
+ if (binding.kind === 'import')
+ return {ref: importedReference(module, binding)};
+ if (binding.kind !== 'const') return NOT_STATIC;
+ return slotData(module, binding.node, new Set([...path, node.name]));
+ }
+ if (node?.type === 'MemberExpression' && !node.optional) {
+ const name = node.computed
+ ? typeof node.property.value === 'string'
+ ? node.property.value
+ : null
+ : propertyName(node.property);
+ if (name === null) return NOT_STATIC;
+ const object = await slotData(module, node.object, path);
+ if (object === NOT_STATIC) return NOT_STATIC;
+ if ('ref' in object)
+ return {ref: {...object.ref, members: [...object.ref.members, name]}};
+ if ('object' in object) {
+ // The last property with a name wins, as in the object literal.
+ const entry = [...object.object]
+ .reverse()
+ .find(([key]) => key === name);
+ return entry ? entry[1] : {json: undefined};
+ }
+ return NOT_STATIC;
+ }
+ if (node?.type !== 'ObjectExpression') return NOT_STATIC;
+ /** @type {Array<[string, SlotData]>} */
+ const entries = [];
+ for (const item of node.properties) {
+ const key = plainKey(item);
+ if (key === null) return NOT_STATIC;
+ const value = await slotData(module, item.value, path);
+ if (value === NOT_STATIC) return NOT_STATIC;
+ entries.push([key, value]);
+ }
+ return {object: entries};
+ }
+
+ /** @param {any} module @param {any} node @param {Set<string>} [seen] @returns {boolean} */
+ function isLocalFunction(module, node, seen = new Set()) {
+ node = unwrap(node);
+ if (node?.type === 'Identifier' && !seen.has(node.name)) {
+ seen.add(node.name);
+ const binding = module.bindings.get(node.name);
+ return (
+ binding?.kind === 'const' && isLocalFunction(module, binding.node, seen)
+ );
+ }
+ return ['ArrowFunctionExpression', 'FunctionExpression'].includes(
+ node?.type,
+ );
+ }
+
+ /** @param {any} module @param {any} node @param {string} slot @returns {Promise<SlotData>} */
+ async function slotValue(module, node, slot) {
+ const data = await slotData(module, node);
+ if (data !== NOT_STATIC) return data;
+ invalidRegistry(
+ undefined,
+ isLocalFunction(module, node)
+ ? `The slot function for "${slot}" is defined in the theme file.`
+ : `The value for "${slot}" is neither a static value nor an imported binding.`,
+ );
+ }
+
+ /**
+ * An inline `componentIcons` object. Spreads and own slots apply in source
+ * order, as in the object itself.
+ * @param {any} module @param {any} node @returns {Promise<RegistryPlan | null>}
+ */
+ async function slotObject(module, node) {
+ /** @type {RegistryPlan | null} */
+ let result = null;
+ /** @type {Array<[string, SlotData]> | null} */
+ let entries = null;
+ /** @param {RegistryPlan | null} next */
+ const add = next => {
+ if (next)
+ result = result ? {kind: 'merge', base: result, own: next} : next;
+ };
+ for (const item of node.properties) {
+ if (item.type === 'SpreadElement' || item.type === 'SpreadProperty') {
+ if (entries) add({kind: 'object', entries});
+ entries = null;
+ add(await registry(module, item.argument));
+ continue;
+ }
+ const key = plainKey(item);
+ if (key === null)
+ invalidRegistry(
+ undefined,
+ 'A slot must be a plain property with a static name.',
+ );
+ entries ??= [];
+ entries.push([key, await slotValue(module, item.value, key)]);
+ }
+ if (entries) add({kind: 'object', entries});
+ return result;
+ }
+
/** @param {any} module @param {any} node @returns {Promise<Map<string, any>>} */
async function fields(module, node) {
node = unwrap(node);
@@ -516,7 +733,7 @@ export async function resolveIconImports(
if (ref) return referenceFields(ref);
}
if (node?.type === 'CallExpression' && isDefineTheme(module, node.callee)) {
- return new Map([['icons', {plan: await theme(module, node)}]]);
+ return new Map([[field, {plan: await theme(module, node)}]]);
}
if (node?.type !== 'ObjectExpression') invalidRegistry();
const result = new Map();
@@ -533,7 +750,7 @@ export async function resolveIconImports(
: propertyName(item.key);
if (key === null)
invalidRegistry(undefined, 'Computed theme keys cannot be resolved.');
- if (!['icons', '__icons', 'extends'].includes(key)) continue;
+ if (![field, entriesField, 'extends'].includes(key)) continue;
if (
!['ObjectProperty', 'Property'].includes(item.type) ||
item.method ||
@@ -586,9 +803,9 @@ export async function resolveIconImports(
}
const config = await fields(module, node);
const baseField = config.get('extends');
- // 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');
+ // A built module keeps its functions in `__icons` (or `__componentIcons`)
+ // beside the public view; those entries are the values to carry.
+ const iconField = config.get(entriesField) ?? config.get(field);
const base = baseField
? await theme(baseField.module, baseField.node)
: null;
@@ -597,7 +814,18 @@ export async function resolveIconImports(
? iconField.plan
: await registry(iconField.module, iconField.node)
: null;
- return base && own ? {kind: 'merge', base, own} : (own ?? base);
+ // A root's own slot values pass through the theme merge too, so an
+ // `undefined` slot is dropped as `defineTheme` drops it.
+ if (staticSlots && own && !base)
+ return {
+ kind: 'merge',
+ base: {kind: 'object', entries: []},
+ own,
+ theme: true,
+ };
+ return base && own
+ ? {kind: 'merge', base, own, theme: true}
+ : (own ?? base);
}
let plan;
@@ -626,7 +854,7 @@ export async function resolveIconImports(
/^[A-Za-z_$][\w$]*$/u.test(preferred) &&
!['default', 'await', 'yield'].includes(preferred)
? preferred
- : 'themeIcons';
+ : defaultName;
let name = stem;
let counter = 1;
while (used.has(name)) name = `${stem}${counter++}`;
@@ -652,19 +880,8 @@ export async function resolveIconImports(
return relative.startsWith('.') ? relative : `./${relative}`;
}
- /** @param {RegistryPlan} value @returns {{expression: string, preferredName: string, overridePath?: string, overrideLocalName?: string}} */
- function render(value) {
- if (value.kind === 'merge') {
- const base = render(value.base);
- const own = render(value.own);
- return {
- expression: `{...${base.expression}, ...${own.expression}}`,
- preferredName: 'themeIcons',
- overridePath: own.overridePath,
- overrideLocalName: own.overrideLocalName,
- };
- }
- const {ref} = value;
+ /** @param {RegistryReference} ref */
+ function importedTarget(ref) {
const source = importPath(ref);
const identity = `${source}\0${ref.binding.importedName}\0${JSON.stringify(ref.members)}`;
let localName = emitted.get(identity);
@@ -677,12 +894,54 @@ export async function resolveIconImports(
localName,
});
}
- const target = ref.members.reduce(
- (result, member) => `${result}[${JSON.stringify(member)}]`,
+ return {
+ source,
localName,
- );
+ target: ref.members.reduce(
+ (result, member) => `${result}[${JSON.stringify(member)}]`,
+ localName,
+ ),
+ };
+ }
+
+ /** @param {SlotData} data @returns {string} */
+ function renderData(data) {
+ if ('ref' in data) return importedTarget(data.ref).target;
+ if ('object' in data)
+ return `{${data.object
+ .map(([key, entry]) => `${JSON.stringify(key)}: ${renderData(entry)}`)
+ .join(', ')}}`;
+ return data.json === undefined ? 'void 0' : JSON.stringify(data.json);
+ }
+
+ /** @param {RegistryPlan} value @returns {{expression: string, preferredName: string, overridePath?: string, overrideLocalName?: string}} */
+ function render(value) {
+ if (value.kind === 'merge') {
+ const base = render(value.base);
+ const own = render(value.own);
+ const themeMerge = staticSlots && value.theme === true;
+ if (themeMerge) usesMerge = true;
+ return {
+ expression: themeMerge
+ ? `${mergeName}(${base.expression}, ${own.expression})`
+ : `{...${base.expression}, ...${own.expression}}`,
+ preferredName: defaultName,
+ overridePath: own.overridePath,
+ overrideLocalName: own.overrideLocalName,
+ };
+ }
+ if (value.kind === 'object') {
+ // An `undefined` slot stays in the object, as in the source, so the
+ // theme merge leaves the inherited slot in place.
+ return {
+ expression: renderData({object: value.entries}),
+ preferredName: defaultName,
+ };
+ }
+ const {ref} = value;
+ const {source, localName, target} = importedTarget(ref);
const expression = value.entries
- ? `{...${target}["icons"], ...${target}["__icons"]}`
+ ? `{...${target}[${JSON.stringify(field)}], ...${target}[${JSON.stringify(entriesField)}]}`
: target;
return {
expression,
@@ -696,6 +955,7 @@ export async function resolveIconImports(
};
}
+ let usesMerge = false;
const rendered = render(plan);
const name =
rendered.preferredName === rendered.expression &&
@@ -706,6 +966,7 @@ export async function resolveIconImports(
imports,
expression: rendered.expression,
exportName: name,
+ ...(usesMerge ? {mergeName} : {}),
...(rendered.overridePath
? {
iconsSpecifierImportPath: rendered.overridePath,
diff --git a/packages/cli/assets/docs/author-a-theme.doc.mjs b/packages/cli/assets/docs/author-a-theme.doc.mjs
index e335e426df..6c084752ed 100644
--- a/packages/cli/assets/docs/author-a-theme.doc.mjs
+++ b/packages/cli/assets/docs/author-a-theme.doc.mjs
@@ -139,7 +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."},
+ {type: 'prose', text: "A built theme keeps its `componentIcons`. Names, `null` values, and static requests are written into the module. A slot function stays a function: the module imports it from the module the theme source imports it from, so component slots resolve the same for the built theme as for the runtime theme. The built theme's `componentIcons` field leaves out slot functions, as the runtime theme's does. A slot function defined in the theme file fails the build: move it to its own module and import it. In `--family` output, a member supplies its own slot functions through a named import of its whole `componentIcons` map. The module keeps each slot import as the theme source spells it, and `--icons-specifier` does not change it, so with `--out` in another directory, make a module answer to that specifier from the output directory, as for the icon registry."},
],
},
{
diff --git a/packages/cli/assets/theme.template.ts b/packages/cli/assets/theme.template.ts
index 82253d80c9..971025a4af 100644
--- a/packages/cli/assets/theme.template.ts
+++ b/packages/cli/assets/theme.template.ts
@@ -351,9 +351,12 @@ export const myTheme = defineTheme({
* 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.
+ * Keep a slot function in its own module and import it, so a built theme
+ * can import it too. Here `copySlot` is
+ * `({copied}) => ({icon: copied ? 'checkDouble' : 'copy'})`.
* Reference: `astryx docs icons`; each component's docs list its slots.
*/
- // componentIcons: {'code-block-copy': 'clock'},
+ // componentIcons: {'code-block-copy': copySlot},
/**
* Replace the small components that DRAW control state — the checkbox box,