An open source design system that's fully customizable and agent ready
TypeScript
fix(Avatar): in forced colors the initials take the color around them (#8819)
Cindy Zhang9e7c02cddc2e
diff --git a/.changeset/avatar-initials-forced-colors.md b/.changeset/avatar-initials-forced-colors.mdnew file mode 100644index 0000000000..9b18bcbd5c--- /dev/null+++ b/.changeset/avatar-initials-forced-colors.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] In forced colors (Windows High Contrast), a lone `Avatar`'s initials and default person icon now take the color around them, as the browser forces it, instead of always showing CanvasText: inside a control that paints itself disabled they show GrayText. Faces inside an `AvatarGroup` keep CanvasText on the group's ring. Outside forced colors nothing changes.++@cixzhangdiff --git a/packages/core/src/Avatar/Avatar.spec.md b/packages/core/src/Avatar/Avatar.spec.mdindex 5190d3e8d2..fdd30fbe3d 100644--- a/packages/core/src/Avatar/Avatar.spec.md+++ b/packages/core/src/Avatar/Avatar.spec.md@@ -122,17 +122,17 @@ Consumer migration instructions belong in consumer docs and release notes.## Behavioral and layout contract-| ID | Invariant | Basis |-| --- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------ |-| FR1 | The root is a relative, non-shrinking inline-flex box of the resolved size with the shape's radius; it carries the `avatar` target, which reflects `size` and `shape`. A clipped content area fills it with the same radius and suppresses text selection. | Current source and tests |-| FR2 | The content area shows `src` while it has not failed, then `fallbackSrc` while it has not failed, then initials when the name yields any, then a default person icon at 60% of the box. Each image renders with empty `alt` and `object-fit: cover`. A failure is tracked per source, so a changed `src` or `fallbackSrc` is tried again. | Current source and tests |-| FR3 | Initials are the first letter, digit, or emoji of the first and last words of the trimmed `name`, uppercased; leading punctuation in a word is skipped, words with none are dropped, one qualifying word yields one initial, and grapheme clusters are never split. A whitespace-only name counts as absent. Initials and the default icon paint on the `avatar-fallback` target (reflecting `size`) with `--color-neutral`, secondary text, body family, medium weight, and initials at 40% of the box. | Current source and tests |-| FR4 | A truthy `status` renders in an absolutely positioned slot outside the clipped content area. On a circle it centers on the circle's edge at the bottom inline-end 45° point; on other shapes it sits at the bottom inline-end corner, offset outward by a quarter of its size. Placement mirrors in right-to-left documents. | Current source and tests |-| FR5 | The resolved name is `alt`, else `name` (blank strings count as absent), composed with the status label as the translated "{name}, {status}" when both exist; a status label alone also names the avatar. The status label comes from a string `label` on the passed element, read on every render, and from a label an AvatarStatusDot reports at any wrapper depth, which wins and updates the root before paint without a second render. | Current source and tests |-| FR6 | `href` renders the shared link component (or `as`) with `target` and `rel`; otherwise `onClick` renders a `button type="button"`; otherwise the root is a `div`. Link and button roots carry the `data-avatar-item` marker and the shared focus-visible outline; `onClick` attaches to the link or button. In development, an interactive avatar whose only name is a status label, or that has no name and no caller `aria-label`/`aria-labelledby`, logs a warning. | Current source and tests |-| FR7 | The tooltip shows the trimmed custom string, else the meaningful `name`, placed above, on hover and keyboard focus; `tooltip={false}` or a blank result shows none. A static avatar with a tooltip and outside a group gets `tabIndex={0}` so keyboard users can reveal it. A custom string is added to `aria-describedby` after any caller value; the default name tooltip is not, because it repeats the name. Implementation gap: a grouped link or button avatar that is not the group's tab stop stops opening its tooltip on focus 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 (Current-state impact). | Current source and tests |-| FR8 | Inside an AvatarGroup in the same layer (`spec:AST-038` FR7, FR8), the group's size and shape win over the avatar's own props; the root gains a 2px surface-colored ring outside its box and the group's negative inline-start overlap; a static avatar adds no tooltip tab stop, and link and button roots keep the `data-avatar-item` marker so they join the group's roving set. An avatar in a hover card, popover, or other layer opened from a group keeps its own size and shape, gets no ring or overlap, and keeps its tooltip tab stop; a link or button avatar there still carries the marker, so the group's roving focus, which selects marked elements in its DOM subtree, still includes it. | Current source and tests |-| FR9 | `ref` reaches the root of every variant. Supported DOM, ARIA, data, and event props reach the root after the derived ARIA, so a caller `aria-label`, `role`, or `aria-hidden` wins (`architecture:public-component-api` INV5); `data-testid` reaches the root; `xstyle`, `className`, and `style` merge in that order after component styles. Implementation gap: on the static root the component sets `tabIndex` after caller props, so a caller `tabIndex` is replaced (Current-state impact). | Current source and tests |+| ID | Invariant | Basis |+| --- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------ |+| FR1 | The root is a relative, non-shrinking inline-flex box of the resolved size with the shape's radius; it carries the `avatar` target, which reflects `size` and `shape`. A clipped content area fills it with the same radius and suppresses text selection. | Current source and tests |+| FR2 | The content area shows `src` while it has not failed, then `fallbackSrc` while it has not failed, then initials when the name yields any, then a default person icon at 60% of the box. Each image renders with empty `alt` and `object-fit: cover`. A failure is tracked per source, so a changed `src` or `fallbackSrc` is tried again. | Current source and tests |+| FR3 | Initials are the first letter, digit, or emoji of the first and last words of the trimmed `name`, uppercased; leading punctuation in a word is skipped, words with none are dropped, one qualifying word yields one initial, and grapheme clusters are never split. A whitespace-only name counts as absent. Initials and the default icon paint on the `avatar-fallback` target (reflecting `size`) with `--color-neutral`, secondary text, body family, medium weight, and initials at 40% of the box. In forced colors, a lone Avatar's initials and default icon take the surrounding color (`currentColor`): the forced foreground by default, and the system color of a control that paints one around it (GrayText, HighlightText); inside an AvatarGroup they keep the forced foreground on the group's ring. | Current source and tests |+| FR4 | A truthy `status` renders in an absolutely positioned slot outside the clipped content area. On a circle it centers on the circle's edge at the bottom inline-end 45° point; on other shapes it sits at the bottom inline-end corner, offset outward by a quarter of its size. Placement mirrors in right-to-left documents. | Current source and tests |+| FR5 | The resolved name is `alt`, else `name` (blank strings count as absent), composed with the status label as the translated "{name}, {status}" when both exist; a status label alone also names the avatar. The status label comes from a string `label` on the passed element, read on every render, and from a label an AvatarStatusDot reports at any wrapper depth, which wins and updates the root before paint without a second render. | Current source and tests |+| FR6 | `href` renders the shared link component (or `as`) with `target` and `rel`; otherwise `onClick` renders a `button type="button"`; otherwise the root is a `div`. Link and button roots carry the `data-avatar-item` marker and the shared focus-visible outline; `onClick` attaches to the link or button. In development, an interactive avatar whose only name is a status label, or that has no name and no caller `aria-label`/`aria-labelledby`, logs a warning. | Current source and tests |+| FR7 | The tooltip shows the trimmed custom string, else the meaningful `name`, placed above, on hover and keyboard focus; `tooltip={false}` or a blank result shows none. A static avatar with a tooltip and outside a group gets `tabIndex={0}` so keyboard users can reveal it. A custom string is added to `aria-describedby` after any caller value; the default name tooltip is not, because it repeats the name. Implementation gap: a grouped link or button avatar that is not the group's tab stop stops opening its tooltip on focus 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 (Current-state impact). | Current source and tests |+| FR8 | Inside an AvatarGroup in the same layer (`spec:AST-038` FR7, FR8), the group's size and shape win over the avatar's own props; the root gains a 2px surface-colored ring outside its box and the group's negative inline-start overlap; a static avatar adds no tooltip tab stop, and link and button roots keep the `data-avatar-item` marker so they join the group's roving set. An avatar in a hover card, popover, or other layer opened from a group keeps its own size and shape, gets no ring or overlap, and keeps its tooltip tab stop; a link or button avatar there still carries the marker, so the group's roving focus, which selects marked elements in its DOM subtree, still includes it. | Current source and tests |+| FR9 | `ref` reaches the root of every variant. Supported DOM, ARIA, data, and event props reach the root after the derived ARIA, so a caller `aria-label`, `role`, or `aria-hidden` wins (`architecture:public-component-api` INV5); `data-testid` reaches the root; `xstyle`, `className`, and `style` merge in that order after component styles. Implementation gap: on the static root the component sets `tabIndex` after caller props, so a caller `tabIndex` is replaced (Current-state impact). | Current source and tests |### Allowed variation@@ -227,17 +227,17 @@ 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 | Photo, failure, initials, punctuation, emoji, blank name; `lg` box | A wrong initials-or-icon fallback, split grapheme, lost retry, missing target, or wrong `lg` box size 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` |+| 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.tsx b/packages/core/src/Avatar/Avatar.tsxindex f7ac763c86..fe5bf6c783 100644--- a/packages/core/src/Avatar/Avatar.tsx+++ b/packages/core/src/Avatar/Avatar.tsx@@ -193,6 +193,19 @@ const styles = stylex.create({fontWeight: fontWeightVars['--font-weight-medium'],textTransform: 'uppercase',},+ // 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+ // selected (HighlightText) carries them with it; an+ // authored color would be forced to CanvasText whatever the control shows.+ // A grouped face keeps it: its ring's opaque fill is forced to Canvas, so+ // only CanvasText is sure to read on it.+ loneFallback: {+ color: {+ default: colorVars['--color-text-secondary'],+ '@media (forced-colors: active)': 'currentColor',+ },+ },status: {position: 'absolute',},@@ -784,6 +797,7 @@ export function Avatar({themeProps('avatar-fallback', {size: resolvedSize}),stylex.props(styles.fallback,+ avatarGroup == null && styles.loneFallback,dynamicStyles.fontSize(numericSize),),)}>@@ -794,7 +808,10 @@ export function Avatar({<div{...mergeProps(themeProps('avatar-fallback', {size: resolvedSize}),- stylex.props(styles.fallback),+ stylex.props(+ styles.fallback,+ avatarGroup == null && styles.loneFallback,+ ),)}><DefaultIcon size={numericSize} /></div>diff --git a/packages/core/src/Avatar/__tests__/AvatarForcedColors.a11y.chromium.spec.ts b/packages/core/src/Avatar/__tests__/AvatarForcedColors.a11y.chromium.spec.tsnew file mode 100644index 0000000000..6a4e04a749--- /dev/null+++ b/packages/core/src/Avatar/__tests__/AvatarForcedColors.a11y.chromium.spec.ts@@ -0,0 +1,126 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// @pr-a11y scope ^packages/core/src/Avatar/ ^apps/storybook/stories/Avatar++/**+ * @file AvatarForcedColors.a11y.chromium.spec.ts+ * @input The built Avatar "Initials Fallback" story in real Chromium, with+ * forced colors emulated and without+ * @output Browser evidence that, in forced colors, a lone Avatar's initials+ * take the color around them: CanvasText by default, GrayText inside a control+ * that paints itself disabled, HighlightText inside a+ * selected one, while grouped faces keep CanvasText on the group's ring;+ * outside forced colors they keep the theme's color+ * @position Regression proof for Avatar's fallback color (Chromium only:+ * Playwright's WebKit matches the forced-colors query but forces nothing)+ */++import {expect, test, type Page} from '@playwright/test';+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();+});++/**+ * The initials' color, with `around` painted on `host`: the Avatar's own box+ * for a lone Avatar, the group's for grouped ones.+ */+async function initialsColor(+ page: Page,+ forcedColors: 'active' | 'none',+ around: string | null,+ {+ story = 'core-avatar--initials-fallback',+ host = '.astryx-avatar',+ }: {story?: string; host?: string} = {},+): Promise<{initials: string; reference: string}> {+ await page.emulateMedia({forcedColors});+ await page.goto(`${storybook.origin}/iframe.html?id=${story}&viewMode=story`);+ await page.locator('.astryx-avatar-fallback').first().waitFor();+ if (around != null) {+ await page.addStyleTag({content: `${host} { ${around} }`});+ }+ return page.evaluate(() => {+ const initials = document.querySelector('.astryx-avatar-fallback');+ // A probe painted with the system color the initials should show.+ const probe = document.createElement('span');+ document.body.append(probe);+ const read = (color: string) => {+ probe.style.color = color;+ return getComputedStyle(probe).color;+ };+ const result = {+ initials: initials == null ? '' : getComputedStyle(initials).color,+ reference: JSON.stringify({+ CanvasText: read('CanvasText'),+ GrayText: read('GrayText'),+ HighlightText: read('HighlightText'),+ }),+ };+ probe.remove();+ return result;+ });+}++test('in forced colors the initials are CanvasText by default', async ({+ page,+}) => {+ const {initials, reference} = await initialsColor(page, 'active', null);+ expect(initials).toBe(JSON.parse(reference).CanvasText);+});++test('in forced colors the initials take GrayText inside a control that paints itself disabled', async ({+ page,+}) => {+ const {initials, reference} = await initialsColor(+ page,+ 'active',+ 'color: GrayText;',+ );+ expect(initials).toBe(JSON.parse(reference).GrayText);+});++test('in forced colors the initials take HighlightText inside a selected control', async ({+ page,+}) => {+ const {initials, reference} = await initialsColor(+ page,+ 'active',+ 'forced-color-adjust: none; background: Highlight; color: HighlightText;',+ );+ expect(initials).toBe(JSON.parse(reference).HighlightText);+});++test("outside forced colors the initials keep the theme's color, whatever is around them", async ({+ page,+}) => {+ const plain = await initialsColor(page, 'none', null);+ const around = await initialsColor(page, 'none', 'color: rgb(200, 0, 0);');+ expect(around.initials).toBe(plain.initials);+ expect(plain.initials).not.toBe('rgb(200, 0, 0)');+});++test("in forced colors grouped initials keep CanvasText on the group's ring", async ({+ page,+}) => {+ const {initials, reference} = await initialsColor(+ page,+ 'active',+ 'color: GrayText;',+ {+ story: 'core-avatargroup--initials-fallback',+ host: '.astryx-avatar-group',+ },+ );+ expect(initials).toBe(JSON.parse(reference).CanvasText);+});