An open source design system that's fully customizable and agent ready
TypeScript
feat(Avatar): optional href/onClick interactivity + roving focus in AvatarGroup (#4170) (#4225)
Cindy Zhangae1eaed9543a
diff --git a/.changeset/avatar-interactive-roving.md b/.changeset/avatar-interactive-roving.mdnew file mode 100644index 0000000000..136575b074--- /dev/null+++ b/.changeset/avatar-interactive-roving.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[feat] `Avatar` gains optional interactivity via `href`/`onClick` (with `as`/`target`/`rel`), following Button's element-swap trichotomy: `href` renders a link through `useLinkComponent`, `onClick` (no href) renders a `<button type="button">`, and with neither the avatar stays the static, non-focusable element it is today (non-breaking default). Interactive avatars get the focus-visible accent ring and a required accessible name (from `alt`/`name`). Inside `AvatarGroup`, interactive avatars — and an interactive `AvatarGroupOverflow` — now share a single Tab stop with roving ArrowLeft/ArrowRight focus, and the group exposes a screen-reader keyboard hint via `aria-describedby`. A purely static facepile is unchanged. (#4170)++@cixzhangdiff --git a/apps/storybook/stories/Avatar.stories.tsx b/apps/storybook/stories/Avatar.stories.tsxindex 8a55fa34c0..cf6161e213 100644--- a/apps/storybook/stories/Avatar.stories.tsx+++ b/apps/storybook/stories/Avatar.stories.tsx@@ -682,3 +682,40 @@ export const TooltipDisabled: Story = {</div>),};++/**+ * Interactive avatars. `href` renders an `<a>` (native right-click / Cmd+click);+ * `onClick` renders a `<button>`. Both get a focus-visible accent ring. A+ * meaningful `name`/`alt` is required so the control has an accessible name.+ */+export const Interactive: Story = {+ render: () => (+ <div {...stylex.props(styles.storyWrapper)}>+ <div>+ <h4 {...stylex.props(styles.heading)}>As a link (href)</h4>+ <div {...stylex.props(styles.row)}>+ <Avatar name="Ada Lovelace" href="https://example.com/ada" />+ <Avatar+ name="Grace Hopper"+ src="https://i.pravatar.cc/150?img=5"+ href="https://example.com/grace"+ />+ </div>+ </div>+ <div>+ <h4 {...stylex.props(styles.heading)}>As a button (onClick)</h4>+ <div {...stylex.props(styles.row)}>+ <Avatar+ name="Alan Turing"+ onClick={() => alert('Open Alan Turing')}+ />+ <Avatar+ name="Katherine Johnson"+ src="https://i.pravatar.cc/150?img=9"+ onClick={() => alert('Open Katherine Johnson')}+ />+ </div>+ </div>+ </div>+ ),+};diff --git a/apps/storybook/stories/AvatarGroup.stories.tsx b/apps/storybook/stories/AvatarGroup.stories.tsxindex 170ecaf80a..0a2004f2a1 100644--- a/apps/storybook/stories/AvatarGroup.stories.tsx+++ b/apps/storybook/stories/AvatarGroup.stories.tsx@@ -250,3 +250,51 @@ export const ManyAvatars: Story = {);},};++/**+ * Interactive avatars — a mix of links (`href`) and buttons (`onClick`) plus an+ * interactive overflow. The whole group is a single Tab stop: Tab into it once,+ * then use ArrowLeft/ArrowRight to move focus between avatars and the overflow+ * button. Screen readers hear a keyboard hint from the group.+ */+export const Interactive: Story = {+ render: () => (+ <AvatarGroup size="lg" aria-label="Project team">+ <Avatar+ src={USERS[0].src}+ name={USERS[0].name}+ href="https://example.com/users/alice"+ />+ <Avatar+ src={USERS[1].src}+ name={USERS[1].name}+ href="https://example.com/users/bob"+ />+ <Avatar+ src={USERS[2].src}+ name={USERS[2].name}+ onClick={() => alert(`Open ${USERS[2].name}`)}+ />+ <AvatarGroupOverflow+ count={USERS.length - 3}+ onClick={() => alert('Show all members')}+ />+ </AvatarGroup>+ ),+};++/**+ * Static facepile (no href/onClick) — unchanged behavior. Not focusable, no Tab+ * stop, no keyboard hint. Shown here alongside the interactive variant for+ * contrast.+ */+export const StaticFacepile: Story = {+ render: () => (+ <AvatarGroup size="lg">+ {USERS.slice(0, 4).map(u => (+ <Avatar key={u.key} src={u.src} name={u.name} />+ ))}+ <AvatarGroupOverflow count={USERS.length - 4} />+ </AvatarGroup>+ ),+};diff --git a/packages/cli/templates/blocks/components/Avatar/AvatarInteractive.doc.mjs b/packages/cli/templates/blocks/components/Avatar/AvatarInteractive.doc.mjsnew file mode 100644index 0000000000..a385a69d60--- /dev/null+++ b/packages/cli/templates/blocks/components/Avatar/AvatarInteractive.doc.mjs@@ -0,0 +1,13 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('../../../../../core/src/docs-types').TemplateDoc} */+export const doc = {+ type: 'block',+ exampleFor: 'Avatar',+ name: 'Avatar — Interactive',+ displayName: 'Avatar — Interactive',+ description: 'Make an avatar interactive by passing `href` to render it as a link or `onClick` to render it as a button. Both forms are focusable and show a focus-visible ring for keyboard users. Use for profile links, mention pop-ups, or any avatar people can act on.',+ isReady: true,+ aspectRatio: 16 / 9,+ componentsUsed: ['Avatar', 'Layout', 'Text'],+};diff --git a/packages/cli/templates/blocks/components/Avatar/AvatarInteractive.tsx b/packages/cli/templates/blocks/components/Avatar/AvatarInteractive.tsxnew file mode 100644index 0000000000..aab69d94c9--- /dev/null+++ b/packages/cli/templates/blocks/components/Avatar/AvatarInteractive.tsx@@ -0,0 +1,36 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++import {Avatar} from '@astryxdesign/core/Avatar';+import {Stack} from '@astryxdesign/core/Layout';+import {Text} from '@astryxdesign/core/Text';++export default function AvatarInteractive() {+ return (+ <Stack direction="horizontal" gap={6} vAlign="start">+ <Stack direction="vertical" gap={2} hAlign="center">+ <Avatar+ src="https://lookaside.facebook.com/assets/astryx/DATA-Itai-Jordaan.png"+ name="Itai Jordaan"+ size="xl"+ href="https://example.com/people/itai-jordaan"+ />+ <Text type="supporting" color="secondary">+ Link (href)+ </Text>+ </Stack>+ <Stack direction="vertical" gap={2} hAlign="center">+ <Avatar+ src="https://lookaside.facebook.com/assets/astryx/DATA-Margot-Schroder.png"+ name="Margot Schroder"+ size="xl"+ onClick={() => window.alert('Opening Margot Schroder’s profile')}+ />+ <Text type="supporting" color="secondary">+ Button (onClick)+ </Text>+ </Stack>+ </Stack>+ );+}diff --git a/packages/core/locales/en.json b/packages/core/locales/en.jsonindex acb303cef7..7b0ae1cd6c 100644--- a/packages/core/locales/en.json+++ b/packages/core/locales/en.json@@ -239,6 +239,10 @@"defaultMessage": "Avatars","description": "Screen-reader-only fallback name for a horizontal cluster of user avatar images. Plural noun; consumers usually override with \"Team members\", \"Attendees\", etc."},+ "@astryx.avatarGroup.keyboardHint": {+ "defaultMessage": "Use arrow keys to move between avatars",+ "description": "Screen-reader-only instruction attached (via aria-describedby) to a group of interactive avatars that share a single Tab stop. Tells keyboard users the Left/Right arrow keys move focus between the avatars. Only announced when the group has interactive (link/button) avatars."+ },"@astryx.banner.dismiss": {"defaultMessage": "Dismiss","description": "\"Dismiss\" = close/hide this notification (not \"reject a person\"). Aria label AND tooltip on the small X button on a Banner."diff --git a/packages/core/src/Avatar/Avatar.doc.mjs b/packages/core/src/Avatar/Avatar.doc.mjsindex 3ea7472b10..a763315648 100644--- a/packages/core/src/Avatar/Avatar.doc.mjs+++ b/packages/core/src/Avatar/Avatar.doc.mjs@@ -82,6 +82,34 @@ export const docs = {"Tooltip shown on hover and keyboard focus. Omitted or true shows the avatar's name; a string shows that text instead; false shows no tooltip. Not auto-disabled when wrapped in your own Tooltip/HoverCard — set tooltip={false} if you supply your own overlay. No tooltip is shown when tooltip is true/omitted and there is no name.",default: 'true',},+ {+ name: 'href',+ type: 'string',+ description:+ 'When set, the avatar renders as an interactive link (`<a>` or a custom link component) pointing here — 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.',+ },+ {+ name: 'as',+ type: 'ElementType',+ description:+ 'Custom link component used when `href` is set (e.g. Next.js `Link`). Overrides the provider-level LinkProvider default. Only applies with `href`.',+ },+ {+ name: 'target',+ type: 'string',+ description: 'Link target attribute. Only applies with `href`.',+ },+ {+ name: 'rel',+ type: 'string',+ description: 'Link rel attribute. Only applies with `href`.',+ },+ {+ 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`.',+ },],components: [{name: 'AvatarStatusDot'},@@ -125,6 +153,11 @@ export const docsDense = {status: 'corner content for status indicators',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.',+ 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.',},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 0b88bf7049..d464cbdb0f 100644--- a/packages/core/src/Avatar/Avatar.test.tsx+++ b/packages/core/src/Avatar/Avatar.test.tsx@@ -2,6 +2,7 @@import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';import {render, screen, fireEvent} from '@testing-library/react';+import userEvent from '@testing-library/user-event';import {Avatar} from './Avatar';describe('Avatar', () => {@@ -221,3 +222,114 @@ describe('Avatar', () => {});});});++describe('Avatar — interactivity (Button trichotomy)', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('renders a link when `href` is set (default LinkComponent is <a>)', () => {+ render(<Avatar name="Ada Lovelace" href="/users/ada" />);+ const link = screen.getByRole('link', {name: 'Ada Lovelace'});+ expect(link.tagName).toBe('A');+ expect(link).toHaveAttribute('href', '/users/ada');+ // The static img semantics are gone — it's a control now.+ expect(screen.queryByRole('img')).not.toBeInTheDocument();+ });++ it('forwards target/rel on the link', () => {+ render(+ <Avatar+ name="Ada"+ href="https://example.com"+ target="_blank"+ rel="noopener noreferrer"+ />,+ );+ const link = screen.getByRole('link', {name: 'Ada'});+ expect(link).toHaveAttribute('target', '_blank');+ expect(link).toHaveAttribute('rel', 'noopener noreferrer');+ });++ it('renders a <button type="button"> when `onClick` is set (no href)', async () => {+ const user = userEvent.setup();+ const handleClick = vi.fn();+ render(<Avatar name="Ada" onClick={handleClick} />);+ const button = screen.getByRole('button', {name: 'Ada'});+ expect(button.tagName).toBe('BUTTON');+ expect(button).toHaveAttribute('type', 'button');+ await user.click(button);+ expect(handleClick).toHaveBeenCalledOnce();+ });++ it('href wins over onClick (link, not button)', () => {+ render(<Avatar name="Ada" href="/ada" onClick={() => {}} />);+ expect(screen.getByRole('link', {name: 'Ada'})).toBeInTheDocument();+ expect(screen.queryByRole('button')).not.toBeInTheDocument();+ });++ it('stays a static element (no href, no onClick) — non-breaking default', () => {+ render(<Avatar name="Ada" />);+ expect(screen.getByRole('img', {name: 'Ada'})).toBeInTheDocument();+ expect(screen.queryByRole('link')).not.toBeInTheDocument();+ expect(screen.queryByRole('button')).not.toBeInTheDocument();+ });++ it('stamps the data-avatar-item marker on the interactive link', () => {+ render(<Avatar name="Ada" href="/ada" />);+ expect(screen.getByRole('link', {name: 'Ada'})).toHaveAttribute(+ 'data-avatar-item',+ );+ });++ it('stamps the data-avatar-item marker on the interactive button', () => {+ render(<Avatar name="Ada" onClick={() => {}} />);+ expect(screen.getByRole('button', {name: 'Ada'})).toHaveAttribute(+ 'data-avatar-item',+ );+ });++ it('does not stamp data-avatar-item on a static avatar', () => {+ render(<Avatar name="Ada" data-testid="a" />);+ expect(screen.getByTestId('a')).not.toHaveAttribute('data-avatar-item');+ });++ it('carries a focus-visible ring class on the interactive element', () => {+ // The interactive element applies the shared focus-visible accent ring via+ // its StyleX class. We assert the element is focusable and receives focus.+ render(<Avatar name="Ada" onClick={() => {}} />);+ const button = screen.getByRole('button', {name: 'Ada'});+ button.focus();+ expect(button).toHaveFocus();+ // className carries the avatar theming target so themes can style it.+ expect(button.className).toContain('astryx-avatar');+ });++ it('warns in dev when interactive without an accessible name (href)', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ render(<Avatar href="/somewhere" />);+ expect(warn).toHaveBeenCalledWith(+ expect.stringContaining('interactive avatar'),+ );+ });++ it('warns in dev when interactive without an accessible name (onClick)', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ render(<Avatar onClick={() => {}} />);+ expect(warn).toHaveBeenCalledWith(+ expect.stringContaining('interactive avatar'),+ );+ });++ it('does not warn when interactive with a name', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ render(<Avatar name="Ada" href="/ada" />);+ expect(warn).not.toHaveBeenCalled();+ });++ it('does not warn for a static avatar without a name (decorative is fine)', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ render(<Avatar data-testid="a" />);+ expect(warn).not.toHaveBeenCalled();+ });+});diff --git a/packages/core/src/Avatar/Avatar.tsx b/packages/core/src/Avatar/Avatar.tsxindex 3e394c9349..887b53944a 100644--- a/packages/core/src/Avatar/Avatar.tsx+++ b/packages/core/src/Avatar/Avatar.tsx@@ -14,6 +14,8 @@* - /packages/core/src/Avatar/index.ts (exports if types change)* - /apps/storybook/stories/Avatar.stories.tsx (storybook stories)* - /packages/cli/templates/blocks/components/Avatar/ (showcase blocks)+ *+ * Last synced props: alt, fallbackSrc, name, size, src, status, href, as, target, rel, onClick*/import {useMemo, useState, type ReactNode} from 'react';@@ -30,6 +32,8 @@ import {useAvatarGroup} from '../AvatarGroup/AvatarGroupContext';import {mergeProps, mergeRefs} from '../utils';import {themeProps} from '../utils/themeProps';import {useTooltip} from '../Tooltip/useTooltip';+import {useLinkComponent} from '../Link/useLinkComponent';+import type {LinkComponentType} from '../Link/types';/*** The offset ratio for positioning elements on a circle's edge at 45°.@@ -148,6 +152,39 @@ const styles = stylex.create({':focus-visible': '2px',},},+ // Reset the intrinsic styling of the interactive element (<a>/<button>) so it+ // is a transparent, correctly-sized wrapper around the avatar visuals. The+ // element carries the focus-visible accent ring for keyboard users.+ interactive: {+ appearance: 'none',+ padding: 0,+ margin: 0,+ borderWidth: 0,+ borderStyle: 'none',+ backgroundColor: 'transparent',+ color: 'inherit',+ font: 'inherit',+ textDecoration: 'none',+ cursor: 'pointer',+ // Match the avatar's circular shape so the focus ring hugs it.+ borderRadius: radiusVars['--radius-full'],+ outlineWidth: {+ default: 0,+ ':focus-visible': 2,+ },+ outlineStyle: {+ default: 'none',+ ':focus-visible': 'solid',+ },+ outlineColor: {+ default: null,+ ':focus-visible': colorVars['--color-accent'],+ },+ outlineOffset: {+ default: 0,+ ':focus-visible': 2,+ },+ },});/**@@ -244,6 +281,35 @@ export interface AvatarProps extends BaseProps<HTMLDivElement> {* @default true*/tooltip?: string | boolean;+ /**+ * When provided, the avatar becomes an interactive link (`<a>` or custom+ * link component) pointing at `href`. Follows the same element-swap rules as+ * Button: `href` renders a link, otherwise `onClick` renders a+ * `<button type="button">`, otherwise the avatar stays a static (non-focusable)+ * element. An interactive avatar requires a meaningful accessible name via+ * `alt` or `name`.+ */+ href?: string;+ /**+ * Custom link component to use when `href` is provided. Overrides the+ * provider-level default set by LinkProvider. Useful for Next.js `<Link>` or+ * other router-aware components. Only applies when `href` is provided.+ */+ as?: LinkComponentType;+ /**+ * HTML target attribute for the link. Only applies when `href` is provided.+ */+ target?: string;+ /**+ * HTML rel attribute for the link. Only applies when `href` is provided.+ */+ rel?: string;+ /**+ * Click handler. When provided without `href`, renders the avatar as a+ * focusable `<button type="button">`. An interactive avatar requires a+ * meaningful accessible name via `alt` or `name`.+ */+ onClick?: React.MouseEventHandler<HTMLElement>;}/**@@ -295,6 +361,8 @@ function DefaultIcon({size}: {size: number}) {* <Avatar src="/user.jpg" status={<OnlineIndicator />} />* <Avatar name="jsmith" tooltip="Jane Smith, Staff Engineer" />* <Avatar name="Jane" tooltip={false} />+ * <Avatar src="/user.jpg" name="John Doe" href="/users/john" />+ * <Avatar src="/user.jpg" name="John Doe" onClick={() => openProfile()} />* ```*/export function Avatar({@@ -306,6 +374,11 @@ export function Avatar({src,status,tooltip = true,+ href,+ as,+ target,+ rel,+ onClick,xstyle,className,style,@@ -359,11 +432,14 @@ export function Avatar({// returns `describedBy` as a value we choose whether to apply — the only way// to satisfy the per-case aria-describedby rule (default name: none; custom// string: describe) without editing Tooltip. `focusTrigger: 'auto'` shows the- // tooltip on keyboard focus once the root is made focusable (below).+ // tooltip on keyboard focus once the root is focusable (natively for the+ // interactive <a>/<button>, or via an explicit tab stop on the static div).const tooltipHook = useTooltip({placement: 'above',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);const describedByProp =showTooltip && isCustomTooltip@@ -375,8 +451,136 @@ export function Avatar({}: null;- const avatarElement = (- <AvatarSizeContext value={numericSize}>+ // Element-swap trichotomy, copied from Button: `href` renders a link,+ // otherwise `onClick` renders a `<button>`, otherwise today's static element+ // is unchanged (the non-breaking default).+ const renderAsLink = href != null;+ const renderAsButton = !renderAsLink && onClick != null;+ const isInteractive = renderAsLink || renderAsButton;+ 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`.',+ );+ }++ // The inner visuals are identical across the static and interactive variants.+ const visualContent = (+ <>+ <div {...stylex.props(styles.content, dynamicStyles.size(numericSize))}>+ {showImage && (+ <img+ src={src}+ alt=""+ onError={() => setErroredSrc(src)}+ {...stylex.props(styles.image)}+ />+ )}+ {showFallbackImage && (+ <img+ src={fallbackSrc}+ alt=""+ onError={() => setErroredFallbackSrc(fallbackSrc)}+ {...stylex.props(styles.image)}+ />+ )}+ {showInitials && (+ <div+ {...stylex.props(+ styles.fallback,+ dynamicStyles.fontSize(numericSize),+ )}>+ {getInitials(name)}+ </div>+ )}+ {showIcon && (+ <div {...stylex.props(styles.fallback)}>+ <DefaultIcon size={numericSize} />+ </div>+ )}+ </div>+ {status && (+ <div+ {...stylex.props(+ styles.status,+ dynamicStyles.statusPosition(numericSize),+ )}>+ {status}+ </div>+ )}+ </>+ );++ // Shared StyleX + theme props for the root element in every variant. The+ // group ring/overlap, the interactive focus-visible ring, and the+ // tooltip tab-stop focus ring all live here so the interactive+ // `<a>`/`<button>` and the static `<div>` carry the exact same box.+ const rootStylexProps = mergeProps(+ themeProps('avatar', {size: resolvedSize}),+ stylex.props(+ styles.wrapper,+ isInteractive && styles.interactive,+ !isInteractive && showTooltip && !avatarGroup && styles.focusable,+ avatarGroup && groupStyles.ring,+ avatarGroup && groupStyles.overlap,+ avatarGroup && groupDynamicStyles.overlap(-avatarGroup.overlap),+ xstyle,+ ),+ className,+ style,+ );++ let rootElement: ReactNode;++ // `props` is typed for the default `<div>` root (its event handlers are+ // HTMLDivElement-typed). The interactive branches render an `<a>`/`<button>`,+ // so the passthrough props are re-typed to the generic element here — the+ // avatar's own handlers (onClick) are declared on HTMLElement and stay typed.+ const interactivePassthrough = props as React.HTMLAttributes<HTMLElement>;++ if (renderAsLink) {+ // The rendered link carries the `data-avatar-item` marker so AvatarGroup's+ // roving focus (which selects on `[data-avatar-item]`, not a tag/role) picks+ // it up while ignoring nested buttons in a custom status/badge slot.+ rootElement = (+ <LinkComponent+ {...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}+ {...rootStylexProps}>+ {visualContent}+ </LinkComponent>+ );+ } else if (renderAsButton) {+ rootElement = (+ <button+ {...interactivePassthrough}+ {...describedByProp}+ ref={rootRef}+ type="button"+ aria-label={accessibleName}+ data-avatar-item=""+ data-testid={testId}+ onClick={onClick}+ {...rootStylexProps}>+ {visualContent}+ </button>+ );+ } else {+ rootElement = (<div{...props}ref={rootRef}@@ -385,66 +589,19 @@ export function Avatar({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. Only while active.- tabIndex={showTooltip ? 0 : undefined}+ // (WCAG 1.4.13 / 2.1.1) — matching Timestamp/Button. Suppressed inside+ // an AvatarGroup, which owns a single roving tab stop for its members.+ tabIndex={showTooltip && !avatarGroup ? 0 : undefined}data-testid={testId}{...describedByProp}- {...mergeProps(- themeProps('avatar', {size: resolvedSize}),- stylex.props(- styles.wrapper,- showTooltip && styles.focusable,- avatarGroup && groupStyles.ring,- avatarGroup && groupStyles.overlap,- avatarGroup && groupDynamicStyles.overlap(-avatarGroup.overlap),- xstyle,- ),- className,- style,- )}>- <div {...stylex.props(styles.content, dynamicStyles.size(numericSize))}>- {showImage && (- <img- src={src}- alt=""- onError={() => setErroredSrc(src)}- {...stylex.props(styles.image)}- />- )}- {showFallbackImage && (- <img- src={fallbackSrc}- alt=""- onError={() => setErroredFallbackSrc(fallbackSrc)}- {...stylex.props(styles.image)}- />- )}- {showInitials && (- <div- {...stylex.props(- styles.fallback,- dynamicStyles.fontSize(numericSize),- )}>- {getInitials(name)}- </div>- )}- {showIcon && (- <div {...stylex.props(styles.fallback)}>- <DefaultIcon size={numericSize} />- </div>- )}- </div>- {status && (- <div- {...stylex.props(- styles.status,- dynamicStyles.statusPosition(numericSize),- )}>- {status}- </div>- )}+ {...rootStylexProps}>+ {visualContent}</div>- </AvatarSizeContext>+ );+ }++ const avatarElement = (+ <AvatarSizeContext value={numericSize}>{rootElement}</AvatarSizeContext>);if (!showTooltip) {diff --git a/packages/core/src/AvatarGroup/AvatarGroup.doc.mjs b/packages/core/src/AvatarGroup/AvatarGroup.doc.mjsindex 43475c77c1..d5d85d2059 100644--- a/packages/core/src/AvatarGroup/AvatarGroup.doc.mjs+++ b/packages/core/src/AvatarGroup/AvatarGroup.doc.mjs@@ -14,6 +14,7 @@ export const docs = {{guidance: true, description: 'Set max to limit visible avatars when the list is long; 3-5 is typical.'},{guidance: true, description: 'Use AvatarGroupOverflow for custom overflow content like a popover trigger or "add member" button.'},{guidance: true, description: 'Pass status dots, click handlers, or tooltips directly on each Avatar child.'},+ {guidance: true, description: 'Make avatars interactive with href or onClick to link to profiles. Interactive avatars share a single Tab stop; arrow keys move between them, and the group announces a keyboard hint to assistive tech.'},{guidance: false, description: "Don't nest AvatarGroups; use a single group with all avatars."},],anatomy: [@@ -94,6 +95,7 @@ export const docsDense = {{guidance: true, description: 'Set max to limit visible avatars (3-5 typical).'},{guidance: true, description: 'Use AvatarGroupOverflow for custom overflow (popover, add button).'},{guidance: true, description: 'Pass status dots / click handlers directly on each Avatar.'},+ {guidance: true, description: 'Interactive avatars (href/onClick) share one Tab stop; arrows rove between them + the overflow button.'},{guidance: false, description: "Don't nest AvatarGroups."},],},diff --git a/packages/core/src/AvatarGroup/AvatarGroup.test.tsx b/packages/core/src/AvatarGroup/AvatarGroup.test.tsxindex 8ba9122cef..53bd2cd49a 100644--- a/packages/core/src/AvatarGroup/AvatarGroup.test.tsx+++ b/packages/core/src/AvatarGroup/AvatarGroup.test.tsx@@ -226,3 +226,128 @@ describe('AvatarGroupOverflow — hardening', () => {expect(screen.getByLabelText('4912 more')).toBeInTheDocument();});});++describe('AvatarGroup — roving focus + keyboard hint', () => {+ it('is a single tab stop over interactive avatars (one tabindex=0, rest -1)', () => {+ render(+ <AvatarGroup>+ <Avatar name="Alice" href="/alice" />+ <Avatar name="Bob" href="/bob" />+ <Avatar name="Charlie" href="/charlie" />+ </AvatarGroup>,+ );++ const alice = screen.getByRole('link', {name: 'Alice'});+ const bob = screen.getByRole('link', {name: 'Bob'});+ const charlie = screen.getByRole('link', {name: 'Charlie'});++ expect(alice).toHaveAttribute('tabindex', '0');+ expect(bob).toHaveAttribute('tabindex', '-1');+ expect(charlie).toHaveAttribute('tabindex', '-1');+ });++ it('roves focus with ArrowRight/ArrowLeft across interactive avatars', async () => {+ const user = userEvent.setup();+ render(+ <AvatarGroup>+ <Avatar name="Alice" href="/alice" />+ <Avatar name="Bob" onClick={() => {}} />+ <Avatar name="Charlie" href="/charlie" />+ </AvatarGroup>,+ );++ const alice = screen.getByRole('link', {name: 'Alice'});+ const bob = screen.getByRole('button', {name: 'Bob'});+ const charlie = screen.getByRole('link', {name: 'Charlie'});++ alice.focus();+ expect(alice).toHaveFocus();++ await user.keyboard('{ArrowRight}');+ expect(bob).toHaveFocus();+ expect(bob).toHaveAttribute('tabindex', '0');+ expect(alice).toHaveAttribute('tabindex', '-1');++ await user.keyboard('{ArrowRight}');+ expect(charlie).toHaveFocus();++ await user.keyboard('{ArrowLeft}');+ expect(bob).toHaveFocus();+ });++ it('includes the overflow button as the last roving item', async () => {+ const user = userEvent.setup();+ render(+ <AvatarGroup>+ <Avatar name="Alice" href="/alice" />+ <AvatarGroupOverflow count={3} onClick={() => {}} />+ </AvatarGroup>,+ );++ const alice = screen.getByRole('link', {name: 'Alice'});+ const overflow = screen.getByRole('button', {name: '3 more'});+ expect(overflow).toHaveAttribute('data-avatar-item');++ alice.focus();+ await user.keyboard('{ArrowRight}');+ expect(overflow).toHaveFocus();+ });++ it('does NOT rove over a non-avatar button in a status slot', async () => {+ const user = userEvent.setup();+ render(+ <AvatarGroup>+ <Avatar+ name="Alice"+ href="/alice"+ status={<button type="button">badge</button>}+ />+ <Avatar name="Bob" href="/bob" />+ </AvatarGroup>,+ );++ const alice = screen.getByRole('link', {name: 'Alice'});+ const bob = screen.getByRole('link', {name: 'Bob'});+ const statusButton = screen.getByRole('button', {name: 'badge'});++ // The status button carries no data-avatar-item marker.+ expect(statusButton).not.toHaveAttribute('data-avatar-item');++ alice.focus();+ await user.keyboard('{ArrowRight}');+ // Arrow moves to the next avatar, skipping the nested status button.+ expect(bob).toHaveFocus();+ expect(statusButton).not.toHaveFocus();+ });++ it('attaches an aria-describedby keyboard hint when interactive children exist', () => {+ render(+ <AvatarGroup>+ <Avatar name="Alice" href="/alice" />+ <Avatar name="Bob" href="/bob" />+ </AvatarGroup>,+ );++ const group = screen.getByRole('group');+ const describedBy = group.getAttribute('aria-describedby');+ expect(describedBy).toBeTruthy();+ const hint = document.getElementById(describedBy!);+ expect(hint).not.toBeNull();+ expect(hint).toHaveTextContent('Use arrow keys to move between avatars');+ });++ it('a purely static group has no tab stop and no keyboard hint', () => {+ render(+ <AvatarGroup>+ <Avatar name="Alice" data-testid="alice" />+ <Avatar name="Bob" data-testid="bob" />+ </AvatarGroup>,+ );++ const group = screen.getByRole('group');+ expect(group).not.toHaveAttribute('aria-describedby');+ // Static avatars are not focusable — no roving tabindex stamped.+ expect(screen.getByTestId('alice')).not.toHaveAttribute('tabindex');+ expect(screen.getByTestId('bob')).not.toHaveAttribute('tabindex');+ });+});diff --git a/packages/core/src/AvatarGroup/AvatarGroup.tsx b/packages/core/src/AvatarGroup/AvatarGroup.tsxindex d81fb72029..3e9c4608d2 100644--- a/packages/core/src/AvatarGroup/AvatarGroup.tsx+++ b/packages/core/src/AvatarGroup/AvatarGroup.tsx@@ -11,6 +11,12 @@* one AvatarGroupOverflow). The group provides overlap styling via* context — no child introspection needed.*+ * When the group contains interactive avatars (rendered as links/buttons) or an+ * interactive AvatarGroupOverflow, it becomes a single Tab stop with roving+ * arrow-key focus (via useListFocus with hasRovingTabIndex) and exposes a+ * screen-reader keyboard hint via aria-describedby. A purely static facepile+ * gets neither — it stays a plain non-focusable group.+ ** SYNC: When modified, update these files to stay in sync:* - /packages/core/src/AvatarGroup/AvatarGroup.doc.mjs (props table, features)* - /packages/core/src/AvatarGroup/index.ts (exports if types change)@@ -18,14 +24,18 @@* - /packages/cli/templates/blocks/components/AvatarGroup/ (showcase blocks)*/-import {useMemo, type ReactNode} from 'react';+import {useId, useMemo, useState, type ReactNode} from 'react';import type {BaseProps} from '../BaseProps';import {resolveSize, type AvatarSize} from '../Avatar';import * as stylex from '@stylexjs/stylex';-import {mergeProps} from '../utils';+import {mergeProps, mergeRefs} from '../utils';+import {composeEventHandlers} from '../utils/composeEventHandlers';import {AvatarGroupContext} from './AvatarGroupContext';import {themeProps} from '../utils/themeProps';import {useTranslator} from '../i18n';+import {useListFocus} from '../hooks/useListFocus';+import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';+import {VisuallyHidden} from '../VisuallyHidden';const OVERLAP_RATIO = 0.25;@@ -78,6 +88,9 @@ export function AvatarGroup({size = 'md','data-testid': testId,'aria-label': ariaLabelFromProps,+ 'aria-describedby': ariaDescribedByFromProps,+ onKeyDown,+ onFocus,xstyle,className,style,@@ -94,14 +107,51 @@ export function AvatarGroup({[size, overlap, numericSize],);+ // The keyboard hint and roving tab stop only make sense once the group has+ // interactive children. Detect their presence (and the writing direction for+ // RTL-correct arrow navigation) from the rendered DOM after commit, matching+ // how the codebase reads direction elsewhere (`getComputedStyle(el).direction`).+ const [hasInteractiveItems, setHasInteractiveItems] = useState(false);+ const [isRtl, setIsRtl] = useState(false);++ // Single tab stop + roving arrow focus over the group's interactive items.+ // `itemSelector` targets the shared `[data-avatar-item]` marker stamped on+ // interactive avatars (their rendered <a>/<button>) and on the overflow+ // button — NOT a tag/role selector — so roving never catches a nested button+ // inside a custom status/badge slot (O5).+ const {listRef, handleKeyDown, handleFocus} = useListFocus<HTMLDivElement>({+ itemSelector: '[data-avatar-item]',+ orientation: 'horizontal',+ hasRovingTabIndex: true,+ isRtl,+ });++ useIsomorphicLayoutEffect(() => {+ const root = listRef.current;+ if (!root) {+ return;+ }+ setHasInteractiveItems(root.querySelector('[data-avatar-item]') != null);+ setIsRtl(getComputedStyle(root).direction === 'rtl');+ });++ const hintId = useId();+ const describedBy =+ [ariaDescribedByFromProps, hasInteractiveItems ? hintId : null]+ .filter(Boolean)+ .join(' ') || undefined;+return (<AvatarGroupContext value={contextValue}><div{...props}- ref={ref}+ ref={mergeRefs(ref, listRef)}role="group"aria-label={ariaLabel}+ aria-describedby={describedBy}data-testid={testId}+ onKeyDown={composeEventHandlers(onKeyDown, handleKeyDown)}+ onFocus={composeEventHandlers(onFocus, handleFocus)}{...mergeProps(themeProps('avatar-group', {size}),stylex.props(styles.root, xstyle),@@ -109,6 +159,11 @@ export function AvatarGroup({style,)}>{children}+ {hasInteractiveItems && (+ <VisuallyHidden id={hintId}>+ {t('@astryx.avatarGroup.keyboardHint')}+ </VisuallyHidden>+ )}</div></AvatarGroupContext>);diff --git a/packages/core/src/AvatarGroup/AvatarGroupOverflow.tsx b/packages/core/src/AvatarGroup/AvatarGroupOverflow.tsxindex aa6cffb7be..920eaf7abe 100644--- a/packages/core/src/AvatarGroup/AvatarGroupOverflow.tsx+++ b/packages/core/src/AvatarGroup/AvatarGroupOverflow.tsx@@ -165,6 +165,7 @@ export function AvatarGroupOverflow({onClick={onClick}{...rest}aria-label={label}+ data-avatar-item=""{...mergeProps(themeProps('avatar-group-overflow'),stylex.props(