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

SettingsVoiceRouteScreen.tsx

448 lines16.5 KB

1import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
2import { useAtomSet, useAtomValue } from "@effect/atom-react";
3import { AsyncResult } from "effect/reactivity";
4import { getRecordingPermissionsAsync, requestRecordingPermissionsAsync } from "expo-audio";
5import { useState } from "react";
6import { Linking, Platform, useWindowDimensions, View } from "react-native";
7import Reanimated, { ReduceMotion, useAnimatedStyle, withTiming } from "react-native-reanimated";
8import { useSafeAreaInsets } from "react-native-safe-area-context";
9​
10import { type AppSymbolName } from "../../components/ui/AppSymbol";
11import { AppText as Text } from "../../components/ui/AppText";
12import { cn } from "../../lib/cn";
13import { makePermissionStatusAtom } from "../../lib/permissionStatusAtom";
14import {
15 isMicrophoneDevice,
16 type MicrophoneEntry,
17 type MicrophoneKind,
18 microphoneEntryKey,
19} from "../../lib/microphonePriority";
20import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
21import { ListRowLayout } from "../../components/ui/ListRowLayout";
22import { ListChoiceRow } from "../../components/ui/ListChoiceRow";
23import * as Dialog from "../../components/ui/Dialog";
24import { useEnvironments, type EnvironmentPresentation } from "../../state/environments";
25import {
26 chooseVoiceDestination,
27 voiceConnectionAtom,
28 voiceGrantAtom,
29 voiceSpeechStatusAtom,
30 hasEnvironmentVoiceCapture,
31} from "../voice-input/voiceDestination";
32import { VoiceModelSection } from "./VoiceModelSection";
33import { CloudVoiceSection } from "./CloudVoiceSection";
34import type { EnvironmentId } from "@t3tools/contracts";
35import { ThreadSwipeable } from "../home/thread-swipe-actions";
36import { ListActionRow as SettingsActionRow } from "../../components/ui/ListActionRow";
37import { SettingsDragHandle } from "./components/SettingsDragHandle";
38import { SettingsScreen } from "./components/SettingsScreen";
39import { SettingsSection } from "./components/SettingsSection";
40import {
41 deviceMicrophoneOrder,
42 localVoiceTranscriberAtom,
43} from "../voice-input/VoiceInputProvider";
44​
45type MicrophonePermission = "checking" | "granted" | "ask" | "denied";
46​
47function toMicrophonePermission(response: {
48 readonly granted: boolean;
49 readonly canAskAgain: boolean;
50}): MicrophonePermission {
51 return response.granted ? "granted" : response.canAskAgain ? "ask" : "denied";
53​
54const readMicrophonePermission = () =>
55 getRecordingPermissionsAsync().then(toMicrophonePermission, (): MicrophonePermission => "ask");
56​
57const microphonePermissionAtom = makePermissionStatusAtom<MicrophonePermission>({
58 label: "mobile:microphone-permission",
59 initial: "checking",
60 read: readMicrophonePermission,
61});
62​
63function useMicrophonePermission() {
64 const permission = useAtomValue(microphonePermissionAtom);
65 const setPermission = useAtomSet(microphonePermissionAtom);
66 const request = () =>
67 void requestRecordingPermissionsAsync()
68 .then(toMicrophonePermission, readMicrophonePermission)
69 .then(setPermission);
70 return { permission, request };
72​
73const KINDS: Record<
74 MicrophoneKind,
75 {
76 readonly label: string;
77 readonly row: string;
78 readonly rowDescription: string;
79 readonly icon: AppSymbolName;
80 }
81> = {
82 wired: {
83 label: "Wired",
84 row: "Other wired",
85 rowDescription: "Headsets and USB microphones not listed here",
86 icon: "cable.connector",
87 },
88 bluetooth: {
89 label: "Bluetooth",
90 row: "Other Bluetooth",
91 rowDescription:
92 Platform.OS === "android"
93 ? "Earbuds, headsets, and cars, including Android Auto, not listed here"
94 : "AirPods, headsets, and cars not listed here",
95 icon: "headphones",
96 },
97 builtIn: {
98 label: "Built-in",
99 row: "Built-in microphone",
100 rowDescription: "The microphone on this device",
101 icon: "iphone",
102 },
103 carPlay: {
104 label: "CarPlay",
105 row: "CarPlay",
106 rowDescription: "The car’s microphone",
107 icon: "car",
108 },
109};
110​
111const UNAVAILABLE_EXPLANATION =
112 Platform.OS === "android"
113 ? "Dictation on this device needs Android 12 or later and Google speech services that support your language. Your keyboard’s voice typing is separate."
114 : "Dictation on this device needs iOS 26 or later, a supported device, and a supported language. Your keyboard’s dictation is separate.";
115​
116function saveDestination(id: EnvironmentId | null) {
117 try {
118 chooseVoiceDestination(id);
119 } catch {
120 Dialog.alert(
121 "Could not save transcription choice",
122 "Dictation on an environment is off for this session. Save again before closing the app, or your previous choice may return when it restarts.",
123 );
124 }
126​
127function EnvironmentChoice({
128 environment,
129 selected,
130}: {
131 environment: EnvironmentPresentation;
132 selected: boolean;
133}) {
134 const usable = useAtomValue(voiceConnectionAtom(environment.environmentId)) !== null;
135 const status = AsyncResult.getOrElse(
136 useAtomValue(voiceSpeechStatusAtom(environment.environmentId)),
137 () => null,
138 );
139 return (
140 <ListChoiceRow
141 label={environment.label}
142 selected={selected}
143 disabled={!usable}
144 description={
145 !usable
146 ? environment.connection.phase !== "connected"
147 ? "Not connected"
148 : "Transcription unavailable"
149 : status?.supported === false
150 ? status.reason
151 : status?.state === "missing-model"
152 ? "No transcription model installed"
153 : (environment.displayUrl ?? "Send finished recordings to this environment.")
154 }
155 separated
156 onPress={() => {
157 if (!selected)
158 Dialog.confirm({
159 title: `Send microphone audio to ${environment.label}?`,
160 message: `Finished recordings will be sent to ${environment.displayUrl ?? environment.label} for transcription. You can switch back to This device at any time.`,
161 confirmText: "Use environment",
162 onConfirm: () => saveDestination(environment.environmentId),
163 });
164 }}
165 />
166 );
168​
169export function SettingsVoiceRouteScreen() {
170 const transcriber = useAtomValue(localVoiceTranscriberAtom);
171 const grant = useAtomValue(voiceGrantAtom);
172 const { environments, isReady } = useEnvironments();
173 const grantEnvironment = grant
174 ? environments.find(
175 (environment) => environment.environmentId === grant.destination.environmentId,
176 )
177 : undefined;
178 const insets = useSafeAreaInsets();
179 const preferencesResult = useAtomValue(mobilePreferencesAtom);
180 const savePreferences = useAtomSet(updateMobilePreferencesAtom);
181 const ready = AsyncResult.isSuccess(preferencesResult) && !preferencesResult.waiting;
182 const entries = deviceMicrophoneOrder(
183 AsyncResult.isSuccess(preferencesResult) ? preferencesResult.value.microphones : undefined,
184 );
185 const { permission, request: requestPermission } = useMicrophonePermission();
186 const [drag, setDrag] = useState<{ readonly key: string; readonly translation: number } | null>(
187 null,
188 );
189 const [rowHeight, setRowHeight] = useState(0);
190 // Each drop remounts the rows so the new order and the cleared offsets land in one frame.
191 const [drops, setDrops] = useState(0);
192​
193 // Transforms apply to the stored order, so a device recorded meanwhile is kept.
194 const move = (key: string, steps: number) =>
195 savePreferences({
196 transform: (current) => {
197 const next = [...deviceMicrophoneOrder(current.microphones)];
198 const from = next.findIndex((entry) => microphoneEntryKey(entry) === key);
199 const to = Math.min(next.length - 1, Math.max(0, from + steps));
200 if (from === -1 || from === to) return {};
201 const [moved] = next.splice(from, 1);
202 next.splice(to, 0, moved!);
203 return { microphones: next };
204 },
205 });
206 const forget = (key: string) =>
207 savePreferences({
208 transform: (current) => ({
209 microphones: deviceMicrophoneOrder(current.microphones).filter(
210 (entry) => microphoneEntryKey(entry) !== key,
211 ),
212 }),
213 });
214 const dropSteps = (from: number, translation: number) =>
215 rowHeight === 0
216 ? 0
217 : Math.min(entries.length - 1, Math.max(0, from + Math.round(translation / rowHeight))) -
218 from;
219​
220 const dragFrom =
221 drag === null ? -1 : entries.findIndex((entry) => microphoneEntryKey(entry) === drag.key);
222 const dragTo = drag === null ? -1 : dragFrom + dropSteps(dragFrom, drag.translation);
223​
224 return (
225 <SettingsScreen title="Voice">
226 <ScrollView
227 contentInsetAdjustmentBehavior="automatic"
228 showsVerticalScrollIndicator={false}
229 className="flex-1"
230 contentContainerClassName="gap-3 px-5 pt-4"
231 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
232 >
233 <SettingsSection title="Transcribe on">
234 <ListChoiceRow
235 label="This device"
236 description="Audio stays on this device and is transcribed here."
237 selected={!grant}
238 onPress={() => saveDestination(null)}
239 />
240 {hasEnvironmentVoiceCapture &&
241 environments.map((environment) => (
242 <EnvironmentChoice
243 key={environment.environmentId}
244 environment={environment}
245 selected={
246 grant?.destination.kind === "environment" &&
247 grant.destination.environmentId === environment.environmentId
248 }
249 />
250 ))}
251 {isReady && grant && !grantEnvironment ? (
252 <ListChoiceRow
253 label="Previously selected environment"
254 description="No longer paired"
255 separated
256 selected
257 disabled
258 onPress={() => {}}
259 />
260 ) : null}
261 </SettingsSection>
262 {hasEnvironmentVoiceCapture &&
263 environments
264 .filter(
265 (env) =>
266 env.serverConfig?.environment.capabilities.cloudVoiceTranscription ||
267 (grant?.destination.kind === "cloud" &&
268 grant.destination.environmentId === env.environmentId),
269 )
270 .map((environment) => (
271 <CloudVoiceSection
272 key={environment.environmentId}
273 environment={environment}
274 active={
275 grant?.destination.kind === "cloud" &&
276 grant.destination.environmentId === environment.environmentId
277 ? grant.destination
278 : null
279 }
280 />
281 ))}
282 {grantEnvironment && grant?.destination.kind === "environment" ? (
283 <VoiceModelSection
284 environmentId={grantEnvironment.environmentId}
285 label={grantEnvironment.label}
286 />
287 ) : null}
288 {!grant && transcriber === null ? (
289 <Text className="px-2 text-sm text-foreground-muted">{UNAVAILABLE_EXPLANATION}</Text>
290 ) : null}
291 {permission === "ask" || permission === "denied" ? (
292 <>
293 <SettingsSection title="Microphone access">
294 <SettingsActionRow
295 icon="mic"
296 label={permission === "ask" ? "Allow microphone access" : "Open Settings"}
297 onPress={
298 permission === "ask" ? requestPermission : () => void Linking.openSettings()
299 }
300 />
301 </SettingsSection>
302 <Text className="px-2 text-sm text-foreground-muted">
303 {permission === "ask"
304 ? "Allow microphone access to record and to see your microphones."
305 : "Turn on microphone access for T3 Code in Settings to use voice input."}
306 </Text>
307 </>
308 ) : null}
309 <SettingsSection title="Preferred order">
310 {entries.map((entry, index) => {
311 const key = microphoneEntryKey(entry);
312 const shift =
313 dragFrom === -1 || index === dragFrom
314 ? 0
315 : dragFrom < dragTo && index > dragFrom && index <= dragTo
316 ? -rowHeight
317 : dragFrom > dragTo && index < dragFrom && index >= dragTo
318 ? rowHeight
319 : 0;
320 return (
321 <MicrophoneRow
322 key={`${key}:${drops}`}
323 entry={entry}
324 position={index + 1}
325 count={entries.length}
326 reorderable={ready}
327 offset={index === dragFrom ? (drag?.translation ?? 0) : shift}
328 lifted={index === dragFrom}
329 onHeight={setRowHeight}
330 onDragStart={() => setDrag({ key, translation: 0 })}
331 onDragMove={(translation) => setDrag({ key, translation })}
332 onDragEnd={(translation, cancelled) => {
333 setDrag(null);
334 setDrops((count) => count + 1);
335 if (!cancelled) move(key, dropSteps(index, translation));
336 }}
337 onStep={(direction) => move(key, direction === "up" ? -1 : 1)}
338 onForget={isMicrophoneDevice(entry) ? () => forget(key) : undefined}
339 />
340 );
341 })}
342 </SettingsSection>
343 <Text className="px-2 text-sm text-foreground-muted">
344 Voice input uses the first connected microphone in this list. A wired or Bluetooth
345 microphone is added by name the first time you dictate with it connected; until then it
346 falls under Other. Swipe left on a named microphone to forget it.
347 {Platform.OS === "android"
348 ? " Android may still use a different microphone if the preferred one can’t be routed."
349 : null}
350 </Text>
351 </ScrollView>
352 </SettingsScreen>
353 );
355​
356function MicrophoneRow(props: {
357 readonly entry: MicrophoneEntry;
358 readonly position: number;
359 readonly count: number;
360 readonly reorderable: boolean;
361 readonly offset: number;
362 readonly lifted: boolean;
363 readonly onHeight: (height: number) => void;
364 readonly onDragStart: () => void;
365 readonly onDragMove: (translation: number) => void;
366 readonly onDragEnd: (translation: number, cancelled: boolean) => void;
367 readonly onStep: (direction: "up" | "down") => void;
368 readonly onForget: (() => void) | undefined;
369}) {
370 const { lifted, offset, entry, onForget } = props;
371 const kind = KINDS[entry.kind];
372 const title = isMicrophoneDevice(entry) ? entry.name : kind.row;
373 const { width: windowWidth } = useWindowDimensions();
374 const style = useAnimatedStyle(() => ({
375 transform: [
376 {
377 translateY: lifted
378 ? offset
379 : withTiming(offset, { duration: 160, reduceMotion: ReduceMotion.System }),
380 },
381 ],
382 zIndex: lifted ? 1 : 0,
383 }));
384 const row = (
385 // Opaque so the swipe actions stay hidden until the row slides over them.
386 <View className="flex-row items-center bg-grouped-card">
387 <View
388 accessible
389 accessibilityLabel={`${title}, ${kind.label}, ${props.position} of ${props.count}`}
390 accessibilityActions={onForget ? [{ name: "forget", label: "Forget" }] : undefined}
391 onAccessibilityAction={({ nativeEvent }) => {
392 if (nativeEvent.actionName === "forget") onForget?.();
393 }}
394 className="min-w-0 flex-1"
395 >
396 <ListRowLayout
397 icon={kind.icon}
398 label={title}
399 description={isMicrophoneDevice(entry) ? kind.label : kind.rowDescription}
400 />
401 </View>
402 {props.reorderable ? (
403 <SettingsDragHandle
404 title={title}
405 canMoveUp={props.position > 1}
406 canMoveDown={props.position < props.count}
407 onStart={props.onDragStart}
408 onMove={props.onDragMove}
409 onEnd={props.onDragEnd}
410 onStep={props.onStep}
411 />
412 ) : null}
413 </View>
414 );
415 return (
416 <Reanimated.View
417 style={style}
418 onLayout={(event) => props.onHeight(event.nativeEvent.layout.height)}
419 className={cn(
420 props.position > 1 && !lifted && "border-t border-border-subtle",
421 lifted && "bg-grouped-card shadow-md",
422 )}
423 >
424 {onForget ? (
425 <ThreadSwipeable
426 backgroundColor="transparent"
427 fullSwipeAction="primary"
428 fullSwipeWidth={windowWidth - 40}
429 onDelete={onForget}
430 primaryAction={{
431 accessibilityLabel: `Forget ${title}`,
432 destructive: true,
433 icon: "trash",
434 label: "Forget",
435 onPress: onForget,
436 }}
437 secondaryAction={null}
438 threadKey={`microphone:${microphoneEntryKey(entry)}`}
439 threadTitle={title}
440 >
441 {() => row}
442 </ThreadSwipeable>
443 ) : (
444 row
445 )}
446 </Reanimated.View>
447 );