An open source design system that's fully customizable and agent ready
TypeScript
fix(ChatMessageList, Tooltip, HoverCard): the chat log and text trigger spans draw the shared focus ring (#8876)
Cindy Zhang0d436a195193
diff --git a/.changeset/log-trigger-focus-ring.md b/.changeset/log-trigger-focus-ring.mdnew file mode 100644index 0000000000..4691ea3865--- /dev/null+++ b/.changeset/log-trigger-focus-ring.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] `ChatMessageList`, `Tooltip` and `HoverCard`: the chat log and the span that `Tooltip` and `HoverCard` wrap around text-only children draw the theme's focus ring instead of the browser's default. A theme's `--focus-outline-*` tokens now reach them. The chat log's ring sits inside its box, so the area that scrolls it no longer cuts it off.++@cixzhangdiff --git a/apps/storybook/stories/FocusRingTextTriggersA11y.stories.tsx b/apps/storybook/stories/FocusRingTextTriggersA11y.stories.tsxnew file mode 100644index 0000000000..d86c38b224--- /dev/null+++ b/apps/storybook/stories/FocusRingTextTriggersA11y.stories.tsx@@ -0,0 +1,43 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file FocusRingTextTriggersA11y.stories.tsx+ * @input ChatMessageList inside a clipping scroll area, and text-only Tooltip+ * and HoverCard triggers+ * @output Fixtures for the Chromium focus-ring check of the tab stops Astryx+ * adds; excluded from the visual matrix+ * @position Browser fixtures for the shared focus ring on the chat log and+ * the text trigger spans+ */++import type {Meta, StoryObj} from '@storybook/react';+import {ChatMessageList, ChatMessageBubble} from '@astryxdesign/core/Chat';+import {Tooltip} from '@astryxdesign/core/Tooltip';+import {HoverCard} from '@astryxdesign/core/HoverCard';++const meta = {+ title: 'A11y/FocusRingTextTriggers',+ tags: ['no-visual'],+ parameters: {layout: 'padded'},+} satisfies Meta;++export default meta;+type Story = StoryObj<typeof meta>;++export const TabStops: Story = {+ render: () => (+ <div style={{display: 'grid', gap: 24, maxWidth: 480}}>+ <div+ data-testid="log-scroller"+ style={{height: 160, overflow: 'auto', display: 'flex'}}>+ <ChatMessageList>+ <ChatMessageBubble>The issue is resolved.</ChatMessageBubble>+ </ChatMessageList>+ </div>+ <p>+ Saved by <Tooltip content="Signed in as Rowan">Rowan</Tooltip> and{' '}+ <HoverCard content={<p>Reviewer since 2024</p>}>Kai</HoverCard>.+ </p>+ </div>+ ),+};diff --git a/packages/core/src/Chat/ChatMessageList.focusRing.test.tsx b/packages/core/src/Chat/ChatMessageList.focusRing.test.tsxnew file mode 100644index 0000000000..df422fc107--- /dev/null+++ b/packages/core/src/Chat/ChatMessageList.focusRing.test.tsx@@ -0,0 +1,73 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file ChatMessageList.focusRing.test.tsx+ * @input Uses ChatMessageList, Tooltip, HoverCard, focusOutlineStyles+ * @output Tests that the chat log and the text-only Tooltip and HoverCard+ * trigger spans draw the shared focus ring+ * @position Colocated test; the ring's geometry is checked in a real browser+ *+ * jsdom does not match `:focus-visible`, so these pin the composition: each+ * tab stop carries the atomic classes the ring compiles to.+ */++import {describe, it, expect} from 'vitest';+import {render, screen} from '@testing-library/react';+import * as stylex from '@stylexjs/stylex';+import {focusOutlineStyles} from '../utils/focusOutline.stylex';+import {focusVars} from '../theme/tokens.stylex';+import {ChatMessageList} from './ChatMessageList';+import {Tooltip} from '../Tooltip';+import {HoverCard} from '../HoverCard';++const inset = stylex.create({+ ring: {+ outlineOffset: {+ default: null,+ ':focus-visible': `calc(-1 * ${focusVars['--focus-outline-width']})`,+ },+ },+});++// Debug class names name their source file; only the atoms matter.+const atoms = (className: string | undefined) =>+ (className ?? '').split(' ').filter(c => c !== '' && !c.includes('__'));++function expectAtoms(el: Element, expected: string[]) {+ const classes = el.className.split(' ');+ for (const c of expected) {+ expect(classes).toContain(c);+ }+}++describe('Astryx-made tab stops draw the shared focus ring', () => {+ it('the chat log, inset inside the area that scrolls it', () => {+ render(+ <ChatMessageList>+ <p>Hello</p>+ </ChatMessageList>,+ );+ expectAtoms(+ screen.getByRole('log'),+ atoms(+ stylex.props(focusOutlineStyles.focusVisible, inset.ring).className,+ ),+ );+ });++ it('the text-only Tooltip trigger', () => {+ render(<Tooltip content="More about it">plain text</Tooltip>);+ expectAtoms(+ screen.getByText('plain text'),+ atoms(stylex.props(focusOutlineStyles.focusVisible).className),+ );+ });++ it('the text-only HoverCard trigger', () => {+ render(<HoverCard content={<p>Card</p>}>plain text</HoverCard>);+ expectAtoms(+ screen.getByText('plain text'),+ atoms(stylex.props(focusOutlineStyles.focusVisible).className),+ );+ });+});diff --git a/packages/core/src/Chat/ChatMessageList.tsx b/packages/core/src/Chat/ChatMessageList.tsxindex a13a3b82a3..bdfb265682 100644--- a/packages/core/src/Chat/ChatMessageList.tsx+++ b/packages/core/src/Chat/ChatMessageList.tsx@@ -26,7 +26,8 @@import {type ReactNode, useEffect, useMemo, useRef, useTransition} from 'react';import * as stylex from '@stylexjs/stylex';-import {spacingVars} from '../theme/tokens.stylex';+import {focusVars, spacingVars} from '../theme/tokens.stylex';+import {focusOutlineStyles} from '../utils/focusOutline.stylex';import {ChatListContext,type ChatDensity,@@ -127,6 +128,14 @@ const styles = stylex.create({flex: 1,minHeight: 0,},+ // The log fills the area that scrolls it, which clips at its edges, so its+ // keyboard ring sits inside its own box instead of around it.+ focusRingInset: {+ outlineOffset: {+ default: null,+ ':focus-visible': `calc(-1 * ${focusVars['--focus-outline-width']})`,+ },+ },inner: {display: 'flex',flexDirection: 'column',@@ -310,7 +319,14 @@ export function ChatMessageList({data-testid={testId}{...mergeProps(themeProps('chat-message-list', {density}),- stylex.props(styles.root, xstyle),+ // A tab stop: the shared ring, which a theme restyles through the+ // focus-outline tokens.+ stylex.props(+ styles.root,+ focusOutlineStyles.focusVisible,+ styles.focusRingInset,+ xstyle,+ ),className,style,)}>diff --git a/packages/core/src/Chat/__tests__/FocusRingTextTriggers.a11y.chromium.spec.ts b/packages/core/src/Chat/__tests__/FocusRingTextTriggers.a11y.chromium.spec.tsnew file mode 100644index 0000000000..a499dfe2c1--- /dev/null+++ b/packages/core/src/Chat/__tests__/FocusRingTextTriggers.a11y.chromium.spec.ts@@ -0,0 +1,173 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// @pr-a11y scope core/Chat core/Tooltip core/HoverCard ^packages/core/src/utils/focusOutline ^apps/storybook/stories/FocusRingTextTriggers++/**+ * @file FocusRingTextTriggers.a11y.chromium.spec.ts+ * @input The built A11y/FocusRingTextTriggers story; real Chromium keyboard+ * focus and computed styles+ * @output Browser evidence that the chat log and the text-only Tooltip and+ * HoverCard trigger spans draw the shared token ring under :focus-visible,+ * that a theme's focus tokens restyle all three, and that the log's ring+ * stays inside the area that scrolls it+ * @position Chromium proof for the focus ring on tab stops Astryx adds. jsdom+ * does not match :focus-visible, so ChatMessageList.focusRing.test.tsx can+ * only check the composed classes.+ */++import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright';+import {holdMotionStill} from '@astryxdesign/a11y-spec/chromium';+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();+});++test.use({viewport: {width: 1024, height: 768}});++// Tab order in the story: the log, then the Tooltip span, then the HoverCard+// span.+const STOPS = ['log', 'tooltip', 'hovercard'] as const;++interface Ring {+ focusVisible: boolean;+ width: string;+ style: string;+ color: string;+ offset: string;+ tokenWidth: string;+ tokenColor: string;+}++/** The focused element's ring, and the ring the focus tokens resolve to. */+async function focusedRing(page: Page): Promise<Ring> {+ return page.evaluate(() => {+ const el = document.activeElement as HTMLElement;+ const style = getComputedStyle(el);+ // Resolve the tokens to computed values with a probe in the same scope.+ const probe = document.createElement('span');+ probe.style.outlineStyle = 'solid';+ probe.style.outlineWidth = 'var(--focus-outline-width)';+ probe.style.outlineColor = 'var(--focus-outline-color)';+ (el.parentElement ?? document.body).appendChild(probe);+ const resolved = getComputedStyle(probe);+ const ring = {+ focusVisible: el.matches(':focus-visible'),+ width: style.outlineWidth,+ style: style.outlineStyle,+ color: style.outlineColor,+ offset: style.outlineOffset,+ tokenWidth: resolved.outlineWidth,+ tokenColor: resolved.outlineColor,+ };+ probe.remove();+ return ring;+ });+}++async function tabThroughStops(page: Page): Promise<Ring[]> {+ const rings: Ring[] = [];+ for (const stop of STOPS) {+ await page.keyboard.press('Tab');+ const role = await page.evaluate(+ () => document.activeElement?.getAttribute('role') ?? null,+ );+ if (stop === 'log') {+ expect(role).toBe('log');+ }+ rings.push(await focusedRing(page));+ }+ return rings;+}++async function open(page: Page) {+ await page.goto(+ `${storybook.origin}/iframe.html?id=a11y-focusringtexttriggers--tab-stops&viewMode=story`,+ );+ await holdMotionStill(page);+ await expect(page.getByRole('log')).toBeVisible();+}++test('each tab stop draws the token ring under keyboard focus', async ({+ page,+}) => {+ await open(page);+ const rings = await tabThroughStops(page);+ rings.forEach((ring, index) => {+ const stop = STOPS[index];+ expect(ring.focusVisible, stop).toBe(true);+ expect(ring.style, stop).toBe('solid');+ expect(ring.width, stop).toBe(ring.tokenWidth);+ expect(ring.color, stop).toBe(ring.tokenColor);+ });+});++test("a theme's focus tokens restyle all three rings", async ({page}) => {+ await open(page);+ await page.evaluate(() => {+ document.documentElement.style.setProperty(+ '--focus-outline-color',+ 'rgb(255, 0, 255)',+ );+ document.documentElement.style.setProperty('--focus-outline-width', '4px');+ });+ const rings = await tabThroughStops(page);+ rings.forEach((ring, index) => {+ const stop = STOPS[index];+ expect(ring.color, stop).toBe('rgb(255, 0, 255)');+ expect(ring.width, stop).toBe('4px');+ });+});++test("the log's ring stays inside the area that scrolls it", async ({page}) => {+ await open(page);+ await page.keyboard.press('Tab');+ const geometry = await page.evaluate(() => {+ const log = document.activeElement as HTMLElement;+ const scroller = document.querySelector<HTMLElement>(+ '[data-testid="log-scroller"]',+ );+ if (scroller == null) {+ throw new Error('the story has no log scroller');+ }+ const style = getComputedStyle(log);+ // An outline extends past the border box by offset + width on each side.+ const extent =+ parseFloat(style.outlineOffset) + parseFloat(style.outlineWidth);+ const box = log.getBoundingClientRect();+ const clip = scroller.getBoundingClientRect();+ return {+ role: log.getAttribute('role'),+ focusVisible: log.matches(':focus-visible'),+ extent,+ ring: {+ left: box.left - extent,+ top: box.top - extent,+ right: box.right + extent,+ bottom: box.bottom + extent,+ },+ clip: {+ left: clip.left,+ top: clip.top,+ right: clip.left + scroller.clientWidth,+ bottom: clip.top + scroller.clientHeight,+ },+ };+ });+ expect(geometry.role).toBe('log');+ expect(geometry.focusVisible).toBe(true);+ expect(geometry.extent).toBeLessThanOrEqual(0);+ expect(geometry.ring.left).toBeGreaterThanOrEqual(geometry.clip.left - 0.5);+ expect(geometry.ring.top).toBeGreaterThanOrEqual(geometry.clip.top - 0.5);+ expect(geometry.ring.right).toBeLessThanOrEqual(geometry.clip.right + 0.5);+ expect(geometry.ring.bottom).toBeLessThanOrEqual(geometry.clip.bottom + 0.5);+});diff --git a/packages/core/src/HoverCard/HoverCard.tsx b/packages/core/src/HoverCard/HoverCard.tsxindex 82565dc56e..c020f36950 100644--- a/packages/core/src/HoverCard/HoverCard.tsx+++ b/packages/core/src/HoverCard/HoverCard.tsx@@ -27,6 +27,7 @@ import {isRenderable} from '../utils/isRenderable';import {observeMutations} from '../utils/sharedMutationObserver';import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';import * as stylex from '@stylexjs/stylex';+import {focusOutlineProps} from '../utils/focusOutline.stylex';import {useHoverCard,type HoverCardFocusTrigger,@@ -483,7 +484,9 @@ export function HoverCard({// No aria-expanded: this wrapper is a role-less <span>, and// aria-expanded is invalid on it (see EXPANDABLE_ROLES above).aria-describedby={label ? undefined : hoverCard.describedBy}- {...stylex.props(+ // The span is a tab stop Astryx adds: it draws the shared ring,+ // which a theme restyles through the focus-outline tokens.+ {...focusOutlineProps.focusVisible(styles.wrapperInline,showHoverIndication && styles.hoverIndication,)}>diff --git a/packages/core/src/Tooltip/Tooltip.tsx b/packages/core/src/Tooltip/Tooltip.tsxindex 373286dc0a..768c2f26e9 100644--- a/packages/core/src/Tooltip/Tooltip.tsx+++ b/packages/core/src/Tooltip/Tooltip.tsx@@ -22,6 +22,7 @@ import React, {} from 'react';import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';import * as stylex from '@stylexjs/stylex';+import {focusOutlineProps} from '../utils/focusOutline.stylex';import {useTooltip,type TooltipFocusTrigger,@@ -341,7 +342,9 @@ export function Tooltip({ref={tooltip.ref}tabIndex={0}aria-describedby={tooltip.describedBy}- {...stylex.props(+ // The span is a tab stop Astryx adds: it draws the shared ring,+ // which a theme restyles through the focus-outline tokens.+ {...focusOutlineProps.focusVisible(styles.wrapperInline,showHoverIndication && styles.hoverIndication,)}>