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

SettingsMicrophoneRouteScreen.tsx

316 lines11.3 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 { useCallback, useEffect, useState } from "react";
6import { AppState, Linking, Pressable, 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, SymbolView } from "../../components/ui/AppSymbol";
11import { AppText as Text } from "../../components/ui/AppText";
12import { cn } from "../../lib/cn";
13import {
14 isMicrophoneDevice,
15 type MicrophoneEntry,
16 type MicrophoneKind,
17 microphoneEntryKey,
18 microphoneOrder,
19} from "../../lib/microphonePriority";
20import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
21import { SettingsActionRow } from "./components/SettingsActionRow";
22import { SettingsDragHandle } from "./components/SettingsDragHandle";
23import { SettingsSection } from "./components/SettingsSection";
24​
25const REMOVE_SIZE = 20;
26​
27type MicrophonePermission = "checking" | "granted" | "ask" | "denied";
28​
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 readonly label: string;
58 readonly row: string;
59 readonly rowDescription: string;
60 readonly icon: AppSymbolName;
61 }
62> = {
63 wired: {
64 label: "Wired",
65 row: "Other wired",
66 rowDescription: "Headsets and USB microphones not listed",
67 icon: "cable.connector",
68 },
69 bluetooth: {
70 label: "Bluetooth",
71 row: "Other Bluetooth",
72 rowDescription: "AirPods, headsets, and cars not listed",
73 icon: "headphones",
74 },
75 builtIn: {
76 label: "Built-in",
77 row: "Built-in microphone",
78 rowDescription: "The microphone on this device",
79 icon: "iphone",
80 },
81 carPlay: {
82 label: "CarPlay",
83 row: "CarPlay",
84 rowDescription: "The car’s microphone",
85 icon: "car",
86 },
87};
88​
89export function SettingsMicrophoneRouteScreen() {
90 const insets = useSafeAreaInsets();
91 const preferencesResult = useAtomValue(mobilePreferencesAtom);
92 const savePreferences = useAtomSet(updateMobilePreferencesAtom);
93 const ready = AsyncResult.isSuccess(preferencesResult) && !preferencesResult.waiting;
94 const entries = microphoneOrder(
95 AsyncResult.isSuccess(preferencesResult) ? preferencesResult.value.microphones : undefined,
96 );
97 const hasDevices = entries.some(isMicrophoneDevice);
98 const { permission, request: requestPermission } = useMicrophonePermission();
99 const [editing, setEditing] = useState(false);
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
166 title="Preferred order"
167 trailing={
168 hasDevices ? (
169 <Pressable
170 accessibilityRole="button"
171 onPress={() => setEditing((value) => !value)}
172 className="px-2 py-1 active:opacity-70"
173 >
174 <Text className="text-sm font-t3-medium text-foreground">
175 {editing ? "Done" : "Edit"}
176 </Text>
177 </Pressable>
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 );
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 gap-4 pl-4",
259 props.position > 1 && !lifted && "border-t border-border-subtle",
260 lifted && "bg-grouped-card shadow-md",
261 !props.reorderable && "pr-4",
262 )}
263 >
264 {props.editing && props.onForget ? (
265 <Pressable
266 accessibilityRole="button"
267 accessibilityLabel={`Forget ${title}`}
268 hitSlop={8}
269 onPress={props.onForget}
270 className="active:opacity-70"
271 >
272 <SymbolView
273 name="xmark.circle.fill"
274 size={REMOVE_SIZE}
275 tintColorClassName="accent-danger-foreground"
276 type="monochrome"
277 />
278 </Pressable>
279 ) : props.editing ? (
280 <View style={{ width: REMOVE_SIZE }} />
281 ) : null}
282 <View
283 accessible
284 accessibilityLabel={`${title}, ${kind.label}, ${props.position} of ${props.count}`}
285 className="min-w-0 flex-1 flex-row items-center gap-4 py-4"
286 >
287 <SymbolView
288 name={kind.icon}
289 size={22}
290 tintColorClassName="accent-icon"
291 type="monochrome"
292 weight="regular"
293 />
294 <View className="min-w-0 flex-1 gap-0.5">
295 <Text numberOfLines={1} className="text-lg text-foreground">
296 {title}
297 </Text>
298 <Text numberOfLines={1} className="text-sm text-foreground-muted">
299 {isMicrophoneDevice(entry) ? kind.label : kind.rowDescription}
300 </Text>
301 </View>
302 </View>
303 {props.reorderable ? (
304 <SettingsDragHandle
305 title={title}
306 canMoveUp={props.position > 1}
307 canMoveDown={props.position < props.count}
308 onStart={props.onDragStart}
309 onMove={props.onDragMove}
310 onEnd={props.onDragEnd}
311 onStep={props.onStep}
312 />
313 ) : null}
314 </Reanimated.View>
315 );