An open source design system that's fully customizable and agent ready
TypeScript
fix(Icon): ref reaches the rendered svg for every name (#9782)
Cindy Zhang3090f98334d8
diff --git a/.changeset/icon-audit-docs.md b/.changeset/icon-audit-docs.mdindex ebce43d45e..0851e16264 100644--- a/.changeset/icon-audit-docs.md+++ b/.changeset/icon-audit-docs.md@@ -2,6 +2,6 @@'@astryxdesign/core': patch----[docs] Icon: list the ten palette `color` values and namespaced `icon` keys, and document `className`, `style`, and `ref` in every doc language, including that `ref` reaches the SVG only when `icon` is an icon component.+[docs] Icon: list the ten palette `color` values and namespaced `icon` keys, and document `className`, `style`, and `ref` in every doc language.@cixzhangdiff --git a/.changeset/icon-ref-every-name.md b/.changeset/icon-ref-every-name.mdnew file mode 100644index 0000000000..a33a097241--- /dev/null+++ b/.changeset/icon-ref-every-name.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] `Icon`'s `ref` now reaches the rendered `<svg>` for a semantic or namespaced name, as its type promises. Before, it reached the `<svg>` only when `icon` was a component; for a name, the ref stayed empty. For a name whose glyph has no `<svg>`, the ref is `null`.++@cixzhangdiff --git a/docs/specs/components/Icon/Icon.spec.md b/docs/specs/components/Icon/Icon.spec.mdindex 02a635351d..b09db13744 100644--- a/docs/specs/components/Icon/Icon.spec.md+++ b/docs/specs/components/Icon/Icon.spec.md@@ -89,15 +89,16 @@ existing behavior, not an intentional fallback promise.Requirements identify their basis so observed code is not mistaken for anintentional decision.-| ID | Candidate invariant | Basis | Draft review state |-| --- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------- | ------------------------------------------------------- |-| FR1 | Icon MUST present at most one glyph from the supplied semantic key, namespaced key, or icon component. | Documented promise and current tests. | Settled intent. |-| FR2 | Every rendered glyph MUST carry the `icon` theming target with its resolved size and selected color reflected as target data. | Current source, docs, and theming tests. | Settled intent. |-| FR3 | Icon MUST apply the resolved size as width and height for every glyph, plus font size where needed for 1em-based icon sources. This sizing contract MUST NOT promise an HTML or SVG element type. | Human decision, current source, and tests. | Settled intent. |-| FR4 | Supported SVG and styling escape hatches MUST retain their established merge and override behavior. | Current source and regression tests. | Current compatibility behavior; verify before changing. |-| FR5 | An explicit Icon `size` MUST win. Without one, Icon MUST use the nearest default supplied by an owning Astryx component for its documented icon slot; without such a default, Icon MUST use `md`. | Component-size precedence and Button sizing decision. | Settled intent. |-| FR6 | In registry mode, Icon MUST pass `{size, variant}` to the selected entry, where `size` is the size resolved by ORD1 and `variant` is the requested variant when the active theme lists it and, for a theme-supplied entry, the theme that defined the entry lists it too, otherwise `undefined`. A supplied icon component MUST NOT receive `variant`, Icon MUST NOT forward `variant` to the DOM, and the `icon` target MUST NOT reflect it. | `spec:AST-087` FR1–FR5 and FR9. | Settled intent. |-| FR7 | The `icon` target MUST guarantee `width` and `height` on its `size:*` selectors as reviewed target-specific additions, so a theme sets each size's dimension. Without theme styles, sizes are 12, 16, 20, and 24px at a 16px root and scale with the root font size. | `spec:AST-087` FR10. | Settled intent. |+| ID | Candidate invariant | Basis | Draft review state |+| --- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ------------------------------------------------------- |+| FR1 | Icon MUST present at most one glyph from the supplied semantic key, namespaced key, or icon component. | Documented promise and current tests. | Settled intent. |+| FR2 | Every rendered glyph MUST carry the `icon` theming target with its resolved size and selected color reflected as target data. | Current source, docs, and theming tests. | Settled intent. |+| FR3 | Icon MUST apply the resolved size as width and height for every glyph, plus font size where needed for 1em-based icon sources. This sizing contract MUST NOT promise an HTML or SVG element type. | Human decision, current source, and tests. | Settled intent. |+| FR4 | Supported SVG and styling escape hatches MUST retain their established merge and override behavior. | Current source and regression tests. | Current compatibility behavior; verify before changing. |+| FR5 | An explicit Icon `size` MUST win. Without one, Icon MUST use the nearest default supplied by an owning Astryx component for its documented icon slot; without such a default, Icon MUST use `md`. | Component-size precedence and Button sizing decision. | Settled intent. |+| FR6 | In registry mode, Icon MUST pass `{size, variant}` to the selected entry, where `size` is the size resolved by ORD1 and `variant` is the requested variant when the active theme lists it and, for a theme-supplied entry, the theme that defined the entry lists it too, otherwise `undefined`. A supplied icon component MUST NOT receive `variant`, Icon MUST NOT forward `variant` to the DOM, and the `icon` target MUST NOT reflect it. | `spec:AST-087` FR1–FR5 and FR9. | Settled intent. |+| FR7 | The `icon` target MUST guarantee `width` and `height` on its `size:*` selectors as reviewed target-specific additions, so a theme sets each size's dimension. Without theme styles, sizes are 12, 16, 20, and 24px at a 16px root and scale with the root font size. | `spec:AST-087` FR10. | Settled intent. |+| FR8 | `ref` reaches the svg the resolved glyph renders, for every name; when the glyph renders no svg, `ref` is `null`. A glyph that later replaces its own svg is not followed. | Consistency with Icon's public `ref` type, `Ref<SVGSVGElement>`; defect fix. | Settled intent. |### Allowed variation@@ -191,15 +192,16 @@ not promise a `span`, `svg`, or other element type.## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |-| ------------------- | --------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------- |-| FR1, FR3, FR5 | `Icon.test.tsx` sizing suites and `IconButton.test.tsx` contextual-size suites | standalone default; Button sizes; explicit override; both modes | Breaking source rendering, standalone fallback, contextual mapping, explicit precedence, or cross-mode sizing fails assertions. | `audit:Icon/behavior` |-| FR2, FR4 | `Icon.test.tsx` theming-target reflection and styling-prop suites | both source modes; every color and size; omitted color; `className`, `style`, and `xstyle` | Removing the target, dropping `data-color` or `data-size` in either mode, or breaking override composition fails assertions. | `audit:Icon/theming` |-| FR2, FR3 (rendered) | `IconAudit.a11y.chromium.spec.ts` sensor receipts | semantic key and icon component; every size and color; Neutral and Butter in light and dark; right-to-left; 320px | A glyph without its target data, a color that does not paint its token, sizes that do not step 12, 16, 20, and 24px at the Neutral theme, registry artwork that does not fill its box, or a transformed glyph fails a receipt. | `audit:Icon/theming` |-| AR1, AR2, AR3 | `Icon.test.tsx` accessible-name suites and the `IconAudit.a11y.chromium.spec.ts` accessible-name receipts | decorative, labelled, explicit ARIA override; labelled icon component that writes its own `aria-hidden` | Changing default or labelled semantics, or leaving a component's own `aria-hidden` on a labelled glyph, fails accessibility assertions. | `audit:Icon/accessibility` |-| FR6 | `Icon.test.tsx` variant suite | listed, unlisted, and omitted variant; no active list; inherited entry under a replaced list; supplied component | An unlisted variant, or one the entry's defining theme does not list, reaches an entry, or `variant` reaches a supplied component or the DOM. | `audit:Icon/behavior` |-| FR7 | `Icon.test.tsx` theme size dimension suite | each size with and without theme styles, both source modes | A themed size does not change the glyph dimension, or an unstyled size changes. | `audit:Icon/theming` |-| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical consumer anatomy and current target | Missing, extra, prefixed, or stale mappings fail repository validation. | `audit:Icon/theming` |+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| ------------------- | --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------- |+| FR1, FR3, FR5 | `Icon.test.tsx` sizing suites and `IconButton.test.tsx` contextual-size suites | standalone default; Button sizes; explicit override; both modes | Breaking source rendering, standalone fallback, contextual mapping, explicit precedence, or cross-mode sizing fails assertions. | `audit:Icon/behavior` |+| FR2, FR4 | `Icon.test.tsx` theming-target reflection and styling-prop suites | both source modes; every color and size; omitted color; `className`, `style`, and `xstyle` | Removing the target, dropping `data-color` or `data-size` in either mode, or breaking override composition fails assertions. | `audit:Icon/theming` |+| FR2, FR3 (rendered) | `IconAudit.a11y.chromium.spec.ts` sensor receipts | semantic key and icon component; every size and color; Neutral and Butter in light and dark; right-to-left; 320px | A glyph without its target data, a color that does not paint its token, sizes that do not step 12, 16, 20, and 24px at the Neutral theme, registry artwork that does not fill its box, or a transformed glyph fails a receipt. | `audit:Icon/theming` |+| AR1, AR2, AR3 | `Icon.test.tsx` accessible-name suites and the `IconAudit.a11y.chromium.spec.ts` accessible-name receipts | decorative, labelled, explicit ARIA override; labelled icon component that writes its own `aria-hidden` | Changing default or labelled semantics, or leaving a component's own `aria-hidden` on a labelled glyph, fails accessibility assertions. | `audit:Icon/accessibility` |+| FR6 | `Icon.test.tsx` variant suite | listed, unlisted, and omitted variant; no active list; inherited entry under a replaced list; supplied component | An unlisted variant, or one the entry's defining theme does not list, reaches an entry, or `variant` reaches a supplied component or the DOM. | `audit:Icon/behavior` |+| FR7 | `Icon.test.tsx` theme size dimension suite | each size with and without theme styles, both source modes | A themed size does not change the glyph dimension, or an unstyled size changes. | `audit:Icon/theming` |+| FR8 | `Icon.test.tsx` "ref reaches the rendered svg for every name" suite | icon component; semantic name; namespaced key; text glyph; glyph change (component to component, svg to text); function entry across rerenders; unmount | A ref that stays empty, or holds anything but the rendered `<svg>`, for any name kind fails; so do a non-null ref for a text glyph, a ref left on a replaced glyph, a ref re-attached on every rerender, and a ref left set after unmount. | `audit:Icon/ref` |+| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical consumer anatomy and current target | Missing, extra, prefixed, or stale mappings fail repository validation. | `audit:Icon/theming` |## Decision logdiff --git a/packages/core/src/Icon/Icon.doc.mjs b/packages/core/src/Icon/Icon.doc.mjsindex ffc71884f1..d9de13d943 100644--- a/packages/core/src/Icon/Icon.doc.mjs+++ b/packages/core/src/Icon/Icon.doc.mjs@@ -124,7 +124,7 @@ export const docs = {name: 'ref',type: 'Ref<SVGSVGElement>',description:- 'Ref to the rendered SVG element when icon is an icon component. A semantic or namespaced name renders inside an internal wrapper, and the ref is not attached.',+ 'Ref to the rendered SVG element, for an icon component and for a semantic or namespaced name. For a name, it is the <svg> inside the wrapper, or null when the resolved glyph has no <svg>.',},],theming: {@@ -278,7 +278,7 @@ export const docsZh = {name: 'ref',type: 'Ref<SVGSVGElement>',description:- 'icon 为图标组件时,指向渲染的 SVG 元素的 ref。语义名称或命名空间名称在内部包装元素中渲染,不会附加 ref。',+ '指向渲染的 SVG 元素的 ref,适用于图标组件以及语义名称或命名空间名称。对于名称,它指向包装元素内的 <svg>;若解析出的图形没有 <svg>,则为 null。',},],theming: {@@ -439,6 +439,6 @@ export const docsDense = {'StyleX styles (color, size, opacity) via stylex.create(); composes with the base color/size styles.',className: 'Class added to the rendered glyph beside astryx-icon.',style: "Inline styles merged after Icon's size and color styles.",- ref: 'Reaches the SVG only when icon is a component; a semantic or namespaced name renders in a wrapper and gets no ref.',+ ref: 'Reaches the rendered SVG for every icon value; null when a resolved glyph has no <svg>.',},};diff --git a/packages/core/src/Icon/Icon.test.tsx b/packages/core/src/Icon/Icon.test.tsxindex b19a4b0a4b..13ea4e607e 100644--- a/packages/core/src/Icon/Icon.test.tsx+++ b/packages/core/src/Icon/Icon.test.tsx@@ -10,6 +10,7 @@* SYNC: When Icon.tsx changes, update tests to match new behavior*/+import {createRef} from 'react';import {describe, it, expect, vi} from 'vitest';import {render, screen} from '@testing-library/react';import * as stylex from '@stylexjs/stylex';@@ -191,10 +192,103 @@ describe('Icon', () => {}});- it('forwards ref correctly', () => {- const ref = vi.fn();- render(<Icon icon={TestIcon} ref={ref} />);- expect(ref).toHaveBeenCalledWith(expect.any(SVGSVGElement));+ describe('ref reaches the rendered svg for every name', () => {+ it('an icon component', () => {+ const ref = vi.fn();+ render(<Icon icon={TestIcon} ref={ref} />);+ expect(ref).toHaveBeenCalledWith(expect.any(SVGSVGElement));+ });++ it('a semantic name', () => {+ const ref = createRef<SVGSVGElement>();+ render(<Icon icon="close" ref={ref} data-testid="icon" />);+ expect(ref.current).toBeInstanceOf(SVGSVGElement);+ expect(screen.getByTestId('icon')).toContainElement(ref.current);+ });++ it('a namespaced key', () => {+ resetIcons();+ resetThemes();+ registerIcons({+ 'numberInput:stepperDown': <svg data-testid="stepper-svg" />,+ });+ const ref = vi.fn();+ render(<Icon icon="numberInput:stepperDown" ref={ref} />);+ expect(ref).toHaveBeenCalledWith(screen.getByTestId('stepper-svg'));+ });++ it('a name whose theme entry renders text, not an svg, leaves the ref null', () => {+ resetIcons();+ resetThemes();+ registerIcons({'numberInput:stepperDown': 'text-glyph'});+ const ref = createRef<SVGSVGElement>();+ render(<Icon icon="numberInput:stepperDown" ref={ref} />);+ expect(ref.current).toBeNull();+ });++ it('moves to the new svg when the name changes', () => {+ resetIcons();+ resetThemes();+ function DownGlyph() {+ return <svg data-testid="down-svg" />;+ }+ function UpGlyph() {+ return <svg data-testid="up-svg" />;+ }+ registerIcons({+ 'numberInput:stepperDown': <DownGlyph />,+ 'numberInput:stepperUp': <UpGlyph />,+ });+ const ref = createRef<SVGSVGElement>();+ const {rerender} = render(+ <Icon icon="numberInput:stepperDown" ref={ref} />,+ );+ const down = screen.getByTestId('down-svg');+ expect(ref.current).toBe(down);+ rerender(<Icon icon="numberInput:stepperUp" ref={ref} />);+ expect(ref.current).toBe(screen.getByTestId('up-svg'));+ expect(ref.current).not.toBe(down);+ });++ it('attaches a stable callback ref once for a function entry, across rerenders', () => {+ resetIcons();+ resetThemes();+ registerIcons({+ 'numberInput:stepperDown': () => <svg data-testid="fn-svg" />,+ });+ const ref = vi.fn();+ const {rerender} = render(+ <Icon icon="numberInput:stepperDown" ref={ref} />,+ );+ rerender(<Icon icon="numberInput:stepperDown" ref={ref} />);+ rerender(<Icon icon="numberInput:stepperDown" ref={ref} />);+ expect(ref).toHaveBeenCalledTimes(1);+ expect(ref).toHaveBeenCalledWith(screen.getByTestId('fn-svg'));+ });++ it('becomes null when the name changes to a text glyph', () => {+ resetIcons();+ resetThemes();+ registerIcons({+ 'numberInput:stepperDown': <svg data-testid="down-svg" />,+ 'numberInput:stepperUp': 'text-glyph',+ });+ const ref = createRef<SVGSVGElement>();+ const {rerender} = render(+ <Icon icon="numberInput:stepperDown" ref={ref} />,+ );+ expect(ref.current).toBe(screen.getByTestId('down-svg'));+ rerender(<Icon icon="numberInput:stepperUp" ref={ref} />);+ expect(ref.current).toBeNull();+ });++ it('clears the ref when a named icon unmounts', () => {+ const ref = createRef<SVGSVGElement>();+ const {unmount} = render(<Icon icon="close" ref={ref} />);+ expect(ref.current).toBeInstanceOf(SVGSVGElement);+ unmount();+ expect(ref.current).toBeNull();+ });});it('passes additional SVG props', () => {diff --git a/packages/core/src/Icon/Icon.tsx b/packages/core/src/Icon/Icon.tsxindex a0577e72ab..c03c0f5355 100644--- a/packages/core/src/Icon/Icon.tsx+++ b/packages/core/src/Icon/Icon.tsx@@ -30,7 +30,7 @@* - /packages/cli/assets/templates/blocks/components/Icon/ (showcase blocks)*/-import React, {type ComponentType, type SVGProps} from 'react';+import React, {useCallback, type ComponentType, type SVGProps} from 'react';import * as stylex from '@stylexjs/stylex';import type {StyleXStyles} from '@stylexjs/stylex';import {colorVars} from '../theme/tokens.stylex';@@ -39,6 +39,7 @@ import {resolveIcon} from './globalIconRegistry';import type {IconName, NamespacedIconName} from './globalIconRegistry';import type {IconVariant} from './index';import {mergeProps} from '../utils/mergeProps';+import {mergeRefs} from '../utils/mergeRefs';import {themeProps} from '../utils/themeProps';import {useIconSize} from './IconDefaultSizeContext';import {iconSizeStyles, type IconSize} from './IconSize.stylex';@@ -177,9 +178,9 @@ export interface IconProps extends Omit<'ref' | 'color'> {/**- * Ref to the rendered SVG element when `icon` is an icon component. A- * semantic or namespaced name renders inside an internal wrapper, and the- * ref is not attached.+ * Ref to the rendered SVG element. For a semantic or namespaced name it is+ * the `<svg>` inside Icon's wrapper, or `null` when the resolved glyph has+ * no `<svg>`.*/ref?: React.Ref<SVGSVGElement>;/**@@ -335,6 +336,7 @@ export function Icon({className={className}style={style}xstyle={xstyle}+ svgRef={ref}spanProps={props}/>);@@ -394,6 +396,7 @@ function IconFromRegistry({className,style,xstyle,+ svgRef,spanProps,}: {name: IconName | NamespacedIconName;@@ -404,10 +407,21 @@ function IconFromRegistry({className?: string;style?: React.CSSProperties;xstyle?: StyleXStyles;+ svgRef?: React.Ref<SVGSVGElement>;spanProps?: Omit<SVGProps<SVGSVGElement>, 'ref' | 'color'>;}) {const themeName = useThemeName();const resolvedIcon = resolveIcon(name, themeName, {size, variant});+ // The glyph can change while the span stays. Attach the ref again when it+ // does.+ const attachSvgRef = useCallback(+ (span: HTMLSpanElement | null) =>+ svgRef == null+ ? undefined+ : mergeRefs(svgRef)(span?.querySelector('svg') ?? null),+ // eslint-disable-next-line @eslint-react/exhaustive-deps -- resolveIcon's inputs: a new glyph gets a new attach, and a function entry's new element each render does not.+ [svgRef, name, themeName, size, variant],+ );if (resolvedIcon == null) {return null;@@ -423,6 +437,7 @@ function IconFromRegistry({return (<span+ ref={svgRef == null ? undefined : attachSvgRef}// Derived a11y — decorative (aria-hidden) by default, or a meaningful// image (role="img" + aria-label) when `label` is set. Placed BEFORE the// prop spread so consumers can still override it with explicit