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

SettingsVoiceRouteScreen.tsx

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