An open source design system that's fully customizable and agent ready
TypeScript
fix(Avatar): an interactive initials avatar passes Label in Name (#10816)
Cindy Zhangbf13b026eaa3
diff --git a/.changeset/avatar-initials-label-in-name.md b/.changeset/avatar-initials-label-in-name.mdnew file mode 100644index 0000000000..e35ff37842--- /dev/null+++ b/.changeset/avatar-initials-label-in-name.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Avatar: initials are drawn as generated content with empty alternative text instead of text, so axe's Label in Name check (`label-content-name-mismatch`) no longer flags a link or button avatar that shows initials. The accessible name, the name tooltip and the initials' appearance are unchanged. Tests that find initials by text read the `data-initials` attribute instead.++@cixzhangdiff --git a/docs/specs/components/Avatar/Avatar.spec.md b/docs/specs/components/Avatar/Avatar.spec.mdindex 451f182362..9f5d59471c 100644--- a/docs/specs/components/Avatar/Avatar.spec.md+++ b/docs/specs/components/Avatar/Avatar.spec.md@@ -13,6 +13,7 @@ review_triggers: [public-api, behavior, layout, theming, accessibility]verified_by:[packages/core/src/Avatar/Avatar.test.tsx,+ packages/core/src/Avatar/__tests__/AvatarLabelInName.a11y.chromium.spec.ts,packages/core/src/AvatarGroup/AvatarGroup.test.tsx,packages/core/src/Layer/layerScopedContext.test.tsx,packages/core/src/theme/themingTargets.test.ts,@@ -175,6 +176,10 @@ Consumer migration instructions belong in consumer docs and release notes.- **AR1 — Named image.** A static avatar with a name is `role="img"` with thatname; without one, and without a status label, it is `role="presentation"`with `aria-hidden="true"`. Inner images and the default icon are decorative.+ Initials are the photo's fallback and are decorative like an inner image:+ every root (link, button, static) hides them from assistive technology, so+ the accessible name is only the person's name, and the default name tooltip+ (FR7) shows that name on hover and focus.- **AR2 — Status reaches assistive technology.** Because a `role="img"` rootprunes its descendants, the status label is composed into the avatar's ownname (FR5).@@ -227,17 +232,18 @@ no root part, so no anatomy-theming block is declared.## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |-| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------- |-| FR1–FR3 | `Avatar.test.tsx` fallback, initials, retry, and target tests; `AvatarForcedColors.a11y.chromium.spec.ts` in real Chromium with forced colors emulated | Photo, failure, initials, punctuation, emoji, blank name; `lg` box; forced colors alone, inside GrayText and HighlightText, and grouped | A wrong initials-or-icon fallback, split grapheme, lost retry, missing target, wrong `lg` box size, or forced-colors initials that miss the surrounding system color (lone) or leave the forced foreground (grouped) fails. Gap: no test sets `src` and `fallbackSrc` together, so the `src`-first order is unchecked, and sizes other than `lg` and numeric sizes are visible only in `Avatar.stories.tsx`. | `audit:Avatar/behavior` |-| FR4 | `Avatar.test.tsx` shape and status tests; `Avatar.stories.tsx` status fixtures | Every shape with a status; RTL | A missing status slot fails. Gap: the tests assert presence only, so the slot's position, mirroring, and offset are visible only in the rendered fixtures. | `audit:Avatar/layout` |-| FR5, AR1, AR2, PR1 | `Avatar.test.tsx` status-name and wrapper suites | Direct, wrapped, changing, removed labels | A lost composed name, extra render, or stale label fails. | `audit:Avatar/a11y` |-| FR6, AR3 | `Avatar.test.tsx` interactivity suite | Link, button, static, dev warnings | A wrong root, a missing marker, or a missing warning fails. Gap: no test checks the focus-visible outline. | `audit:Avatar/behavior` |-| FR7, AR4, AR5 | `Avatar.test.tsx` name-tooltip suite | Default, custom, disabled, blank | A missing tab stop, a duplicated description, or a lost ref fails. Gap: no test covers a grouped avatar's tooltip after a re-render that re-attaches its root element: a new `status` element (an inline `status` prop creates one on every parent render), a changed `name`, `alt`, locale, caller ARIA, or caller `ref`, or a tooltip that turns on after mount. | `audit:Avatar/a11y` |-| FR8 | `Avatar.test.tsx` group shape tests; `AvatarGroup.test.tsx` size-cascade, overlap, and roving suites; `layerScopedContext.test.tsx` AvatarGroup layer tests | Inside a group; in a layer opened from a group; outside a group | An avatar size or shape prop winning inside a group, a lost overlap, an interactive avatar missing from the roving set, or a static avatar in a layer losing its tooltip tab stop fails. Gap: no test asserts the ring, or size and shape inside a layer. | `audit:Avatar/behavior` |-| FR9, AR6 | `Avatar.test.tsx` consumer-ARIA override suite | Static and interactive roots | A derived value replacing a caller `aria-label`, `role`, or `aria-hidden` fails. Gap: no test covers a caller `tabIndex`. | `audit:Avatar/a11y` |-| AR1–AR3, AR5 | Accessibility-tree evidence (`spec:AST-009` FR3) | Named, decorative, status-composed, interactive | Gap: no accessibility-tree check proves the computed roles, names, or description; the unit tests query the DOM. | `audit:Avatar/a11y` |-| AR7 | `Avatar.stories.tsx` interactive and size fixtures in a browser | Interactive avatars at every size | Gap: no automated target-size check; the undersized targets are the recorded gap. | `audit:Avatar/a11y` |+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------- |+| FR1–FR3 | `Avatar.test.tsx` fallback, initials, retry, and target tests; `AvatarForcedColors.a11y.chromium.spec.ts` in real Chromium with forced colors emulated | Photo, failure, initials, punctuation, emoji, blank name; `lg` box; forced colors alone, inside GrayText and HighlightText, and grouped | A wrong initials-or-icon fallback, split grapheme, lost retry, missing target, wrong `lg` box size, or forced-colors initials that miss the surrounding system color (lone) or leave the forced foreground (grouped) fails. Gap: no test sets `src` and `fallbackSrc` together, so the `src`-first order is unchecked, and sizes other than `lg` and numeric sizes are visible only in `Avatar.stories.tsx`. | `audit:Avatar/behavior` |+| FR4 | `Avatar.test.tsx` shape and status tests; `Avatar.stories.tsx` status fixtures | Every shape with a status; RTL | A missing status slot fails. Gap: the tests assert presence only, so the slot's position, mirroring, and offset are visible only in the rendered fixtures. | `audit:Avatar/layout` |+| FR5, AR1, AR2, PR1 | `Avatar.test.tsx` status-name and wrapper suites | Direct, wrapped, changing, removed labels | A lost composed name, extra render, or stale label fails. | `audit:Avatar/a11y` |+| AR1, AR3 | `Avatar.test.tsx` "initials are part of the picture, not text of the control" suite; `AvatarLabelInName.a11y.chromium.spec.ts` in real Chromium (axe `label-content-name-mismatch`, drawn initials with and without forced colors, the name tooltip on keyboard focus) | Static, link, and button roots with initials; photo root; forced colors | Initials that become text of the control, a name other than the person's, initials that leave the screen, or a tooltip that does not show the name on focus fails. | `audit:Avatar/a11y` |+| FR6, AR3 | `Avatar.test.tsx` interactivity suite | Link, button, static, dev warnings | A wrong root, a missing marker, or a missing warning fails. Gap: no test checks the focus-visible outline. | `audit:Avatar/behavior` |+| FR7, AR4, AR5 | `Avatar.test.tsx` name-tooltip suite | Default, custom, disabled, blank | A missing tab stop, a duplicated description, or a lost ref fails. Gap: no test covers a grouped avatar's tooltip after a re-render that re-attaches its root element: a new `status` element (an inline `status` prop creates one on every parent render), a changed `name`, `alt`, locale, caller ARIA, or caller `ref`, or a tooltip that turns on after mount. | `audit:Avatar/a11y` |+| FR8 | `Avatar.test.tsx` group shape tests; `AvatarGroup.test.tsx` size-cascade, overlap, and roving suites; `layerScopedContext.test.tsx` AvatarGroup layer tests | Inside a group; in a layer opened from a group; outside a group | An avatar size or shape prop winning inside a group, a lost overlap, an interactive avatar missing from the roving set, or a static avatar in a layer losing its tooltip tab stop fails. Gap: no test asserts the ring, or size and shape inside a layer. | `audit:Avatar/behavior` |+| FR9, AR6 | `Avatar.test.tsx` consumer-ARIA override suite | Static and interactive roots | A derived value replacing a caller `aria-label`, `role`, or `aria-hidden` fails. Gap: no test covers a caller `tabIndex`. | `audit:Avatar/a11y` |+| AR1–AR3, AR5 | Accessibility-tree evidence (`spec:AST-009` FR3) | Named, decorative, status-composed, interactive | Gap: no accessibility-tree check proves the computed roles, names, or description; the unit tests query the DOM. | `audit:Avatar/a11y` |+| AR7 | `Avatar.stories.tsx` interactive and size fixtures in a browser | Interactive avatars at every size | Gap: no automated target-size check; the undersized targets are the recorded gap. | `audit:Avatar/a11y` |## Decision logdiff --git a/packages/core/src/Avatar/Avatar.doc.mjs b/packages/core/src/Avatar/Avatar.doc.mjsindex 04cc55e4e2..67dfc59b4b 100644--- a/packages/core/src/Avatar/Avatar.doc.mjs+++ b/packages/core/src/Avatar/Avatar.doc.mjs@@ -23,7 +23,7 @@ export const docs = {],anatomy: [{name: 'Photo', required: false, description: 'The profile image, loaded from the src URL. Shown when available.'},- {name: 'Initials', required: false, description: 'The first letter, digit or emoji of the first and last words of the name; punctuation is skipped. Shown when no photo is available. A name with no letters, digits or emoji shows the default icon instead.'},+ {name: 'Initials', required: false, description: 'The first letter, digit or emoji of the first and last words of the name; punctuation is skipped. Shown when no photo is available. A name with no letters, digits or emoji shows the default icon instead. Like the photo, the initials are part of the picture: assistive technology reads the name, not the letters.'},{name: 'Default icon', required: false, description: 'A generic person silhouette. Shown when there is no photo or name.'},{name: 'Status dot', required: false, description: 'A small indicator in the bottom-right corner showing availability (online, away, busy). Each variant pairs colour with a distinct shape so status does not rely on colour alone.'},],diff --git a/packages/core/src/Avatar/Avatar.test.tsx b/packages/core/src/Avatar/Avatar.test.tsxindex 21ecabd29a..2b463f301f 100644--- a/packages/core/src/Avatar/Avatar.test.tsx+++ b/packages/core/src/Avatar/Avatar.test.tsx@@ -9,6 +9,25 @@ import {colorVars} from '../theme/tokens.stylex';import {Avatar} from './Avatar';import {AvatarStatusDot} from './AvatarStatusDot';import {AvatarGroup} from '../AvatarGroup';+import {rulesDeclaredFor} from '../__tests__/pressState';++/** The initials an avatar draws, from the attribute its generated content reads. */+function initialsIn(el: Element): string {+ return (+ el.querySelector('[data-initials]')?.getAttribute('data-initials') ?? ''+ );+}++/** The element that draws the given initials. */+function initialsElement(initials: string): HTMLElement {+ const el = document.querySelector<HTMLElement>(+ `[data-initials="${initials}"]`,+ );+ if (el == null) {+ throw new Error(`No avatar draws the initials ${initials}`);+ }+ return el;+}describe('Avatar', () => {it('exposes role="img" with the name as accessible name', () => {@@ -43,7 +62,7 @@ describe('Avatar', () => {it('renders fallback initials at the proportional size via a StyleX class, not an inline property', () => {render(<Avatar name="Ada Lovelace" size="sm" data-testid="a" />);- const initials = screen.getByText('AL');+ const initials = initialsElement('AL');// The default proportional size (sm = 24 × 0.4 = 9.6px) is fed to StyleX as// a dynamic value: StyleX applies `font-size` through a class and sets only// the computed value inline (as a custom property). Because the property@@ -59,9 +78,7 @@ describe('Avatar', () => {// The background is themed directly on `.astryx-avatar-fallback`, so both// the initials and the default-icon fallback must carry the class.const {rerender} = render(<Avatar name="Ada Lovelace" />);- expect(screen.getByText('AL').className).toContain(- 'astryx-avatar-fallback',- );+ expect(initialsElement('AL').className).toContain('astryx-avatar-fallback');rerender(<Avatar />);const icon = document.querySelector('.astryx-avatar-fallback');@@ -81,7 +98,7 @@ describe('Avatar', () => {},});render(<Avatar name="Ada Lovelace" />);- const initials = screen.getByText('AL');+ const initials = initialsElement('AL');const classesOf = (style: stylex.StyleXStyles) =>(stylex.props(style).className ?? '').split(' ')@@ -105,7 +122,7 @@ describe('Avatar', () => {<Avatar name="Grace Hopper" /></AvatarGroup>,);- const initials = screen.getByText('AL');+ const initials = initialsElement('AL');const classes = (stylex.props(probe.ink).className ?? '').split(' ').filter(cls => cls !== '' && !cls.includes('__'));@@ -138,17 +155,17 @@ describe('Avatar', () => {it('does not split an emoji surrogate pair when generating initials', () => {render(<Avatar name="😀 Ada" data-testid="avatar" />);- expect(screen.getByTestId('avatar')).toHaveTextContent('😀A');+ expect(initialsIn(screen.getByTestId('avatar'))).toBe('😀A');});it('preserves a complete character when generating initials', () => {render(<Avatar name="🇬🇧 Ada" data-testid="avatar" />);- expect(screen.getByTestId('avatar')).toHaveTextContent('🇬🇧A');+ expect(initialsIn(screen.getByTestId('avatar'))).toBe('🇬🇧A');});it('keeps a ZWJ family emoji intact when generating initials', () => {render(<Avatar name="👨👩👧👦 Ada" data-testid="avatar" />);- expect(screen.getByTestId('avatar')).toHaveTextContent('👨👩👧👦A');+ expect(initialsIn(screen.getByTestId('avatar'))).toBe('👨👩👧👦A');});describe('initials come from letters, digits and emoji, not punctuation', () => {@@ -168,19 +185,65 @@ describe('Avatar', () => {['Ada (😀)', 'A😀'],])('%s renders %s', (name, expected) => {render(<Avatar name={name} data-testid="avatar" />);- expect(screen.getByTestId('avatar').textContent).toBe(expected);+ expect(initialsIn(screen.getByTestId('avatar'))).toBe(expected);});it('falls through to the default icon when no word yields an initial', () => {render(<Avatar name="- ()" data-testid="a" />);const el = screen.getByTestId('a');expect(el.querySelector('svg')).not.toBeNull();- expect(el).toHaveTextContent('');+ expect(initialsIn(el)).toBe('');// The name still names the avatar.expect(screen.getByRole('img', {name: '- ()'})).toBeInTheDocument();});});+ describe('initials are part of the picture, not text of the control', () => {+ // An interactive avatar is named by the person's name. Initials as text+ // would be a visible label that the name does not contain (WCAG 2.5.3+ // Label in Name), so they are drawn as generated content instead.+ it.each([+ ['static', {}, 'img'],+ ['link', {href: '/ada'}, 'link'],+ ['button', {onClick: () => {}}, 'button'],+ ] as const)(+ 'a %s avatar has no text content and is named by the person',+ (_root, rootProps, role) => {+ render(<Avatar name="Ada Lovelace" data-testid="a" {...rootProps} />);+ const root = screen.getByTestId('a');+ expect(root.textContent).toBe('');+ expect(screen.getByRole(role, {name: 'Ada Lovelace'})).toBe(root);+ expect(initialsIn(root)).toBe('AL');+ },+ );++ it('draws the initials with empty alternative text', () => {+ render(<Avatar name="Ada Lovelace" onClick={() => {}} />);+ const before = rulesDeclaredFor(initialsElement('AL')).filter(rule =>+ rule.slice(0, rule.indexOf('{')).includes('::before'),+ );+ expect(before.some(rule => rule.includes('attr(data-initials)'))).toBe(+ true,+ );+ expect(before.some(rule => rule.includes('/ ""'))).toBe(true);+ });++ it('keeps the photo path free of initials', () => {+ render(+ <Avatar+ name="Ada Lovelace"+ src="https://example.com/ada.jpg"+ onClick={() => {}}+ data-testid="a"+ />,+ );+ const root = screen.getByTestId('a');+ expect(root.querySelector('img')).toHaveAttribute('alt', '');+ expect(initialsIn(root)).toBe('');+ expect(screen.getByRole('button', {name: 'Ada Lovelace'})).toBe(root);+ });+ });+it('retries a new src after a previous src failed to load', () => {const {rerender} = render(<Avatar name="Ada" src="https://example.com/broken.jpg" />,@@ -189,7 +252,7 @@ describe('Avatar', () => {fireEvent.error(wrapper.querySelector('img')!);// Broken image falls back to initials.expect(wrapper.querySelector('img')).toBeNull();- expect(wrapper).toHaveTextContent('A');+ expect(initialsIn(wrapper)).toBe('A');// A different src must get a fresh load attempt, not the stale error.rerender(<Avatar name="Ada" src="https://example.com/ada.jpg" />);@@ -224,7 +287,7 @@ describe('Avatar', () => {);const avatar = screen.getByRole('img', {name: 'Ada Lovelace, Busy'});expect(avatar).toBeInTheDocument();- expect(avatar).toHaveTextContent('AL');+ expect(initialsIn(avatar)).toBe('AL');});it('composes the status label with alt when alt overrides name', () => {@@ -456,7 +519,7 @@ describe('Avatar', () => {render(<Avatar name=" " data-testid="a" />);const el = screen.getByTestId('a');expect(el.querySelector('svg')).not.toBeNull();- expect(el).toHaveTextContent('');+ expect(initialsIn(el)).toBe('');});it('is decorative rather than a role="img" with a blank name', () => {diff --git a/packages/core/src/Avatar/Avatar.tsx b/packages/core/src/Avatar/Avatar.tsxindex d07dc9c1ba..5a767b87cb 100644--- a/packages/core/src/Avatar/Avatar.tsx+++ b/packages/core/src/Avatar/Avatar.tsx@@ -202,6 +202,17 @@ const styles = stylex.create({fontWeight: fontWeightVars['--font-weight-medium'],textTransform: 'uppercase',},+ // Generated content with empty alternative text draws the initials. They are+ // part of the picture, not text of the control. On a link or button, visible+ // text that the name does not contain fails Label in Name.+ initials: {+ '::before': {+ content: stylex.firstThatWorks(+ 'attr(data-initials) / ""',+ 'attr(data-initials)',+ ),+ },+ },// After `fallback` on a lone Avatar: in forced colors its initials and// default icon take the color around them, which the browser forces to// CanvasText, so a control that paints itself disabled (GrayText) or@@ -806,12 +817,13 @@ export function Avatar({themeProps('avatar-fallback', {size: resolvedSize}),stylex.props(styles.fallback,+ styles.initials,avatarGroup == null && styles.loneFallback,dynamicStyles.fontSize(numericSize),),- )}>- {initials}- </div>+ )}+ data-initials={initials}+ />)}{showIcon && (<divdiff --git a/packages/core/src/Avatar/__tests__/AvatarLabelInName.a11y.chromium.spec.ts b/packages/core/src/Avatar/__tests__/AvatarLabelInName.a11y.chromium.spec.tsnew file mode 100644index 0000000000..578430eb34--- /dev/null+++ b/packages/core/src/Avatar/__tests__/AvatarLabelInName.a11y.chromium.spec.ts@@ -0,0 +1,88 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// @pr-a11y scope ^packages/core/src/Avatar/ ^apps/storybook/stories/Avatar++/**+ * @file AvatarLabelInName.a11y.chromium.spec.ts+ * @input The built Avatar "Interactive" and "Initials Fallback" stories in+ * real Chromium, axe, and keyboard focus+ * @output Browser evidence that an initials avatar's control is named by the+ * person's name with no visible text label it does not contain (WCAG 2.5.3+ * Label in Name), that the initials stay on screen, also in forced colors,+ * and that keyboard focus shows the name tooltip+ * @position Regression proof for Avatar AR1 and AR3+ */++import AxeBuilder from '@axe-core/playwright';+import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++let storybook: StaticServer;+test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});+test.afterAll(async () => {+ await storybook?.close();+});++async function openStory(page: Page, story: string): Promise<void> {+ await page.goto(`${storybook.origin}/iframe.html?id=${story}&viewMode=story`);+ await page.locator('.astryx-avatar').first().waitFor();+}++/** The text each initials element draws through its generated content. */+async function drawnInitials(page: Page): Promise<string[]> {+ return page.evaluate(() =>+ Array.from(+ document.querySelectorAll('[data-initials]'),+ el => getComputedStyle(el, '::before').content,+ ),+ );+}++test('no interactive initials avatar fails Label in Name', async ({page}) => {+ await openStory(page, 'core-avatar--interactive');+ const results = await new AxeBuilder({page})+ .withRules(['label-content-name-mismatch'])+ .analyze();+ expect(results.violations).toEqual([]);+ // The rule saw initials avatars, not an empty page.+ const named = page.getByRole('link', {name: 'Grace Hopper'});+ await expect(named).toBeVisible();+ await expect(named.locator('[data-initials="GH"]')).toHaveCount(1);+ await expect(+ page.getByRole('button', {name: /Dorothy Vaughan/}),+ ).toBeVisible();+});++test('the initials stay on screen as generated content', async ({page}) => {+ await openStory(page, 'core-avatar--initials-fallback');+ const drawn = await drawnInitials(page);+ expect(drawn.length).toBeGreaterThan(0);+ for (const content of drawn) {+ expect(content).toMatch(/\S/);+ expect(content).not.toBe('none');+ }+});++test('the initials stay on screen in forced colors', async ({page}) => {+ await page.emulateMedia({forcedColors: 'active'});+ await openStory(page, 'core-avatar--initials-fallback');+ const drawn = await drawnInitials(page);+ expect(drawn.length).toBeGreaterThan(0);+ for (const content of drawn) {+ expect(content).not.toBe('none');+ }+});++test('keyboard focus on an initials avatar shows the name', async ({page}) => {+ await openStory(page, 'core-avatar--interactive');+ const grace = page.getByRole('link', {name: 'Grace Hopper'});+ await grace.focus();+ await expect(page.getByRole('tooltip', {name: 'Grace Hopper'})).toBeVisible();+});diff --git a/packages/lab/src/CommentPin/CommentPin.test.tsx b/packages/lab/src/CommentPin/CommentPin.test.tsxindex 6d945e24a2..dd4465c3a3 100644--- a/packages/lab/src/CommentPin/CommentPin.test.tsx+++ b/packages/lab/src/CommentPin/CommentPin.test.tsx@@ -143,7 +143,8 @@ describe('CommentPin', () => {expect(pin).toHaveAttribute('data-unread', 'unread');expect(pin).not.toHaveAttribute('data-grouped');expect(container.querySelector('.astryx-status-dot')).not.toBeNull();- expect(pin).toHaveTextContent(/^AL$/);+ expect(pin.textContent).toBe('');+ expect(pin.querySelector('[data-initials="AL"]')).not.toBeNull();});it.each([