An open source design system that's fully customizable and agent ready
TypeScript
Avatar: nightly component audit (rubric v1.4), 70.8 C to 78.4 C (#5030)
Cindy Zhangc5dd8eb84dc4
diff --git a/.changeset/avatar-audit-theme-box-blank-name.md b/.changeset/avatar-audit-theme-box-blank-name.mdnew file mode 100644index 0000000000..fd70d56f01--- /dev/null+++ b/.changeset/avatar-audit-theme-box-blank-name.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] Avatar: put the avatar box on the element that carries the `astryx-avatar` theme target, so a theme rule on the documented `size` axis resizes the whole avatar instead of growing the wrapper around a fixed-size circle; treat a whitespace-only `name` or `alt` as absent, so it falls through to the default icon rather than rendering an empty plate behind a blank accessible name; warn through the shared `useDevWarning` hook rather than a bare `console.warn` in the render body; and replace the phantom `<OnlineIndicator />` in the JSDoc example with the real `AvatarStatusDot`+@cixzhangdiff --git a/.github/a11y-baseline.json b/.github/a11y-baseline.jsonindex 1666760822..45c233f4fb 100644--- a/.github/a11y-baseline.json+++ b/.github/a11y-baseline.json@@ -3,16 +3,6 @@"version": 1,"generatedAt": "2026-07-31T09:21:12.717Z","entries": [- {- "key": "Avatar::Default::color-contrast",- "impact": "serious",- "helpUrl": "https://dequeuniversity.com/rules/axe/4.12/color-contrast?application=playwright"- },- {- "key": "Avatar::Initials Fallback::color-contrast",- "impact": "serious",- "helpUrl": "https://dequeuniversity.com/rules/axe/4.12/color-contrast?application=playwright"- },{"key": "AvatarGroup::Initials Fallback::color-contrast","impact": "serious",diff --git a/apps/storybook/stories/Avatar.stories.tsx b/apps/storybook/stories/Avatar.stories.tsxindex a9daa706ec..a273cc35f3 100644--- a/apps/storybook/stories/Avatar.stories.tsx+++ b/apps/storybook/stories/Avatar.stories.tsx@@ -1,6 +1,7 @@// Copyright (c) Meta Platforms, Inc. and affiliates.import type {Meta, StoryObj} from '@storybook/react';+import type {ComponentPropsWithoutRef} from 'react';import * as stylex from '@stylexjs/stylex';import {Avatar} from '@astryxdesign/core/Avatar';import {AvatarStatusDot} from '@astryxdesign/core/Avatar';@@ -26,8 +27,30 @@ const styles = stylex.create({margin: `0 0 ${spacingVars['--spacing-2']} 0`,fontFamily: typographyVars['--font-family-body'],},+ narrow: {+ maxWidth: '320px',+ width: '100%',+ borderWidth: '1px',+ borderStyle: 'dashed',+ borderColor: 'currentColor',+ padding: spacingVars['--spacing-2'],+ },+ wrapRow: {+ display: 'flex',+ flexWrap: 'wrap',+ alignItems: 'center',+ gap: spacingVars['--spacing-4'],+ },});+function RouterLink({href, children, ...rest}: ComponentPropsWithoutRef<'a'>) {+ return (+ <a href={href} data-router-link="" {...rest}>+ {children}+ </a>+ );+}+const meta: Meta<typeof Avatar> = {title: 'Core/Avatar',component: Avatar,@@ -725,3 +748,114 @@ export const ThemedFallbackBackground: Story = {</div>),};++export const Interactive: Story = {+ name: 'Interactive (link and button)',+ render: () => (+ <div {...stylex.props(styles.storyWrapper)}>+ <h4 {...stylex.props(styles.heading)}>+ Link avatars (href) — Tab to reach, focus ring on the avatar+ </h4>+ <div {...stylex.props(styles.row)}>+ <Avatar+ src="https://i.pravatar.cc/150?img=30"+ name="Ada Lovelace"+ href="https://example.com/users/ada"+ size="lg"+ />+ <Avatar+ name="Grace Hopper"+ href="https://example.com/users/grace"+ target="_blank"+ rel="noopener noreferrer"+ size="lg"+ />+ <Avatar+ name="Katherine Johnson"+ href="https://example.com/users/katherine"+ as={RouterLink}+ size="lg"+ />+ </div>++ <h4 {...stylex.props(styles.heading)}>Button avatars (onClick)</h4>+ <div {...stylex.props(styles.row)}>+ <Avatar+ src="https://i.pravatar.cc/150?img=31"+ name="Mary Jackson"+ onClick={() => {}}+ size="lg"+ />+ <Avatar+ name="Dorothy Vaughan"+ onClick={() => {}}+ size="lg"+ status={<AvatarStatusDot variant="success" label="Online" />}+ />+ </div>++ <h4 {...stylex.props(styles.heading)}>+ Interactive at every size — the smallest tiers are the touch-target case+ </h4>+ <div {...stylex.props(styles.row)}>+ <Avatar name="Ada Lovelace" href="https://example.com" size="xsm" />+ <Avatar name="Ada Lovelace" href="https://example.com" size="sm" />+ <Avatar name="Ada Lovelace" href="https://example.com" size="md" />+ <Avatar name="Ada Lovelace" href="https://example.com" size="lg" />+ <Avatar name="Ada Lovelace" onClick={() => {}} size={16} />+ </div>+ </div>+ ),+};++export const LongAndNonLatinNames: Story = {+ name: 'Long and Non-Latin Names',+ render: () => (+ <div {...stylex.props(styles.storyWrapper)}>+ <h4 {...stylex.props(styles.heading)}>+ Initials are one grapheme from the first and last word, in any script+ </h4>+ <div {...stylex.props(styles.row)}>+ <Avatar name="Bartholomew" size="lg" tooltip={false} />+ <Avatar+ name="Maria Fernanda de la Cruz y Villalobos"+ size="lg"+ tooltip={false}+ />+ <Avatar name="محمد علي" size="lg" tooltip={false} />+ <Avatar name="李小龍" size="lg" tooltip={false} />+ <Avatar name="Ἀριστοτέλης Σταγειρίτης" size="lg" tooltip={false} />+ <Avatar name="🇬🇧 Ada" size="lg" tooltip={false} />+ </div>++ <h4 {...stylex.props(styles.heading)}>+ A long name in the tooltip, and as the accessible name+ </h4>+ <div {...stylex.props(styles.row)}>+ <Avatar+ name="Maria Fernanda de la Cruz y Villalobos"+ size="lg"+ tooltip="Maria Fernanda de la Cruz y Villalobos, Principal Engineer, Platform Infrastructure"+ />+ </div>+ </div>+ ),+};++export const NarrowContainer: Story = {+ render: () => (+ <div {...stylex.props(styles.narrow)}>+ <h4 {...stylex.props(styles.heading)}>320px container</h4>+ <div {...stylex.props(styles.wrapRow)}>+ <Avatar name="Ada Lovelace" size="lg" />+ <Avatar name="Grace Hopper" size="lg" />+ <Avatar+ name="Katherine Johnson"+ size="lg"+ status={<AvatarStatusDot variant="success" label="Online" />}+ />+ <Avatar name="Mary Jackson" size="xl" />+ </div>+ </div>+ ),+};diff --git a/packages/core/src/Avatar/Avatar.doc.mjs b/packages/core/src/Avatar/Avatar.doc.mjsindex 1ccf79e432..aa33ab93cd 100644--- a/packages/core/src/Avatar/Avatar.doc.mjs+++ b/packages/core/src/Avatar/Avatar.doc.mjs@@ -62,7 +62,7 @@ export const docs = {{name: 'size',type: "'xsm' | 'sm' | 'md' | 'lg' | 'xl' | number",- description: "Avatar size. Use a named size ('xsm' 20px, 'sm' 24px, 'md' 36px, 'lg' 48px, 'xl' 128px) or a numeric pixel value. Avatar shares Icon's abbreviated scale, but its tiers are larger because avatars align with media rather than glyphs.",+ description: "Avatar size. Use a named size ('xsm' 20px, 'sm' 24px, 'md' 36px, 'lg' 48px, 'xl' 128px) or a numeric pixel value. Avatar shares Icon's abbreviated scale, but its tiers are larger because avatars align with media rather than glyphs. Inside an AvatarGroup the group's size wins and this prop is ignored.",default: "'md'",},{@@ -154,7 +154,7 @@ export const docsDense = {fallbackSrc: 'fallback image when primary fails',name: 'user name for initials and alt text',alt: 'alt text; falls back to name',- size: "avatar size. Named ('xsm' 20px, 'sm' 24px, 'md' 36px, 'lg' 48px, 'xl' 128px) or numeric px.",+ size: "avatar size. Named ('xsm' 20px, 'sm' 24px, 'md' 36px, 'lg' 48px, 'xl' 128px) or numeric px. An AvatarGroup's size overrides it.",status:'corner content for status indicators; its `label` is composed into the avatar accessible name ("Jane Doe, Online")',tooltip:diff --git a/packages/core/src/Avatar/Avatar.test.tsx b/packages/core/src/Avatar/Avatar.test.tsxindex f91daa50ab..1d9dc5cc24 100644--- a/packages/core/src/Avatar/Avatar.test.tsx+++ b/packages/core/src/Avatar/Avatar.test.tsx@@ -65,6 +65,27 @@ describe('Avatar', () => {expect(icon?.querySelector('svg')).not.toBeNull();});+ it('puts the avatar box on the element that carries the theme target', () => {+ // T7: `.astryx-avatar` documents a `size` visual prop, so the width and+ // height that prop selects on must live on the targeted element — a theme+ // rule that resizes the target has to resize the whole avatar, not leave a+ // fixed-size circle inside a grown box.+ render(<Avatar name="Ada Lovelace" size="lg" data-testid="a" />);+ const root = screen.getByTestId('a');+ expect(root.className).toContain('astryx-avatar');+ const rootStyle = root.getAttribute('style') ?? '';+ expect(rootStyle).toContain('48px');++ const content = root.firstElementChild as HTMLElement;+ expect(content.getAttribute('style') ?? '').not.toContain('48px');+ });++ it('keeps the box on the root for an interactive avatar too', () => {+ render(<Avatar name="Ada" size="lg" href="/ada" />);+ const link = screen.getByRole('link', {name: 'Ada'});+ expect(link.getAttribute('style') ?? '').toContain('48px');+ });+it('does not split an emoji surrogate pair when generating initials', () => {render(<Avatar name="😀 Ada" data-testid="avatar" />);expect(screen.getByTestId('avatar')).toHaveTextContent('😀A');@@ -184,6 +205,36 @@ describe('Avatar', () => {});});+ describe('a whitespace-only name carries no identity', () => {+ it('falls through to the default icon instead of an empty plate', () => {+ render(<Avatar name=" " data-testid="a" />);+ const el = screen.getByTestId('a');+ expect(el.querySelector('svg')).not.toBeNull();+ expect(el).toHaveTextContent('');+ });++ it('is decorative rather than a role="img" with a blank name', () => {+ render(<Avatar name=" " data-testid="a" />);+ const el = screen.getByTestId('a');+ expect(el).toHaveAttribute('aria-hidden', 'true');+ expect(el).not.toHaveAttribute('aria-label');+ });++ it('keeps a meaningful alt as the accessible name and still shows the icon', () => {+ render(<Avatar name=" " alt="Profile photo" data-testid="a" />);+ const el = screen.getByRole('img', {name: 'Profile photo'});+ expect(el).toBe(screen.getByTestId('a'));+ expect(el.querySelector('svg')).not.toBeNull();+ });++ it('treats a whitespace-only alt the same way', () => {+ render(<Avatar alt=" " name="Ada Lovelace" data-testid="a" />);+ expect(+ screen.getByRole('img', {name: 'Ada Lovelace'}),+ ).toBeInTheDocument();+ });+ });+it('retries a new fallbackSrc after a previous fallbackSrc failed to load', () => {const {rerender} = render(<Avatar name="Ada" fallbackSrc="https://example.com/broken.jpg" />,diff --git a/packages/core/src/Avatar/Avatar.tsx b/packages/core/src/Avatar/Avatar.tsxindex 2707a90650..2e54ad2251 100644--- a/packages/core/src/Avatar/Avatar.tsx+++ b/packages/core/src/Avatar/Avatar.tsx@@ -33,6 +33,7 @@ import {mergeProps, mergeRefs} from '../utils';import {themeProps} from '../utils/themeProps';import {focusOutlineProps} from '../utils/focusOutline.stylex';import {useTooltip} from '../Tooltip/useTooltip';+import {useDevWarning} from '../hooks/useDevWarning';import {useLinkComponent} from '../Link/useLinkComponent';import type {LinkComponentType} from '../Link/types';import {useTranslator} from '../i18n';@@ -112,16 +113,17 @@ const styles = stylex.create({position: 'relative',display: 'inline-flex',flexShrink: 0,- // The wrapper is not clipped (so the status dot can overflow), so it must be- // rounded itself: a theme can set a background on the `.astryx-avatar`- // wrapper, and an unrounded wrapper would show that fill as square corners- // behind the circular content.+ // The wrapper carries the avatar's box as well as its radius, so a theme+ // rule on the `.astryx-avatar` target reaches both: the size the `size`+ // visual prop selects on is set here, and the content below fills it.borderRadius: radiusVars['--radius-full'],},content: {display: 'flex',alignItems: 'center',justifyContent: 'center',+ width: '100%',+ height: '100%',borderRadius: radiusVars['--radius-full'],overflow: 'hidden',userSelect: 'none',@@ -251,6 +253,9 @@ export interface AvatarProps extends BaseProps<HTMLDivElement> {/*** The size of the avatar. A named size (`xsm` 20px, `sm` 24px, `md` 36px,* `lg` 48px, `xl` 128px) or a specific pixel value.+ *+ * Inside an `AvatarGroup` the group's `size` wins: a group sizes its members+ * uniformly, so this prop is ignored there.* @default 'md'*/size?: AvatarSize;@@ -397,7 +402,7 @@ function DefaultIcon({size}: {size: number}) {* ```* <Avatar src="/user.jpg" name="John Doe" />* <Avatar name="Jane Smith" size="xl" />- * <Avatar src="/user.jpg" status={<OnlineIndicator />} />+ * <Avatar src="/user.jpg" status={<AvatarStatusDot variant="success" label="Online" />} />* <Avatar name="jsmith" tooltip="Jane Smith, Staff Engineer" />* <Avatar name="Jane" tooltip={false} />* <Avatar src="/user.jpg" name="John Doe" href="/users/john" />@@ -434,8 +439,13 @@ export function Avatar({const showImage = src && erroredSrc !== src;const showFallbackImage =!showImage && fallbackSrc && erroredFallbackSrc !== fallbackSrc;- const showInitials = !showImage && !showFallbackImage && name;- const showIcon = !showImage && !showFallbackImage && !name;+ // A whitespace-only string carries no identity. Without this it produces no+ // initials (getInitials trims to nothing) and no default icon (a space is+ // truthy), leaving an empty plate behind a blank accessible name.+ const meaningfulName = name?.trim() ? name : undefined;+ const meaningfulAlt = alt?.trim() ? alt : undefined;+ const showInitials = !showImage && !showFallbackImage && meaningfulName;+ const showIcon = !showImage && !showFallbackImage && !meaningfulName;// A meaningful accessible name comes from `alt`/`name`, composed with the// status element's `label` when one is present ("Jane Doe, Online") — the@@ -446,7 +456,7 @@ export function Avatar({// it as `presentation`/`aria-hidden` rather than announcing a meaningless// generic "Avatar" (obs-9).const t = useTranslator();- const nameLabel = alt || name;+ const nameLabel = meaningfulAlt || meaningfulName;const statusLabel = getStatusLabel(status);const accessibleName =nameLabel && statusLabel@@ -471,7 +481,7 @@ export function Avatar({? undefined: typeof tooltip === 'string'? tooltip- : name;+ : meaningfulName;const trimmedTooltip = tooltipContent?.trim();const showTooltip = trimmedTooltip != null && trimmedTooltip !== '';// Whether the tooltip text is a consumer-authored override (a custom string)@@ -513,20 +523,19 @@ export function Avatar({const LinkComponent = useLinkComponent(as);// An interactive control with no accessible name is an unacceptable control- // name. Warn in the same client-safe way sibling components do (Field,- // Timestamp, Popover) — a plain `console.warn`, never gated on `process.env`- // (which is not available on the client in this codebase).- if (isInteractive && !accessibleName) {- console.warn(- 'Avatar: an interactive avatar (with `href` or `onClick`) needs a ' +- 'meaningful accessible name. Pass `alt` or `name`.',- );- }+ // name. `useDevWarning` is the shared guardrail: it warns once per mount+ // rather than on every render, and compiles out of production builds.+ useDevWarning(+ 'Avatar',+ 'an interactive avatar (with `href` or `onClick`) needs a meaningful ' ++ 'accessible name. Pass `alt` or `name`.',+ isInteractive && !accessibleName,+ );// The inner visuals are identical across the static and interactive variants.const visualContent = (<>- <div {...stylex.props(styles.content, dynamicStyles.size(numericSize))}>+ <div {...stylex.props(styles.content)}>{showImage && (<imgsrc={src}@@ -552,7 +561,7 @@ export function Avatar({dynamicStyles.fontSize(numericSize),),)}>- {getInitials(name)}+ {getInitials(meaningfulName)}</div>)}{showIcon && (@@ -585,6 +594,7 @@ export function Avatar({themeProps('avatar', {size: resolvedSize}),focusOutlineProps.focusVisible(styles.wrapper,+ dynamicStyles.size(numericSize),isInteractive && styles.interactive,avatarGroup && groupStyles.ring,avatarGroup && groupStyles.overlap,