An open source design system that's fully customizable and agent ready
TypeScript
fix(ChatDictationButton): preserve unsupported and theme states (#6444)
Cindy Zhang423c87c56fa5
diff --git a/.changeset/chat-dictation-button-unsupported-state.md b/.changeset/chat-dictation-button-unsupported-state.mdnew file mode 100644index 0000000000..e252a10df1--- /dev/null+++ b/.changeset/chat-dictation-button-unsupported-state.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Keep the chat dictation control disabled when speech recognition is unavailable, and preserve theme control over its clipping feedback.++@cixzhangdiff --git a/apps/storybook/rtl-audit/verified-not-applicable.json b/apps/storybook/rtl-audit/verified-not-applicable.jsonindex b01b5380d9..570b5aecf9 100644--- a/apps/storybook/rtl-audit/verified-not-applicable.json+++ b/apps/storybook/rtl-audit/verified-not-applicable.json@@ -226,5 +226,14 @@"packages/core/src/Chat/ChatSendButton.tsx": "sha256:0e4948ab7b94b456da37d04cefc2473f893b79d12cde954a7b8923085923a2be","packages/core/src/Chat/index.ts": "sha256:1e1883f9baa0b9661fefe855a7df6db2a0d0e69118734b3d309543a6c5518b46"}+ },+ {+ "component": "core/ChatDictationButton",+ "reason": "ChatDictationButton is a symmetric inline-flex icon control. Its microphone glyph and five centered equalizer bars are direction-neutral; the component owns no inline-axis placement, ordering, directional glyph, horizontal scrolling or dragging, overlay placement, or horizontal keyboard behavior.",+ "evidence": {+ "apps/storybook/stories/ChatDictation.stories.tsx": "sha256:64429848dec3034113095f53ac860be3dddcc4b1dc0e6318d380bffac994366e",+ "packages/core/src/Chat/ChatDictationButton.tsx": "sha256:bad96c58a64ed9463c428ab7ef53a8c41794bb685eb34b4b333c6cad5c8993c2",+ "packages/core/src/Chat/index.ts": "sha256:0f4a9d3ee08b4fcd43698ad017460aad109c500d2411913f509506d2a27387bb"+ }}]diff --git a/apps/storybook/stories/ChatDictation.stories.tsx b/apps/storybook/stories/ChatDictation.stories.tsxindex ad3d5306c7..3b19771f89 100644--- a/apps/storybook/stories/ChatDictation.stories.tsx+++ b/apps/storybook/stories/ChatDictation.stories.tsx@@ -57,6 +57,12 @@ const speakingDictation: UseSpeechRecognitionReturn = {toggle: () => {},};+const clippingDictation: UseSpeechRecognitionReturn = {+ ...speakingDictation,+ volume: 0.3,+ bands: [0.2, 0.2, 0.2, 0.2, 0.2],+};+const unsupportedDictation: UseSpeechRecognitionReturn = {volume: 0,rawBands: [0, 0, 0, 0, 0],@@ -76,7 +82,7 @@ const unsupportedDictation: UseSpeechRecognitionReturn = {// =============================================================================const meta: Meta<typeof ChatDictationButton> = {- title: 'Core/ChatDictation',+ title: 'Core/ChatDictationButton',component: ChatDictationButton,tags: ['autodocs'],parameters: {@@ -103,16 +109,22 @@ export const Idle: Story = {render: () => <ChatDictationButton dictation={idleDictation} />,};-/** Listening state — pulsing red record indicator */+/** Listening state — volume-reactive equalizer bars */export const Listening: Story = {render: () => <ChatDictationButton dictation={listeningDictation} />,};-/** Speaking state — more intense pulse while speech is detected */+/** Speaking state — stronger equalizer bars */export const Speaking: Story = {render: () => <ChatDictationButton dictation={speakingDictation} />,};+/** Clipping state — bars blend from accent toward the theme's error color */+export const Clipping: Story = {+ tags: ['visual-baseline'],+ render: () => <ChatDictationButton dictation={clippingDictation} />,+};+/** Unsupported browser — button hidden by default */export const Unsupported: Story = {render: () => (@@ -125,8 +137,9 @@ export const Unsupported: Story = {),};-/** Unsupported browser — button visible when isHiddenWhenUnsupported is false */+/** Unsupported browser — button visible but disabled when explicitly retained */export const UnsupportedVisible: Story = {+ tags: ['visual-baseline'],render: () => (<ChatDictationButtondictation={unsupportedDictation}diff --git a/packages/core/src/Chat/ChatDictationButton.doc.mjs b/packages/core/src/Chat/ChatDictationButton.doc.mjsindex 1f5ada74ab..d4cf0e07eb 100644--- a/packages/core/src/Chat/ChatDictationButton.doc.mjs+++ b/packages/core/src/Chat/ChatDictationButton.doc.mjs@@ -47,7 +47,7 @@ export const docs = {name: 'isHiddenWhenUnsupported',type: 'boolean',description:- 'When true, renders nothing if the browser does not support SpeechRecognition.',+ 'When true, renders nothing if the browser does not support SpeechRecognition. When false, keeps the button visible but disabled.',default: 'true',},{@@ -81,7 +81,7 @@ export const docsZh = {propDescriptions: {dictation: 'The return value from useChatDictation or useSpeechRecognition. Controls all button state.',size: 'Button size.',- isHiddenWhenUnsupported: 'When true, renders nothing if SpeechRecognition is unsupported.',+ isHiddenWhenUnsupported: 'When true, hides unsupported dictation; when false, keeps a disabled button visible.',label: 'Accessible label override.',xstyle: 'Additional StyleX styles.',},@@ -104,7 +104,7 @@ export const docsDense = {propDescriptions: {dictation: 'return from useChatDictation/useSpeechRecognition; controls state',size: 'btn size',- isHiddenWhenUnsupported: 'hide when SpeechRecognition unsupported',+ isHiddenWhenUnsupported: 'hide unsupported dictation; false keeps disabled btn visible',label: 'a11y label override',xstyle: 'extra StyleX styles',},diff --git a/packages/core/src/Chat/ChatDictationButton.spec.md b/packages/core/src/Chat/ChatDictationButton.spec.mdnew file mode 100644index 0000000000..f6305559af--- /dev/null+++ b/packages/core/src/Chat/ChatDictationButton.spec.md@@ -0,0 +1,160 @@+---+schema_version: 3+template_version: 5+kind: component+id: component:ChatDictationButton+authority: draft+archive_reason: null+superseded_by: null+approved_by: null+approved_at: null+owners: [cixzhang]+review_triggers: [public-api, behavior, accessibility, theming, testing]+verified_by:+ [+ packages/core/src/Chat/ChatDictationButton.test.tsx,+ apps/storybook/stories/ChatDictation.stories.tsx,+ apps/storybook/rtl-audit/verified-not-applicable.json,+ ]+modules: []+families: []+design_specs: []+architecture:+ [+ architecture:public-component-api,+ architecture:component-style-authoring,+ architecture:theme-tokens,+ architecture:component-test-sufficiency,+ architecture:knowledge-contracts,+ ]+contributing: []+system_specs: [spec:AST-029]+---++# ChatDictationButton component contract++## Contract at a glance++| Area | Contract |+| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| Public contract | `dictation` supplies support, listening, volume, bands, and toggle state; `size`, `label`, root span props, styles, and ref remain additive inputs. |+| Behavior | The idle button shows the microphone action. Listening replaces the icon with five volume-reactive bars. Unsupported dictation is hidden by default or disabled when explicitly retained. |+| End-user impact | Voice input remains operable and labelled; unsupported browsers do not expose an action that cannot run. |+| Builder impact | Builders can place the control in ChatComposer send actions and safely customize its root layout without owning speech state. |+| Compatibility/readiness | Patch-compatible repair: existing supported behavior is unchanged; the opt-in unsupported-visible state becomes accurately disabled. |+| Review checks | Reject an enabled unsupported action, a missing listening label, raw theme-inaccessible clipping color, or lost root passthrough. |+| Governing rules | `architecture:component-style-authoring/INV1–INV3`; `architecture:theme-tokens/INV3`; `architecture:public-component-api/INV1, INV5–INV6, INV8`; `architecture:component-test-sufficiency/INV1–INV8, INV10–INV11`. |++This table is a review projection; the body below is authoritative.++## Intent++ChatDictationButton renders the visible control for an existing speech-recognition+state owner. It translates that owner's support and listening states into one+icon-only Button and a direction-neutral equalizer visualization.++## Compatibility and migration++- Released default preserved: yes+- Compatibility class: behavioral bug fix for the explicit unsupported-visible state+- Supported idle and listening states: unchanged+- Migration decision: none++## Ownership boundary++**Owns**++- The start/stop accessible label and optional caller label override.+- Hidden-versus-disabled presentation when speech recognition is unsupported.+- The five-bar visual projection of supplied band and volume values.+- Theme-aware accent-to-error clipping feedback.+- Root span ref and accepted neutral span props.++**Does not own / non-goals**++- Speech recognition support detection, lifecycle, transcripts, or errors.+- Microphone permission UX or audio capture.+- ChatComposer placement beyond documented composition guidance.+- A public color, threshold, or equalizer-shape axis.++## Public concepts++| Concept | Closed values or states | Meaning | Default | Owner | Stability |+| ------------ | -------------------------------------------------- | ------------------------------------------------------------- | --------------------------- | ---------------------------------------- | --------- |+| support | supported; unsupported-hidden; unsupported-visible | Determines whether the control can render and operate. | unsupported-hidden | speech owner projected by this component | stable |+| listening | idle; listening | Selects the start/stop label and microphone/equalizer visual. | idle | `dictation` | stable |+| size | `sm`; `md` | Sizes the Button and equalizer geometry together. | `md` | component | stable |+| label | translated default; caller override | Names the action for assistive technology. | state-dependent translation | component/caller | stable |+| root surface | ref; DOM/data/ARIA props; className/style/xstyle | Extends the positioning wrapper. | omitted | public component API | stable |++## Behavioral and layout contract++| ID | Candidate invariant | Basis | Draft review state |+| --- | ------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------- | ------------------ |+| FR1 | Supported idle state MUST expose an enabled Button named by the start label and invoke `dictation.toggle` on activation. | shipped API and Button contract | verify |+| FR2 | Supported listening state MUST expose the stop label and five aria-hidden visualizer bars derived from `bands`. | shipped implementation and docs | verify |+| FR3 | Unsupported state MUST render nothing by default. If explicitly retained, its Button MUST be disabled. | public option plus operability/accessibility repair | settled |+| FR4 | Clipping feedback MUST derive from portable semantic color tokens so a consumer theme can retint both endpoints. | `architecture:theme-tokens/INV3` and lint enforcement | settled |+| FR5 | Accepted ref, DOM/data/ARIA, className, style, and xstyle inputs MUST reach and compose on the root span. | `architecture:public-component-api` | settled |++### Allowed variation++- Callers may replace the translated start/stop label with `label`.+- Band amplitudes and clipping strength vary with the supplied dictation owner.+- Consumer themes may change the accent and error colors used by the bars.++## Accessibility contract++- The nested Button owns keyboard and pointer activation, focus, and disabled semantics.+- The equalizer is decorative and MUST remain hidden from the accessibility tree.+- The visible control MUST have a state-appropriate accessible label.+- An unsupported visible control MUST communicate disabled state and MUST NOT activate.+- Reduced-motion preference removes the equalizer's transition duration.++## Design relationships++- Idle uses the shared microphone Icon through Button.+- Listening bars begin at `--color-accent` and blend toward `--color-error` as clipping increases.+- The component adds no portable token or public theme target.+- Equalizer dimensions remain private component geometry.++## Responsive and bidirectional behavior++The control has fixed `sm` and `md` sizes and no viewport-owned behavior. Its+microphone glyph, centered bars, and block-axis scale are direction-neutral; the+verified-N/A ledger records this with source evidence.++## Family and system relationships++- ChatComposer owns placement through its `sendActions` slot.+- Button owns activation, focus, disabled semantics, hit target, and icon-only presentation.+- Icon owns the microphone glyph.+- `useChatDictation` and `useSpeechRecognition` own speech lifecycle and state.+- Theme token architecture owns the accent and error semantic roles.++## Verification map++| Contract | Evidence |+| ----------------------- | --------------------------------------------------------------------- |+| FR1, labels, activation | `ChatDictationButton.test.tsx` idle activation and custom-label cases |+| FR2 | listening structure test and Listening/Speaking stories |+| FR3 | unsupported hidden and visible-disabled tests/stories |+| FR4 | clipping semantic-color test, lint, and Clipping story |+| FR5 | typed ref and root-passthrough test |+| rendered states | exact-head Storybook, a11y, and visual CI |+| RTL N/A | `apps/storybook/rtl-audit/verified-not-applicable.json` |++## Decision log++| Decision | Reason | Authority |+| ---------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | ------------------------------------------ |+| Keep unsupported dictation hidden by default and disabled when explicitly visible. | An unavailable action must not present as operable. | objective accessibility/operability repair |+| Blend portable accent and error tokens for clipping. | Preserves the existing progressive clipping cue while keeping both endpoints theme-owned. | `architecture:theme-tokens/INV3` |++## Open questions++None for this repair.++## Content boundary++Labels may be translated defaults or caller overrides. The component does not own transcript text, permission errors, microphone instructions, or product-specific voice-input guidance.diff --git a/packages/core/src/Chat/ChatDictationButton.test.tsx b/packages/core/src/Chat/ChatDictationButton.test.tsxindex fd9eea3a37..420d38c8e5 100644--- a/packages/core/src/Chat/ChatDictationButton.test.tsx+++ b/packages/core/src/Chat/ChatDictationButton.test.tsx@@ -1,43 +1,108 @@// Copyright (c) Meta Platforms, Inc. and affiliates.-import {describe, it, expect} from 'vitest';-import {render, screen} from '@testing-library/react';+import {createRef} from 'react';+import {describe, it, expect, vi} from 'vitest';+import {fireEvent, render, screen} from '@testing-library/react';+import {colorVars} from '../theme/tokens.stylex';import {ChatDictationButton} from './ChatDictationButton';+import type {ChatDictationButtonProps} from './ChatDictationButton';import type {UseSpeechRecognitionReturn} from './useSpeechRecognition';-const dictation: UseSpeechRecognitionReturn = {- isSupported: true,- isListening: false,- isSpeaking: false,- volume: 0,- bands: [0, 0, 0, 0, 0],- rawBands: [0, 0, 0, 0, 0],- interimTranscript: '',- start: () => {},- stop: () => {},- abort: () => {},- toggle: () => {},-};+function makeDictation(+ overrides: Partial<UseSpeechRecognitionReturn> = {},+): UseSpeechRecognitionReturn {+ return {+ isSupported: true,+ isListening: false,+ isSpeaking: false,+ volume: 0,+ bands: [0, 0, 0, 0, 0],+ rawBands: [0, 0, 0, 0, 0],+ interimTranscript: '',+ start: vi.fn(),+ stop: vi.fn(),+ abort: vi.fn(),+ toggle: vi.fn(),+ ...overrides,+ };+}describe('ChatDictationButton', () => {- it('renders a dictation button', () => {- render(- <ChatDictationButton dictation={dictation} data-testid="dictation" />,+ it('labels and toggles the idle button', () => {+ const dictation = makeDictation();+ render(<ChatDictationButton dictation={dictation} />);++ fireEvent.click(screen.getByRole('button', {name: 'Start dictation'}));+ expect(dictation.toggle).toHaveBeenCalledTimes(1);+ });++ it('shows five hidden visualizer bars and the stop label while listening', () => {+ const dictation = makeDictation({+ isListening: true,+ bands: [0.02, 0.04, 0.08, 0.12, 0.18],+ });+ const {container} = render(<ChatDictationButton dictation={dictation} />);++ expect(screen.getByRole('button', {name: 'Stop dictation'})).toBeEnabled();+ const visualizer = container.querySelector('[aria-hidden="true"]');+ expect(visualizer).not.toBeNull();+ expect(visualizer?.children).toHaveLength(5);+ });++ it('uses theme-owned colors for clipping feedback', () => {+ const dictation = makeDictation({+ isListening: true,+ volume: 0.3,+ bands: [0.2, 0.2, 0.2, 0.2, 0.2],+ });+ const {container} = render(<ChatDictationButton dictation={dictation} />);++ const barStyle = container+ .querySelector('[aria-hidden="true"] > span')+ ?.getAttribute('style');+ expect(barStyle).toContain('color-mix(in srgb');+ expect(barStyle).toContain(colorVars['--color-accent']);+ expect(barStyle).toContain(colorVars['--color-error']);+ expect(barStyle).not.toContain('hsl(');+ });++ it('hides unsupported dictation by default', () => {+ const {container} = render(+ <ChatDictationButton dictation={makeDictation({isSupported: false})} />,);- expect(screen.getByTestId('dictation')).toBeTruthy();++ expect(container).toBeEmptyDOMElement();});- it('forwards rest props (data-*, aria-*, id) to the root element', () => {+ it('disables an unsupported button when explicitly kept visible', () => {render(<ChatDictationButton- dictation={dictation}- data-testid="dictation"- data-custom="x"- id="dictate-1"+ dictation={makeDictation({isSupported: false})}+ isHiddenWhenUnsupported={false}/>,);- const root = screen.getByTestId('dictation');- expect(root).toHaveAttribute('data-custom', 'x');- expect(root).toHaveAttribute('id', 'dictate-1');++ expect(+ screen.getByRole('button', {name: 'Start dictation'}),+ ).toBeDisabled();+ });++ it('forwards the root ref and accepted span props', () => {+ const ref = createRef<HTMLSpanElement>();+ const props = {+ dictation: makeDictation(),+ 'data-testid': 'dictation',+ 'data-custom': 'x',+ id: 'dictate-1',+ label: 'Use voice input',+ ref,+ } satisfies ChatDictationButtonProps;++ render(<ChatDictationButton {...props} />);++ expect(ref.current).toBe(screen.getByTestId('dictation'));+ expect(ref.current).toHaveAttribute('data-custom', 'x');+ expect(ref.current).toHaveAttribute('id', 'dictate-1');+ expect(screen.getByRole('button', {name: 'Use voice input'})).toBeEnabled();});});diff --git a/packages/core/src/Chat/ChatDictationButton.tsx b/packages/core/src/Chat/ChatDictationButton.tsxindex bea36aaed0..364247f542 100644--- a/packages/core/src/Chat/ChatDictationButton.tsx+++ b/packages/core/src/Chat/ChatDictationButton.tsx@@ -11,7 +11,8 @@* A toggle button that connects to useChatDictation. Shows a microphone* icon when idle. When listening, replaces the icon with volume-reactive* frequency bars (equalizer style) that respond to real mic input.- * Bars use the accent color and hue-shift when volume clips past 10%.+ * Bars use the accent color and blend toward the semantic error color when+ * volume clips past 20%.** SYNC: When modified, update:* - /packages/core/src/Chat/index.ts (exports)@@ -39,7 +40,7 @@ export interface ChatDictationButtonProps extends BaseProps<HTMLSpanElement> {dictation: UseSpeechRecognitionReturn;/** Button size. @default "md" */size?: 'sm' | 'md';- /** Hide the button when SpeechRecognition is not supported. @default true */+ /** Hide the button when SpeechRecognition is unsupported. When false, the unsupported button remains visible but disabled. @default true */isHiddenWhenUnsupported?: boolean;/** Accessible label override. */label?: string;@@ -128,13 +129,13 @@ export function ChatDictationButton({// Boost each band for visibility — quiet speech (0-10%) maps to full visual rangeconst boostedBands = bands.map(b => Math.min(Math.pow(b / 0.2, 0.5), 1));- // Hue shift from accent color when volume clips past 10%+ // Blend toward the theme's semantic error color as clipping increases.const isClipping = rawVolume >= 0.2;- const hueShift = isClipping ? Math.min((rawVolume - 0.2) / 0.1, 1) * 60 : 0;+ const clippingStrength = Math.min((rawVolume - 0.2) / 0.1, 1) * 100;const barColor = isClipping- ? `hsl(calc(var(--accent-hue, 210) + ${hueShift}), 80%, 50%)`- : `var(--color-accent, ${colorVars['--color-accent']})`;+ ? `color-mix(in srgb, ${colorVars['--color-accent']}, ${colorVars['--color-error']} ${clippingStrength}%)`+ : colorVars['--color-accent'];const {barWidth, barGap, barMaxHeight} = SIZE_CONFIG[size];@@ -180,6 +181,7 @@ export function ChatDictationButton({size={size}icon={isListening ? undefined : <Icon icon="microphone" size={size} />}isIconOnly+ isDisabled={!dictation.isSupported}onClick={dictation.toggle}/></span>