An open source design system that's fully customizable and agent ready
TypeScript
fix(core): Avatar a11y: warn on an unnamed interactive avatar, carry the status label in a ref (#5034)
Cindy Zhang83661ae6ca8e
diff --git a/.changeset/avatar-interactive-name-status-label.md b/.changeset/avatar-interactive-name-status-label.mdnew file mode 100644index 0000000000..d573c97704--- /dev/null+++ b/.changeset/avatar-interactive-name-status-label.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Avatar: a status element now reports its own accessible label to the avatar through context, so wrapping `AvatarStatusDot` in a component of your own keeps the status in the avatar's accessible name ("Jane Doe, Online") instead of silently dropping it — the `role="img"` root prunes descendant semantics, so composing it in is the only route to assistive tech (WCAG 4.1.2). Reading `label` off a directly-passed element still works and still resolves on the first render. An interactive avatar (`href`/`onClick`) with no `name`/`alt` warns in development, and a status label no longer counts as the control's identity: "Online" reads as a legitimate name while saying nothing about where the link goes. Derived `role`/`aria-label`/`aria-hidden` now spread before the passthrough props, following Icon, so a consumer's own values win. No API change (#5034)++@cixzhangdiff --git a/apps/storybook/stories/Avatar.stories.tsx b/apps/storybook/stories/Avatar.stories.tsxindex a273cc35f3..dbd63158ef 100644--- a/apps/storybook/stories/Avatar.stories.tsx+++ b/apps/storybook/stories/Avatar.stories.tsx@@ -264,6 +264,41 @@ export const WithStatus: Story = {),};+export const StatusLabelSources: Story = {+ render: () => {+ // A consumer's own wrapper. AvatarStatusDot reports its label to the+ // avatar through context, so the status still reaches the accessible name.+ function PresenceDot({presence}: {presence: string}) {+ return <AvatarStatusDot variant="success" label={presence} />;+ }++ return (+ <div {...stylex.props(styles.storyWrapper)}>+ <h4 {...stylex.props(styles.heading)}>+ Every route to a status in the accessible name+ </h4>+ <div {...stylex.props(styles.row)}>+ <Avatar+ name="Ada Lovelace"+ size="xl"+ status={<AvatarStatusDot variant="success" label="Online" />}+ />+ <Avatar+ name="Grace Hopper"+ size="xl"+ status={<PresenceDot presence="Online" />}+ />+ <Avatar+ name="Katherine Johnson"+ size="xl"+ status={<AvatarStatusDot variant="neutral" label="On leave" />}+ />+ </div>+ </div>+ );+ },+};+export const StatusAcrossAllSizes: Story = {name: 'Status Dot Across All Sizes',render: () => (diff --git a/packages/core/src/Avatar/Avatar.doc.mjs b/packages/core/src/Avatar/Avatar.doc.mjsindex aa33ab93cd..084aa45010 100644--- a/packages/core/src/Avatar/Avatar.doc.mjs+++ b/packages/core/src/Avatar/Avatar.doc.mjs@@ -16,6 +16,8 @@ export const docs = {{guidance: true, description: 'Pick a size that matches the context: xsm or sm for inline mentions, md or lg for lists and cards, xl for profile headers.'},{guidance: true, description: 'Add a status dot when knowing someone\'s availability matters, like in chat or team views.'},{guidance: true, description: 'When wrapping an Avatar in your own Tooltip or HoverCard, set tooltip={false} so the built-in name tooltip does not overlap yours.'},+ {guidance: true, description: 'Give every interactive avatar (href or onClick) a name or alt. It is the control\'s accessible name, and it warns in development when it is missing.'},+ {guidance: false, description: 'Rely on a status label to name an interactive avatar. "Online" says nothing about where the link goes.'},{guidance: false, description: 'Use Avatar for logos, product images, or anything that isn\'t a person or team. Use an image or icon instead.'},{guidance: false, description: 'Force a square or custom shape. Avatars are always circular to stay consistent across the system.'},],@@ -68,7 +70,7 @@ export const docs = {{name: 'status',type: 'ReactNode',- description: 'Corner content for status indicators. A string `label` on the element (as on AvatarStatusDot) is composed into the avatar\'s accessible name (e.g. "Jane Doe, Online") so screen readers announce the status.',+ description: 'Corner content for status indicators. AvatarStatusDot reports its `label` to the avatar, which composes it into the accessible name (e.g. "Jane Doe, Online") so screen readers announce the status. Reporting goes through context, so it still works when the dot sits inside a wrapper component of your own.',slotElements: [{__element: 'AvatarStatusDot',@@ -90,7 +92,7 @@ export const docs = {name: 'href',type: 'string',description:- 'When set, the avatar renders as an interactive link (`<a>` or a custom link component) pointing here. This follows the same element-swap rule as Button. Requires a meaningful accessible name via `alt` or `name`. Inside an AvatarGroup, interactive avatars share a single Tab stop and are reached with arrow keys.',+ 'When set, the avatar renders as an interactive link (`<a>` or a custom link component) pointing here. This follows the same element-swap rule as Button. Requires a meaningful accessible name via `alt` or `name`: an interactive avatar without one warns in development. Inside an AvatarGroup, interactive avatars share a single Tab stop and are reached with arrow keys.',},{name: 'as',@@ -112,7 +114,7 @@ export const docs = {name: 'onClick',type: '(e: MouseEvent) => void',description:- 'Click handler. When set without `href`, the avatar renders as a focusable `<button type="button">`. Requires a meaningful accessible name via `alt` or `name`.',+ 'Click handler. When set without `href`, the avatar renders as a focusable `<button type="button">`. Requires a meaningful accessible name via `alt` or `name`: an interactive avatar without one warns in development.',},],components: [@@ -128,6 +130,7 @@ export const docsZh = {bestPractices: [{guidance: true, description: 'Always provide a name prop so the component can generate meaningful initials and alt text when the image fails to load.'},{guidance: true, description: 'Use the status slot with AvatarStatusDot to indicate online presence or availability when relevant to the context.'},+ {guidance: true, description: 'Give every interactive avatar (href or onClick) a name or alt. It is the control\'s accessible name, and it warns in development when it is missing.'},{guidance: false, description: 'Use Avatar for decorative images or logos that aren\'t representing a person or entity. Use an image or icon component instead.'},{guidance: false, description: 'Override the circular shape. Avatars are always round to maintain visual consistency across the system.'},],@@ -145,6 +148,7 @@ export const docsDense = {{guidance: true, description: 'Match size to context: xsm/sm inline, md/lg in lists, xl for profiles.'},{guidance: true, description: 'Add a status dot in chat or team views where availability matters.'},{guidance: true, description: 'When wrapping Avatar in your own Tooltip or HoverCard, set tooltip={false} so the built-in name tooltip does not overlap yours.'},+ {guidance: true, description: 'Interactive avatars (href/onClick) need name or alt; without one they warn in development. A status label is not a name.'},{guidance: false, description: 'Use for logos or product images. Use an image or icon instead.'},{guidance: false, description: 'Force a square or custom shape. Avatars are always circular.'},],@@ -156,14 +160,14 @@ export const docsDense = {alt: 'alt text; falls back to name',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")',+ 'corner content for status indicators; AvatarStatusDot reports its `label`, composed into the avatar accessible name ("Jane Doe, Online"), at any nesting depth',tooltip:"hover/focus tooltip. true/omitted → name; string → that text; false → none. Owns its tooltip; set false when wrapping in your own Tooltip/HoverCard. Default true.",- href: 'renders avatar as a link (<a>/custom). Needs alt/name. Button-style element swap.',+ href: 'renders avatar as a link (<a>/custom). Needs alt/name for an accessible name; warns in development without one. Button-style element swap.',as: 'custom link component for href (e.g. Next Link). Only with href.',target: 'link target. Only with href.',rel: 'link rel. Only with href.',- onClick: 'click handler → renders <button> when no href. Needs alt/name.',+ onClick: 'click handler → renders <button> when no href. Needs alt/name; warns in development without one.',},components: [{name: 'AvatarStatusDot', description: 'size-aware status indicator rendered in the Avatar corner'},diff --git a/packages/core/src/Avatar/Avatar.test.tsx b/packages/core/src/Avatar/Avatar.test.tsxindex 7ece01e6af..3be98ee700 100644--- a/packages/core/src/Avatar/Avatar.test.tsx+++ b/packages/core/src/Avatar/Avatar.test.tsx@@ -1,7 +1,8 @@// Copyright (c) Meta Platforms, Inc. and affiliates.+import {Profiler, useState} from 'react';import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';-import {render, screen, fireEvent} from '@testing-library/react';+import {act, render, screen, fireEvent} from '@testing-library/react';import userEvent from '@testing-library/user-event';import {Avatar} from './Avatar';import {AvatarStatusDot} from './AvatarStatusDot';@@ -210,6 +211,167 @@ describe('Avatar', () => {});});+ describe('status label through a consumer wrapper (P14)', () => {+ // A consumer's own component around AvatarStatusDot. Its prop is+ // deliberately not called `label`, so `status.props.label` introspection+ // has nothing to read; the dot's own report through context reaches it.+ function PresenceDot({presence = 'Online'}: {presence?: string}) {+ return <AvatarStatusDot variant="success" label={presence} />;+ }++ it('composes a label reported from inside a wrapper component', () => {+ render(<Avatar name="Ada Lovelace" status={<PresenceDot />} />);+ expect(+ screen.getByRole('img', {name: 'Ada Lovelace, Online'}),+ ).toBeInTheDocument();+ });++ it('composes a label reported at any nesting depth', () => {+ function Outer() {+ return (+ <span>+ <PresenceDot presence="Away" />+ </span>+ );+ }+ render(<Avatar name="Ada Lovelace" status={<Outer />} />);+ expect(+ screen.getByRole('img', {name: 'Ada Lovelace, Away'}),+ ).toBeInTheDocument();+ });++ it('follows a label that changes after mount', () => {+ const {rerender} = render(+ <Avatar+ name="Ada Lovelace"+ status={<PresenceDot presence="Online" />}+ />,+ );+ expect(+ screen.getByRole('img', {name: 'Ada Lovelace, Online'}),+ ).toBeInTheDocument();++ rerender(+ <Avatar name="Ada Lovelace" status={<PresenceDot presence="Busy" />} />,+ );+ expect(+ screen.getByRole('img', {name: 'Ada Lovelace, Busy'}),+ ).toBeInTheDocument();+ });++ it('drops the label when the status element unmounts', () => {+ const {rerender} = render(+ <Avatar name="Ada Lovelace" status={<PresenceDot />} data-testid="a" />,+ );+ expect(+ screen.getByRole('img', {name: 'Ada Lovelace, Online'}),+ ).toBeInTheDocument();++ rerender(<Avatar name="Ada Lovelace" data-testid="a" />);+ expect(screen.getByTestId('a')).toHaveAttribute(+ 'aria-label',+ 'Ada Lovelace',+ );+ });++ it('announces a wrapped status on an otherwise decorative avatar', () => {+ render(<Avatar data-testid="a" status={<PresenceDot />} />);+ const el = screen.getByTestId('a');+ expect(el).toHaveAttribute('role', 'img');+ expect(el).toHaveAttribute('aria-label', 'Online');+ expect(el).not.toHaveAttribute('aria-hidden');+ });++ it('lets a reported label win over introspection', () => {+ // The wrapper's own `label` prop is not the string the dot renders with,+ // so introspection and the dot's report disagree here.+ function TranslatedDot({label}: {label: string}) {+ return <AvatarStatusDot label={label === 'busy' ? 'Busy' : label} />;+ }+ render(+ <Avatar name="Ada Lovelace" status={<TranslatedDot label="busy" />} />,+ );+ expect(+ screen.getByRole('img', {name: 'Ada Lovelace, Busy'}),+ ).toBeInTheDocument();+ });++ it('costs no extra render and does not loop', () => {+ // The label arrives in the commit phase, after this render composed the+ // name. It lands on the root element directly, so a wrapped status is+ // named without a second render. `tooltip={false}` keeps the tooltip's+ // own mount commit out of the count.+ const commits: number[] = [];+ render(+ <Profiler id="avatar" onRender={() => commits.push(1)}>+ <Avatar+ name="Ada Lovelace"+ tooltip={false}+ status={<PresenceDot />}+ />+ </Profiler>,+ );+ expect(+ screen.getByRole('img', {name: 'Ada Lovelace, Online'}),+ ).toBeInTheDocument();+ expect(commits).toHaveLength(1);+ });++ it('names a directly-passed dot on the first render, before any report', () => {+ // Introspection answers render one; the dot's report then lands on the+ // same name, still without a second render.+ const commits: number[] = [];+ render(+ <Profiler id="avatar" onRender={() => commits.push(1)}>+ <Avatar+ name="Ada Lovelace"+ tooltip={false}+ status={<AvatarStatusDot label="Online" />}+ />+ </Profiler>,+ );+ expect(+ screen.getByRole('img', {name: 'Ada Lovelace, Online'}),+ ).toBeInTheDocument();+ expect(commits).toHaveLength(1);+ });++ it('follows a label that changes without re-rendering the avatar', () => {+ // State inside the consumer's wrapper: the dot re-renders alone, so the+ // avatar never gets the chance to recompose during render.+ let setPresence: (presence: string) => void = () => {};+ function SelfUpdatingDot() {+ const [presence, setter] = useState('Online');+ setPresence = setter;+ return <AvatarStatusDot label={presence} />;+ }+ render(<Avatar name="Ada Lovelace" status={<SelfUpdatingDot />} />);+ expect(+ screen.getByRole('img', {name: 'Ada Lovelace, Online'}),+ ).toBeInTheDocument();++ act(() => setPresence('Busy'));+ expect(+ screen.getByRole('img', {name: 'Ada Lovelace, Busy'}),+ ).toBeInTheDocument();+ });++ it('leaves a consumer aria-label alone when a wrapped status reports', () => {+ render(+ <Avatar+ name="Ada Lovelace"+ aria-label="Ada Lovelace, first programmer"+ data-testid="a"+ status={<PresenceDot />}+ />,+ );+ expect(screen.getByTestId('a')).toHaveAttribute(+ 'aria-label',+ 'Ada Lovelace, first programmer',+ );+ });+ });+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" />);@@ -519,4 +681,60 @@ describe('Avatar — interactivity (Button trichotomy)', () => {render(<Avatar data-testid="a" />);expect(warn).not.toHaveBeenCalled();});++ it('warns when the only accessible name is a status label', () => {+ // A status is not an identity: "Online" alone is a worse control name than+ // none, because it reads as a legitimate one.+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ render(+ <Avatar+ href="/somewhere"+ src="https://example.com/ada.jpg"+ status={<AvatarStatusDot label="Online" />}+ />,+ );+ expect(warn).toHaveBeenCalledWith(+ expect.stringContaining('interactive avatar'),+ );+ });++ it('warns when interactive with an empty-string name and alt', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ render(<Avatar href="/ada" name="" alt="" />);+ expect(warn).toHaveBeenCalledWith(+ expect.stringContaining('interactive avatar'),+ );+ });++ it('does not warn when the consumer names the control with aria-label', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ render(<Avatar href="/ada" aria-label="Ada Lovelace" />);+ expect(warn).not.toHaveBeenCalled();+ });+});++describe('Avatar — consumer ARIA overrides win (Icon labelling pattern)', () => {+ it('lets a consumer aria-label override the derived name on the static root', () => {+ render(<Avatar name="Ada" aria-label="Ada Lovelace, on leave" />);+ expect(+ screen.getByRole('img', {name: 'Ada Lovelace, on leave'}),+ ).toBeInTheDocument();+ });++ it('lets a consumer role override the derived role', () => {+ render(<Avatar name="Ada" role="presentation" data-testid="a" />);+ expect(screen.getByTestId('a')).toHaveAttribute('role', 'presentation');+ });++ it('lets a consumer hide a named avatar with aria-hidden', () => {+ render(<Avatar name="Ada" aria-hidden="true" data-testid="a" />);+ expect(screen.getByTestId('a')).toHaveAttribute('aria-hidden', 'true');+ });++ it('lets a consumer aria-label override the derived name on an interactive root', () => {+ render(<Avatar name="Ada" href="/ada" aria-label="Ada Lovelace profile" />);+ expect(+ screen.getByRole('link', {name: 'Ada Lovelace profile'}),+ ).toBeInTheDocument();+ });});diff --git a/packages/core/src/Avatar/Avatar.tsx b/packages/core/src/Avatar/Avatar.tsxindex 32525dd58e..92a7b3c8c8 100644--- a/packages/core/src/Avatar/Avatar.tsx+++ b/packages/core/src/Avatar/Avatar.tsx@@ -4,7 +4,7 @@/*** @file Avatar.tsx- * @input Uses React, HTMLAttributes, ReactNode, useState; useTooltip+ * @input Uses React, HTMLAttributes, ReactNode, useState, useRef; useTooltip* (Tooltip hook) for the optional name-on-hover tooltip; useTranslator (i18n)* @output Exports Avatar component, AvatarProps, AvatarSize types* @position Core implementation; consumed by index.ts@@ -12,13 +12,14 @@* SYNC: When modified, update these files to stay in sync:* - /packages/core/src/Avatar/Avatar.doc.mjs (props table, features, implementation notes)* - /packages/core/src/Avatar/index.ts (exports if types change)+ * - /packages/core/src/Avatar/AvatarStatusLabelContext.ts (the status label ref)* - /apps/storybook/stories/Avatar.stories.tsx (storybook stories)* - /packages/cli/assets/templates/blocks/components/Avatar/ (showcase blocks)** Last synced props: alt, fallbackSrc, name, size, src, status, href, as, target, rel, onClick*/-import {isValidElement, useMemo, useState, type ReactNode} from 'react';+import {isValidElement, useMemo, useRef, useState, type ReactNode} from 'react';import type {BaseProps} from '../BaseProps';import * as stylex from '@stylexjs/stylex';import {@@ -28,6 +29,10 @@ import {radiusVars,} from '../theme/tokens.stylex';import {AvatarSizeContext} from './AvatarSizeContext';+import {+ AvatarStatusLabelContext,+ type AvatarStatusLabelTarget,+} from './AvatarStatusLabelContext';import {useAvatarGroup} from '../AvatarGroup/AvatarGroupContext';import {mergeProps, mergeRefs} from '../utils';import {themeProps} from '../utils/themeProps';@@ -37,7 +42,7 @@ 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';+import {useTranslator, type TranslatorFn} from '../i18n';/*** The offset ratio for positioning elements on a circle's edge at 45°.@@ -268,10 +273,14 @@ export interface AvatarProps extends BaseProps<HTMLDivElement> {* Content displayed in the corner of the avatar.* Typically used for status indicators or badges.*- * When the element carries a string `label` prop (as `AvatarStatusDot`- * does), the label is composed into the avatar's accessible name- * (e.g. "Jane Doe, Online") so assistive tech can reach the status —- * the `role="img"` root prunes descendant semantics (WCAG 4.1.2).+ * `AvatarStatusDot` reports its own `label` to the avatar, which composes+ * it into the avatar's accessible name (e.g. "Jane Doe, Online") so+ * assistive tech can reach the status: the `role="img"` root prunes+ * descendant semantics (WCAG 4.1.2). Reporting goes through context, so it+ * still works when the dot sits inside a wrapper component of your own. A+ * custom status element that is not an `AvatarStatusDot` names itself the+ * same way, by rendering an `AvatarStatusDot` or by carrying a string+ * `label` prop.*/status?: ReactNode;/**@@ -342,13 +351,13 @@ function getInitials(name: string): string {/*** Reads the accessible status label off the `status` element, when it- * exposes one. `AvatarStatusDot`'s `label` prop is the canonical source,- * but any custom status element with a string `label` prop participates.+ * exposes one.*- * The avatar root is `role="img"`, which prunes ALL descendant semantics- * from the accessibility tree — a label inside the status subtree is never- * announced on its own. Composing it into the avatar's own accessible name- * is the only way the status reaches assistive tech (WCAG 4.1.2).+ * Only sees a literal `label` prop on the element the consumer passes, so a+ * consumer's own wrapper around the dot hides it — that case comes in through+ * `AvatarStatusLabelContext` instead. Kept because it answers the first+ * render, before any report has landed, and because it tracks a label that+ * changes on an element that does not report at all.*/function getStatusLabel(status: ReactNode): string | undefined {if (!isValidElement(status)) {@@ -358,6 +367,68 @@ function getStatusLabel(status: ReactNode): string | undefined {return typeof label === 'string' && label !== '' ? label : undefined;}+/**+ * The string when it carries something, `undefined` when it is absent or+ * blank. An empty accessible name is meaningless, so a blank reads as+ * absent, the way Icon treats `label=""`.+ */+function meaningful(value: unknown): string | undefined {+ return typeof value === 'string' && value.trim() !== '' ? value : undefined;+}++/**+ * Derives the root's ARIA attributes from the resolved accessible name,+ * following Icon's `getIconA11yProps`.+ *+ * - A name → meaningful image: `role="img"` + `aria-label`.+ * - No name → decorative: `role="presentation"` + `aria-hidden="true"`, rather+ * than announcing a meaningless generic "Avatar" (obs-9).+ *+ * The result is spread BEFORE `{...props}` on every root so an explicit+ * `aria-label` / `role` / `aria-hidden` from the consumer always wins.+ */+function getAvatarA11yProps(+ accessibleName: string | undefined,+):+ | {role: 'img'; 'aria-label': string}+ | {role: 'presentation'; 'aria-hidden': 'true'} {+ return accessibleName != null && accessibleName !== ''+ ? {role: 'img', 'aria-label': accessibleName}+ : {role: 'presentation', 'aria-hidden': 'true'};+}++/**+ * The avatar's accessible name: its own name, the status label, or the two+ * composed ("Jane Doe, Online"). Used both by render and by the commit-phase+ * update, so the two can never compose differently.+ */+function composeAccessibleName(+ t: TranslatorFn,+ nameLabel: string | undefined,+ statusLabel: string | undefined,+): string | undefined {+ if (nameLabel && statusLabel) {+ return t('@astryx.avatar.nameWithStatus', {+ name: nameLabel,+ status: statusLabel,+ });+ }+ return nameLabel || statusLabel;+}++/** Sets an attribute, or removes it when the value is absent. */+function setAttributeOrRemove(+ element: HTMLElement,+ name: string,+ value: string | undefined,+): void {+ if (value == null) {+ element.removeAttribute(name);+ } else {+ element.setAttribute(name, value);+ }+}+/*** Default person icon SVG for when no image or name is provided*/@@ -424,8 +495,8 @@ export function Avatar({// 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 meaningfulName = meaningful(name);+ const meaningfulAlt = meaningful(alt);const showInitials = !showImage && !showFallbackImage && meaningfulName;const showIcon = !showImage && !showFallbackImage && !meaningfulName;@@ -439,15 +510,21 @@ export function Avatar({// generic "Avatar" (obs-9).const t = useTranslator();const nameLabel = meaningfulAlt || meaningfulName;- const statusLabel = getStatusLabel(status);- const accessibleName =- nameLabel && statusLabel- ? t('@astryx.avatar.nameWithStatus', {- name: nameLabel,- status: statusLabel,- })- : nameLabel || statusLabel;- const isDecorative = !accessibleName;+ // This render can only see a label introspected off a directly-passed+ // element. A status inside a consumer's own wrapper reports through the ref+ // below, in the commit phase, and lands on the root element from there.+ const accessibleName = composeAccessibleName(+ t,+ nameLabel,+ getStatusLabel(status),+ );+ const a11yProps = getAvatarA11yProps(accessibleName);+ // An `<a>`/`<button>` root carries its own role and must not be hidden, so+ // only the name transfers. Spread before `{...props}` for the same+ // consumer-wins precedence as the static root.+ const a11yLabelProps = accessibleName+ ? {'aria-label': accessibleName}+ : undefined;const avatarGroup = useAvatarGroup();const resolvedSize = avatarGroup?.size ?? size;const numericSize = useMemo(() => resolveSize(resolvedSize), [resolvedSize]);@@ -484,8 +561,8 @@ export function Avatar({isEnabled: showTooltip,});// The tooltip ref attaches to whichever root element renders (static or- // interactive), so the tooltip works for link/button avatars too.- const rootRef = mergeRefs(ref, showTooltip ? tooltipHook.ref : undefined);+ // interactive), so the tooltip works for link/button avatars too. The root+ // ref itself is assembled below, once the element swap is resolved.const describedByProp =showTooltip && isCustomTooltip? {@@ -504,14 +581,74 @@ export function Avatar({const isInteractive = renderAsLink || renderAsButton;const LinkComponent = useLinkComponent(as);- // An interactive control with no accessible name is an unacceptable control- // name. `useDevWarning` is the shared guardrail: it warns once per mount- // rather than on every render, and compiles out of production builds.+ // An interactive control needs an identity of its own. A status label is not+ // one: it composes into the accessible name, so `<Avatar href status={<dot+ // label="Online" />} />` resolves a name that reads as legitimate and says+ // nothing about who the link points at. Only `alt`/`name` count, or a+ // consumer's own `aria-label`/`aria-labelledby` escape hatch, which wins+ // over the derived props below.+ const consumerName =+ meaningful(props['aria-label']) ?? meaningful(props['aria-labelledby']);useDevWarning('Avatar','an interactive avatar (with `href` or `onClick`) needs a meaningful ' +'accessible name. Pass `alt` or `name`.',- isInteractive && !accessibleName,+ isInteractive && !nameLabel && consumerName == null,+ );++ // A status inside a consumer's own wrapper is invisible to render: the dot+ // writes its label into this ref from its own callback ref, in the commit+ // phase. A ref write cannot re-render, so the composed name is written+ // straight onto the root element instead — still before paint, and with no+ // second render.+ const statusLabelRef = useRef<AvatarStatusLabelTarget>({+ label: undefined,+ update: null,+ });+ // A fresh callback ref every render, so React reattaches it on every commit+ // and the name is recomposed after React has written this render's props.+ // `update` covers the other direction: a label that changes while the avatar+ // itself does not re-render.+ const nameRef = (element: HTMLElement | null) => {+ if (element == null) {+ return;+ }+ const target = statusLabelRef.current;+ target.update = () => {+ const composed = composeAccessibleName(+ t,+ nameLabel,+ meaningful(target.label) ?? getStatusLabel(status),+ );+ // A consumer's own ARIA wins here exactly as it does in render, where+ // the derived props spread before `{...props}`.+ if (props['aria-label'] == null) {+ setAttributeOrRemove(element, 'aria-label', composed);+ }+ // An `<a>`/`<button>` root carries its own role and must not be hidden,+ // so only the name transfers there.+ if (!isInteractive) {+ if (props.role == null) {+ element.setAttribute('role', composed ? 'img' : 'presentation');+ }+ if (props['aria-hidden'] == null) {+ setAttributeOrRemove(+ element,+ 'aria-hidden',+ composed ? undefined : 'true',+ );+ }+ }+ };+ target.update();+ return () => {+ target.update = null;+ };+ };+ const rootRef = mergeRefs(+ ref,+ showTooltip ? tooltipHook.ref : undefined,+ nameRef,);// The inner visuals are identical across the static and interactive variants.@@ -601,13 +738,13 @@ export function Avatar({// it up while ignoring nested buttons in a custom status/badge slot.rootElement = (<LinkComponent+ {...a11yLabelProps}{...interactivePassthrough}{...describedByProp}ref={rootRef as React.Ref<HTMLAnchorElement>}href={href}target={target}rel={rel}- aria-label={accessibleName}data-avatar-item=""data-testid={testId}onClick={onClick}@@ -618,11 +755,11 @@ export function Avatar({} else if (renderAsButton) {rootElement = (<button+ {...a11yLabelProps}{...interactivePassthrough}{...describedByProp}ref={rootRef}type="button"- aria-label={accessibleName}data-avatar-item=""data-testid={testId}onClick={onClick}@@ -633,11 +770,9 @@ export function Avatar({} else {rootElement = (<div+ {...a11yProps}{...props}ref={rootRef}- role={isDecorative ? 'presentation' : 'img'}- aria-label={isDecorative ? undefined : accessibleName}- aria-hidden={isDecorative || undefined}// The root is a div[role="img"], not natively focusable. When a name// tooltip is active, add a tab stop so keyboard users can reveal it// (WCAG 1.4.13 / 2.1.1) — matching Timestamp/Button. Suppressed inside@@ -652,7 +787,11 @@ export function Avatar({}const avatarElement = (- <AvatarSizeContext value={numericSize}>{rootElement}</AvatarSizeContext>+ <AvatarSizeContext value={numericSize}>+ <AvatarStatusLabelContext value={statusLabelRef}>+ {rootElement}+ </AvatarStatusLabelContext>+ </AvatarSizeContext>);// Always return the same structure so the avatar keeps its position in thediff --git a/packages/core/src/Avatar/AvatarStatusDot.tsx b/packages/core/src/Avatar/AvatarStatusDot.tsxindex bca496ece7..855e039763 100644--- a/packages/core/src/Avatar/AvatarStatusDot.tsx+++ b/packages/core/src/Avatar/AvatarStatusDot.tsx@@ -4,7 +4,8 @@/*** @file AvatarStatusDot.tsx- * @input Uses React, StyleX, theme tokens, and AvatarSizeContext+ * @input Uses React, StyleX, theme tokens, AvatarSizeContext, and+ * AvatarStatusLabelContext (label reporting)* @output Exports AvatarStatusDot component and AvatarStatusDotProps type* @position Sub-component of Avatar; renders a size-aware status indicator*@@ -15,12 +16,13 @@* - /packages/cli/assets/templates/blocks/components/Avatar/ (showcase blocks)*/-import React, {use, type ReactNode} from 'react';+import React, {use, useCallback, useMemo, type ReactNode} from 'react';import type {BaseProps} from '../BaseProps';import * as stylex from '@stylexjs/stylex';import {colorVars, radiusVars} from '../theme/tokens.stylex';import {AvatarSizeContext} from './AvatarSizeContext';-import {isRenderable, mergeProps} from '../utils';+import {AvatarStatusLabelContext} from './AvatarStatusLabelContext';+import {isRenderable, mergeProps, mergeRefs} from '../utils';import {themeProps} from '../utils/themeProps';import type {AvatarStatusDotVariantMap} from './index';@@ -311,6 +313,30 @@ export function AvatarStatusDot({...props}: AvatarStatusDotProps) {const avatarSize = use(AvatarSizeContext);+ const statusLabelRef = use(AvatarStatusLabelContext);+ // Report the label through the avatar's ref from a callback ref rather than+ // an Effect: the ref runs in the commit phase, so the avatar's accessible+ // name is composed before paint, and a ref write costs no render.+ /* eslint-disable react-compiler/react-compiler -- the avatar shares its own+ ref through context so the dot can write into it; a context read looks+ immutable to the compiler */+ const reportRef = useCallback(() => {+ const target = statusLabelRef?.current;+ if (target == null) {+ return;+ }+ target.label = label;+ target.update?.();+ return () => {+ target.label = undefined;+ target.update?.();+ };+ }, [statusLabelRef, label]);+ /* eslint-enable react-compiler/react-compiler */+ // Memoized so React only detaches and reattaches when the reported label+ // actually changes; an inline merge would withdraw and re-report on every+ // render of the avatar.+ const rootRef = useMemo(() => mergeRefs(ref, reportRef), [ref, reportRef]);const {dotSize, borderWidth, iconSize, tier} =resolveStatusDotSize(avatarSize);const showsIcon = isRenderable(icon) && iconSize > 0;@@ -321,7 +347,7 @@ export function AvatarStatusDot({return (<div{...props}- ref={ref}+ ref={rootRef}{...(label ? {role: 'img', 'aria-label': label} : undefined)}{...mergeProps(themeProps('avatar-status-dot', {variant}),diff --git a/packages/core/src/Avatar/AvatarStatusLabelContext.ts b/packages/core/src/Avatar/AvatarStatusLabelContext.tsnew file mode 100644index 0000000000..5e5ba5fc54--- /dev/null+++ b/packages/core/src/Avatar/AvatarStatusLabelContext.ts@@ -0,0 +1,47 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file AvatarStatusLabelContext.ts+ * @input Uses React createContext, RefObject+ * @output Exports AvatarStatusLabelContext, AvatarStatusLabelTarget+ * @position Internal context; provided by Avatar, consumed by AvatarStatusDot+ *+ * SYNC: When modified, update:+ * - /packages/core/src/Avatar/Avatar.doc.mjs+ */++import {createContext, type RefObject} from 'react';++/**+ * The box a status element writes its label into.+ *+ * `update` is the avatar's own recompose, set while its root element is+ * attached and null otherwise. Writing `label` alone is enough on mount (the+ * avatar reads the box when its root attaches, which happens after its+ * children's refs); calling `update` covers a label that changes later+ * without the avatar itself re-rendering.+ */+export interface AvatarStatusLabelTarget {+ label: string | undefined;+ update: (() => void) | null;+}++/**+ * Lets a status element hand its accessible label to the enclosing Avatar,+ * which composes it into its own accessible name ("Jane Doe, Online").+ *+ * The avatar root is `role="img"`, which prunes all descendant semantics, so+ * composing the label in is the only way the status reaches assistive tech+ * (WCAG 4.1.2). Reading `label` off the passed element only works when the+ * consumer passes `AvatarStatusDot` directly; this route works through a+ * consumer's own wrapper, at any depth.+ *+ * The value is a ref, written from the dot's own callback ref in the commit+ * phase, so reporting a label costs no render and no state. `null` outside an+ * Avatar, where a standalone dot names itself and has nobody to report to.+ */+export const AvatarStatusLabelContext =+ createContext<RefObject<AvatarStatusLabelTarget> | null>(null);+AvatarStatusLabelContext.displayName = 'AvatarStatusLabelContext';