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