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