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

SettingsMicrophoneRouteScreen.tsx

323 lines11.7 KB

1import { useAtomSet, useAtomValue } from "@effect/atom-react";
2import { AsyncResult } from "effect/reactivity";
3import { getRecordingPermissionsAsync, requestRecordingPermissionsAsync } from "expo-audio";
4import { useCallback, useEffect, useState } from "react";
5import { AppState, Linking, Pressable, ScrollView, View } from "react-native";
6import Reanimated, { ReduceMotion, useAnimatedStyle, withTiming } from "react-native-reanimated";
7import { useSafeAreaInsets } from "react-native-safe-area-context";
8​
9import { type AppSymbolName, SymbolView } from "../../components/AppSymbol";
10import { AppText as Text } from "../../components/AppText";
11import { cn } from "../../lib/cn";
12import {
13 isMicrophoneDevice,
14 type MicrophoneEntry,
15 type MicrophoneKind,
16 microphoneEntryKey,
17 microphoneOrder,
18} from "../../lib/microphonePriority";
19import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
20import { SettingsActionRow } from "./components/SettingsActionRow";
21import { SettingsDragHandle } from "./components/SettingsDragHandle";
22import { SettingsSection } from "./components/SettingsSection";
23​
24const REMOVE_SIZE = 20;
25​
26type MicrophonePermission = "checking" | "granted" | "ask" | "denied";
27​
28/** Re-reads microphone access whenever the app returns from system Settings. */
29function useMicrophonePermission() {
30 const [permission, setPermission] = useState<MicrophonePermission>("checking");
31 const apply = useCallback(
32 (response: { readonly granted: boolean; readonly canAskAgain: boolean }) =>
33 setPermission(response.granted ? "granted" : response.canAskAgain ? "ask" : "denied"),
34 [],
35 );
36 const refresh = useCallback(
37 () => void getRecordingPermissionsAsync().then(apply, () => setPermission("ask")),
38 [apply],
39 );
40 useEffect(() => {
41 refresh();
42 const subscription = AppState.addEventListener("change", (state) => {
43 if (state === "active") refresh();
44 });
45 return () => subscription.remove();
46 }, [refresh]);
47 const request = useCallback(
48 () => void requestRecordingPermissionsAsync().then(apply, refresh),
49 [apply, refresh],
50 );
51 return { permission, request };
53​
54const KINDS: Record<
55 MicrophoneKind,
56 {
57 /** Shown under a remembered device's name. */
58 readonly label: string;
59 readonly row: string;
60 readonly rowDescription: string;
61 readonly icon: AppSymbolName;
62 }
63> = {
64 wired: {
65 label: "Wired",
66 row: "Other wired",
67 rowDescription: "Headsets and USB microphones not listed",
68 icon: "cable.connector",
69 },
70 bluetooth: {
71 label: "Bluetooth",
72 row: "Other Bluetooth",
73 rowDescription: "AirPods, headsets, and cars not listed",
74 icon: "headphones",
75 },
76 builtIn: {
77 label: "Built-in",
78 row: "Built-in microphone",
79 rowDescription: "The microphone on this device",
80 icon: "iphone",
81 },
82 carPlay: {
83 label: "CarPlay",
84 row: "CarPlay",
85 rowDescription: "The car’s microphone",
86 icon: "car",
87 },
88};
89​
90/**
91 * Microphone kinds and remembered devices, in the order voice input prefers
92 * them. iOS only. A device joins the list the first time it is connected
93 * during dictation; until then its kind's row ranks it.
94 */
95export function SettingsMicrophoneRouteScreen() {
96 const insets = useSafeAreaInsets();
97 const preferencesResult = useAtomValue(mobilePreferencesAtom);
98 const savePreferences = useAtomSet(updateMobilePreferencesAtom);
99 const ready = AsyncResult.isSuccess(preferencesResult) && !preferencesResult.waiting;
100 const entries = microphoneOrder(
101 AsyncResult.isSuccess(preferencesResult) ? preferencesResult.value.microphones : undefined,
102 );
103 const hasDevices = entries.some(isMicrophoneDevice);
104 const { permission, request: requestPermission } = useMicrophonePermission();
105 const [editing, setEditing] = useState(false);
106 const [drag, setDrag] = useState<{ readonly key: string; readonly translation: number } | null>(
107 null,
108 );
109 const [rowHeight, setRowHeight] = useState(0);
110 // Each drop remounts the rows so the new order and the cleared offsets land in one frame.
111 const [drops, setDrops] = useState(0);
112​
113 // Transforms apply to the stored order, so a device recorded meanwhile is kept.
114 const move = (key: string, steps: number) =>
115 savePreferences({
116 transform: (current) => {
117 const next = [...microphoneOrder(current.microphones)];
118 const from = next.findIndex((entry) => microphoneEntryKey(entry) === key);
119 const to = Math.min(next.length - 1, Math.max(0, from + steps));
120 if (from === -1 || from === to) return {};
121 const [moved] = next.splice(from, 1);
122 next.splice(to, 0, moved!);
123 return { microphones: next };
124 },
125 });
126 const forget = (key: string) =>
127 savePreferences({
128 transform: (current) => ({
129 microphones: microphoneOrder(current.microphones).filter(
130 (entry) => microphoneEntryKey(entry) !== key,
131 ),
132 }),
133 });
134 // A lifted row takes a neighbour's slot once it has moved past half of that row.
135 const dropSteps = (from: number, translation: number) =>
136 rowHeight === 0
137 ? 0
138 : Math.min(entries.length - 1, Math.max(0, from + Math.round(translation / rowHeight))) -
139 from;
140​
141 const dragFrom =
142 drag === null ? -1 : entries.findIndex((entry) => microphoneEntryKey(entry) === drag.key);
143 const dragTo = drag === null ? -1 : dragFrom + dropSteps(dragFrom, drag.translation);
144​
145 return (
146 <View collapsable={false} className="flex-1 bg-sheet">
147 <ScrollView
148 contentInsetAdjustmentBehavior="automatic"
149 showsVerticalScrollIndicator={false}
150 className="flex-1"
151 contentContainerClassName="gap-3 px-5 pt-4"
152 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
153 >
154 {permission === "ask" || permission === "denied" ? (
155 <>
156 <SettingsSection title="Microphone access">
157 <SettingsActionRow
158 icon="mic"
159 label={permission === "ask" ? "Allow microphone access" : "Open Settings"}
160 onPress={
161 permission === "ask" ? requestPermission : () => void Linking.openSettings()
162 }
163 />
164 </SettingsSection>
165 <Text className="px-2 text-sm text-foreground-muted">
166 {permission === "ask"
167 ? "Voice input needs microphone access before it can record or list your microphones."
168 : "Microphone access is off for T3 Code. Turn it on in Settings to use voice input."}
169 </Text>
170 </>
171 ) : null}
172 <SettingsSection
173 title="Preferred order"
174 trailing={
175 hasDevices ? (
176 <Pressable
177 accessibilityRole="button"
178 onPress={() => setEditing((value) => !value)}
179 className="px-2 py-1 active:opacity-70"
180 >
181 <Text className="text-sm font-t3-medium text-foreground">
182 {editing ? "Done" : "Edit"}
183 </Text>
184 </Pressable>
185 ) : undefined
186 }
187 >
188 {entries.map((entry, index) => {
189 const key = microphoneEntryKey(entry);
190 const shift =
191 dragFrom === -1 || index === dragFrom
192 ? 0
193 : dragFrom < dragTo && index > dragFrom && index <= dragTo
194 ? -rowHeight
195 : dragFrom > dragTo && index < dragFrom && index >= dragTo
196 ? rowHeight
197 : 0;
198 return (
199 <MicrophoneRow
200 key={`${key}:${drops}`}
201 entry={entry}
202 position={index + 1}
203 count={entries.length}
204 reorderable={ready}
205 editing={editing && hasDevices}
206 offset={index === dragFrom ? (drag?.translation ?? 0) : shift}
207 lifted={index === dragFrom}
208 onHeight={setRowHeight}
209 onDragStart={() => setDrag({ key, translation: 0 })}
210 onDragMove={(translation) => setDrag({ key, translation })}
211 onDragEnd={(translation, cancelled) => {
212 setDrag(null);
213 setDrops((count) => count + 1);
214 if (!cancelled) move(key, dropSteps(index, translation));
215 }}
216 onStep={(direction) => move(key, direction === "up" ? -1 : 1)}
217 onForget={isMicrophoneDevice(entry) ? () => forget(key) : undefined}
218 />
219 );
220 })}
221 </SettingsSection>
222 <Text className="px-2 text-sm text-foreground-muted">
223 Voice input records from the first connected microphone in this list. Wired and Bluetooth
224 devices are added by name after you use voice input with them connected; until then, the
225 Other row ranks them.
226 </Text>
227 </ScrollView>
228 </View>
229 );
231​
232function MicrophoneRow(props: {
233 readonly entry: MicrophoneEntry;
234 readonly position: number;
235 readonly count: number;
236 readonly reorderable: boolean;
237 readonly editing: boolean;
238 readonly offset: number;
239 readonly lifted: boolean;
240 readonly onHeight: (height: number) => void;
241 readonly onDragStart: () => void;
242 readonly onDragMove: (translation: number) => void;
243 readonly onDragEnd: (translation: number, cancelled: boolean) => void;
244 readonly onStep: (direction: "up" | "down") => void;
245 readonly onForget: (() => void) | undefined;
246}) {
247 const { lifted, offset, entry } = props;
248 const kind = KINDS[entry.kind];
249 const title = isMicrophoneDevice(entry) ? entry.name : kind.row;
250 const style = useAnimatedStyle(() => ({
251 transform: [
252 {
253 translateY: lifted
254 ? offset
255 : withTiming(offset, { duration: 160, reduceMotion: ReduceMotion.System }),
256 },
257 ],
258 zIndex: lifted ? 1 : 0,
259 }));
260 return (
261 <Reanimated.View
262 style={style}
263 onLayout={(event) => props.onHeight(event.nativeEvent.layout.height)}
264 className={cn(
265 "flex-row items-center gap-4 pl-4",
266 props.position > 1 && !lifted && "border-t border-border-subtle",
267 lifted && "bg-grouped-card shadow-md",
268 !props.reorderable && "pr-4",
269 )}
270 >
271 {props.editing && props.onForget ? (
272 <Pressable
273 accessibilityRole="button"
274 accessibilityLabel={`Forget ${title}`}
275 hitSlop={8}
276 onPress={props.onForget}
277 className="active:opacity-70"
278 >
279 <SymbolView
280 name="xmark.circle.fill"
281 size={REMOVE_SIZE}
282 tintColorClassName="accent-danger-foreground"
283 type="monochrome"
284 />
285 </Pressable>
286 ) : props.editing ? (
287 <View style={{ width: REMOVE_SIZE }} />
288 ) : null}
289 <View
290 accessible
291 accessibilityLabel={`${title}, ${kind.label}, ${props.position} of ${props.count}`}
292 className="min-w-0 flex-1 flex-row items-center gap-4 py-4"
293 >
294 <SymbolView
295 name={kind.icon}
296 size={22}
297 tintColorClassName="accent-icon"
298 type="monochrome"
299 weight="regular"
300 />
301 <View className="min-w-0 flex-1 gap-0.5">
302 <Text numberOfLines={1} className="text-lg text-foreground">
303 {title}
304 </Text>
305 <Text numberOfLines={1} className="text-sm text-foreground-muted">
306 {isMicrophoneDevice(entry) ? kind.label : kind.rowDescription}
307 </Text>
308 </View>
309 </View>
310 {props.reorderable ? (
311 <SettingsDragHandle
312 title={title}
313 canMoveUp={props.position > 1}
314 canMoveDown={props.position < props.count}
315 onStart={props.onDragStart}
316 onMove={props.onDragMove}
317 onEnd={props.onDragEnd}
318 onStep={props.onStep}
319 />
320 ) : null}
321 </Reanimated.View>
322 );