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

VoiceInputSetup.tsx

302 lines12.4 KB

1import { T, Var, msg, useGT, useLocale } from "gt-react";
2import { m } from "~/i18n/messages";
3import { useStableCallback } from "~/hooks/useStableCallback";
4import {
5 listBrowserMicrophones,
6 updateMicrophoneOrder,
7 type BrowserMicrophone,
8} from "../../speech/browserMicrophones";
9import type {
10 EnvironmentId,
11 EnvironmentSpeechModel,
12 EnvironmentSpeechStatus,
13} from "@t3tools/contracts";
14import { useNavigate } from "@tanstack/react-router";
15import { CircleAlertIcon, MicIcon, RefreshCwIcon } from "lucide-react";
16import { useEffect, useRef, useState } from "react";
17​
18import { useClientSettings } from "../../hooks/useSettings";
19import {
20 isSystemDefaultDeviceId,
21 microphoneOrder,
22 preferMicrophone,
23 preferredMicrophoneId,
24} from "../../speech/microphoneOrder";
25import { useEnvironment } from "../../state/environments";
26import { AuthSettingsWriteScope } from "@t3tools/contracts";
27import { speechModelDownloadPercent } from "@t3tools/shared/speech";
28import { useEnvironmentScope } from "../../state/session";
29import { languageLabel } from "../settings/SpeechLanguageSelect";
30import { Button } from "../ui/button";
31import { Dialog } from "../ui/dialog";
32import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
33import { WizardFooter, WizardHeader, WizardPanel, WizardPopup } from "../ui/wizard";
34​
35export function VoiceInputSetup(props: {
36 environmentId: EnvironmentId | null;
37 open: boolean;
38 step: number;
39 status: EnvironmentSpeechStatus | null;
40 model: EnvironmentSpeechModel | null;
41 /** The language the offered model was chosen for. */
42 language: string | null;
43 downloading: boolean;
44 error: string | null;
45 onOpenChange(open: boolean): void;
46 onRetryCatalog: (() => void) | null;
47 onDownload(): void;
48 onCancelDownload(): void;
49 onStartRecording(): void;
50}) {
51 const gt = useGT();
52 const locale = useLocale();
53 const navigate = useNavigate();
54 const environment = useEnvironment(props.environmentId);
55 const languageName = props.language ? languageLabel(props.language, locale) : null;
56 const canManage = useEnvironmentScope(props.environmentId, AuthSettingsWriteScope);
57 const order = useClientSettings(microphoneOrder);
58 const [microphones, setMicrophones] = useState<BrowserMicrophone[]>([]);
59 const selectedMicrophone = preferredMicrophoneId(order, microphones);
60 const [loadingMicrophones, setLoadingMicrophones] = useState(false);
61 const [microphoneError, setMicrophoneError] = useState<string | null>(null);
62 const microphoneRefreshId = useRef(0);
63 const refreshMicrophones = useStableCallback(async () => {
64 if (!navigator.mediaDevices?.enumerateDevices) return;
65 const requestId = ++microphoneRefreshId.current;
66 setLoadingMicrophones(true);
67 const devices = await listBrowserMicrophones().catch(() => null);
68 if (requestId !== microphoneRefreshId.current) return;
69​
70 if (devices === null) {
71 setMicrophoneError(m(msg("Couldn’t list microphones. The system default still works.")));
72 } else {
73 setMicrophones(devices);
74 setMicrophoneError(null);
75 }
76 setLoadingMicrophones(false);
77 });
78 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to native microphone changes while the device setup step is visible
79 useEffect(() => {
80 if (!props.open || props.step !== 1) return;
81 queueMicrotask(() => void refreshMicrophones());
82 const mediaDevices = navigator.mediaDevices;
83 mediaDevices?.addEventListener?.("devicechange", refreshMicrophones);
84 return () => mediaDevices?.removeEventListener?.("devicechange", refreshMicrophones);
85 }, [props.open, props.step, refreshMicrophones]);
86 const selectedIsUnavailable = Boolean(
87 selectedMicrophone && !microphones.some((device) => device.deviceId === selectedMicrophone),
88 );
89 const selectedMicrophoneLabel = selectedMicrophone
90 ? (microphones.find((device) => device.deviceId === selectedMicrophone)?.label ??
91 gt("Selected microphone (Unavailable)"))
92 : gt("System default");
93 const status = props.status?.supported ? props.status : null;
94 const model = props.model;
95 const progress =
96 model?.downloaded === undefined
97 ? null
98 : speechModelDownloadPercent(model.downloaded, model.size);
99 const openSettings = (hash: string) => {
100 props.onOpenChange(false);
101 void navigate({ to: "/settings/voice", hash });
102 };
103​
104 return (
105 <Dialog open={props.open} onOpenChange={props.onOpenChange}>
106 <WizardPopup>
107 <WizardHeader
108 title={props.step === 0 ? gt("Set up voice input") : gt("Voice input is ready")}
109 description={
110 props.step === 0
111 ? environment?.label != null
112 ? gt("Download a speech model once. Your audio is transcribed on {destination}.", {
113 destination: environment.label,
114 })
115 : gt(
116 "Download a speech model once. Your audio is transcribed on your transcription environment.",
117 )
118 : gt("Pick a microphone, then start talking.")
119 }
120 />
121 <WizardPanel>
122 {props.step === 0 ? (
123 <section className="space-y-3 text-sm">
124 {model ? (
125 <div className="space-y-3 rounded-lg border border-border/70 bg-card/60 p-3">
126 <div className="flex items-baseline justify-between gap-3">
127 <h3 className="min-w-0 truncate font-medium">{model.name}</h3>
128 <span className="shrink-0 text-xs text-muted-foreground tabular-nums">
129 {gt("{size} MB", { size: Math.round(model.size / 1024 / 1024) })}
130 </span>
131 </div>
132 <p className="text-xs text-muted-foreground">
133 {model.recommended && props.language ? (
134 <T>
135 Recommended for <Var>{languageName}</Var>. Includes a 1.2 MB silence
136 detector.
137 </T>
138 ) : (
139 <T>Includes a 1.2 MB silence detector.</T>
140 )}
141 </p>
142 {props.downloading ? (
143 <div role="status" className="space-y-1.5">
144 <div
145 role="progressbar"
146 aria-label={gt("Speech model download progress")}
147 aria-valuemin={0}
148 aria-valuemax={100}
149 aria-valuenow={progress ?? undefined}
150 className="h-1 overflow-hidden rounded-full bg-muted"
151 >
152 <div
153 className="h-full bg-primary transition-[width] duration-200"
154 style={{ width: `${progress ?? 0}%` }}
155 />
156 </div>
157 <p className="text-xs text-muted-foreground tabular-nums">
158 {model.state === "verifying"
159 ? gt("Verifying…")
160 : progress === null
161 ? gt("Starting download…")
162 : gt("{progress}% downloaded", { progress })}
163 </p>
164 </div>
165 ) : null}
166 </div>
167 ) : !props.error ? (
168 <p role="status" className="text-muted-foreground">
169 <T>Loading transcription models…</T>
170 </p>
171 ) : null}
172 {props.error ? (
173 <p role="alert" className="flex items-start gap-1.5 text-destructive">
174 <CircleAlertIcon aria-hidden className="mt-0.5 size-3.5 shrink-0" />
175 {props.error}
176 </p>
177 ) : null}
178 </section>
179 ) : (
180 <section className="space-y-2 text-sm">
181 <label className="sr-only" htmlFor="voice-setup-microphone">
182 <T>Microphone</T>
183 </label>
184 <div className="flex items-center gap-2">
185 <Select
186 value={selectedMicrophone ? `device:${selectedMicrophone}` : "system-default"}
187 disabled={loadingMicrophones}
188 onValueChange={(value) => {
189 if (!value) return;
190 const deviceId = value.slice("device:".length);
191 const label =
192 microphones.find((device) => device.deviceId === deviceId)?.label ?? "";
193 updateMicrophoneOrder((order) =>
194 preferMicrophone(
195 order,
196 value === "system-default" || isSystemDefaultDeviceId(deviceId)
197 ? { kind: "default" }
198 : { kind: "device", deviceId, label },
199 ),
200 );
201 }}
202 >
203 <SelectTrigger
204 id="voice-setup-microphone"
205 size="sm"
206 aria-label={gt("Microphone")}
207 className="min-w-0 flex-1"
208 >
209 <MicIcon aria-hidden className="size-3.5 shrink-0 text-muted-foreground" />
210 <SelectValue>{selectedMicrophoneLabel}</SelectValue>
211 </SelectTrigger>
212 <SelectPopup align="end" alignItemWithTrigger={false}>
213 <SelectItem value="system-default">
214 <T>System default</T>
215 </SelectItem>
216 {selectedIsUnavailable ? (
217 <SelectItem value={`device:${selectedMicrophone}`}>
218 <T>Selected microphone (Unavailable)</T>
219 </SelectItem>
220 ) : null}
221 {microphones.map((device) => (
222 <SelectItem key={device.deviceId} value={`device:${device.deviceId}`}>
223 {device.label}
224 </SelectItem>
225 ))}
226 </SelectPopup>
227 </Select>
228 <Button
229 type="button"
230 variant="ghost"
231 size="icon-sm"
232 disabled={loadingMicrophones}
233 aria-label={gt("Refresh microphones")}
234 onClick={() => void refreshMicrophones()}
235 >
236 <RefreshCwIcon className="size-3.5" />
237 </Button>
238 </div>
239 {selectedIsUnavailable ? (
240 <p className="text-xs text-destructive">
241 <T>That microphone is unplugged. Pick another one.</T>
242 </p>
243 ) : null}
244 {microphoneError ? (
245 <p role="alert" className="text-xs text-muted-foreground">
246 {microphoneError}
247 </p>
248 ) : null}
249 </section>
250 )}
251 </WizardPanel>
252 {props.step === 0 ? (
253 <WizardFooter
254 leading={
255 <Button variant="ghost" onClick={() => openSettings("speech-models")}>
256 {model ? gt("Other models") : gt("Choose a model")}
257 </Button>
258 }
259 >
260 {props.onRetryCatalog ? (
261 <Button onClick={props.onRetryCatalog}>
262 <T>Retry loading models</T>
263 </Button>
264 ) : null}
265 {props.downloading ? (
266 <Button variant="outline" disabled={!canManage} onClick={props.onCancelDownload}>
267 <T>Cancel download</T>
268 </Button>
269 ) : null}
270 {model ? (
271 <Button
272 disabled={!canManage || props.downloading || !status}
273 onClick={props.onDownload}
274 >
275 {props.downloading
276 ? gt("Downloading…")
277 : props.error
278 ? gt("Try again")
279 : canManage
280 ? gt("Download model")
281 : gt("Needs an admin to download")}
282 </Button>
283 ) : null}
284 </WizardFooter>
285 ) : (
286 <WizardFooter
287 leading={
288 <Button variant="ghost" onClick={() => openSettings("")}>
289 <T>Voice settings</T>
290 </Button>
291 }
292 >
293 <Button onClick={props.onStartRecording}>
294 <MicIcon />
295 <T>Start dictating</T>
296 </Button>
297 </WizardFooter>
298 )}
299 </WizardPopup>
300 </Dialog>
301 );