import { ScreenScrollView as ScrollView } from "../../components/ScreenScrollView"; import { useAtomSet, useAtomValue } from "@effect/atom-react"; import { AsyncResult } from "effect/reactivity"; import { getRecordingPermissionsAsync, requestRecordingPermissionsAsync } from "expo-audio"; import { useCallback, useEffect, useState } from "react"; import { AppState, Linking, Pressable, View } from "react-native"; import Reanimated, { ReduceMotion, useAnimatedStyle, withTiming } from "react-native-reanimated"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { type AppSymbolName, SymbolView } from "../../components/AppSymbol"; import { AppText as Text } from "../../components/AppText"; import { cn } from "../../lib/cn"; import { isMicrophoneDevice, type MicrophoneEntry, type MicrophoneKind, microphoneEntryKey, microphoneOrder, } from "../../lib/microphonePriority"; import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences"; import { SettingsActionRow } from "./components/SettingsActionRow"; import { SettingsDragHandle } from "./components/SettingsDragHandle"; import { SettingsSection } from "./components/SettingsSection"; const REMOVE_SIZE = 20; type MicrophonePermission = "checking" | "granted" | "ask" | "denied"; /** Re-reads microphone access whenever the app returns from system Settings. */ function useMicrophonePermission() { const [permission, setPermission] = useState("checking"); const apply = useCallback( (response: { readonly granted: boolean; readonly canAskAgain: boolean }) => setPermission(response.granted ? "granted" : response.canAskAgain ? "ask" : "denied"), [], ); const refresh = useCallback( () => void getRecordingPermissionsAsync().then(apply, () => setPermission("ask")), [apply], ); useEffect(() => { refresh(); const subscription = AppState.addEventListener("change", (state) => { if (state === "active") refresh(); }); return () => subscription.remove(); }, [refresh]); const request = useCallback( () => void requestRecordingPermissionsAsync().then(apply, refresh), [apply, refresh], ); return { permission, request }; } const KINDS: Record< MicrophoneKind, { /** Shown under a remembered device's name. */ readonly label: string; readonly row: string; readonly rowDescription: string; readonly icon: AppSymbolName; } > = { wired: { label: "Wired", row: "Other wired", rowDescription: "Headsets and USB microphones not listed", icon: "cable.connector", }, bluetooth: { label: "Bluetooth", row: "Other Bluetooth", rowDescription: "AirPods, headsets, and cars not listed", icon: "headphones", }, builtIn: { label: "Built-in", row: "Built-in microphone", rowDescription: "The microphone on this device", icon: "iphone", }, carPlay: { label: "CarPlay", row: "CarPlay", rowDescription: "The car’s microphone", icon: "car", }, }; /** * Microphone kinds and remembered devices, in the order voice input prefers * them. iOS only. A device joins the list the first time it is connected * during dictation; until then its kind's row ranks it. */ export function SettingsMicrophoneRouteScreen() { const insets = useSafeAreaInsets(); const preferencesResult = useAtomValue(mobilePreferencesAtom); const savePreferences = useAtomSet(updateMobilePreferencesAtom); const ready = AsyncResult.isSuccess(preferencesResult) && !preferencesResult.waiting; const entries = microphoneOrder( AsyncResult.isSuccess(preferencesResult) ? preferencesResult.value.microphones : undefined, ); const hasDevices = entries.some(isMicrophoneDevice); const { permission, request: requestPermission } = useMicrophonePermission(); const [editing, setEditing] = useState(false); const [drag, setDrag] = useState<{ readonly key: string; readonly translation: number } | null>( null, ); const [rowHeight, setRowHeight] = useState(0); // Each drop remounts the rows so the new order and the cleared offsets land in one frame. const [drops, setDrops] = useState(0); // Transforms apply to the stored order, so a device recorded meanwhile is kept. const move = (key: string, steps: number) => savePreferences({ transform: (current) => { const next = [...microphoneOrder(current.microphones)]; const from = next.findIndex((entry) => microphoneEntryKey(entry) === key); const to = Math.min(next.length - 1, Math.max(0, from + steps)); if (from === -1 || from === to) return {}; const [moved] = next.splice(from, 1); next.splice(to, 0, moved!); return { microphones: next }; }, }); const forget = (key: string) => savePreferences({ transform: (current) => ({ microphones: microphoneOrder(current.microphones).filter( (entry) => microphoneEntryKey(entry) !== key, ), }), }); // A lifted row takes a neighbour's slot once it has moved past half of that row. const dropSteps = (from: number, translation: number) => rowHeight === 0 ? 0 : Math.min(entries.length - 1, Math.max(0, from + Math.round(translation / rowHeight))) - from; const dragFrom = drag === null ? -1 : entries.findIndex((entry) => microphoneEntryKey(entry) === drag.key); const dragTo = drag === null ? -1 : dragFrom + dropSteps(dragFrom, drag.translation); return ( {permission === "ask" || permission === "denied" ? ( <> void Linking.openSettings() } /> {permission === "ask" ? "Voice input needs microphone access before it can record or list your microphones." : "Microphone access is off for T3 Code. Turn it on in Settings to use voice input."} ) : null} setEditing((value) => !value)} className="px-2 py-1 active:opacity-70" > {editing ? "Done" : "Edit"} ) : undefined } > {entries.map((entry, index) => { const key = microphoneEntryKey(entry); const shift = dragFrom === -1 || index === dragFrom ? 0 : dragFrom < dragTo && index > dragFrom && index <= dragTo ? -rowHeight : dragFrom > dragTo && index < dragFrom && index >= dragTo ? rowHeight : 0; return ( setDrag({ key, translation: 0 })} onDragMove={(translation) => setDrag({ key, translation })} onDragEnd={(translation, cancelled) => { setDrag(null); setDrops((count) => count + 1); if (!cancelled) move(key, dropSteps(index, translation)); }} onStep={(direction) => move(key, direction === "up" ? -1 : 1)} onForget={isMicrophoneDevice(entry) ? () => forget(key) : undefined} /> ); })} Voice input records from the first connected microphone in this list. Wired and Bluetooth devices are added by name after you use voice input with them connected; until then, the Other row ranks them. ); } function MicrophoneRow(props: { readonly entry: MicrophoneEntry; readonly position: number; readonly count: number; readonly reorderable: boolean; readonly editing: boolean; readonly offset: number; readonly lifted: boolean; readonly onHeight: (height: number) => void; readonly onDragStart: () => void; readonly onDragMove: (translation: number) => void; readonly onDragEnd: (translation: number, cancelled: boolean) => void; readonly onStep: (direction: "up" | "down") => void; readonly onForget: (() => void) | undefined; }) { const { lifted, offset, entry } = props; const kind = KINDS[entry.kind]; const title = isMicrophoneDevice(entry) ? entry.name : kind.row; const style = useAnimatedStyle(() => ({ transform: [ { translateY: lifted ? offset : withTiming(offset, { duration: 160, reduceMotion: ReduceMotion.System }), }, ], zIndex: lifted ? 1 : 0, })); return ( props.onHeight(event.nativeEvent.layout.height)} className={cn( "flex-row items-center gap-4 pl-4", props.position > 1 && !lifted && "border-t border-border-subtle", lifted && "bg-grouped-card shadow-md", !props.reorderable && "pr-4", )} > {props.editing && props.onForget ? ( ) : props.editing ? ( ) : null} {title} {isMicrophoneDevice(entry) ? kind.label : kind.rowDescription} {props.reorderable ? ( 1} canMoveDown={props.position < props.count} onStart={props.onDragStart} onMove={props.onDragMove} onEnd={props.onDragEnd} onStep={props.onStep} /> ) : null} ); }