Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ComposerSpeechButton.tsx

266 lines8.4 KB

1import type { VoiceInputState } from "@t3tools/client-runtime/voice-input";
2import { speechModelDownloadPercent } from "@t3tools/shared/speech";
3import { msg, useGT, useMessages } from "gt-react";
4import { CheckIcon, MicIcon, XIcon } from "lucide-react";
5import { useEffect, useState, type PointerEvent, type ReactElement } from "react";
6​
7import { VoiceInputErrorPill } from "./VoiceInputErrorPill";
8import { VoiceInputPill, VoiceWaveform } from "./VoiceInputPill";
9import { m, type MessageResolver } from "~/i18n/messages";
10import { cn } from "~/lib/utils";
11import { Button } from "../ui/button";
12import { Spinner } from "../ui/spinner";
13import { SharedTooltipTrigger } from "../ui/shared-tooltip";
14​
15type DownloadProgress = { downloaded: number; total: number } | null;
16​
17const keepFocus = (event: PointerEvent) => event.preventDefault();
18​
19/** One short status line per phase; also mirrored into the preview annotation editor. */
20export function resolveSpeechPresentation(
21 state: VoiceInputState,
22 progress: DownloadProgress,
23 resolve: MessageResolver = m,
24): { status: string | null; active: boolean } {
25 switch (state.phase) {
26 case "idle":
27 return { status: null, active: false };
28 case "error":
29 return { status: state.error ?? resolve(msg("Voice input failed")), active: false };
30 case "preparing":
31 return {
32 status: progress
33 ? resolve(
34 msg`Downloading model ${{
35 percent: speechModelDownloadPercent(
36 progress.downloaded,
37 Math.max(1, progress.total),
38 ),
39 }}%`,
40 )
41 : resolve(msg("Starting…")),
42 active: true,
43 };
44 case "recording":
45 return {
46 status: resolve(msg({ context: "voice input status" })`Recording`),
47 active: true,
48 };
49 case "transcribing":
50 return { status: resolve(msg("Transcribing…")), active: true };
51 case "post-processing":
52 return { status: resolve(msg("Cleaning up…")), active: true };
53 }
55​
56function formatElapsed(seconds: number) {
57 return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
59​
60function RecordingStatus(props: {
61 level: number;
62 preparing: boolean;
63 recordingStartedAt?: number | null | undefined;
64 recordingLimitSeconds?: number | undefined;
65}) {
66 const { preparing, recordingStartedAt } = props;
67 const [elapsedSeconds, setElapsedSeconds] = useState(() =>
68 recordingStartedAt ? Math.max(0, Math.floor((Date.now() - recordingStartedAt) / 1_000)) : 0,
69 );
70​
71 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- owns the timer displaying the native recording duration
72 useEffect(() => {
73 if (preparing) return;
74 const startedAt = recordingStartedAt ?? Date.now();
75 const timer = window.setInterval(
76 () => setElapsedSeconds(Math.floor((Date.now() - startedAt) / 1_000)),
77 250,
78 );
79 return () => window.clearInterval(timer);
80 }, [preparing, recordingStartedAt]);
81​
82 return (
83 <>
84 <span
85 aria-hidden
86 className={cn(
87 "size-2 shrink-0 rounded-full",
88 preparing ? "bg-muted-foreground/40" : "bg-destructive",
89 )}
90 />
91 <span className="shrink-0 text-xs text-muted-foreground tabular-nums">
92 {formatElapsed(preparing ? 0 : elapsedSeconds)}
93 {props.recordingLimitSeconds !== undefined
94 ? ` / ${formatElapsed(props.recordingLimitSeconds)}`
95 : ""}
96 </span>
97 <div className="me-1.5 flex w-16 min-w-0 shrink grow">
98 <VoiceWaveform level={props.level} />
99 </div>
100 </>
101 );
103​
104function ShortcutTooltip(props: {
105 label: string;
106 shortcut?: string | null | undefined;
107 children: ReactElement;
108}) {
109 return (
110 <SharedTooltipTrigger
111 render={props.children}
112 label={
113 <>
114 {props.label}
115 {props.shortcut ? ` (${props.shortcut})` : ""}
116 </>
117 }
118 />
119 );
121​
122export function ComposerSpeechButton(props: {
123 state: VoiceInputState;
124 shortcutLabel?: string | null;
125 disabled?: boolean;
126 /** Compact matches the `xs` buttons beside text-field editors. */
127 size?: "default" | "compact";
128 onStart(): void;
129}) {
130 const gt = useGT();
131 if (props.state.phase !== "idle") return null;
132 const label = gt`Start voice input`;
133​
134 return (
135 <ShortcutTooltip label={label} shortcut={props.shortcutLabel}>
136 <Button
137 type="button"
138 size={props.size === "compact" ? "icon-xs" : "icon-sm"}
139 variant="ghost"
140 aria-label={label}
141 disabled={props.disabled}
142 onPointerDown={keepFocus}
143 onClick={() => {
144 if (!props.disabled) props.onStart();
145 }}
146 className="shrink-0"
147 >
148 <MicIcon />
149 </Button>
150 </ShortcutTooltip>
151 );
153​
154export function ComposerSpeechRecordingPill(props: {
155 state: VoiceInputState;
156 progress: DownloadProgress;
157 finishShortcutLabel?: string | null;
158 cancelShortcutLabel?: string | null;
159 level: number;
160 recordingStartedAt?: number | null | undefined;
161 recordingLimitSeconds?: number | undefined;
162 /** Compact matches the `xs` buttons beside text-field editors. */
163 size?: "default" | "compact";
164 onStart(): void;
165 disabled?: boolean;
166 onStop(): void;
167 onCancel(): void;
168 onSkipPostProcessing(): void;
169}) {
170 const gt = useGT();
171 const m = useMessages();
172 const { phase } = props.state;
173 const compact = props.size === "compact";
174 if (phase === "error") {
175 return (
176 <VoiceInputErrorPill
177 size={props.size}
178 error={props.state.error}
179 errorAction={props.state.errorAction}
180 errorCode={props.state.errorCode}
181 disabled={props.disabled ?? false}
182 cancelShortcutLabel={props.cancelShortcutLabel ?? null}
183 onRetry={props.onStart}
184 onDismiss={props.onCancel}
185 />
186 );
187 }
188 const presentation = resolveSpeechPresentation(props.state, props.progress, m);
189 if (!presentation.active) return null;
190 const recording = phase === "recording";
191 const starting = phase === "preparing" && props.progress === null;
192 const showRecordingLayout = starting || recording;
193 const trailing = showRecordingLayout || phase === "post-processing";
194​
195 return (
196 <VoiceInputPill size={props.size}>
197 <ShortcutTooltip label={gt`Cancel voice input`} shortcut={props.cancelShortcutLabel}>
198 <Button
199 type="button"
200 size={compact ? "icon-xs" : "icon-sm-pill"}
201 variant="ghost"
202 aria-label={gt`Cancel voice input`}
203 onPointerDown={keepFocus}
204 onClick={props.onCancel}
205 className="shrink-0"
206 >
207 <XIcon />
208 </Button>
209 </ShortcutTooltip>
210 <div
211 className={cn(
212 "flex min-w-0 flex-1 items-center gap-2 overflow-hidden",
213 !trailing && "pe-2.5",
214 )}
215 role="status"
216 aria-live={recording ? "off" : "polite"}
217 aria-label={presentation.status ?? undefined}
218 >
219 {showRecordingLayout ? (
220 <>
221 {starting && <span className="sr-only">{presentation.status}</span>}
222 <RecordingStatus
223 preparing={starting}
224 level={starting ? 0 : props.level}
225 recordingStartedAt={props.recordingStartedAt}
226 recordingLimitSeconds={props.recordingLimitSeconds}
227 />
228 </>
229 ) : (
230 <>
231 <Spinner aria-hidden size="sm" tone="muted" className="shrink-0" />
232 <span className="min-w-0 truncate text-sm text-muted-foreground">
233 {presentation.status}
234 </span>
235 </>
236 )}
237 </div>
238 {phase === "post-processing" ? (
239 <Button
240 type="button"
241 size={compact ? "xs" : "sm-pill"}
242 variant="ghost"
243 onPointerDown={keepFocus}
244 onClick={props.onSkipPostProcessing}
245 className="shrink-0"
246 >
247 {gt({ context: "verb, skips cleaning up the transcript" })`Skip`}
248 </Button>
249 ) : showRecordingLayout ? (
250 <ShortcutTooltip label={gt`Finish voice input`} shortcut={props.finishShortcutLabel}>
251 <Button
252 type="button"
253 size={compact ? "icon-xs" : "icon-sm-pill"}
254 aria-label={gt`Finish voice input`}
255 disabled={starting}
256 onPointerDown={keepFocus}
257 onClick={props.onStop}
258 className="shrink-0"
259 >
260 {starting ? <Spinner aria-hidden /> : <CheckIcon />}
261 </Button>
262 </ShortcutTooltip>
263 ) : null}
264 </VoiceInputPill>
265 );