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