An open source design system that's fully customizable and agent ready
TypeScript
feat(lab): InfoTip — accessible info-icon help affordance (RFC #3349) (#3355)
David Petersen02643db26217
diff --git a/packages/lab/src/InfoTip/InfoTip.doc.mjs b/packages/lab/src/InfoTip/InfoTip.doc.mjsnew file mode 100644index 0000000000..318fd5bb6f--- /dev/null+++ b/packages/lab/src/InfoTip/InfoTip.doc.mjs@@ -0,0 +1,97 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('../docs-types').ComponentDoc} */++export const docs = {+ name: 'InfoTip',+ displayName: 'Info Tip',+ category: 'Feedback & Status',+ keywords: ["info","tooltip","help","hint","affordance","icon","label","field","metric","definition"],+ props: [+ {+ name: 'content',+ type: 'ReactNode',+ description: 'Content to display in the tooltip. Typically short, non-interactive text. Mirrors Tooltip’s content prop.',+ required: true,+ },+ {+ name: 'label',+ type: 'string',+ description: 'Accessible name for the trigger button.',+ default: "'More information'",+ },+ {+ name: 'size',+ type: "'xsm' | 'sm' | 'md' | 'lg'",+ description: 'Size of the info icon (12px, 16px, 20px, 24px). Maps 1:1 to Icon sizes.',+ default: "'sm'",+ },+ ],+ usage: {+ description:+ 'An inline info-icon help affordance: a small "i" button that reveals a tooltip on hover and keyboard focus. Use it next to labels, values, and metrics for permission notes, metric definitions, and field help. Its value over hand-composing Icon inside Tooltip is the pre-wired accessible trigger: a real button with an aria-label, Tab-reachable, tooltip on hover AND focus, and Escape dismissal.',+ bestPractices: [+ { guidance: true, description: 'Keep tooltip content concise, plain, and non-interactive; use Popover or HoverCard for links and buttons.' },+ { guidance: true, description: 'Override label when "More information" is too generic, e.g. "About this metric".' },+ { guidance: false, description: 'Hand-compose Icon inside Tooltip for info affordances; the bare Icon is aria-hidden and unfocusable, so keyboard and screen-reader users never see it.' },+ { guidance: false, description: 'Use InfoTip for essential information users must see to complete a task; put that text inline instead.' },+ ],+ },+};++/** @type {import('../docs-types').ComponentDoc} */+export const docsZh = {+ name: 'InfoTip',+ displayName: 'Info Tip',+ props: [+ {+ name: 'content',+ type: 'ReactNode',+ description: '工具提示中显示的内容。通常为简短的非交互文本。与 Tooltip 的 content 属性一致。',+ required: true,+ },+ {+ name: 'label',+ type: 'string',+ description: '触发按钮的无障碍名称。',+ default: "'More information'",+ },+ {+ name: 'size',+ type: "'xsm' | 'sm' | 'md' | 'lg'",+ description: '信息图标的尺寸(12px、16px、20px、24px)。与 Icon 尺寸一一对应。',+ default: "'sm'",+ },+ ],+ usage: {+ description:+ 'An inline info-icon help affordance: a small "i" button that reveals a tooltip on hover and keyboard focus. Use it next to labels, values, and metrics for permission notes, metric definitions, and field help.',+ bestPractices: [+ { guidance: true, description: 'Keep tooltip content concise, plain, and non-interactive; use Popover or HoverCard for links and buttons.' },+ { guidance: true, description: 'Override label when "More information" is too generic, e.g. "About this metric".' },+ { guidance: false, description: 'Hand-compose Icon inside Tooltip for info affordances; the bare Icon is aria-hidden and unfocusable, so keyboard and screen-reader users never see it.' },+ { guidance: false, description: 'Use InfoTip for essential information users must see to complete a task; put that text inline instead.' },+ ],+ },+};++/** @type {import('../docs-types').TranslationDoc} */+export const docsDense = {+ description:+ 'Inline info-icon help affordance: accessible "i" button trigger pre-wired into a Tooltip.',+ usage: {+ description:+ 'A small "i" button that reveals a tooltip on hover and keyboard focus. Use next to labels, values, and metrics for permission notes, metric definitions, and field help. Pre-wired accessible trigger: real button, aria-label, Tab-reachable, tooltip on hover AND focus, Escape dismissal.',+ bestPractices: [+ { guidance: true, description: 'Keep tooltip content concise, plain, and non-interactive; use Popover or HoverCard for links and buttons.' },+ { guidance: true, description: 'Override label when "More information" is too generic, e.g. "About this metric".' },+ { guidance: false, description: 'Hand-compose Icon inside Tooltip for info affordances; the bare Icon is aria-hidden and unfocusable.' },+ { guidance: false, description: 'Use InfoTip for essential information users must see to complete a task; put that text inline instead.' },+ ],+ },+ propDescriptions: {+ content: 'Tooltip content. Short, non-interactive text. Mirrors Tooltip content prop.',+ label: "Accessible name for the trigger button. Default 'More information'.",+ size: 'Info icon size (12/16/20/24px). Maps 1:1 to Icon sizes.',+ },+};diff --git a/packages/lab/src/InfoTip/InfoTip.test.tsx b/packages/lab/src/InfoTip/InfoTip.test.tsxnew file mode 100644index 0000000000..59de8ffceb--- /dev/null+++ b/packages/lab/src/InfoTip/InfoTip.test.tsx@@ -0,0 +1,169 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file InfoTip.test.tsx+ * @input Uses vitest, @testing-library/react, @testing-library/user-event, InfoTip component+ * @output Unit tests for InfoTip trigger accessibility and tooltip behavior+ * @position Testing; validates InfoTip.tsx implementation+ *+ * SYNC: When InfoTip.tsx changes, update tests to match new behavior+ */++import {describe, it, expect, vi, beforeAll, afterAll} from 'vitest';+import {render, screen, fireEvent, waitFor, act} from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import {InfoTip} from './InfoTip';++// Store original matches to restore later+const originalMatches = HTMLElement.prototype.matches;++// Track popover open state per element+const popoverOpenState = new WeakMap<HTMLElement, boolean>();++// Mock Popover API for jsdom, and :focus-visible for keyboard-focus tests+// (same harness as core Tooltip.test.tsx, plus :focus-visible)+beforeAll(() => {+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {+ popoverOpenState.set(this, true);+ });+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {+ popoverOpenState.set(this, false);+ });++ // Intercept :popover-open and :focus-visible, delegate everything else+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ (HTMLElement.prototype as any).matches = function (+ selector: string,+ ): boolean {+ if (selector === ':popover-open') {+ return popoverOpenState.get(this) ?? false;+ }+ if (selector === ':focus-visible') {+ // Treat any focused element as keyboard-focused in tests+ return this === document.activeElement;+ }+ return originalMatches.call(this, selector);+ };+});++afterAll(() => {+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ (HTMLElement.prototype as any).matches = originalMatches;+});++/** Focus the trigger the way a keyboard user would land on it. */+function focusTrigger(trigger: HTMLElement) {+ act(() => {+ trigger.focus();+ });+ fireEvent.focusIn(trigger);+}++describe('InfoTip', () => {+ it('renders a button trigger with the default accessible name', () => {+ render(<InfoTip content="Helpful context" />);+ expect(+ screen.getByRole('button', {name: 'More information'}),+ ).toBeInTheDocument();+ });++ it('uses a custom label as the accessible name', () => {+ render(+ <InfoTip content="30-day rolling average." label="About this metric" />,+ );+ const trigger = screen.getByRole('button', {name: 'About this metric'});+ expect(trigger).toHaveAttribute('aria-label', 'About this metric');+ });++ it('links the trigger to the tooltip layer via aria-describedby', () => {+ render(<InfoTip content="Helpful context" />);+ const layer = screen.getByRole('tooltip', {hidden: true});+ expect(layer).toHaveTextContent('Helpful context');+ const trigger = screen.getByRole('button', {name: 'More information'});+ expect(trigger.getAttribute('aria-describedby')).toBe(layer.id);+ });++ it('is reachable with Tab', async () => {+ const user = userEvent.setup();+ render(<InfoTip content="Helpful context" />);+ const trigger = screen.getByRole('button', {name: 'More information'});+ await user.tab();+ expect(trigger).toHaveFocus();+ });++ it('shows the tooltip on hover', async () => {+ vi.mocked(HTMLElement.prototype.showPopover).mockClear();+ render(<InfoTip content="Helpful context" />);+ const trigger = screen.getByRole('button', {name: 'More information'});++ fireEvent.mouseEnter(trigger);++ await waitFor(() => {+ expect(HTMLElement.prototype.showPopover).toHaveBeenCalled();+ });+ });++ it('shows the tooltip on keyboard focus', async () => {+ vi.mocked(HTMLElement.prototype.showPopover).mockClear();+ render(<InfoTip content="Helpful context" />);+ const trigger = screen.getByRole('button', {name: 'More information'});++ focusTrigger(trigger);++ await waitFor(() => {+ expect(HTMLElement.prototype.showPopover).toHaveBeenCalled();+ });+ const layer = screen.getByRole('tooltip', {hidden: true});+ expect(popoverOpenState.get(layer)).toBe(true);+ });++ it('closes the tooltip on Escape', async () => {+ render(<InfoTip content="Helpful context" />);+ const trigger = screen.getByRole('button', {name: 'More information'});+ const layer = screen.getByRole('tooltip', {hidden: true});++ focusTrigger(trigger);+ await waitFor(() => {+ expect(popoverOpenState.get(layer)).toBe(true);+ });++ fireEvent.keyDown(trigger, {key: 'Escape'});++ await waitFor(() => {+ expect(popoverOpenState.get(layer)).toBe(false);+ });+ });++ it('re-opens after Escape once the trigger is left and re-hovered', async () => {+ render(<InfoTip content="Helpful context" />);+ const trigger = screen.getByRole('button', {name: 'More information'});+ const layer = screen.getByRole('tooltip', {hidden: true});++ focusTrigger(trigger);+ await waitFor(() => {+ expect(popoverOpenState.get(layer)).toBe(true);+ });++ fireEvent.keyDown(trigger, {key: 'Escape'});+ await waitFor(() => {+ expect(popoverOpenState.get(layer)).toBe(false);+ });++ // Leave (resets dismissal), then re-enter+ act(() => {+ trigger.blur();+ });+ fireEvent.focusOut(trigger);+ fireEvent.mouseLeave(trigger);++ fireEvent.mouseEnter(trigger);+ await waitFor(() => {+ expect(popoverOpenState.get(layer)).toBe(true);+ });+ });++ it('renders ReactNode tooltip content', () => {+ render(<InfoTip content={<span data-testid="rich-content">Rich</span>} />);+ expect(screen.getByTestId('rich-content')).toBeInTheDocument();+ });+});diff --git a/packages/lab/src/InfoTip/InfoTip.tsx b/packages/lab/src/InfoTip/InfoTip.tsxnew file mode 100644index 0000000000..b208041807--- /dev/null+++ b/packages/lab/src/InfoTip/InfoTip.tsx@@ -0,0 +1,155 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file InfoTip.tsx+ * @input Uses React, stylex, Tooltip + Icon from @astryxdesign/core, color/spacing/radius/duration/ease tokens+ * @output Exports InfoTip component, InfoTipProps, InfoTipSize types+ * @position Lab experiment (RFC facebook/astryx#3349); core implementation consumed by index.ts+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/lab/src/InfoTip/InfoTip.doc.mjs (props table, features)+ * - /packages/lab/src/InfoTip/InfoTip.test.tsx (tests for new/changed behavior)+ * - /packages/lab/src/InfoTip/index.ts (exports if types change)+ */++import {useCallback, useRef, useState, type ReactNode} from 'react';+import * as stylex from '@stylexjs/stylex';++import {Icon, type IconSize} from '@astryxdesign/core/Icon';+import {Tooltip} from '@astryxdesign/core/Tooltip';+import {+ colorVars,+ durationVars,+ easeVars,+ radiusVars,+ spacingVars,+} from '@astryxdesign/core/theme/tokens.stylex';++/**+ * Size of the info icon. Maps 1:1 to Icon sizes+ * (xsm: 12px, sm: 16px, md: 20px, lg: 24px).+ */+export type InfoTipSize = IconSize;++export interface InfoTipProps {+ /**+ * Content to display in the tooltip.+ * Typically short, non-interactive text. Mirrors Tooltip's `content` prop.+ */+ content: ReactNode;+ /**+ * Accessible name for the trigger button.+ * @default 'More information'+ */+ label?: string;+ /**+ * Size of the info icon.+ * @default 'sm'+ */+ size?: InfoTipSize;+}++const styles = stylex.create({+ trigger: {+ display: 'inline-flex',+ alignItems: 'center',+ justifyContent: 'center',+ verticalAlign: 'middle',+ padding: spacingVars['--spacing-0-5'],+ margin: 0,+ borderStyle: 'none',+ backgroundColor: 'transparent',+ borderRadius: radiusVars['--radius-full'],+ cursor: 'pointer',+ color: {+ default: colorVars['--color-icon-secondary'],+ ':hover': {+ default: null,+ '@media (hover: hover)': colorVars['--color-icon-primary'],+ },+ },+ outline: {+ default: null,+ ':focus-visible': `2px solid ${colorVars['--color-accent']}`,+ },+ outlineOffset: {+ default: '0',+ ':focus-visible': '2px',+ },+ transitionProperty: 'color',+ transitionDuration: durationVars['--duration-fast'],+ transitionTimingFunction: easeVars['--ease-standard'],+ },+});++/**+ * An inline info-icon help affordance: a small "i" button that reveals a+ * tooltip on hover and keyboard focus. Use it next to labels, values, and+ * metrics for permission notes, metric definitions, and field help.+ *+ * The value over hand-composing Icon inside Tooltip is the pre-wired+ * accessible trigger: a real button with an aria-label, Tab-reachable,+ * tooltip on hover AND focus, and Escape dismissal.+ *+ * Composed entirely from core primitives (Tooltip + Icon); the info icon+ * resolves from the global icon registry, so themes can override it.+ *+ * @example+ * ```+ * <InfoTip content="Editors can change this field; viewers cannot." />+ * <InfoTip content="30-day rolling average." label="About this metric" />+ * ```+ */+export function InfoTip({+ content,+ label = 'More information',+ size = 'sm',+}: InfoTipProps): ReactNode {+ // Escape dismissal: `true` force-hides the tooltip (Tooltip isOpen={false});+ // `false` returns control to Tooltip's own hover/focus triggers (isOpen+ // undefined). Reset when the pointer or focus leaves the trigger so the+ // tooltip can re-open on the next hover/focus.+ const [isDismissed, setIsDismissed] = useState(false);+ const isOpenRef = useRef(false);++ const handleOpenChange = useCallback((isOpen: boolean) => {+ isOpenRef.current = isOpen;+ }, []);++ const handleKeyDown = useCallback(+ (event: React.KeyboardEvent<HTMLButtonElement>) => {+ if (event.key === 'Escape' && isOpenRef.current) {+ // Only swallow Escape when it actually dismissed the tooltip, so an+ // enclosing dialog still closes on the next press.+ event.stopPropagation();+ setIsDismissed(true);+ }+ },+ [],+ );++ const handleReset = useCallback(() => {+ setIsDismissed(false);+ }, []);++ return (+ <Tooltip+ content={content}+ isOpen={isDismissed ? false : undefined}+ onOpenChange={handleOpenChange}>+ <button+ type="button"+ aria-label={label}+ onKeyDown={handleKeyDown}+ onBlur={handleReset}+ onMouseLeave={handleReset}+ {...stylex.props(styles.trigger)}>+ <Icon icon="info" size={size} />+ </button>+ </Tooltip>+ );+}++InfoTip.displayName = 'InfoTip';diff --git a/packages/lab/src/InfoTip/index.ts b/packages/lab/src/InfoTip/index.tsnew file mode 100644index 0000000000..7aa409a085--- /dev/null+++ b/packages/lab/src/InfoTip/index.ts@@ -0,0 +1,10 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file InfoTip component barrel export+ */++export {InfoTip} from './InfoTip';+export type {InfoTipProps, InfoTipSize} from './InfoTip';diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.tsindex ae28fd91d5..9e1650ee78 100644--- a/packages/lab/src/index.ts+++ b/packages/lab/src/index.ts@@ -22,6 +22,9 @@ export {type SyntaxToken,} from '@astryxdesign/core/CodeBlock';+// InfoTip — accessible info-icon help affordance (RFC facebook/astryx#3349)+export {InfoTip, type InfoTipProps, type InfoTipSize} from './InfoTip';+// Chat — experimental reasoning displayexport {ChatReasoning,