Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(Avatar): add tooltip prop (string | boolean) for name-on-hover (#4164) (#4219)

Cindy Zhang79b8f07e5f2f
diff --git a/.changeset/avatar-name-tooltip.md b/.changeset/avatar-name-tooltip.md
new file mode 100644
index 0000000000..33ae787a53
--- /dev/null
+++ b/.changeset/avatar-name-tooltip.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] Avatar: add a `tooltip?: string | boolean` prop for a name-on-hover tooltip. Omitting it (or `true`) shows the avatar's `name` on hover and keyboard focus; a string shows that text instead (no need to wrap in `Tooltip`); `false` disables it. Avatar owns the tooltip via the existing Tooltip hook, so there's no extra wrapper DOM. Because this adds a default tooltip to every existing named Avatar, set `tooltip={false}` when you supply your own `Tooltip`/`HoverCard` overlay. The root `aria-label` (`alt || name`) is unchanged; the default name tooltip is visual-only (no `aria-describedby` double-announce), while a custom string tooltip is exposed as a description. Decorative avatars (no `name`/`alt`) get no tooltip. (#4164)
+@cixzhang
diff --git a/apps/storybook/stories/Avatar.stories.tsx b/apps/storybook/stories/Avatar.stories.tsx
index 18a1a89317..8a55fa34c0 100644
--- a/apps/storybook/stories/Avatar.stories.tsx
+++ b/apps/storybook/stories/Avatar.stories.tsx
@@ -73,6 +73,11 @@ const meta: Meta<typeof Avatar> = {
control: 'text',
description: 'Alt text (falls back to name)',
},
+ tooltip: {
+ control: 'text',
+ description:
+ 'Hover/focus tooltip. Omitted or true shows the name; a string shows that text; false disables it. Set false when wrapping in your own Tooltip/HoverCard.',
+ },
status: {
control: 'boolean',
description: 'Show status indicator dot',
@@ -600,3 +605,80 @@ export const NumericSizes: Story = {
</div>
),
};
+
+/**
+ * By default, hovering (or keyboard-focusing) any named Avatar reveals its
+ * `name` in a tooltip. No configuration required.
+ */
+export const NameTooltip: Story = {
+ render: () => (
+ <div {...stylex.props(styles.storyWrapper)}>
+ <h4 {...stylex.props(styles.heading)}>
+ Default name tooltip (hover or focus each avatar)
+ </h4>
+ <div {...stylex.props(styles.row)}>
+ <Avatar
+ src="https://i.pravatar.cc/150?img=11"
+ name="Ada Lovelace"
+ size="lg"
+ />
+ <Avatar name="Grace Hopper" size="lg" />
+ <Avatar
+ src="https://i.pravatar.cc/150?img=12"
+ name="Katherine Johnson"
+ size="lg"
+ />
+ </div>
+ </div>
+ ),
+};
+
+/**
+ * Pass a string to `tooltip` to show custom text instead of the `name` —
+ * without wrapping the Avatar in a `Tooltip`. Handy when the display name
+ * differs from a short handle, or when you want to add a role/title.
+ */
+export const CustomTooltip: Story = {
+ render: () => (
+ <div {...stylex.props(styles.storyWrapper)}>
+ <h4 {...stylex.props(styles.heading)}>Custom tooltip text</h4>
+ <div {...stylex.props(styles.row)}>
+ <Avatar
+ src="https://i.pravatar.cc/150?img=13"
+ name="alovelace"
+ tooltip="Ada Lovelace — Mathematician"
+ size="lg"
+ />
+ <Avatar
+ name="ghopper"
+ tooltip="Grace Hopper — Rear Admiral"
+ size="lg"
+ />
+ </div>
+ </div>
+ ),
+};
+
+/**
+ * Set `tooltip={false}` to opt out of the built-in name tooltip — for example
+ * when you supply your own richer overlay (a `Tooltip` or `HoverCard`) around
+ * the Avatar and don't want a second popup.
+ */
+export const TooltipDisabled: Story = {
+ render: () => (
+ <div {...stylex.props(styles.storyWrapper)}>
+ <h4 {...stylex.props(styles.heading)}>
+ Tooltip disabled (no popup on hover)
+ </h4>
+ <div {...stylex.props(styles.row)}>
+ <Avatar
+ src="https://i.pravatar.cc/150?img=14"
+ name="Ada Lovelace"
+ tooltip={false}
+ size="lg"
+ />
+ <Avatar name="Grace Hopper" tooltip={false} size="lg" />
+ </div>
+ </div>
+ ),
+};
diff --git a/packages/cli/templates/blocks/components/Avatar/AvatarTooltip.doc.mjs b/packages/cli/templates/blocks/components/Avatar/AvatarTooltip.doc.mjs
new file mode 100644
index 0000000000..de2439945a
--- /dev/null
+++ b/packages/cli/templates/blocks/components/Avatar/AvatarTooltip.doc.mjs
@@ -0,0 +1,14 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('../../../../../core/src/docs-types').TemplateDoc} */
+export const doc = {
+ type: 'block',
+ exampleFor: 'Avatar',
+ name: 'Avatar — Tooltip',
+ displayName: 'Avatar — Tooltip',
+ description:
+ "By default an avatar shows its name in a tooltip on hover and keyboard focus. Pass a string to show custom text instead, or false to turn the tooltip off.",
+ isReady: true,
+ aspectRatio: 16 / 9,
+ componentsUsed: ['Avatar', 'Layout', 'Text'],
+};
diff --git a/packages/cli/templates/blocks/components/Avatar/AvatarTooltip.tsx b/packages/cli/templates/blocks/components/Avatar/AvatarTooltip.tsx
new file mode 100644
index 0000000000..ee0d840343
--- /dev/null
+++ b/packages/cli/templates/blocks/components/Avatar/AvatarTooltip.tsx
@@ -0,0 +1,47 @@
+// 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 AvatarTooltip() {
+ return (
+ <Stack direction="vertical" gap={5}>
+ <Stack direction="vertical" gap={2}>
+ <Text type="supporting" color="secondary">
+ Hover or focus to reveal each name
+ </Text>
+ <Stack direction="horizontal" gap={4} vAlign="center">
+ <Avatar
+ src="https://lookaside.facebook.com/assets/astryx/DATA-Ana-Thomas.png"
+ name="Ana Thomas"
+ size="xl"
+ />
+ <Avatar
+ src="https://lookaside.facebook.com/assets/astryx/DATA-Drew-Young.png"
+ name="Drew Young"
+ size="xl"
+ />
+ <Avatar
+ src="https://lookaside.facebook.com/assets/astryx/DATA-Jihoo-Song.png"
+ name="Jihoo Song"
+ size="xl"
+ />
+ </Stack>
+ </Stack>
+ <Stack direction="vertical" gap={2}>
+ <Text type="supporting" color="secondary">
+ Custom tooltip text
+ </Text>
+ <Avatar
+ src="https://lookaside.facebook.com/assets/astryx/DATA-Itai-Jordaan.png"
+ name="Itai Jordaan"
+ size="xl"
+ tooltip="Itai Jordaan · Engineering Lead"
+ />
+ </Stack>
+ </Stack>
+ );
+}
diff --git a/packages/core/src/Avatar/Avatar.doc.mjs b/packages/core/src/Avatar/Avatar.doc.mjs
index 96ffac0c25..3ea7472b10 100644
--- a/packages/core/src/Avatar/Avatar.doc.mjs
+++ b/packages/core/src/Avatar/Avatar.doc.mjs
@@ -15,6 +15,7 @@ export const docs = {
{guidance: true, description: 'Always pass a name so the avatar can show initials if the photo fails to load, and so screen readers can announce who it represents.'},
{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: 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.'},
],
@@ -74,6 +75,13 @@ export const docs = {
},
],
},
+ {
+ name: 'tooltip',
+ type: 'string | boolean',
+ description:
+ "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',
+ },
],
components: [
{name: 'AvatarStatusDot'},
@@ -115,6 +123,8 @@ 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.",
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.",
},
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.tsx
index aced738291..0b88bf7049 100644
--- a/packages/core/src/Avatar/Avatar.test.tsx
+++ b/packages/core/src/Avatar/Avatar.test.tsx
@@ -1,6 +1,6 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-import {describe, it, expect} from 'vitest';
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
import {render, screen, fireEvent} from '@testing-library/react';
import {Avatar} from './Avatar';
@@ -65,4 +65,159 @@ describe('Avatar', () => {
expect(img).not.toBeNull();
expect(img).toHaveAttribute('src', 'https://example.com/ada.jpg');
});
+
+ // --- Name tooltip (tooltip?: string | boolean) ---
+ describe('name tooltip', () => {
+ const originalShowPopover = HTMLElement.prototype.showPopover;
+ const originalHidePopover = HTMLElement.prototype.hidePopover;
+
+ beforeEach(() => {
+ // jsdom does not implement the Popover API the tooltip layer uses.
+ HTMLElement.prototype.showPopover = vi.fn();
+ HTMLElement.prototype.hidePopover = vi.fn();
+ });
+
+ afterEach(() => {
+ HTMLElement.prototype.showPopover = originalShowPopover;
+ HTMLElement.prototype.hidePopover = originalHidePopover;
+ });
+
+ it('shows the name in a tooltip by default', () => {
+ render(<Avatar name="Ada Lovelace" />);
+ const tooltip = screen.getByRole('tooltip', {hidden: true});
+ expect(tooltip).toHaveTextContent('Ada Lovelace');
+ });
+
+ it('shows a custom string tooltip instead of the name', () => {
+ render(<Avatar name="alovelace" tooltip="Ada Lovelace, Mathematician" />);
+ const tooltip = screen.getByRole('tooltip', {hidden: true});
+ expect(tooltip).toHaveTextContent('Ada Lovelace, Mathematician');
+ expect(tooltip).not.toHaveTextContent('alovelace');
+ });
+
+ it('renders no tooltip when tooltip={false}', () => {
+ render(<Avatar name="Ada Lovelace" tooltip={false} />);
+ expect(screen.queryByRole('tooltip', {hidden: true})).toBeNull();
+ });
+
+ it('renders no tooltip for a decorative avatar (no name/alt)', () => {
+ render(<Avatar src="https://example.com/x.jpg" />);
+ expect(screen.queryByRole('tooltip', {hidden: true})).toBeNull();
+ });
+
+ it('renders no tooltip when tooltip is true/default but name is empty', () => {
+ render(<Avatar name=" " alt="Profile photo" data-testid="a" />);
+ // A whitespace-only name yields nothing to show, and the default tooltip
+ // uses `name` (not `alt`), so there is no tooltip.
+ expect(screen.queryByRole('tooltip', {hidden: true})).toBeNull();
+ // The accessible name still comes from alt, unaffected.
+ expect(
+ screen.getByRole('img', {name: 'Profile photo'}),
+ ).toBeInTheDocument();
+ });
+
+ it('still shows a custom string tooltip when there is no name', () => {
+ render(<Avatar tooltip="Anonymous user" data-testid="a" />);
+ const tooltip = screen.getByRole('tooltip', {hidden: true});
+ expect(tooltip).toHaveTextContent('Anonymous user');
+ });
+
+ it('makes the root focusable while a tooltip is attached', () => {
+ render(<Avatar name="Ada Lovelace" data-testid="a" />);
+ expect(screen.getByTestId('a')).toHaveAttribute('tabindex', '0');
+ });
+
+ it('does not add a tab stop when the tooltip is disabled', () => {
+ render(<Avatar name="Ada Lovelace" tooltip={false} data-testid="a" />);
+ expect(screen.getByTestId('a')).not.toHaveAttribute('tabindex');
+ });
+
+ it('keeps the accessible name on the root regardless of the tooltip', () => {
+ const {rerender} = render(<Avatar name="Ada Lovelace" />);
+ expect(
+ screen.getByRole('img', {name: 'Ada Lovelace'}),
+ ).toBeInTheDocument();
+
+ rerender(<Avatar name="Ada Lovelace" tooltip={false} />);
+ expect(
+ screen.getByRole('img', {name: 'Ada Lovelace'}),
+ ).toBeInTheDocument();
+
+ rerender(<Avatar name="alovelace" tooltip="Ada Lovelace, Eng" />);
+ // alt||name still drives the accessible name — not the custom tooltip.
+ expect(screen.getByRole('img', {name: 'alovelace'})).toBeInTheDocument();
+
+ rerender(<Avatar name="alovelace" alt="Ada's profile photo" />);
+ expect(
+ screen.getByRole('img', {name: "Ada's profile photo"}),
+ ).toBeInTheDocument();
+ });
+
+ it('does not describe the root with the default name tooltip (no double-announce)', () => {
+ render(<Avatar name="Ada Lovelace" data-testid="a" />);
+ // The default name tooltip is visual-only: its text duplicates the root
+ // aria-label, so we deliberately do NOT wire aria-describedby (OQ-4).
+ expect(screen.getByTestId('a')).not.toHaveAttribute('aria-describedby');
+ });
+
+ it('describes the root with a custom string tooltip (matches Button)', () => {
+ render(
+ <Avatar
+ name="alovelace"
+ tooltip="Ada Lovelace, Mathematician"
+ data-testid="a"
+ />,
+ );
+ const root = screen.getByTestId('a');
+ const describedBy = root.getAttribute('aria-describedby');
+ expect(describedBy).toBeTruthy();
+ // aria-describedby points at the rendered tooltip layer.
+ const tooltip = screen.getByRole('tooltip', {hidden: true});
+ expect(tooltip.id).toBeTruthy();
+ expect(describedBy).toContain(tooltip.id);
+ });
+
+ it('composes a consumer aria-describedby with the custom tooltip description', () => {
+ render(
+ <>
+ <span id="extra-desc">extra description</span>
+ <Avatar
+ name="alovelace"
+ tooltip="Ada Lovelace, Eng"
+ aria-describedby="extra-desc"
+ data-testid="a"
+ />
+ </>,
+ );
+ const describedBy = screen
+ .getByTestId('a')
+ .getAttribute('aria-describedby');
+ expect(describedBy).toContain('extra-desc');
+ });
+
+ it('preserves a consumer aria-describedby with the default name tooltip', () => {
+ render(
+ <>
+ <span id="extra-desc">extra description</span>
+ <Avatar
+ name="Ada Lovelace"
+ aria-describedby="extra-desc"
+ data-testid="a"
+ />
+ </>,
+ );
+ // Default name tooltip does not touch aria-describedby, so the consumer
+ // value passes through untouched.
+ expect(screen.getByTestId('a')).toHaveAttribute(
+ 'aria-describedby',
+ 'extra-desc',
+ );
+ });
+
+ it('forwards the consumer ref to the root while a tooltip is attached', () => {
+ const ref = {current: null as HTMLDivElement | null};
+ render(<Avatar name="Ada Lovelace" ref={ref} data-testid="a" />);
+ expect(ref.current).toBe(screen.getByTestId('a'));
+ });
+ });
});
diff --git a/packages/core/src/Avatar/Avatar.tsx b/packages/core/src/Avatar/Avatar.tsx
index 2db1ef9493..3e394c9349 100644
--- a/packages/core/src/Avatar/Avatar.tsx
+++ b/packages/core/src/Avatar/Avatar.tsx
@@ -4,7 +4,8 @@
/**
* @file Avatar.tsx
- * @input Uses React, HTMLAttributes, ReactNode, useState
+ * @input Uses React, HTMLAttributes, ReactNode, useState; useTooltip
+ * (Tooltip hook) for the optional name-on-hover tooltip
* @output Exports Avatar component, AvatarProps, AvatarSize types
* @position Core implementation; consumed by index.ts
*
@@ -26,8 +27,9 @@ import {
} from '../theme/tokens.stylex';
import {AvatarSizeContext} from './AvatarSizeContext';
import {useAvatarGroup} from '../AvatarGroup/AvatarGroupContext';
-import {mergeProps} from '../utils';
+import {mergeProps, mergeRefs} from '../utils';
import {themeProps} from '../utils/themeProps';
+import {useTooltip} from '../Tooltip/useTooltip';
/**
* The offset ratio for positioning elements on a circle's edge at 45°.
@@ -133,6 +135,19 @@ const styles = stylex.create({
status: {
position: 'absolute',
},
+ // Visible focus ring for the name-tooltip tab stop, matching the repo-wide
+ // focus-visible outline treatment (see Timestamp, Token, Thumbnail). Only
+ // applied when a tooltip is active so keyboard users can reveal it.
+ focusable: {
+ outline: {
+ default: null,
+ ':focus-visible': `2px solid ${colorVars['--color-accent']}`,
+ },
+ outlineOffset: {
+ default: '0',
+ ':focus-visible': '2px',
+ },
+ },
});
/**
@@ -216,6 +231,19 @@ export interface AvatarProps extends BaseProps<HTMLDivElement> {
* Typically used for status indicators or badges.
*/
status?: ReactNode;
+ /**
+ * Tooltip shown on hover (and keyboard focus).
+ * - omitted / `true`: show the avatar's `name`
+ * - a string: show that text instead
+ * - `false`: no tooltip
+ *
+ * The avatar owns this tooltip. It is NOT auto-disabled when wrapped in your
+ * own Tooltip/HoverCard — set `tooltip={false}` if you provide your own
+ * overlay. No tooltip is shown if `tooltip` is `true`/omitted and there is
+ * no (non-whitespace) `name`.
+ * @default true
+ */
+ tooltip?: string | boolean;
}
/**
@@ -265,6 +293,8 @@ function DefaultIcon({size}: {size: number}) {
* <Avatar src="/user.jpg" name="John Doe" />
* <Avatar name="Jane Smith" size="xl" />
* <Avatar src="/user.jpg" status={<OnlineIndicator />} />
+ * <Avatar name="jsmith" tooltip="Jane Smith, Staff Engineer" />
+ * <Avatar name="Jane" tooltip={false} />
* ```
*/
export function Avatar({
@@ -275,6 +305,7 @@ export function Avatar({
size = 'md',
src,
status,
+ tooltip = true,
xstyle,
className,
style,
@@ -303,19 +334,66 @@ export function Avatar({
const resolvedSize = avatarGroup?.size ?? size;
const numericSize = useMemo(() => resolveSize(resolvedSize), [resolvedSize]);
- return (
+ // Resolve the tooltip content:
+ // - `false` → no tooltip
+ // - a string → that string
+ // - `true` / omitted → the `name` (a whitespace-only name yields nothing)
+ // Note: the *visible* tooltip prefers `name` (not `alt`); the *accessible
+ // name* on the root still uses `alt || name` above, independent of this.
+ const tooltipContent =
+ tooltip === false
+ ? undefined
+ : typeof tooltip === 'string'
+ ? tooltip
+ : name;
+ const trimmedTooltip = tooltipContent?.trim();
+ const showTooltip = trimmedTooltip != null && trimmedTooltip !== '';
+ // Whether the tooltip text is a consumer-authored override (a custom string)
+ // rather than the default name. A custom description is worth wiring to
+ // `aria-describedby` (it adds information, matching Button); the default name
+ // tooltip is visual-only — its text duplicates the root `aria-label`, so
+ // describing it too would double-announce the same name (OQ-4).
+ const isCustomTooltip = typeof tooltip === 'string';
+
+ // Own the name tooltip via the Tooltip hook (the Button pattern), which
+ // 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).
+ const tooltipHook = useTooltip({
+ placement: 'above',
+ isEnabled: showTooltip,
+ });
+ const rootRef = mergeRefs(ref, showTooltip ? tooltipHook.ref : undefined);
+ const describedByProp =
+ showTooltip && isCustomTooltip
+ ? {
+ 'aria-describedby':
+ [props['aria-describedby'], tooltipHook.describedBy]
+ .filter(Boolean)
+ .join(' ') || undefined,
+ }
+ : null;
+
+ const avatarElement = (
<AvatarSizeContext value={numericSize}>
<div
{...props}
- ref={ref}
+ 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. Only while active.
+ tabIndex={showTooltip ? 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),
@@ -368,6 +446,20 @@ export function Avatar({
</div>
</AvatarSizeContext>
);
+
+ if (!showTooltip) {
+ return avatarElement;
+ }
+
+ // Render the tooltip as a sibling (no wrapper DOM) — the hook's ref is already
+ // attached to the root via `rootRef` above. `trimmedTooltip` is guaranteed
+ // non-empty here.
+ return (
+ <>
+ {avatarElement}
+ {tooltipHook.renderTooltip(trimmedTooltip)}
+ </>
+ );
}
Avatar.displayName = 'Avatar';