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, 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: environment.label }}.`
113 : gt`Download a speech model once. Your audio is transcribed on your transcription environment.`
114 : gt`Pick a microphone, then start talking.`
115 }
116 />
117 <WizardPanel>
118 {props.step === 0 ? (
119 <section className="space-y-3 text-sm">
120 {model ? (
121 <div className="space-y-3 rounded-lg border border-border/70 bg-card/60 p-3">
122 <div className="flex items-baseline justify-between gap-3">
123 <h3 className="min-w-0 truncate font-medium">{model.name}</h3>
124 <span className="shrink-0 text-xs text-muted-foreground tabular-nums">
125 {gt`${{ size: Math.round(model.size / 1024 / 1024) }} MB`}
126 </span>
127 </div>
128 <p className="text-xs text-muted-foreground">
129 {model.recommended && props.language ? (
130 <T>
131 Recommended for <Var>{languageName}</Var>. Includes a 1.2 MB silence
132 detector.
133 </T>
134 ) : (
135 <T>Includes a 1.2 MB silence detector.</T>
136 )}
137 </p>
138 {props.downloading ? (
139 <div role="status" className="space-y-1.5">
140 <div
141 role="progressbar"
142 aria-label={gt`Speech model download progress`}
143 aria-valuemin={0}
144 aria-valuemax={100}
145 aria-valuenow={progress ?? undefined}
146 className="h-1 overflow-hidden rounded-full bg-muted"
147 >
148 <div
149 className="h-full bg-primary transition-[width] duration-200"
150 style={{ width: `${progress ?? 0}%` }}
151 />
152 </div>
153 <p className="text-xs text-muted-foreground tabular-nums">
154 {model.state === "verifying"
155 ? gt`Verifying…`
156 : progress === null
157 ? gt`Starting download…`
158 : gt`${{ progress }}% downloaded`}
159 </p>
160 </div>
161 ) : null}
162 </div>
163 ) : !props.error ? (
164 <p role="status" className="text-muted-foreground">
165 <T>Loading transcription models…</T>
166 </p>
167 ) : null}
168 {props.error ? (
169 <p role="alert" className="flex items-start gap-1.5 text-destructive">
170 <CircleAlertIcon aria-hidden className="mt-0.5 size-3.5 shrink-0" />
171 {props.error}
172 </p>
173 ) : null}
174 </section>
175 ) : (
176 <section className="space-y-2 text-sm">
177 <label className="sr-only" htmlFor="voice-setup-microphone">
178 <T>Microphone</T>
179 </label>
180 <div className="flex items-center gap-2">
181 <Select
182 value={selectedMicrophone ? `device:${selectedMicrophone}` : "system-default"}
183 disabled={loadingMicrophones}
184 onValueChange={(value) => {
185 if (!value) return;
186 const deviceId = value.slice("device:".length);
187 const label =
188 microphones.find((device) => device.deviceId === deviceId)?.label ?? "";
189 updateMicrophoneOrder((order) =>
190 preferMicrophone(
191 order,
192 value === "system-default" || isSystemDefaultDeviceId(deviceId)
193 ? { kind: "default" }
194 : { kind: "device", deviceId, label },
195 ),
196 );
197 }}
198 >
199 <SelectTrigger
200 id="voice-setup-microphone"
201 size="sm"
202 aria-label={gt`Microphone`}
203 className="min-w-0 flex-1"
204 >
205 <MicIcon aria-hidden className="size-3.5 shrink-0 text-muted-foreground" />
206 <SelectValue>{selectedMicrophoneLabel}</SelectValue>
207 </SelectTrigger>
208 <SelectPopup align="end" alignItemWithTrigger={false}>
209 <SelectItem value="system-default">
210 <T>System default</T>
211 </SelectItem>
212 {selectedIsUnavailable ? (
213 <SelectItem value={`device:${selectedMicrophone}`}>
214 <T>Selected microphone (Unavailable)</T>
215 </SelectItem>
216 ) : null}
217 {microphones.map((device) => (
218 <SelectItem key={device.deviceId} value={`device:${device.deviceId}`}>
219 {device.label}
220 </SelectItem>
221 ))}
222 </SelectPopup>
223 </Select>
224 <Button
225 type="button"
226 variant="ghost"
227 size="icon-sm"
228 disabled={loadingMicrophones}
229 aria-label={gt`Refresh microphones`}
230 onClick={() => void refreshMicrophones()}
231 >
232 <RefreshCwIcon className="size-3.5" />
233 </Button>
234 </div>
235 {selectedIsUnavailable ? (
236 <p className="text-xs text-destructive">
237 <T>That microphone is unplugged. Pick another one.</T>
238 </p>
239 ) : null}
240 {microphoneError ? (
241 <p role="alert" className="text-xs text-muted-foreground">
242 {microphoneError}
243 </p>
244 ) : null}
245 </section>
246 )}
247 </WizardPanel>
248 {props.step === 0 ? (
249 <WizardFooter
250 leading={
251 <Button variant="ghost" onClick={() => openSettings("speech-models")}>
252 {model ? gt`Other models` : gt`Choose a model`}
253 </Button>
254 }
255 >
256 {props.onRetryCatalog ? (
257 <Button onClick={props.onRetryCatalog}>
258 <T>Retry loading models</T>
259 </Button>
260 ) : null}
261 {props.downloading ? (
262 <Button variant="outline" disabled={!canManage} onClick={props.onCancelDownload}>
263 <T>Cancel download</T>
264 </Button>
265 ) : null}
266 {model ? (
267 <Button
268 disabled={!canManage || props.downloading || !status}
269 onClick={props.onDownload}
270 >
271 {props.downloading
272 ? gt`Downloading…`
273 : props.error
274 ? gt`Try again`
275 : canManage
276 ? gt`Download model`
277 : gt`Needs an admin to download`}
278 </Button>
279 ) : null}
280 </WizardFooter>
281 ) : (
282 <WizardFooter
283 leading={
284 <Button variant="ghost" onClick={() => openSettings("")}>
285 <T>Voice settings</T>
286 </Button>
287 }
288 >
289 <Button onClick={props.onStartRecording}>
290 <MicIcon />
291 <T>Start dictating</T>
292 </Button>
293 </WizardFooter>
294 )}
295 </WizardPopup>
296 </Dialog>
297 );
298}