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