Open History to see the last commit
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 { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/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 }
50}
51
52function formatElapsed(seconds: number) {
53 return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
54}
55
56function RecordingStatus(props: {
57 level: number;
58 recordingStartedAt?: number | null | undefined;
59 recordingLimitSeconds?: number | undefined;
60}) {
61 const { recordingStartedAt } = props;
62 const [elapsedSeconds, setElapsedSeconds] = useState(() =>
63 recordingStartedAt ? Math.max(0, Math.floor((Date.now() - recordingStartedAt) / 1_000)) : 0,
64 );
65
66 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- owns the timer displaying the native recording duration
67 useEffect(() => {
68 const startedAt = recordingStartedAt ?? Date.now();
69 const timer = window.setInterval(
70 () => setElapsedSeconds(Math.floor((Date.now() - startedAt) / 1_000)),
71 250,
72 );
73 return () => window.clearInterval(timer);
74 }, [recordingStartedAt]);
75
76 return (
77 <>
78 <span aria-hidden className="size-2 shrink-0 rounded-full bg-destructive" />
79 <span className="shrink-0 text-xs text-muted-foreground tabular-nums">
80 {formatElapsed(elapsedSeconds)}
81 {props.recordingLimitSeconds !== undefined
82 ? ` / ${formatElapsed(props.recordingLimitSeconds)}`
83 : ""}
84 </span>
85 <div className="me-1.5 flex w-16 min-w-0 shrink grow">
86 <VoiceWaveform level={props.level} />
87 </div>
88 </>
89 );
90}
91
92function ShortcutTooltip(props: {
93 label: string;
94 shortcut?: string | null | undefined;
95 children: ReactElement;
96}) {
97 return (
98 <Tooltip>
99 <TooltipTrigger render={props.children} />
100 <TooltipPopup side="top">
101 {props.label}
102 {props.shortcut ? ` (${props.shortcut})` : ""}
103 </TooltipPopup>
104 </Tooltip>
105 );
106}
107
108export function ComposerSpeechButton(props: {
109 state: VoiceInputState;
110 shortcutLabel?: string | null;
111 disabled?: boolean;
112 /** Compact matches the `xs` buttons beside text-field editors. */
113 size?: "default" | "compact";
114 onStart(): void;
115}) {
116 const gt = useGT();
117 if (props.state.phase !== "idle") return null;
118 const label = gt("Start voice input");
119
120 return (
121 <ShortcutTooltip label={label} shortcut={props.shortcutLabel}>
122 <Button
123 type="button"
124 size={props.size === "compact" ? "icon-xs" : "icon-sm"}
125 variant="ghost"
126 aria-label={label}
127 disabled={props.disabled}
128 onPointerDown={keepFocus}
129 onClick={() => {
130 if (!props.disabled) props.onStart();
131 }}
132 className="shrink-0"
133 >
134 <MicIcon />
135 </Button>
136 </ShortcutTooltip>
137 );
138}
139
140export function ComposerSpeechRecordingPill(props: {
141 state: VoiceInputState;
142 progress: DownloadProgress;
143 finishShortcutLabel?: string | null;
144 cancelShortcutLabel?: string | null;
145 level: number;
146 recordingStartedAt?: number | null | undefined;
147 recordingLimitSeconds?: number | undefined;
148 /** Compact matches the `xs` buttons beside text-field editors. */
149 size?: "default" | "compact";
150 onStart(): void;
151 disabled?: boolean;
152 onStop(): void;
153 onCancel(): void;
154 onSkipPostProcessing(): void;
155}) {
156 const gt = useGT();
157 const m = useMessages();
158 const { phase } = props.state;
159 const compact = props.size === "compact";
160 if (phase === "error") {
161 return (
162 <VoiceInputErrorPill
163 size={props.size}
164 error={props.state.error}
165 errorAction={props.state.errorAction}
166 errorCode={props.state.errorCode}
167 disabled={props.disabled ?? false}
168 cancelShortcutLabel={props.cancelShortcutLabel ?? null}
169 onRetry={props.onStart}
170 onDismiss={props.onCancel}
171 />
172 );
173 }
174 const presentation = resolveSpeechPresentation(props.state, props.progress, m);
175 if (!presentation.active) return null;
176 const recording = phase === "recording";
177 const trailing = recording || phase === "post-processing";
178
179 return (
180 <VoiceInputPill size={props.size}>
181 <ShortcutTooltip label={gt("Cancel voice input")} shortcut={props.cancelShortcutLabel}>
182 <Button
183 type="button"
184 size={compact ? "icon-xs" : "icon-sm-pill"}
185 variant="ghost"
186 aria-label={gt("Cancel voice input")}
187 onPointerDown={keepFocus}
188 onClick={props.onCancel}
189 className="shrink-0"
190 >
191 <XIcon />
192 </Button>
193 </ShortcutTooltip>
194 <div
195 className={cn(
196 "flex min-w-0 flex-1 items-center gap-2 overflow-hidden",
197 !trailing && "pe-2.5",
198 )}
199 role="status"
200 aria-live={recording ? "off" : "polite"}
201 aria-label={presentation.status ?? undefined}
202 >
203 {recording ? (
204 <RecordingStatus
205 level={props.level}
206 recordingStartedAt={props.recordingStartedAt}
207 recordingLimitSeconds={props.recordingLimitSeconds}
208 />
209 ) : (
210 <>
211 <Spinner aria-hidden size="sm" tone="muted" className="shrink-0" />
212 <span className="min-w-0 truncate text-sm text-muted-foreground">
213 {presentation.status}
214 </span>
215 </>
216 )}
217 </div>
218 {phase === "post-processing" ? (
219 <Button
220 type="button"
221 size={compact ? "xs" : "sm-pill"}
222 variant="ghost"
223 onPointerDown={keepFocus}
224 onClick={props.onSkipPostProcessing}
225 className="shrink-0"
226 >
227 {gt("Skip", { $context: "verb, skips cleaning up the transcript" })}
228 </Button>
229 ) : recording ? (
230 <ShortcutTooltip label={gt("Finish voice input")} shortcut={props.finishShortcutLabel}>
231 <Button
232 type="button"
233 size={compact ? "icon-xs" : "icon-sm-pill"}
234 aria-label={gt("Finish voice input")}
235 onPointerDown={keepFocus}
236 onClick={props.onStop}
237 className="shrink-0"
238 >
239 <CheckIcon />
240 </Button>
241 </ShortcutTooltip>
242 ) : null}
243 </VoiceInputPill>
244 );
245}