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

VoiceInputSetup.tsx

294 lines12.1 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 preferredMicrophone,
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 selectedEntry = preferredMicrophone(order, microphones);
60 const selectedMicrophone = selectedEntry.kind === "device" ? selectedEntry.deviceId : "";
61 const [loadingMicrophones, setLoadingMicrophones] = useState(false);
62 const [microphoneError, setMicrophoneError] = useState<string | null>(null);
63 const microphoneRefreshId = useRef(0);
64 const refreshMicrophones = useStableCallback(async () => {
65 if (!navigator.mediaDevices?.enumerateDevices) return;
66 const requestId = ++microphoneRefreshId.current;
67 setLoadingMicrophones(true);
68 const devices = await listBrowserMicrophones().catch(() => null);
69 if (requestId !== microphoneRefreshId.current) return;
70​
71 if (devices === null) {
72 setMicrophoneError(m(msg("Couldn’t list microphones. The system default still works.")));
73 } else {
74 setMicrophones(devices);
75 setMicrophoneError(null);
76 }
77 setLoadingMicrophones(false);
78 });
79 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to native microphone changes while the device setup step is visible
80 useEffect(() => {
81 if (!props.open || props.step !== 1) return;
82 queueMicrotask(() => void refreshMicrophones());
83 const mediaDevices = navigator.mediaDevices;
84 mediaDevices?.addEventListener?.("devicechange", refreshMicrophones);
85 return () => mediaDevices?.removeEventListener?.("devicechange", refreshMicrophones);
86 }, [props.open, props.step, refreshMicrophones]);
87 const selectedDevice = selectedMicrophone
88 ? microphones.find((device) => device.deviceId === selectedMicrophone)
89 : undefined;
90 const selectedMicrophoneLabel =
91 selectedEntry.kind === "device" && selectedMicrophone
92 ? selectedDevice?.label || selectedEntry.label || gt`Saved microphone`
93 : gt`System default`;
94 const status = props.status?.supported ? props.status : null;
95 const model = props.model;
96 const progress =
97 model?.downloaded === undefined
98 ? null
99 : speechModelDownloadPercent(model.downloaded, model.size);
100 const openSettings = (hash: string) => {
101 props.onOpenChange(false);
102 void navigate({ to: "/settings/voice", hash });
103 };
104​
105 return (
106 <Dialog open={props.open} onOpenChange={props.onOpenChange}>
107 <WizardPopup>
108 <WizardHeader
109 title={props.step === 0 ? gt`Set up voice input` : gt`Voice input is ready`}
110 description={
111 props.step === 0
112 ? environment?.label != null
113 ? gt`Download a speech model once. Your audio is transcribed on ${{ destination: environment.label }}.`
114 : gt`Download a speech model once. Your audio is transcribed on your transcription environment.`
115 : gt`Pick a microphone, then start talking.`
116 }
117 />
118 <WizardPanel>
119 {props.step === 0 ? (
120 <section className="space-y-3 text-sm">
121 {model ? (
122 <div className="space-y-3 rounded-lg border border-border/70 bg-card/60 p-3">
123 <div className="flex items-baseline justify-between gap-3">
124 <h3 className="min-w-0 truncate font-medium">{model.name}</h3>
125 <span className="shrink-0 text-xs text-muted-foreground tabular-nums">
126 {gt`${{ size: Math.round(model.size / 1024 / 1024) }} MB`}
127 </span>
128 </div>
129 <p className="text-xs text-muted-foreground">
130 {model.recommended && props.language ? (
131 <T>
132 Recommended for <Var>{languageName}</Var>. Includes a 1.2 MB silence
133 detector.
134 </T>
135 ) : (
136 <T>Includes a 1.2 MB silence detector.</T>
137 )}
138 </p>
139 {props.downloading ? (
140 <div role="status" className="space-y-1.5">
141 <div
142 role="progressbar"
143 aria-label={gt`Speech model download progress`}
144 aria-valuemin={0}
145 aria-valuemax={100}
146 aria-valuenow={progress ?? undefined}
147 className="h-1 overflow-hidden rounded-full bg-muted"
148 >
149 <div
150 className="h-full bg-primary transition-[width] duration-200"
151 style={{ width: `${progress ?? 0}%` }}
152 />
153 </div>
154 <p className="text-xs text-muted-foreground tabular-nums">
155 {model.state === "verifying"
156 ? gt`Verifying…`
157 : progress === null
158 ? gt`Starting download…`
159 : gt`${{ progress }}% downloaded`}
160 </p>
161 </div>
162 ) : null}
163 </div>
164 ) : !props.error ? (
165 <p role="status" className="text-muted-foreground">
166 <T>Loading transcription models…</T>
167 </p>
168 ) : null}
169 {props.error ? (
170 <p role="alert" className="flex items-start gap-1.5 text-destructive">
171 <CircleAlertIcon aria-hidden className="mt-0.5 size-3.5 shrink-0" />
172 {props.error}
173 </p>
174 ) : null}
175 </section>
176 ) : (
177 <section className="space-y-2 text-sm">
178 <label className="sr-only" htmlFor="voice-setup-microphone">
179 <T>Microphone</T>
180 </label>
181 <div className="flex items-center gap-2">
182 <Select
183 value={selectedMicrophone ? `device:${selectedMicrophone}` : "system-default"}
184 disabled={loadingMicrophones}
185 onValueChange={(value) => {
186 if (!value) return;
187 const deviceId = value.slice("device:".length);
188 const label =
189 microphones.find((device) => device.deviceId === deviceId)?.label ?? "";
190 updateMicrophoneOrder((order) =>
191 preferMicrophone(
192 order,
193 value === "system-default" || isSystemDefaultDeviceId(deviceId)
194 ? { kind: "default" }
195 : { kind: "device", deviceId, label },
196 ),
197 );
198 }}
199 >
200 <SelectTrigger
201 id="voice-setup-microphone"
202 size="sm"
203 aria-label={gt`Microphone`}
204 className="min-w-0 flex-1"
205 >
206 <MicIcon aria-hidden className="size-3.5 shrink-0 text-muted-foreground" />
207 <SelectValue>{selectedMicrophoneLabel}</SelectValue>
208 </SelectTrigger>
209 <SelectPopup align="end" alignItemWithTrigger={false}>
210 <SelectItem value="system-default">
211 <T>System default</T>
212 </SelectItem>
213 {selectedMicrophone && !selectedDevice ? (
214 <SelectItem value={`device:${selectedMicrophone}`}>
215 {selectedMicrophoneLabel}
216 </SelectItem>
217 ) : null}
218 {microphones.map((device) => (
219 <SelectItem key={device.deviceId} value={`device:${device.deviceId}`}>
220 {device.label}
221 </SelectItem>
222 ))}
223 </SelectPopup>
224 </Select>
225 <Button
226 type="button"
227 variant="ghost"
228 size="icon-sm"
229 disabled={loadingMicrophones}
230 aria-label={gt`Refresh microphones`}
231 onClick={() => void refreshMicrophones()}
232 >
233 <RefreshCwIcon className="size-3.5" />
234 </Button>
235 </div>
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 );