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