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

SettingsMicrophoneRouteScreen.tsx

313 lines11.2 KB

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