Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .changeset/3701-voice-accessibility.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"@schlessera/brain-ui-react": patch
---

Voice is announced and keeps keyboard focus in the assembled app (#3701).

- **Announcements.** The dictation and live field's state label is a polite live region. A blocked microphone (D7), a dictation that stops (D8) and a stopped live conversation (L9) are announced assertively, and so is what to tap when an approval is pending (L6). A change to the Start card's notice is announced politely, without moving focus.
- **Focus.** Ending a live conversation, by End, Close or Escape on the Start card, returns focus to the composer's mic instead of the text field. A live control that is disabled or removed while focused (Interrupt once the reply stops, Mute while voice gets ready, Send now after sending) passes focus to Mute, or to the first control still usable, instead of dropping it to the page.
7 changes: 6 additions & 1 deletion packages/ui-react/src/components/chat/composer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -864,6 +864,11 @@ export function Composer({ send, handle }: { send: (msg: ClientMessage) => void
const focusMic = () => setTimeout(() => frameRef.current?.querySelector<HTMLElement>(
'[aria-label="Record on this device"], [aria-label^="Dictate"], [aria-label="Stop and save"]'
)?.focus({ preventScroll: true }), 0);
// A live conversation that ends hands focus back to the mic that started it (#3701).
const focusMicOrField = () => setTimeout(() => {
const mic = frameRef.current?.querySelector<HTMLElement>('[aria-label="Record on this device"], [aria-label^="Dictate"]');
if (mic) mic.focus({ preventScroll: true }); else focusField();
}, 0);
// A take that ends while focus is in the voice field (Finish, V3's
// silence stop, a provider end) hands focus back to the composer: the
// field with the caret after the dictated words (D6), or the mic (D1).
Expand Down Expand Up @@ -1034,7 +1039,7 @@ export function Composer({ send, handle }: { send: (msg: ClientMessage) => void

return (
<>
{conversation.active ? <div className="px-2 md:px-6"><ConversationField backend={[displayProviderLabel, displayProvider?.backendId, displayProvider?.vendor].filter(Boolean).join(" · ")} onLeave={() => queueMicrotask(focusField)} /></div> : <div className="px-4 pt-2 pb-4 md:px-6 md:pb-6">
{conversation.active ? <div className="px-2 md:px-6"><ConversationField backend={[displayProviderLabel, displayProvider?.backendId, displayProvider?.vendor].filter(Boolean).join(" · ")} onLeave={focusMicOrField} /></div> : <div className="px-4 pt-2 pb-4 md:px-6 md:pb-6">
{/* Says where a taken suggestion went, since focus moves with it. */}
<div className="sr-only" aria-live="polite" data-composer-notice="">
{insertNotice}
Expand Down
37 changes: 33 additions & 4 deletions packages/ui-react/src/components/voice/conversation-field.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect, useRef, useState } from "react";
import { useEffect, useLayoutEffect, useRef, useState, type FocusEvent } from "react";
import { useStore } from "zustand";
import { VoiceControlButton, VoiceField, VoiceNotice, VoiceText, type IconName } from "@schlessera/brain-ui-kit";
import { useBrainUiRoot } from "../../root-context.js";
Expand Down Expand Up @@ -114,6 +114,30 @@ export function ConversationField({ backend, onLeave }: { backend: string; onLea
if (s.micOn && !wasOn.current) frame.current?.querySelector<HTMLElement>('[aria-label="Mute"]')?.focus();
wasOn.current = s.micOn;
}, [s.micOn]);
// A field control that held focus and is now disabled or gone (Interrupt
// once the reply stops, Mute while voice readies, Send now after sending)
// hands focus on rather than dropping it to the page (#3701): to Mute, or
// to the first control still usable here (End, or L9's Close).
const held = useRef<HTMLElement | null>(null);
useLayoutEffect(() => {
const control = held.current;
if (!control || control.isConnected && !(control as HTMLButtonElement).disabled) return;
const active = document.activeElement;
if (active && active !== document.body && active !== control) { held.current = null; return; }
held.current = null;
const usable = [...frame.current?.querySelectorAll<HTMLButtonElement>("button:not([disabled])") ?? []];
(usable.find(b => b.getAttribute("aria-label") === "Mute") ?? usable[0])?.focus({ preventScroll: true });
});
const onFocus = (event: FocusEvent) => {
const target = event.target as HTMLElement;
held.current = target.closest(".bk-voice-controls") ? target : null;
};
// Focus the user moved elsewhere is theirs. The check waits a task, since a
// control being removed may blur while still attached; the effect above runs first.
const onBlur = (event: FocusEvent) => {
const target = event.target as HTMLButtonElement;
setTimeout(() => { if (target === held.current && target.isConnected && !target.disabled) held.current = null; }, 0);
};
// Root-owned leases distinguish a true unmount from StrictMode or same-task
// remounts. Component cleanup must never impersonate a manual Mute.
useEffect(() => client.attachControls(), [client]);
Expand Down Expand Up @@ -143,14 +167,19 @@ export function ConversationField({ backend, onLeave }: { backend: string; onLea
: null;
const meta = draft ? DRAFT_META : outputMuted ? "Reply audio off" : readiness ? "mic off"
: [service, state === "S5" ? null : clock(seconds)].filter(Boolean).join(" · ") || undefined;
return <div ref={frame} data-conversation-field="" data-live-state={s.disclosureOpen ? undefined : state ?? undefined} data-voice-refusal-window={permission.line ? "" : undefined} className="mx-auto max-w-3xl bg-background text-foreground" style={{ overflowWrap: "anywhere" }}>
// L6 is an approval request: said at once, with how to answer it (#3701).
// The label still says "Needs your tap" politely; this adds what to tap.
const urgent = !s.disclosureOpen && state === "L6" ? refusal || "Tap Allow or Deny on the card." : "";
return <div ref={frame} data-conversation-field="" data-live-state={s.disclosureOpen ? undefined : state ?? undefined} data-voice-refusal-window={permission.line ? "" : undefined} className="mx-auto max-w-3xl bg-background text-foreground" style={{ overflowWrap: "anywhere" }}
onFocus={onFocus} onBlur={onBlur}>
<div className="sr-only" aria-live="polite" aria-atomic="true">{s.announcement}</div>
<div className="sr-only" aria-live="assertive" aria-atomic="true" data-conversation-urgent="">{urgent}</div>
{s.disclosureOpen ? null : state === "L9"
? <div className="pb-2"><VoiceNotice tone="fail" icon="attention" title="Live conversation stopped" body={s.notice || undefined}
? <div className="pb-2"><VoiceNotice tone="fail" icon="attention" live="assertive" title="Live conversation stopped" body={s.notice || undefined}
actions={[{ label: "Close", onClick: leave }, { label: "Start again", tone: "brain", onClick: client.details }]} /></div>
: state && <div className="pb-2">
<VoiceField shape="tall" name="Live conversation" tone={LOOKS[state].tone} outline={LOOKS[state].outline}
label={{ icon: LOOKS[state].icon, word: LOOKS[state].word, spin: LOOKS[state].spin, meta }}
label={{ icon: LOOKS[state].icon, word: LOOKS[state].word, spin: LOOKS[state].spin, meta, live: "polite" }}
meter={meter} level={meter === "level" ? level : undefined}
controls={<>
<VoiceControlButton name={muted ? "Unmute" : "Mute"} icon={muted ? "mic-off" : "mic"} pressed={muted} disabled={state === "S5" || readiness} onClick={muted ? client.resume : client.mute} />
Expand Down
10 changes: 5 additions & 5 deletions packages/ui-react/src/components/voice/dictation-field.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -75,12 +75,12 @@ export function DictationCapture({ onFinish, onCancel }: { onFinish: () => void;
return (
<div ref={ref} className="mb-0" data-dictation-field={form}>
{form === "D2" ? (
<VoiceNotice tone="you" icon="mic" title="Allow the microphone" body="Your browser is asking. You only need to do this once." actions={[{ label: "Cancel", onClick: onCancel }]} />
<VoiceNotice tone="you" icon="mic" live="polite" title="Allow the microphone" body="Your browser is asking. You only need to do this once." actions={[{ label: "Cancel", onClick: onCancel }]} />
) : form === "Dc" ? (
<VoiceField
shape="compact"
tone="idle"
label={{ icon: "loading", word: "Connecting", meta, spin: true }}
label={{ icon: "loading", word: "Connecting", meta, spin: true, live: "polite" }}
meter="none"
trailing={<VoiceControlButton name="Cancel dictation" icon="dismiss" onClick={onCancel} />}
>
Expand All @@ -90,7 +90,7 @@ export function DictationCapture({ onFinish, onCancel }: { onFinish: () => void;
<VoiceField
shape="compact"
tone="you"
label={{ icon: "mic", word: form === "D5" ? "Finishing" : "Listening", meta }}
label={{ icon: "mic", word: form === "D5" ? "Finishing" : "Listening", meta, live: "polite" }}
meter={form === "D5" ? "sweep" : form === "D4" ? "flat" : "level"}
level={form === "D3" ? level : undefined}
trailing={finish(form === "D5")}
Expand Down Expand Up @@ -171,9 +171,9 @@ export function DictationNotices({ onConfirm, onCancel, onOpenSettings, onRetry,
return (
<div ref={ref} className="mb-2" data-dictation-notice={shown.kind === "blocked" ? "D7" : "D8"}>
{shown.kind === "blocked" ? (
<VoiceNotice tone="fail" icon="attention" live="polite" title={shown.title} body={shown.body} actions={[{ label: "OK", onClick: onDismiss }]} />
<VoiceNotice tone="fail" icon="attention" live="assertive" title={shown.title} body={shown.body} actions={[{ label: "OK", onClick: onDismiss }]} />
) : (
<VoiceNotice tone="idle" icon="retry" live="polite" title={shown.title} body={shown.body}
<VoiceNotice tone="idle" icon="retry" live="assertive" title={shown.title} body={shown.body}
actions={[{ label: "Dismiss", onClick: onDismiss }, { label: "Try again", tone: "you", onClick: onRetry }]} />
)}
</div>
Expand Down
2 changes: 2 additions & 0 deletions packages/ui-react/src/components/voice/start-card.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,8 @@ export function ConversationStartCard({ backend, onLeave }: { backend: string; o
return <div ref={frame} data-start-card="" data-start-service={disclosed?.providerId ?? ""} data-start-persona={selected?.id ?? ""}
style={{ maxHeight: "calc(100dvh - 16px)", overflowY: "auto", overscrollBehavior: "contain" }}
onKeyDown={(event) => { if (event.key === "Escape") { event.preventDefault(); leave(); } }}>
{/* The kit draws the notice; a change to it is said here, without moving focus (#3701). */}
<div className="sr-only" aria-live="polite" aria-atomic="true" data-start-announcement="">{notice?.text}</div>
<StartCard
service={service}
showService={pickable}
Expand Down
8 changes: 5 additions & 3 deletions packages/ui-react/tests/browser/dictation-notice.pointer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ function readable(element: HTMLElement) {
}

for (const theme of ["dark", "light"]) for (const width of [320, 1280]) for (const provider of ["deepgram", "webspeech"] as const) for (const retained of [true, false]) {
test(`${width} ${theme} ${provider} ${retained ? "kept" : "empty"}: D8 quotes the kept words, which are in the draft; one polite announcement; no focus theft`, async ctx => {
test(`${width} ${theme} ${provider} ${retained ? "kept" : "empty"}: D8 quotes the kept words, which are in the draft; one assertive announcement; no focus theft`, async ctx => {
expect(matchMedia("(any-pointer: fine)").matches).toBe(inject("railPointer") !== "coarse");
expect(matchMedia("(any-pointer: coarse)").matches).toBe(inject("railPointer") !== "fine");
await viewport(ctx, width, theme);
Expand All @@ -169,7 +169,8 @@ for (const theme of ["dark", "light"]) for (const width of [320, 1280]) for (con
const announced: string[] = [];
const seen = new Map<Element, string>();
const observer = new MutationObserver(() => {
const regions = [...s.host.querySelectorAll('[role="status"], [aria-live="polite"]')].filter(el => el.textContent?.includes("Dictation stopped"));
// A failure is assertive (#3701), and said by one region only.
const regions = [...s.host.querySelectorAll('[role="status"], [role="alert"], [aria-live]')].filter(el => el.textContent?.includes("Dictation stopped"));
for (const region of regions) if (seen.get(region) !== region.textContent) {
announced.push(region.textContent!); seen.set(region, region.textContent!);
}
Expand All @@ -183,7 +184,8 @@ for (const theme of ["dark", "light"]) for (const width of [320, 1280]) for (con
expect(notice(s)!.querySelector(".bk-voice-notice-body")!.textContent).toBe(body);
expect([...notice(s)!.querySelectorAll("button")].map(b => b.textContent), "D8's actions").toEqual(["Dismiss", "Try again"]);
expect(draft(s), "the words heard are in the draft, never lost").toBe(retained ? words : "");
expect(announced, "one polite announcement, without a mirrored region").toEqual([`Dictation stopped${body}`]);
expect(announced, "one announcement, without a mirrored region").toEqual([`Dictation stopped${body}`]);
expect(notice(s)!.querySelector('[role="alert"]')?.textContent, "D8 is assertive").toBe(`Dictation stopped${body}`);
const box = notice(s)!.getBoundingClientRect();
expect(box.left).toBeGreaterThanOrEqual(0); expect(box.right).toBeLessThanOrEqual(width);
expect(s.host.scrollWidth).toBeLessThanOrEqual(width);
Expand Down
Loading
Loading