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

ComposerSpeechButton.tsx

262 lines8.3 KB

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