Skip to content

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

TypeScript

feat(Icon): a theme's width and height on an Icon size set its glyph dimension (#8759)

Xinzi Zhoudb584bcb0abe
diff --git a/.changeset/icon-theme-size-dimensions.md b/.changeset/icon-theme-size-dimensions.md
new file mode 100644
index 0000000000..ee28a1bf48
--- /dev/null
+++ b/.changeset/icon-theme-size-dimensions.md
@@ -0,0 +1,8 @@
+---
+'@astryxdesign/core': patch
+'@astryxdesign/cli': patch
+---
+
+[feat] A theme sets the dimension of each Icon size: `width` and `height` in `px` or `rem` on `components.icon['size:sm']` (or `xsm`, `md`, `lg`) resize that size's glyph, for semantic icon names and for SVG components passed to `Icon`, in runtime and built themes alike. Before, those properties sized the box around a semantic icon but not its 1em artwork, and an app that compiles StyleX without CSS layers let the icon's own size win over the theme. A size the theme does not style still renders at 12, 16, 20, or 24px at a 16px root and scales with the root font size. `astryx docs theme` gains an Icon sizes section.
+
+@imdreamrunner
diff --git a/apps/storybook/stories/IconSizeTheming.stories.tsx b/apps/storybook/stories/IconSizeTheming.stories.tsx
index 1528c218f9..b75c2cda02 100644
--- a/apps/storybook/stories/IconSizeTheming.stories.tsx
+++ b/apps/storybook/stories/IconSizeTheming.stories.tsx
@@ -24,11 +24,9 @@ const FRUITS: string[] = ['Apple', 'Banana', 'Orange'];
/**
* Icon's own scale is 12/16/20/24px. A theme re-points the whole scale by
- * targeting each `size:*` key on the `icon` target.
- *
- * `fontSize` is set alongside the box because registry icons (`icon="search"`)
- * are 1em-based SVGs inside a span — without it the span resizes and the glyph
- * inside it does not.
+ * setting `width` and `height` on each `size:*` key of the `icon` target. A
+ * registry icon (`icon="search"`) sizes its 1em artwork from that dimension
+ * itself, so no `fontSize` is needed.
*/
function iconScale(
xsm: string,
@@ -39,7 +37,7 @@ function iconScale(
return Object.fromEntries(
([xsm, sm, md, lg] as const).map((value, i) => [
`size:${SIZES[i]}`,
- {width: value, height: value, fontSize: value},
+ {width: value, height: value},
]),
);
}
@@ -198,16 +196,17 @@ const meta: Meta = {
" name: 'spacious-icons',\n" +
' components: {\n' +
' icon: {\n' +
- " 'size:sm': {width: '1.375rem', height: '1.375rem', fontSize: '1.375rem'},\n" +
- " 'size:md': {width: '1.75rem', height: '1.75rem', fontSize: '1.75rem'},\n" +
+ " 'size:sm': {width: '1.375rem', height: '1.375rem'},\n" +
+ " 'size:md': {width: '1.75rem', height: '1.75rem'},\n" +
' },\n' +
' },\n' +
'});\n' +
'```\n\n' +
- 'Set `fontSize` alongside the box: registry icons (`icon="search"`) ' +
- 'are 1em-based SVGs in a span, so the box alone resizes the span and ' +
- 'not the glyph. Component-mode icons (`icon={BellIcon}`) need only ' +
- 'width/height, and setting `fontSize` on them is harmless.',
+ 'Width and height size both registry icons (`icon="search"`), whose ' +
+ '1em artwork follows the dimension, and component-mode icons ' +
+ '(`icon={BellIcon}`). Give them in `px` or `rem`: a registry icon ' +
+ 'takes its font size from the dimension, so an `em` value would ' +
+ 'also grow its box.',
},
},
},
diff --git a/packages/cli/api/theme/build/build.test.mjs b/packages/cli/api/theme/build/build.test.mjs
index 4cf02b8c53..be9534516d 100644
--- a/packages/cli/api/theme/build/build.test.mjs
+++ b/packages/cli/api/theme/build/build.test.mjs
@@ -599,6 +599,33 @@ describe('themeBuild() — component override validation', () => {
});
});
+describe('themeBuild() — Icon size dimensions', () => {
+ it('writes width and height on an icon size into the vars the glyph reads, with no warnings', async () => {
+ // spec:AST-087 FR10: a built theme sets an Icon size's glyph dimension the
+ // way the runtime provider does, through the shared compiler's derived
+ // vars. Raw width/height would lose to a consumer's unlayered StyleX.
+ const themeFile = path.join(tmpDir, 'iconsizes.mjs');
+ fs.writeFileSync(
+ themeFile,
+ `export default {
+ name: 'iconsizes',
+ tokens: {'--color-bg': '#0a0a0a'},
+ components: {icon: {'size:sm': {width: '18px', height: '22px'}}},
+ };\n`,
+ );
+
+ const result = await themeBuild('iconsizes.mjs', {}, {cwd: tmpDir});
+
+ expect(result?.data.warnings).toEqual([]);
+ const css = fs.readFileSync(path.join(tmpDir, 'iconsizes.css'), 'utf8');
+ const rule =
+ css.match(/\.astryx-icon\[data-size="sm"\]\s*\{([^}]*)\}/)?.[1] ?? '';
+ expect(rule).toMatch(/--_icon-width:\s*18px/);
+ expect(rule).toMatch(/--_icon-height:\s*22px/);
+ expect(rule).not.toMatch(/(^|[\s;])(width|height)\s*:/);
+ });
+});
+
describe('themeBuild() — the shipped theme template', () => {
// `assets/theme.template.ts` is what `astryx theme template` puts in a
// consumer's project. It is the one theme file we hand out, so it has to
diff --git a/packages/cli/assets/docs/theme.doc.dense.mjs b/packages/cli/assets/docs/theme.doc.dense.mjs
index 6aa26a666d..6f991dd2d6 100644
--- a/packages/cli/assets/docs/theme.doc.dense.mjs
+++ b/packages/cli/assets/docs/theme.doc.dense.mjs
@@ -21,6 +21,14 @@ export const docsDense = {
{type: 'prose', text: "new palette: `astryx theme palette generate palette.config.json --out palette.generated.ts` → review + commit module and receipt → `import {palette} from './palette.generated';` → map semantic tokens to stable stops such as `palette.neutral.light[100]` / `palette.neutral.dark[15]`. regeneration updates mapped roles; generation does not rewrite the theme."},
],
},
+ {
+ section: 'Icon sizes',
+ title: 'Icon sizes',
+ content: [
+ {type: 'prose', text: "theme sets each Icon size's glyph dimension: `width` + `height` on `components.icon['size:sm']` (or xsm/md/lg); semantic names + SVG components alike. px or rem only: a semantic icon takes its font size from the dimension, so em also grows its box. unstyled: xsm/sm/md/lg = 12/16/20/24px at 16px root, scale w/ root font size (rem keeps it). size names are fixed."},
+ null,
+ ],
+ },
{
section: 'Dark mode',
title: 'Dark mode',
diff --git a/packages/cli/assets/docs/theme.doc.mjs b/packages/cli/assets/docs/theme.doc.mjs
index f5b2c2288b..0df7450e7a 100644
--- a/packages/cli/assets/docs/theme.doc.mjs
+++ b/packages/cli/assets/docs/theme.doc.mjs
@@ -53,6 +53,22 @@ export const docs = {
},
],
},
+ {
+ id: 'icon-sizes',
+ title: 'Icon sizes',
+ content: [
+ {
+ type: 'prose',
+ text: "A theme sets the dimension of each Icon size in its stylesheet: `width` and `height` on `components.icon['size:sm']` (or `xsm`, `md`, `lg`) resize that size's glyph, for semantic icon names and SVG components passed to `Icon` alike. Give the dimension in `px` or `rem`: a semantic icon takes its font size from it, so an `em` value would also grow its box. A size the theme leaves alone stays 12, 16, 20, or 24px at a 16px root (`xsm`, `sm`, `md`, `lg`) and scales with the root font size; `rem` keeps that scaling. The four size names are fixed.",
+ },
+ {
+ type: 'code',
+ lang: 'tsx',
+ label: 'Set Icon size dimensions',
+ code: "const brandTheme = defineTheme({\n name: 'brand',\n components: {\n icon: {\n 'size:sm': {width: '1.125rem', height: '1.125rem'},\n 'size:lg': {width: '1.75rem', height: '1.75rem'},\n },\n },\n});",
+ },
+ ],
+ },
{
id: 'light-dark-mode',
title: 'Dark mode',
diff --git a/packages/cli/assets/docs/theme.doc.zh.mjs b/packages/cli/assets/docs/theme.doc.zh.mjs
index 2bdd7f9e51..6639528c12 100644
--- a/packages/cli/assets/docs/theme.doc.zh.mjs
+++ b/packages/cli/assets/docs/theme.doc.zh.mjs
@@ -25,6 +25,17 @@ export const docsZh = {
},
],
},
+ {
+ section: 'Icon sizes',
+ title: '图标尺寸',
+ content: [
+ {
+ type: 'prose',
+ text: "主题在样式表中设置每个 Icon 尺寸的大小:在 `components.icon['size:sm']`(或 `xsm`、`md`、`lg`)上设置 `width` 和 `height`,即可调整该尺寸的图标,语义图标名称和直接传给 `Icon` 的 SVG 组件都适用。请使用 `px` 或 `rem` 设置尺寸:语义图标会据此设置自身的字号,因此 `em` 值也会放大它的外框。主题未设置的尺寸在 16px 根字号下保持 12、16、20 或 24px(`xsm`、`sm`、`md`、`lg`),并随根字号缩放;`rem` 可保留这种缩放。四个尺寸名称是固定的。",
+ },
+ null,
+ ],
+ },
{
section: 'Dark mode',
title: '深色模式',
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 1e3c320ea5..dc1658e90b 100644
--- a/packages/cli/test/__golden__/no-icon-set/docs-topics.json
+++ b/packages/cli/test/__golden__/no-icon-set/docs-topics.json
@@ -251,10 +251,11 @@
"sections": [
"quick-start",
"creating-a-custom-theme",
+ "icon-sizes",
"light-dark-mode",
"integration-themes"
],
- "skeleton": "4af0a08dbcf2008c2ad6c12e61a1451130f10109fdb666a08933a7ce69ce18bd",
+ "skeleton": "eacd1432d49237ed62f82ea054c0e5930503e9f072ab40b4965461f29cf31080",
"mentions": []
},
"use-a-theme": {
diff --git a/packages/cli/test/__golden__/no-icon-set/docs-tree.json b/packages/cli/test/__golden__/no-icon-set/docs-tree.json
index d25cb9ca7f..973dbe84a4 100644
--- a/packages/cli/test/__golden__/no-icon-set/docs-tree.json
+++ b/packages/cli/test/__golden__/no-icon-set/docs-tree.json
@@ -1217,6 +1217,7 @@
"sections": [
"quick-start",
"creating-a-custom-theme",
+ "icon-sizes",
"light-dark-mode",
"integration-themes"
],
diff --git a/packages/cli/test/__golden__/no-icon-set/search-icon-set.json b/packages/cli/test/__golden__/no-icon-set/search-icon-set.json
index 21d9a87cb7..996e30d2e0 100644
--- a/packages/cli/test/__golden__/no-icon-set/search-icon-set.json
+++ b/packages/cli/test/__golden__/no-icon-set/search-icon-set.json
@@ -3,7 +3,7 @@
"type": "search",
"data": {
"query": "icon set",
- "matchCount": 367,
+ "matchCount": 369,
"results": [
{
"domain": "doc",
@@ -33,6 +33,19 @@
"This lets you swap the icon set (e.g."
]
},
+ {
+ "domain": "doc",
+ "name": "theme",
+ "package": "@astryxdesign/cli",
+ "score": "<text>",
+ "reason": "<text>",
+ "description": "<text>",
+ "section": "<text>",
+ "title": "<text>",
+ "command": "astryx docs theme icon-sizes",
+ "parent": "astryx docs theme --index",
+ "mentions": []
+ },
{
"domain": "template",
"name": "ToolbarTableFilter",
@@ -232,18 +245,6 @@
"kind": "block",
"command": "astryx template ChatComposerDrawerWithProgress --type block",
"mentions": []
- },
- {
- "domain": "template",
- "name": "ChatComposerFooterActions",
- "package": "@astryxdesign/core",
- "score": "<text>",
- "reason": "<text>",
- "description": "<text>",
- "displayName": "<text>",
- "kind": "block",
- "command": "astryx template ChatComposerFooterActions --type block",
- "mentions": []
}
]
},
diff --git a/packages/cli/test/__golden__/no-icon-set/search-icon-set.txt b/packages/cli/test/__golden__/no-icon-set/search-icon-set.txt
index 3806e4d19f..d7c74d2679 100644
--- a/packages/cli/test/__golden__/no-icon-set/search-icon-set.txt
+++ b/packages/cli/test/__golden__/no-icon-set/search-icon-set.txt
@@ -1,4 +1,4 @@
-Results for "icon set" (20 of 367)
+Results for "icon set" (20 of 369)
name: authoring/building-blocks/templates/build-the-template/template-assets/template-icons
section: use-astryx-icon
domain: doc
@@ -11,6 +11,12 @@ domain: doc
package: @astryxdesign/cli
command: pnpm exec astryx docs icons theme-overrides
parent: pnpm exec astryx docs icons --index
+name: theme
+section: icon-sizes
+domain: doc
+package: @astryxdesign/cli
+command: pnpm exec astryx docs theme icon-sizes
+parent: pnpm exec astryx docs theme --index
name: ToolbarTableFilter
domain: template
package: @astryxdesign/core
@@ -83,8 +89,4 @@ command: pnpm exec astryx template ChatComposerDrawerShowcase --type block
name: ChatComposerDrawerWithProgress
domain: template
package: @astryxdesign/core
-command: pnpm exec astryx template ChatComposerDrawerWithProgress --type block
-name: ChatComposerFooterActions
-domain: template
-package: @astryxdesign/core
-command: pnpm exec astryx template ChatComposerFooterActions --type block
\ No newline at end of file
+command: pnpm exec astryx template ChatComposerDrawerWithProgress --type block
\ No newline at end of file
diff --git a/packages/cli/test/__golden__/no-icon-set/search-icon.json b/packages/cli/test/__golden__/no-icon-set/search-icon.json
index 2033da1df8..67a674f40e 100644
--- a/packages/cli/test/__golden__/no-icon-set/search-icon.json
+++ b/packages/cli/test/__golden__/no-icon-set/search-icon.json
@@ -3,7 +3,7 @@
"type": "search",
"data": {
"query": "icon",
- "matchCount": 220,
+ "matchCount": 222,
"results": [
{
"domain": "component",
diff --git a/packages/cli/test/__golden__/no-icon-set/search-icon.txt b/packages/cli/test/__golden__/no-icon-set/search-icon.txt
index 77f45f34fc..aa160626ff 100644
--- a/packages/cli/test/__golden__/no-icon-set/search-icon.txt
+++ b/packages/cli/test/__golden__/no-icon-set/search-icon.txt
@@ -1,4 +1,4 @@
-Results for "icon" (20 of 220)
+Results for "icon" (20 of 222)
name: Icon
domain: component
package: @astryxdesign/core
diff --git a/packages/core/src/Icon/Icon.doc.mjs b/packages/core/src/Icon/Icon.doc.mjs
index 38f084e29f..917c2027da 100644
--- a/packages/core/src/Icon/Icon.doc.mjs
+++ b/packages/core/src/Icon/Icon.doc.mjs
@@ -86,7 +86,7 @@ export const docs = {
name: 'size',
type: "'xsm' | 'sm' | 'md' | 'lg'",
description:
- 'Icon size. An explicit value wins. When omitted, Icon uses the nearest default supplied by an owning Astryx component for its icon slot, then falls back to md when no contextual default exists.',
+ "Icon size. xsm, sm, md, and lg are 12, 16, 20, and 24px at a 16px root and scale with the root font size; a theme sets a size's glyph dimension with width and height, in px or rem, on components.icon['size:sm'] (and the other sizes). An explicit value wins. When omitted, Icon uses the nearest default supplied by an owning Astryx component for its icon slot, then falls back to md when no contextual default exists.",
default: "Contextual; otherwise 'md'",
},
{
@@ -104,6 +104,26 @@ export const docs = {
],
theming: {
targets: [{className: 'astryx-icon', visualProps: ['color', 'size']}],
+ vars: [
+ {
+ name: '--_icon-width',
+ description:
+ 'Glyph width for the size; set by width on the icon target',
+ default: '0.75rem, 1rem, 1.25rem, or 1.5rem by size',
+ private: true,
+ },
+ {
+ name: '--_icon-height',
+ description:
+ 'Glyph height for the size; set by height on the icon target',
+ default: '0.75rem, 1rem, 1.25rem, or 1.5rem by size',
+ private: true,
+ },
+ ],
+ derived: [
+ {property: 'width', vars: ['--_icon-width'], replaces: true},
+ {property: 'height', vars: ['--_icon-height'], replaces: true},
+ ],
},
usage: {
description:
@@ -196,7 +216,7 @@ export const docsZh = {
name: 'size',
type: "'xsm' | 'sm' | 'md' | 'lg'",
description:
- '图标尺寸。显式值优先。省略时,Icon 使用最近的 Astryx 所属组件为其图标槽提供的默认尺寸;如果没有上下文默认值,则回退为 md。',
+ "图标尺寸。xsm、sm、md、lg 在 16px 根字号下分别为 12、16、20、24px,并随根字号缩放;主题在 components.icon['size:sm'](及其他尺寸)上以 px 或 rem 设置 width 和 height,即可决定该尺寸的图标尺寸。显式值优先。省略时,Icon 使用最近的 Astryx 所属组件为其图标槽提供的默认尺寸;如果没有上下文默认值,则回退为 md。",
default: "上下文默认值;否则为 'md'",
},
{
@@ -214,6 +234,24 @@ export const docsZh = {
],
theming: {
targets: [{className: 'astryx-icon', visualProps: ['color', 'size']}],
+ vars: [
+ {
+ name: '--_icon-width',
+ description: '该尺寸的图标宽度;由 icon 目标上的 width 设置',
+ default: '按尺寸为 0.75rem、1rem、1.25rem 或 1.5rem',
+ private: true,
+ },
+ {
+ name: '--_icon-height',
+ description: '该尺寸的图标高度;由 icon 目标上的 height 设置',
+ default: '按尺寸为 0.75rem、1rem、1.25rem 或 1.5rem',
+ private: true,
+ },
+ ],
+ derived: [
+ {property: 'width', vars: ['--_icon-width'], replaces: true},
+ {property: 'height', vars: ['--_icon-height'], replaces: true},
+ ],
},
usage: {
description:
@@ -342,7 +380,7 @@ export const docsDense = {
propDescriptions: {
icon: 'Semantic icon name or SVG component. Valid names: close, chevronDown, chevronLeft, chevronRight, chevronsLeft, chevronsRight, check, success, error, warning, info, calendar, clock, externalLink, menu, moreHorizontal, search, upload, arrowUp, arrowDown, arrowsUpDown, funnel, eyeSlash, viewColumns, copy, checkDouble, wrench, stop, microphone. For others, pass an SVG component.',
color: 'Color variant mapped to Astryx icon color tokens.',
- size: "explicit Icon size; otherwise nearest owning-component default, then 'md' when no contextual default exists",
+ size: "xsm/sm/md/lg = 12/16/20/24px at a 16px root, scale w/ root font size; theme sets a size's glyph dimension via width + height (px or rem) on components.icon['size:sm'] etc. Explicit Icon size; otherwise nearest owning-component default, then 'md' when no contextual default exists",
label:
'Accessible name for a meaningful, standalone icon. Sets role="img" + aria-label and drops the default aria-hidden. Omit (default) for decorative icons (stays aria-hidden). Empty string = decorative. The accessible-name/alt-text prop for icons.',
xstyle:
diff --git a/packages/core/src/Icon/Icon.test.tsx b/packages/core/src/Icon/Icon.test.tsx
index 18e63e29fc..79b75bff80 100644
--- a/packages/core/src/Icon/Icon.test.tsx
+++ b/packages/core/src/Icon/Icon.test.tsx
@@ -3,7 +3,8 @@
/**
* @file Icon.test.tsx
* @input Uses vitest, @testing-library/react, Icon component
- * @output Unit tests for Icon component behavior
+ * @output Unit tests for Icon component behavior, including theme size
+ * dimensions
* @position Testing; validates Icon.tsx implementation
*
* SYNC: When Icon.tsx changes, update tests to match new behavior
@@ -13,6 +14,7 @@ import {describe, it, expect, vi} from 'vitest';
import {render, screen} from '@testing-library/react';
import * as stylex from '@stylexjs/stylex';
import {TestIcon} from '../__tests__/TestIcon';
+import {unthemedLength} from '../__tests__/unthemedLength';
import {Theme} from '../theme/Theme';
import {defineTheme} from '../theme/defineTheme';
import {resetThemes} from '../theme/themeRegistry';
@@ -24,6 +26,11 @@ import {
type IconRequest,
} from './globalIconRegistry';
+/** The custom properties a declaration value reads, in order. */
+function varsRead(value: string): string[] {
+ return [...value.matchAll(/var\(\s*(--[\w-]+)/g)].map(match => match[1]);
+}
+
describe('Icon', () => {
it('renders the icon component', () => {
render(<Icon icon={TestIcon} data-testid="icon" />);
@@ -125,8 +132,8 @@ describe('Icon', () => {
/>,
);
const style = getComputedStyle(screen.getByTestId('icon'));
- expect(style.width).toBe(expected);
- expect(style.height).toBe(expected);
+ expect(unthemedLength(style.width)).toBe(expected);
+ expect(unthemedLength(style.height)).toBe(expected);
unmount();
}
});
@@ -147,10 +154,10 @@ describe('Icon', () => {
/>,
);
const style = getComputedStyle(screen.getByTestId('icon'));
- expect(style.width).toBe(expected);
- expect(style.height).toBe(expected);
+ expect(unthemedLength(style.width)).toBe(expected);
+ expect(unthemedLength(style.height)).toBe(expected);
// fontSize is expressed in rem so 1em-based registry icons scale too.
- expect(style.fontSize).toBe(expected);
+ expect(unthemedLength(style.fontSize)).toBe(expected);
unmount();
}
});
@@ -175,8 +182,113 @@ describe('Icon', () => {
const icon = screen.getByTestId('icon');
expect(icon).toHaveAttribute('data-size', 'md');
- expect(getComputedStyle(icon).width).toBe('1.25rem');
- expect(getComputedStyle(icon).height).toBe('1.25rem');
+ expect(unthemedLength(getComputedStyle(icon).width)).toBe('1.25rem');
+ expect(unthemedLength(getComputedStyle(icon).height)).toBe('1.25rem');
+ });
+
+ describe('theme size dimensions', () => {
+ // spec:AST-087 FR10, component:Icon FR7: width and height on an `icon`
+ // size selector set that size's glyph dimension in both source modes,
+ // and a size the theme leaves alone keeps its own. jsdom resolves neither
+ // `var()` nor the theme's scoped layer, so this checks the two halves that
+ // meet in the browser: the rule the provider mounts writes the dimension
+ // into exactly the vars the glyph's own size styles read.
+ const sizes = {
+ xsm: '0.75rem',
+ sm: '1rem',
+ md: '1.25rem',
+ lg: '1.5rem',
+ } as const;
+ type Size = keyof typeof sizes;
+
+ /** The declarations of the mounted theme rule for one Icon size. */
+ function mountedSizeRule(
+ themeName: string,
+ size: Size,
+ ): Record<string, string> | null {
+ const css =
+ document.querySelector<HTMLStyleElement>(
+ `style[data-astryx-theme="${themeName}"]`,
+ )?.textContent ?? '';
+ const selector = `.astryx-icon[data-size="${size}"] {`;
+ const start = css.indexOf(selector);
+ if (start === -1) {
+ return null;
+ }
+ const body = css.slice(start + selector.length, css.indexOf('}', start));
+ return Object.fromEntries(
+ body
+ .split(';')
+ .map(declaration => declaration.split(':').map(part => part.trim()))
+ .filter(([property]) => property),
+ );
+ }
+
+ it.each(Object.keys(sizes) as Size[])(
+ 'a %s rule sets that glyph in both modes and leaves the other sizes alone',
+ styled => {
+ resetIcons();
+ resetThemes();
+ const themeName = `icon-size-${styled}`;
+ render(
+ <Theme
+ theme={defineTheme({
+ name: themeName,
+ components: {
+ icon: {[`size:${styled}`]: {width: '18px', height: '22px'}},
+ },
+ })}>
+ {(Object.keys(sizes) as Size[]).map(size => (
+ <span key={size}>
+ <Icon
+ icon={TestIcon}
+ size={size}
+ data-testid={`direct-${size}`}
+ />
+ <Icon
+ icon="check"
+ size={size}
+ data-testid={`registry-${size}`}
+ />
+ </span>
+ ))}
+ </Theme>,
+ );
+
+ const mounted = mountedSizeRule(themeName, styled);
+ expect(mounted).not.toBeNull();
+ const declared = mounted ?? {};
+ // Raw width/height would lose to an unlayered StyleX build, so the
+ // rule carries the dimension only through the glyph's vars.
+ expect(Object.keys(declared)).not.toContain('width');
+ expect(Object.keys(declared)).not.toContain('height');
+
+ for (const size of Object.keys(sizes) as Size[]) {
+ for (const mode of ['direct', 'registry']) {
+ const style = getComputedStyle(
+ screen.getByTestId(`${mode}-${size}`),
+ );
+ if (size !== styled) {
+ expect(mountedSizeRule(themeName, size)).toBeNull();
+ expect(unthemedLength(style.width)).toBe(sizes[size]);
+ expect(unthemedLength(style.height)).toBe(sizes[size]);
+ continue;
+ }
+ const [widthVar] = varsRead(style.width);
+ const [heightVar] = varsRead(style.height);
+ expect(declared[widthVar], `${mode} width`).toBe('18px');
+ expect(declared[heightVar], `${mode} height`).toBe('22px');
+ if (mode === 'registry') {
+ // 1em registry artwork follows the font size: the smaller side.
+ expect(style.fontSize).toMatch(/^min\(/);
+ expect(varsRead(style.fontSize).sort()).toEqual(
+ [widthVar, heightVar].sort(),
+ );
+ }
+ }
+ }
+ },
+ );
});
it('applies aria-hidden by default in string (registry) mode', () => {
diff --git a/packages/core/src/Icon/Icon.tsx b/packages/core/src/Icon/Icon.tsx
index c1228df1aa..6e45426b1e 100644
--- a/packages/core/src/Icon/Icon.tsx
+++ b/packages/core/src/Icon/Icon.tsx
@@ -15,6 +15,11 @@
* theme's icon registry (or built-in fallback SVGs) and wrapped in a styled span.
* A function registry entry receives `{size}`, the size resolved by ORD1.
*
+ * Both modes size the glyph from the `icon` target's private size vars
+ * (`iconSizeStyles` in IconSize.stylex.ts, `registrySizeStyles` below), so a
+ * theme's `width` and `height` on that target's size selector set the size's
+ * glyph dimension, including the font size 1em-based registry artwork follows.
+ *
* SYNC: When modified, update these files to stay in sync:
* - /packages/core/src/Icon/Icon.doc.mjs (props table, features, implementation notes)
* - /packages/core/src/Icon/Icon.test.tsx (tests for new/changed behavior)
@@ -33,11 +38,7 @@ import type {IconName, NamespacedIconName} from './globalIconRegistry';
import {mergeProps} from '../utils';
import {themeProps} from '../utils/themeProps';
import {useIconSize} from './IconDefaultSizeContext';
-import {
- iconBoxSizeStyles,
- iconSizeStyles,
- type IconSize,
-} from './IconSize.stylex';
+import {iconSizeStyles, type IconSize} from './IconSize.stylex';
export type {IconSize} from './IconSize.stylex';
@@ -58,6 +59,36 @@ const styles = stylex.create({
},
});
+/**
+ * Size styles for string-based registry icons: the glyph dimensions
+ * `iconSizeStyles` reads from the `icon` target's private vars, plus a
+ * `fontSize`, because registry artwork is 1em-based. `fontSize` is the smaller
+ * side, which fits square artwork into a non-square box the way an SVG viewBox
+ * does.
+ */
+const registrySizeStyles = stylex.create({
+ xsm: {
+ width: 'var(--_icon-width, 0.75rem)',
+ height: 'var(--_icon-height, 0.75rem)',
+ fontSize: 'min(var(--_icon-width, 0.75rem), var(--_icon-height, 0.75rem))',
+ },
+ sm: {
+ width: 'var(--_icon-width, 1rem)',
+ height: 'var(--_icon-height, 1rem)',
+ fontSize: 'min(var(--_icon-width, 1rem), var(--_icon-height, 1rem))',
+ },
+ md: {
+ width: 'var(--_icon-width, 1.25rem)',
+ height: 'var(--_icon-height, 1.25rem)',
+ fontSize: 'min(var(--_icon-width, 1.25rem), var(--_icon-height, 1.25rem))',
+ },
+ lg: {
+ width: 'var(--_icon-width, 1.5rem)',
+ height: 'var(--_icon-height, 1.5rem)',
+ fontSize: 'min(var(--_icon-width, 1.5rem), var(--_icon-height, 1.5rem))',
+ },
+});
+
const colorStyles = stylex.create({
primary: {
color: colorVars['--color-icon-primary'],
@@ -164,6 +195,9 @@ export interface IconProps extends Omit<
* - 'md': 1.25rem (20px at a 16px root)
* - 'lg': 1.5rem (24px at a 16px root)
*
+ * A theme sets a size's glyph dimension with `width` and `height`, in `px`
+ * or `rem`, on `components.icon['size:sm']` (and the other sizes).
+ *
* An explicit value wins. When omitted, Icon uses the nearest default supplied
* by an owning Astryx component for its icon slot, then falls back to 'md'.
*/
@@ -366,7 +400,7 @@ function IconFromRegistry({
stylex.props(
styles.span,
colorStyles[color],
- iconBoxSizeStyles[size],
+ registrySizeStyles[size],
xstyle,
),
className ?? undefined,
diff --git a/packages/core/src/Icon/IconSize.stylex.ts b/packages/core/src/Icon/IconSize.stylex.ts
index b2298707da..523127356b 100644
--- a/packages/core/src/Icon/IconSize.stylex.ts
+++ b/packages/core/src/Icon/IconSize.stylex.ts
@@ -2,9 +2,14 @@
/**
* @file IconSize.stylex.ts
- * @input Defines the Icon size scale
+ * @input Defines the Icon size scale and reads the `icon` target's private
+ * `--_icon-width` / `--_icon-height` vars
* @output Exports shared Icon size types and StyleX styles
* @position Internal Icon sizing source; consumed by Icon and icon-slot owners
+ *
+ * SYNC: When the private vars change, update Icon.tsx (registrySizeStyles),
+ * derivedVarRegistry.ts, and the `theming.vars` / `theming.derived` entries in
+ * Icon.doc.mjs.
*/
import * as stylex from '@stylexjs/stylex';
@@ -22,29 +27,40 @@ const iconSizeValues = {
export type IconSize = keyof typeof iconSizeValues;
+/*
+ * Icon's own glyph dimensions (these and the registry size styles in Icon.tsx)
+ * read private vars rather than being plain declarations. A theme writes
+ * `width`/`height` on the `icon` target's size selector
+ * (`components.icon['size:sm']`), and the derived-var registry emits them as
+ * `--_icon-width` / `--_icon-height` instead of as competing properties.
+ * Nothing else declares the dimensions, so the theme value lands however the
+ * consumer layers StyleX; with no theme value, each size falls back to its own
+ * rem value.
+ */
+
/** Size styles for direct SVG icon components. */
export const iconSizeStyles = stylex.create({
xsm: {
- width: iconSizeValues.xsm,
- height: iconSizeValues.xsm,
+ width: 'var(--_icon-width, 0.75rem)',
+ height: 'var(--_icon-height, 0.75rem)',
},
sm: {
- width: iconSizeValues.sm,
- height: iconSizeValues.sm,
+ width: 'var(--_icon-width, 1rem)',
+ height: 'var(--_icon-height, 1rem)',
},
md: {
- width: iconSizeValues.md,
- height: iconSizeValues.md,
+ width: 'var(--_icon-width, 1.25rem)',
+ height: 'var(--_icon-height, 1.25rem)',
},
lg: {
- width: iconSizeValues.lg,
- height: iconSizeValues.lg,
+ width: 'var(--_icon-width, 1.5rem)',
+ height: 'var(--_icon-height, 1.5rem)',
},
});
/**
- * Size styles for icon boxes and string-based registry icons. `fontSize`
- * keeps 1em-based icons in step with the box.
+ * Size styles for component-owned icon boxes. `fontSize` keeps 1em-based icons
+ * in step with the box.
*/
export const iconBoxSizeStyles = stylex.create({
xsm: {
diff --git a/packages/core/src/IconButton/IconButton.test.tsx b/packages/core/src/IconButton/IconButton.test.tsx
index b10fa75f6b..04f9420e60 100644
--- a/packages/core/src/IconButton/IconButton.test.tsx
+++ b/packages/core/src/IconButton/IconButton.test.tsx
@@ -12,6 +12,7 @@
import {describe, it, expect, vi} from 'vitest';
import {render, screen} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
+import {unthemedLength} from '../__tests__/unthemedLength';
import {Icon} from '../Icon/Icon';
import {IconButton} from './IconButton';
@@ -73,8 +74,10 @@ describe('IconButton', () => {
expect(wrapper).not.toBeNull();
expect(icon).toHaveAttribute('data-size', iconSize);
- expect(getComputedStyle(icon).width).toBe(renderedSize);
- expect(getComputedStyle(icon).height).toBe(renderedSize);
+ // The glyph reads the theme's size vars; with no theme it falls back to
+ // the size's own rem value, which the wrapper declares directly.
+ expect(unthemedLength(getComputedStyle(icon).width)).toBe(renderedSize);
+ expect(unthemedLength(getComputedStyle(icon).height)).toBe(renderedSize);
expect(getComputedStyle(wrapper!).width).toBe(renderedSize);
expect(getComputedStyle(wrapper!).height).toBe(renderedSize);
},
diff --git a/packages/core/src/__tests__/unthemedLength.ts b/packages/core/src/__tests__/unthemedLength.ts
new file mode 100644
index 0000000000..1f68734013
--- /dev/null
+++ b/packages/core/src/__tests__/unthemedLength.ts
@@ -0,0 +1,34 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file unthemedLength.ts
+ * @input A computed style value as jsdom reports it
+ * @output unthemedLength — the length that value resolves to when no theme sets
+ * the custom properties it reads
+ * @position Shared test helper; imported by tests that check an Icon's size
+ * without a theme
+ *
+ * Icon's glyph dimensions read the `icon` target's private vars with each
+ * size's rem value as the fallback, so a theme can set them. jsdom keeps
+ * `var()` and `min()` as written, so a test without a theme reads them through
+ * this helper.
+ *
+ * SYNC: When modified, update this header.
+ */
+
+/**
+ * Resolve every `var()` in `value` to its fallback and reduce a `min()` of two
+ * equal lengths, writing StyleX's `.75rem` as `0.75rem`. Anything else comes
+ * back unchanged, so a comparison against the expected length fails.
+ *
+ * @param value Computed style value, e.g. `var(--_icon-width,.75rem)`.
+ * @returns The length without theme values, e.g. `0.75rem`.
+ */
+export function unthemedLength(value: string): string {
+ const resolved = value
+ .replace(/var\(\s*--[\w-]+\s*,\s*([^()]+?)\s*\)/g, '$1')
+ .replace(/\s+/g, '');
+ const min = /^min\(([^,()]+),([^,()]+)\)$/.exec(resolved);
+ const length = min && min[1] === min[2] ? min[1] : resolved;
+ return length.replace(/^\./, '0.');
+}
diff --git a/packages/core/src/theme/derivedVarRegistry.test.ts b/packages/core/src/theme/derivedVarRegistry.test.ts
index 83d00323f2..cb8dbfed97 100644
--- a/packages/core/src/theme/derivedVarRegistry.test.ts
+++ b/packages/core/src/theme/derivedVarRegistry.test.ts
@@ -237,6 +237,7 @@ const DIR_TO_REGISTRY_KEY: Record<string, string> = {
DropdownMenu: 'dropdown-menu',
Field: 'field',
HoverCard: 'hover-card',
+ Icon: 'icon',
Item: 'item',
NumberInput: 'number-input',
Popover: 'popover',
@@ -505,6 +506,20 @@ describe('getDerivedVars', () => {
expect(result[0].replaces).toBe(true);
});
+ it('marks icon width and height as replacing the source property', () => {
+ // spec:AST-087 FR10: the glyph reads these vars for its dimension, so a
+ // raw width/height beside them would only compete with its size styles.
+ for (const [property, varName] of [
+ ['width', '--_icon-width'],
+ ['height', '--_icon-height'],
+ ]) {
+ const result = getDerivedVars('icon', property);
+ expect(result).toHaveLength(1);
+ expect(result[0].vars).toEqual([varName]);
+ expect(result[0].replaces).toBe(true);
+ }
+ });
+
it('marks progress-bar-mark width and height as replacing the source property', () => {
for (const [property, varName] of [
['width', '--_progressbar-mark-width'],
diff --git a/packages/core/src/theme/derivedVarRegistry.ts b/packages/core/src/theme/derivedVarRegistry.ts
index 7ab9bd2b79..ecee2776ea 100644
--- a/packages/core/src/theme/derivedVarRegistry.ts
+++ b/packages/core/src/theme/derivedVarRegistry.ts
@@ -70,6 +70,10 @@ export const derivedVarRegistry: Record<string, DerivedVarEntry[]> = {
],
field: [{property: 'borderRadius', vars: ['--_field-radius']}],
'hover-card': [{property: 'borderRadius', vars: ['--_hovercard-radius']}],
+ icon: [
+ {property: 'width', vars: ['--_icon-width'], replaces: true},
+ {property: 'height', vars: ['--_icon-height'], replaces: true},
+ ],
item: [{property: 'paddingInline', vars: ['--_item-inset-inline']}],
'number-input': [
{property: 'padding', expand: 'container'},