An open source design system that's fully customizable and agent ready
TypeScript
fix(chat): show composer focus ring for keyboard (#5648)
rubyycheung4f39c7ec9c45
diff --git a/.changeset/chat-composer-keyboard-focus.md b/.changeset/chat-composer-keyboard-focus.mdnew file mode 100644index 0000000000..7296ac0c6d--- /dev/null+++ b/.changeset/chat-composer-keyboard-focus.md@@ -0,0 +1,9 @@+---+'@astryxdesign/core': patch+---++[fix] ChatComposer: add a keyboard-only focus ring around the composer body when its editor receives focus++The ring uses the shared theme focus tokens and does not appear for pointer focus or when an internal action button owns focus.++@rubyycheungdiff --git a/.github/scripts/rtl-audit-coverage.test.mjs b/.github/scripts/rtl-audit-coverage.test.mjsindex f73e48846d..dffdd37c36 100644--- a/.github/scripts/rtl-audit-coverage.test.mjs+++ b/.github/scripts/rtl-audit-coverage.test.mjs@@ -7,6 +7,7 @@import {JSDOM} from 'jsdom';import {describe, expect, it} from 'vitest';import {+ buildAuditedComponentRoster,buildComponentCoverage,classifyDirectionalDecorationPair,collectDirectionalDecorations,@@ -183,3 +184,25 @@ describe('buildComponentCoverage', () => {expect(coverage.gaps).toBe(2);});});++describe('buildAuditedComponentRoster', () => {+ it('uses an umbrella Storybook surface without adding an unknown duplicate', () => {+ expect(+ buildAuditedComponentRoster({+ sourceComponents: ['core/ChatComposer', 'core/ChatMessage'],+ storyComponents: ['core/chat', 'core/chatcomposer'],+ filters: ['chat'],+ }),+ ).toEqual(['core/chat']);+ });++ it('retains an unknown entry when neither source nor stories match', () => {+ expect(+ buildAuditedComponentRoster({+ sourceComponents: ['core/Button'],+ storyComponents: ['core/button'],+ filters: ['missing'],+ }),+ ).toEqual(['unknown/missing']);+ });+});diff --git a/apps/storybook/rtl-audit/rtl-audit-coverage.mjs b/apps/storybook/rtl-audit/rtl-audit-coverage.mjsindex 0ed0546a4d..c4ac167c23 100644--- a/apps/storybook/rtl-audit/rtl-audit-coverage.mjs+++ b/apps/storybook/rtl-audit/rtl-audit-coverage.mjs@@ -260,6 +260,48 @@ function resultIsApplicable(result) {return result?.verdict === 'pass' || result?.verdict === 'fail';}+function componentName(component) {+ return component.split('/').at(-1)?.toLowerCase() ?? component.toLowerCase();+}++/**+ * Build the component roster for a scoped audit.+ *+ * Storybook can expose an umbrella story whose name matches the PR analyzer's+ * module name even when no source component has that exact name. Chat is the+ * canonical example: the source directory contains ChatComposer, ChatMessage,+ * and related components, while Storybook also has a `Core/Chat` surface. A+ * matching story must satisfy the filter so the roster does not invent a+ * second `unknown/chat` coverage entry for the same surface.+ */+export function buildAuditedComponentRoster({+ sourceComponents = [],+ storyComponents = [],+ filters = [],+}) {+ const normalizedFilters = filters.map(filter => filter.toLowerCase());+ const knownComponents = [...sourceComponents, ...storyComponents];+ const unmatchedFilters = normalizedFilters+ .filter(+ filter =>+ !knownComponents.some(component => componentName(component) === filter),+ )+ .map(filter => `unknown/${filter}`);++ return Array.from(+ new Map(+ [...knownComponents, ...unmatchedFilters].map(component => [+ component.toLowerCase(),+ component,+ ]),+ ).values(),+ ).filter(+ component =>+ normalizedFilters.length === 0 ||+ normalizedFilters.includes(componentName(component)),+ );+}+/*** Classify every component in the audited roster. An unexplained all-N/A result* is a coverage gap; a verified-N/A declaration is stale if a detector laterdiff --git a/apps/storybook/rtl-audit/rtl-audit.mjs b/apps/storybook/rtl-audit/rtl-audit.mjsindex 4e4a4a78aa..6ffd662077 100644--- a/apps/storybook/rtl-audit/rtl-audit.mjs+++ b/apps/storybook/rtl-audit/rtl-audit.mjs@@ -48,6 +48,7 @@ import path from 'node:path';import {fileURLToPath} from 'node:url';import {discoverComponents} from '../../../packages/cli/foundation/discovery/component-discovery.mjs';import {+ buildAuditedComponentRoster,buildComponentCoverage,collectDirectionalDecorations,evaluateDirectionalDecorations,@@ -131,8 +132,14 @@ const storyUrl = (port, id, rtl) =>async function settle(page) {// Wait for the story to render (load event + fonts), but do NOT block on// `networkidle` — some stories keep long-lived connections open and would- // stall the whole run. A short fixed settle is enough for RTL to apply.+ // stall the whole run. Wait for Storybook to mount the story root, then use+ // a short fixed settle for fonts, direction globals, and layout to apply.await page.waitForLoadState('load').catch(() => {});+ await page+ .locator('#storybook-root > *')+ .first()+ .waitFor({state: 'attached', timeout: 10000})+ .catch(() => {});await page.evaluate(() => document.fonts?.ready).catch(() => {});await page.addStyleTag({@@ -201,6 +208,7 @@ async function revealInteractionGated(page) {async function boxOf(page, sel, nth = 0) {const loc = page.locator(sel).nth(nth);+ await loc.waitFor({state: 'visible', timeout: 2500}).catch(() => {});if ((await loc.count()) === 0) return null;const b = await loc.first().boundingBox().catch(() => null);return b ? {cx: b.x + b.width / 2, cy: b.y + b.height / 2, ...b} : null;@@ -790,17 +798,11 @@ async function mapPool(items, pages, fn) {console.error(`WARN: cannot discover ${packageName} component roster: ${String(error).slice(0, 120)}`);}}- const unmatchedFilters = FILTER.filter(- filter =>- !sourceComponents.some(- component => component.split('/').at(-1)?.toLowerCase() === filter,- ),- ).map(filter => `unknown/${filter}`);- const auditedComponents = Array.from(- new Map(- [...sourceComponents, ...storyIds.map(componentFromId), ...unmatchedFilters].map(component => [component.toLowerCase(), component]),- ).values(),- ).filter(matchesFilter);+ const auditedComponents = buildAuditedComponentRoster({+ sourceComponents,+ storyComponents: storyIds.map(componentFromId),+ filters: FILTER,+ });// ---- (A) auto-discovery over every audited-package story ----const autoResults = []; // D1 icon-mirrordiff --git a/apps/storybook/rtl-audit/targets.json b/apps/storybook/rtl-audit/targets.jsonindex 9052f011a6..ed930885e7 100644--- a/apps/storybook/rtl-audit/targets.json+++ b/apps/storybook/rtl-audit/targets.json@@ -65,6 +65,17 @@"nextButton": "button[aria-label=\"Scroll right\"]"}},+ {+ "component": "Chat",+ "storyId": "core-chat--mixed-content",+ "dims": [+ "D2"+ ],+ "selectors": {+ "prev": ".astryx-chat-message-bubble[data-sender=\"assistant\"]",+ "next": ".astryx-chat-message-bubble[data-sender=\"user\"]"+ }+ },{"component": "Lightbox","storyId": "core-lightbox--gallery",diff --git a/packages/core/src/Chat/ChatComposer.doc.mjs b/packages/core/src/Chat/ChatComposer.doc.mjsindex fa43ee742b..7d5d765c2e 100644--- a/packages/core/src/Chat/ChatComposer.doc.mjs+++ b/packages/core/src/Chat/ChatComposer.doc.mjs@@ -6,7 +6,8 @@ export const docs = {name: 'ChatComposer',subComponentOf: 'Chat',displayName: 'Chat Composer',- description: 'Layout shell for a chat composer. Arranges named slots (drawer, header, input, footer, send) with page-radius container, hover/focus shadows, and concentric inner radius for child elements.',+ description:+ 'Layout shell for a chat composer. Arranges named slots (drawer, header, input, footer, send) with page-radius container, elevation, a keyboard-only editor focus ring, and concentric inner radius for child elements.',playground: {wrapper: {component: 'Stack', props: {width: 480}},},@@ -60,7 +61,7 @@ export const docs = {name: 'elevation',type: "'none' | 'low'",description:- "Resting elevation of the composer body. `low` (the default) keeps today's raised look: low at rest, bumping to med on hover / focus. `none` flattens it and draws a border with the same rest / hover / focus treatment as a text input (emphasized border → accent on focus, matching inset rings).",+ "Resting elevation of the composer body. `low` (the default) keeps today's raised look: low at rest, bumping to med on hover / focus. `none` flattens it and draws a border. Keyboard focus in the editor adds the shared focus ring in either presentation; pointer focus does not add that ring.",default: "'low'",},{@@ -192,7 +193,8 @@ export const docsZh = {placeholder: '输入为空时显示的占位文本。',isDisabled: '禁用编写器。',density: '视觉密度。',- elevation: "编写器主体的静止高度。low(默认)保持当前的抬起外观——静止时 low,悬停/聚焦时升至 med。none 则扁平化。",+ elevation:+ '编写器主体的静止高度。low(默认)保持当前的抬起外观——静止时 low,悬停/聚焦时升至 med。none 会将其扁平化并绘制边框。编辑器通过键盘获得焦点时,两种呈现方式都会显示共享焦点环;指针聚焦不会显示该焦点环。',drawer: '插槽:输入上方的可折叠抽屉——附件、上下文标签等。使用 ChatComposerDrawer。',headerActions: '插槽:标题左侧操作按钮(附件、提及按钮)。使用仅图标 size="sm" 按钮。',headerContext: '插槽:标题右侧上下文信息(上下文窗口使用情况、ProgressBar、辅助文本)。',@@ -218,7 +220,8 @@ export const docsDense = {placeholder: 'placeholder when empty',isDisabled: 'disabled; use during streaming or unmet prereqs',density: 'visual density',- elevation: "resting elevation of composer body: low (default; low→med on hover/focus) | none (flat)",+ elevation:+ 'resting elevation of composer body: low (default; low→med on hover/focus) | none (flat with border); keyboard-focused editor gets the shared ring in either mode; pointer focus does not',drawer: 'slot: collapsible drawer above input: attachments, context chips, etc.; use ChatComposerDrawer',headerActions: 'slot: left header actions (attach, mention); icon-only sm buttons',headerContext: 'slot: right header context info (window usage, ProgressBar, text)',diff --git a/packages/core/src/Chat/ChatComposer.test.tsx b/packages/core/src/Chat/ChatComposer.test.tsxindex b8d5eded79..3babdec48d 100644--- a/packages/core/src/Chat/ChatComposer.test.tsx+++ b/packages/core/src/Chat/ChatComposer.test.tsx@@ -1,10 +1,15 @@// Copyright (c) Meta Platforms, Inc. and affiliates.-import {describe, it, expect, vi} from 'vitest';-import {render, fireEvent} from '@testing-library/react';+import {beforeEach, describe, it, expect, vi} from 'vitest';+import {act, render, fireEvent} from '@testing-library/react';import {useEffect, useRef} from 'react';import {ChatComposer} from './ChatComposer';import {useChatComposerContext} from './ChatContext';+import {__resetInteractionModalityForTest} from '../utils/interactionModality';++beforeEach(() => {+ __resetInteractionModalityForTest();+});// The composer body — the elevated surface — is the div that wraps the input// area (styles.body). A custom `input` slot renders inside the inputArea div,@@ -36,6 +41,83 @@ describe('ChatComposer elevation', () => {});});+describe('ChatComposer focus indication', () => {+ function renderComposer() {+ const result = render(+ <ChatComposer onSubmit={() => {}} value="Ready to send" />,+ );+ const editor = result.container.querySelector<HTMLElement>(+ '[contenteditable="true"]',+ )!;+ const body = editor.parentElement!.parentElement!.parentElement!;+ const sendButton =+ result.container.querySelector<HTMLButtonElement>('button')!;+ return {...result, body, editor, sendButton};+ }++ it('adds the composer ring when keyboard focus enters the editor', () => {+ const {body, editor} = renderComposer();+ const restingClass = body.className;++ fireEvent.keyDown(document, {key: 'Tab'});+ fireEvent.focus(editor);++ expect(body.className).not.toBe(restingClass);+ });++ it('does not add the composer ring when pointer focus enters the editor', () => {+ const {body, editor} = renderComposer();+ const restingClass = body.className;++ fireEvent.pointerDown(editor);+ fireEvent.focus(editor);++ expect(body.className).toBe(restingClass);+ });++ it('shows the composer ring for programmatic editor focus after keyboard input', () => {+ const {body, editor} = renderComposer();+ const restingClass = body.className;++ fireEvent.keyDown(document, {key: 'Tab'});+ act(() => editor.focus());++ expect(body.className).not.toBe(restingClass);+ });++ it('hides the composer ring for programmatic editor focus after pointer input', () => {+ const {body, editor} = renderComposer();+ const restingClass = body.className;++ fireEvent.pointerDown(document.body);+ act(() => editor.focus());++ expect(body.className).toBe(restingClass);+ });++ it('removes the composer ring when the focused editor receives a pointer press', () => {+ const {body, editor} = renderComposer();+ const restingClass = body.className;++ fireEvent.keyDown(document, {key: 'Tab'});+ fireEvent.focus(editor);+ expect(body.className).not.toBe(restingClass);++ fireEvent.pointerDown(editor);+ expect(body.className).toBe(restingClass);+ });++ it('leaves focus indication on an internal button instead of the composer', () => {+ const {body, sendButton} = renderComposer();+ const restingClass = body.className;++ fireEvent.keyDown(document, {key: 'Tab'});+ fireEvent.focus(sendButton);++ expect(body.className).toBe(restingClass);+ });+});+// A custom input that participates in the composer's composition contract:// reads value/submit from the exported context, and registers a focus control// so the shell can drive body-click-to-focus without knowing its DOM shape.diff --git a/packages/core/src/Chat/ChatComposer.tsx b/packages/core/src/Chat/ChatComposer.tsxindex 067516d230..b337f6d422 100644--- a/packages/core/src/Chat/ChatComposer.tsx+++ b/packages/core/src/Chat/ChatComposer.tsx@@ -25,11 +25,13 @@import React, {useState,+ useEffect,useCallback,useRef,useMemo,type ReactNode,type MouseEvent,+ type FocusEvent,} from 'react';import type {BaseProps} from '../BaseProps';import * as stylex from '@stylexjs/stylex';@@ -52,6 +54,11 @@ import type {ChatComposerInputControl} from './ChatContext';import {ChatSendButton} from './ChatSendButton';import {themeProps} from '../utils/themeProps';import {useTranslator} from '../i18n';+import {focusOutlineStyles} from '../utils/focusOutline.stylex';+import {+ getInteractionModality,+ trackInteractionModality,+} from '../utils/interactionModality';// =============================================================================// Types@@ -88,8 +95,8 @@ export interface ChatComposerProps extends Omit</*** Resting elevation of the composer body. `low` (the default) keeps today's* raised look — low at rest, bumping to med on hover / focus. `none` flattens- * it and draws a border with the same rest / hover / focus treatment as a- * text input (emphasized border → accent on focus, with matching inset rings).+ * it and draws a border. Keyboard focus in the editor adds the shared focus+ * ring in either presentation; pointer focus does not add that ring.* @default 'low'*/elevation?: 'none' | 'low';@@ -264,7 +271,8 @@ const styles = stylex.create({// Resting elevation for the composer body, narrowed to two steps.// - `low` (default) preserves today's look: low at rest, bumping to med on-// hover / focus-within (a CSS-only interaction state the component owns).+// hover / focus-within. The WCAG focus indicator is a separate shared ring,+// gated to keyboard focus in the editor; the shadow change remains depth.// - `none` is flat; depth comes from a border + inset rings instead. The// border is drawn *inside* the padding — its width is subtracted from every// side (like Card) so total inset (border + padding) equals the elevated@@ -306,6 +314,15 @@ const elevationStyles = stylex.create({},});+function isComposerEditor(target: EventTarget | null): target is HTMLElement {+ return (+ target instanceof HTMLElement &&+ target.matches(+ 'textarea, [contenteditable="true"], [role="textbox"], input:not([type]), input[type="text"], input[type="search"], input[type="email"], input[type="url"], input[type="tel"], input[type="password"]',+ )+ );+}+// =============================================================================// Component// =============================================================================@@ -353,6 +370,11 @@ export function ChatComposer(props: ChatComposerProps) {placeholderFromProps ?? t('@astryx.chat.composer.placeholder');const [internalValue, setInternalValue] = useState('');+ const [hasKeyboardEditorFocus, setHasKeyboardEditorFocus] = useState(false);++ useEffect(() => {+ trackInteractionModality();+ }, []);const isControlled = controlledValue !== undefined;const currentValue = isControlled ? controlledValue : internalValue;@@ -410,6 +432,25 @@ export function ChatComposer(props: ChatComposerProps) {editable?.focus();}, []);+ const handleBodyFocusCapture = useCallback(+ (event: FocusEvent<HTMLDivElement>) => {+ setHasKeyboardEditorFocus(+ isComposerEditor(event.target) &&+ getInteractionModality() === 'keyboard',+ );+ },+ [],+ );++ const handleBodyBlurCapture = useCallback(+ (event: FocusEvent<HTMLDivElement>) => {+ if (!event.currentTarget.contains(event.relatedTarget)) {+ setHasKeyboardEditorFocus(false);+ }+ },+ [],+ );+const statusEl = status ? (<divrole={status.type === 'error' ? 'alert' : 'status'}@@ -469,9 +510,13 @@ export function ChatComposer(props: ChatComposerProps) {<divref={bodyRef}onClick={handleBodyClick}+ onPointerDownCapture={() => setHasKeyboardEditorFocus(false)}+ onFocusCapture={handleBodyFocusCapture}+ onBlurCapture={handleBodyBlurCapture}{...stylex.props(styles.body,elevationStyles[elevation],+ hasKeyboardEditorFocus && focusOutlineStyles.focusWithin,density === 'compact' && styles.compact,xstyle,)}>