Skip to content

Colota - Android GPS Location tracker

feat(profiles): pick the Bluetooth device on its own screen (#980)

Max Dietricha8b0c20461e7
diff --git a/apps/docs/docs/development/permissions.md b/apps/docs/docs/development/permissions.md
index f8db63ad..448991c9 100644
--- a/apps/docs/docs/development/permissions.md
+++ b/apps/docs/docs/development/permissions.md
@@ -39,7 +39,7 @@ Only the two location permissions are required. The app does not request anythin
The **Local Network Permission** (Android 17+) is not part of this sequence. It is requested separately when you use **Test connection** with a local/private server endpoint.
-The **Nearby Devices** permission (Android 12+) is not part of the sequence either. The profile editor asks for it when you pick the **Bluetooth device** condition.
+The **Nearby Devices** permission (Android 12+) is not part of the sequence either. The device list of the **Bluetooth device** condition asks for it.
## Detailed Explanations
diff --git a/apps/docs/docs/guides/tracking-profiles.md b/apps/docs/docs/guides/tracking-profiles.md
index 0dc8e729..19f3e626 100644
--- a/apps/docs/docs/guides/tracking-profiles.md
+++ b/apps/docs/docs/guides/tracking-profiles.md
@@ -52,7 +52,7 @@ A stationary profile records less often, but GPS stays on. To stop GPS while you
Wi-Fi conditions react to network changes as they happen. A lost connection deactivates after the profile's deactivation delay — set it to 0 if you want the profile to drop the instant the network disappears. New Wi-Fi / Wi-Fi network profiles get the usual 0 s activation and 60 s deactivation defaults.
-The Bluetooth device condition is for cars without Android Auto: pick the car's audio system from your paired devices and the profile applies while the phone is connected to it. The device is matched by its address, so renaming it does not break the profile. Listing paired devices and seeing connections needs the **Nearby devices** permission (Android 12+), which the editor offers to grant when you pick the condition. Without it the condition never matches. Like Wi-Fi, a disconnect deactivates after the profile's deactivation delay, which also rides out a short drop when the car restarts.
+The Bluetooth device condition is for cars without Android Auto: pick the car's audio system from your paired devices and the profile applies while the phone is connected to it. The device is matched by its address, so renaming it does not break the profile. Listing paired devices and seeing connections needs the **Nearby devices** permission (Android 12+), which the device list asks for. Without it the condition never matches. Like Wi-Fi, a disconnect deactivates after the profile's deactivation delay, which also rides out a short drop when the car restarts.
Speed conditions use a rolling average of the last 5 GPS readings to avoid triggering on momentary speed spikes. The stationary condition uses a fixed speed threshold (0.3 m/s) that has to hold across 60 seconds of fixes, so unlike speed-below it does not flap on GPS noise near zero. The window is measured over the fixes themselves, so a stretch with no fixes at all is not counted as stillness and the profile waits for the stream instead of switching on.
diff --git a/apps/mobile/App.tsx b/apps/mobile/App.tsx
index c9ba42f8..9ec182fc 100644
--- a/apps/mobile/App.tsx
+++ b/apps/mobile/App.tsx
@@ -38,6 +38,7 @@ import {
AboutScreen,
TrackingProfilesScreen,
ProfileEditorScreen,
+ BluetoothDeviceScreen,
SetupImportScreen,
ShareSetupScreen,
TripDetailScreen,
@@ -142,6 +143,11 @@ const SCREEN_CONFIG: readonly ScreenConfig[] = [
component: ProfileEditorScreen,
titleKey: "screen.profileEditor"
},
+ {
+ name: "Bluetooth Device",
+ component: BluetoothDeviceScreen,
+ titleKey: "screen.bluetoothDevice"
+ },
{
name: "About Colota",
component: AboutScreen,
diff --git a/apps/mobile/src/components/index.ts b/apps/mobile/src/components/index.ts
index dc5e2352..b1688cbf 100644
--- a/apps/mobile/src/components/index.ts
+++ b/apps/mobile/src/components/index.ts
@@ -21,7 +21,7 @@ export { HeaderAction } from "./ui/HeaderAction"
export { SectionTitle } from "./ui/SectionTitle"
export { Divider } from "./ui/Divider"
export { EmptyState } from "./ui/EmptyState"
-export { TextField } from "./ui/TextField"
+export { TextField, SelectField } from "./ui/TextField"
export { NumericInput } from "./ui/NumericInput"
export { TimePicker } from "./ui/TimePicker"
export { FloatingSaveIndicator } from "./ui/FloatingSaveIndicator"
diff --git a/apps/mobile/src/components/ui/TextField.tsx b/apps/mobile/src/components/ui/TextField.tsx
index 63531ebd..5eba19d8 100644
--- a/apps/mobile/src/components/ui/TextField.tsx
+++ b/apps/mobile/src/components/ui/TextField.tsx
@@ -6,10 +6,10 @@
import React, { forwardRef, useState } from "react"
import { View, Text, TextInput, Pressable, StyleSheet, StyleProp, ViewStyle } from "react-native"
import type { TextInputProps, TextInputInstance } from "react-native"
-import { Eye, EyeOff, CircleAlert } from "lucide-react-native"
+import { Eye, EyeOff, CircleAlert, ChevronRight } from "lucide-react-native"
import { useTheme } from "../../hooks/useTheme"
import { fontSizes, fonts } from "../../styles/typography"
-import { size, space, HIT_SLOP_MD } from "../../constants"
+import { size, space, HIT_SLOP_MD, STATE_LAYER_ALPHA } from "../../constants"
import { radius } from "@colota/shared"
import { FieldMessage } from "./FieldMessage"
@@ -134,6 +134,44 @@ export const TextField = forwardRef<TextInputInstance, TextFieldProps>(function
)
})
+type SelectFieldProps = {
+ label: string
+ value?: string
+ placeholder: string
+ onPress: () => void
+ error?: string
+ style?: StyleProp<ViewStyle>
+ testID?: string
+}
+
+/** TextField's look for a value picked on another screen: the box opens the picker instead of a keyboard. */
+export function SelectField({ label, value, placeholder, onPress, error, style, testID }: SelectFieldProps) {
+ const { colors } = useTheme()
+ const borderWidth = error ? 2 : 0
+
+ return (
+ <View style={style}>
+ <Text style={[styles.label, { color: colors.textSecondary }]}>{label}</Text>
+ <View style={[styles.selectBox, { borderWidth, borderColor: colors.error, backgroundColor: colors.well }]}>
+ <Pressable
+ testID={testID}
+ onPress={onPress}
+ accessibilityRole="button"
+ accessibilityLabel={[label, value ?? placeholder, error].filter(Boolean).join(", ")}
+ android_ripple={{ color: colors.text + STATE_LAYER_ALPHA }}
+ style={[styles.select, { paddingHorizontal: FIELD_INSET - borderWidth }]}
+ >
+ <Text numberOfLines={1} style={[styles.input, { color: value ? colors.text : colors.textLight }]}>
+ {value ?? placeholder}
+ </Text>
+ <ChevronRight size={size.icon.md} color={colors.textSecondary} />
+ </Pressable>
+ </View>
+ {error ? <FieldMessage variant="error">{error}</FieldMessage> : null}
+ </View>
+ )
+}
+
const styles = StyleSheet.create({
label: {
fontSize: fontSizes.description,
@@ -163,6 +201,16 @@ const styles = StyleSheet.create({
...fonts.medium,
fontVariant: ["tabular-nums"]
},
+ selectBox: {
+ borderRadius: radius.sm,
+ overflow: "hidden"
+ },
+ select: {
+ flexDirection: "row",
+ alignItems: "center",
+ gap: space.sm,
+ minHeight: size.touch
+ },
boxMultiline: {
alignItems: "flex-start",
minHeight: MULTILINE_MIN_HEIGHT,
diff --git a/apps/mobile/src/components/ui/__tests__/TextField.test.tsx b/apps/mobile/src/components/ui/__tests__/TextField.test.tsx
index 1192e8d2..739e8c1c 100644
--- a/apps/mobile/src/components/ui/__tests__/TextField.test.tsx
+++ b/apps/mobile/src/components/ui/__tests__/TextField.test.tsx
@@ -7,7 +7,7 @@ jest.mock("../../../hooks/useTheme", () => ({
useTheme: () => ({ colors: require("@colota/shared").lightColors })
}))
-import { TextField } from "../TextField"
+import { TextField, SelectField } from "../TextField"
const flat = (el: any) => StyleSheet.flatten(el.props.style)
@@ -111,3 +111,38 @@ describe("TextField", () => {
expect(flat(getByTestId("server-input-box")).backgroundColor).not.toBe(lightColors.background)
})
})
+
+describe("SelectField", () => {
+ it("shows the picked value, or the placeholder until there is one, and opens the picker", () => {
+ const onPress = jest.fn()
+ const { getByText, getByTestId, rerender } = render(
+ <SelectField label="Device" placeholder="Pick a device" onPress={onPress} testID="device" />
+ )
+ expect(getByText("Pick a device")).toBeTruthy()
+
+ rerender(
+ <SelectField label="Device" value="My Car" placeholder="Pick a device" onPress={onPress} testID="device" />
+ )
+ expect(getByText("My Car")).toBeTruthy()
+
+ fireEvent.press(getByTestId("device"))
+ expect(onPress).toHaveBeenCalled()
+ })
+
+ // Same rule as TextField: the ring marks the error and the padding gives its width back.
+ it("grows the error ring without moving the value and names the error to a screen reader", () => {
+ const { getByTestId, getByText } = render(
+ <SelectField
+ label="Device"
+ placeholder="Pick a device"
+ error="Pick a device first"
+ onPress={() => {}}
+ testID="device"
+ />
+ )
+
+ expect(flat(getByTestId("device")).paddingHorizontal + 2).toBe(15)
+ expect(getByText("Pick a device first")).toBeTruthy()
+ expect(getByTestId("device").props.accessibilityLabel).toBe("Device, Pick a device, Pick a device first")
+ })
+})
diff --git a/apps/mobile/src/i18n/locales/en.json b/apps/mobile/src/i18n/locales/en.json
index cfb8e594..3ee4da43 100644
--- a/apps/mobile/src/i18n/locales/en.json
+++ b/apps/mobile/src/i18n/locales/en.json
@@ -742,12 +742,18 @@
"profileEditor.activation.hint": "How long the condition must hold first. 0 switches at once, longer ignores a brief plug or unplug.",
"profileEditor.activation.hintStationary": "How long every fix must read as still; 0 switches at the first still fix. Moving again ends the profile at once.",
"profileEditor.bluetooth.allow": "Allow Nearby devices",
+ "profileEditor.bluetooth.device": "Device",
"profileEditor.bluetooth.empty": "Pick a device or the profile can't match",
"profileEditor.bluetooth.hint": "Matches while the phone is connected to this device, such as your car's audio system.",
- "profileEditor.bluetooth.noDevices": "No paired devices. Pair one in Bluetooth settings, then come back.",
- "profileEditor.bluetooth.off": "Bluetooth is off. Turn it on to see your paired devices.",
+ "profileEditor.bluetooth.noDevices": "No paired devices",
+ "profileEditor.bluetooth.noDevices.hint": "Pair one in Bluetooth settings, then come back.",
+ "profileEditor.bluetooth.off": "Bluetooth is off",
+ "profileEditor.bluetooth.off.hint": "Turn it on to see your paired devices.",
+ "profileEditor.bluetooth.openBluetoothSettings": "Open Bluetooth settings",
"profileEditor.bluetooth.openSettings": "Open app settings",
"profileEditor.bluetooth.permission": "Colota needs the Nearby devices permission to see your paired devices and when one connects. It doesn't search for new devices or connect to any.",
+ "profileEditor.bluetooth.permission.title": "Nearby devices not allowed",
+ "profileEditor.bluetooth.pick": "Pick a device",
"profileEditor.bluetooth.unpaired": "No longer paired",
"profileEditor.create": "Create profile",
"profileEditor.deactivation": "Deactivation delay",
@@ -831,6 +837,7 @@
"screen.autoExport": "Auto-export",
"screen.backendTemplate": "Backend template",
"screen.backupRestore": "Backup & restore",
+ "screen.bluetoothDevice": "Bluetooth device",
"screen.connection": "Connection",
"screen.dashboard": "Dashboard",
"screen.dataManagement": "Data management",
diff --git a/apps/mobile/src/i18n/locales/es.json b/apps/mobile/src/i18n/locales/es.json
index 8c5da147..5fec7f45 100644
--- a/apps/mobile/src/i18n/locales/es.json
+++ b/apps/mobile/src/i18n/locales/es.json
@@ -742,12 +742,18 @@
"profileEditor.activation.hint": "Cuánto tiempo debe cumplirse la condición primero. 0 cambia de inmediato; un valor más alto ignora una conexión o desconexión breve.",
"profileEditor.activation.hintStationary": "Cuánto tiempo cada posición debe indicar quietud; 0 cambia en la primera posición quieta. Volver a moverse termina el perfil de inmediato.",
"profileEditor.bluetooth.allow": "Permitir dispositivos cercanos",
+ "profileEditor.bluetooth.device": "Dispositivo",
"profileEditor.bluetooth.empty": "Elige un dispositivo o el perfil no podrá aplicarse",
"profileEditor.bluetooth.hint": "Se aplica mientras el teléfono esté conectado a este dispositivo, como el sistema de audio de tu coche.",
- "profileEditor.bluetooth.noDevices": "No hay dispositivos vinculados. Vincula uno en los ajustes de Bluetooth y vuelve.",
- "profileEditor.bluetooth.off": "El Bluetooth está desactivado. Actívalo para ver tus dispositivos vinculados.",
+ "profileEditor.bluetooth.noDevices": "No hay dispositivos vinculados",
+ "profileEditor.bluetooth.noDevices.hint": "Vincula uno en los ajustes de Bluetooth y vuelve.",
+ "profileEditor.bluetooth.off": "El Bluetooth está desactivado",
+ "profileEditor.bluetooth.off.hint": "Actívalo para ver tus dispositivos vinculados.",
+ "profileEditor.bluetooth.openBluetoothSettings": "Abrir ajustes de Bluetooth",
"profileEditor.bluetooth.openSettings": "Abrir ajustes de la app",
"profileEditor.bluetooth.permission": "Colota necesita el permiso de dispositivos cercanos para ver tus dispositivos vinculados y saber cuándo se conecta uno. No busca dispositivos nuevos ni se conecta a ninguno.",
+ "profileEditor.bluetooth.permission.title": "Dispositivos cercanos no permitidos",
+ "profileEditor.bluetooth.pick": "Elegir un dispositivo",
"profileEditor.bluetooth.unpaired": "Ya no está vinculado",
"profileEditor.create": "Crear perfil",
"profileEditor.deactivation": "Retraso de desactivación",
@@ -831,6 +837,7 @@
"screen.autoExport": "Exportación automática",
"screen.backendTemplate": "Plantilla de backend",
"screen.backupRestore": "Copia de seguridad y restauración",
+ "screen.bluetoothDevice": "Dispositivo Bluetooth",
"screen.connection": "Conexión",
"screen.dashboard": "Panel",
"screen.dataManagement": "Gestión de datos",
diff --git a/apps/mobile/src/i18n/locales/zh.json b/apps/mobile/src/i18n/locales/zh.json
index a7cfe62c..2cb9ce85 100644
--- a/apps/mobile/src/i18n/locales/zh.json
+++ b/apps/mobile/src/i18n/locales/zh.json
@@ -253,6 +253,11 @@
"condition.android_auto.clause": "使用 Android Auto 时",
"condition.android_auto.description": "Android Auto 已连接",
"condition.android_auto.list": "使用 Android Auto 时",
+ "condition.bluetooth_device": "蓝牙设备",
+ "condition.bluetooth_device.clause": "连接到“{{device}}”时",
+ "condition.bluetooth_device.description": "连接到已配对的设备,例如你的汽车",
+ "condition.bluetooth_device.list": "连接到“{{device}}”时",
+ "condition.bluetooth_device.listUnset": "连接到蓝牙设备时",
"condition.charging": "充电中",
"condition.charging.clause": "充电时",
"condition.charging.description": "手机已接入电源",
@@ -269,6 +274,14 @@
"condition.stationary.clause": "静止时",
"condition.stationary.description": "手机在激活延迟期间保持静止",
"condition.stationary.list": "静止时",
+ "condition.wifi_any": "Wi-Fi",
+ "condition.wifi_any.clause": "连接 Wi-Fi 时",
+ "condition.wifi_any.description": "手机已连接 Wi-Fi 网络",
+ "condition.wifi_any.list": "连接 Wi-Fi 时",
+ "condition.wifi_ssid": "Wi-Fi 网络",
+ "condition.wifi_ssid.clause": "连接 Wi-Fi“{{network}}”时",
+ "condition.wifi_ssid.description": "已连接到你指定的网络",
+ "condition.wifi_ssid.list": "连接 Wi-Fi“{{network}}”时",
"connection.endpoint": "服务器端点",
"connection.endpoint.helper": "公共主机使用 https,私有主机仅使用 http。",
"connection.endpoint.key": "此地址包含密钥。它会与设置一起存储,不会加密,并包含在设置链接中。服务器允许时请改用标头。",
@@ -728,6 +741,20 @@
"profileEditor.activation": "激活延迟",
"profileEditor.activation.hint": "条件必须先保持多久,0 表示立即切换,更长时间可忽略短暂插拔。",
"profileEditor.activation.hintStationary": "每个定位点必须显示静止多久;0 表示第一个静止点即切换,再次移动会立即结束配置。",
+ "profileEditor.bluetooth.allow": "允许“附近的设备”权限",
+ "profileEditor.bluetooth.device": "设备",
+ "profileEditor.bluetooth.empty": "请选择一个设备,否则此配置无法生效",
+ "profileEditor.bluetooth.hint": "手机连接到此设备时生效,例如你汽车的音响系统。",
+ "profileEditor.bluetooth.noDevices": "没有已配对的设备",
+ "profileEditor.bluetooth.noDevices.hint": "请先在蓝牙设置中配对一个设备,然后返回。",
+ "profileEditor.bluetooth.off": "蓝牙已关闭",
+ "profileEditor.bluetooth.off.hint": "开启蓝牙后即可查看已配对的设备。",
+ "profileEditor.bluetooth.openBluetoothSettings": "打开蓝牙设置",
+ "profileEditor.bluetooth.openSettings": "打开应用设置",
+ "profileEditor.bluetooth.permission": "Colota 需要“附近的设备”权限才能查看你已配对的设备以及设备何时连接。它不会搜索新设备,也不会连接任何设备。",
+ "profileEditor.bluetooth.permission.title": "未允许“附近的设备”权限",
+ "profileEditor.bluetooth.pick": "选择设备",
+ "profileEditor.bluetooth.unpaired": "已取消配对",
"profileEditor.create": "创建配置",
"profileEditor.deactivation": "停用延迟",
"profileEditor.deactivation.hint": "条件结束后配置保持开启多久,更长时间可度过短暂间隔。",
@@ -755,6 +782,9 @@
"profileEditor.sync.hint": "此配置活动时替换“跟踪和同步”中的 {{interval}} · 越短表示唤醒次数越多",
"profileEditor.titleEdit": "编辑配置",
"profileEditor.titleNew": "新配置",
+ "profileEditor.wifi.empty": "请填写网络名称,否则此配置无法生效",
+ "profileEditor.wifi.hint": "连接到此网络时生效。读取网络名称会被视为位置访问。",
+ "profileEditor.wifi.ssid": "网络名称",
"profiles.empty.hint": "条件成立时(例如充电或驾驶),配置会改变跟踪方式",
"profiles.empty.title": "还没有配置",
"profiles.intro": "跟踪运行时从上到下检查。第一个满足条件的配置会替换“跟踪和同步”中的值。",
@@ -807,6 +837,7 @@
"screen.autoExport": "自动导出",
"screen.backendTemplate": "后端模板",
"screen.backupRestore": "备份与恢复",
+ "screen.bluetoothDevice": "蓝牙设备",
"screen.connection": "连接",
"screen.dashboard": "控制面板",
"screen.dataManagement": "数据管理",
diff --git a/apps/mobile/src/screens/BluetoothDeviceScreen.tsx b/apps/mobile/src/screens/BluetoothDeviceScreen.tsx
new file mode 100644
index 00000000..4e777501
--- /dev/null
+++ b/apps/mobile/src/screens/BluetoothDeviceScreen.tsx
@@ -0,0 +1,149 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+import React, { useState, useEffect, useCallback } from "react"
+import { View, Text, ScrollView, StyleSheet, AppState, Linking } from "react-native"
+import { Bluetooth, BluetoothOff } from "lucide-react-native"
+import { Card, Container, EmptyState, RadioRow } from "../components"
+import { useTheme } from "../hooks/useTheme"
+import { useTimeout } from "../hooks/useTimeout"
+import NativeLocationService from "../services/NativeLocationService"
+import {
+ checkBluetoothPermission,
+ requestBluetoothPermission,
+ type BluetoothPermissionResult
+} from "../services/LocationServicePermission"
+import type { BluetoothDeviceInfo } from "../types/global"
+import { BLUETOOTH_REREAD_MS, space } from "../constants"
+import { fontSizes, fonts, lineHeights } from "../styles/typography"
+import type { RootScreenProps } from "../types/navigation"
+import { useTranslation } from "../i18n/useTranslation"
+
+const openBluetoothSettings = () => Linking.sendIntent("android.settings.BLUETOOTH_SETTINGS")
+
+export function BluetoothDeviceScreen({ navigation, route }: RootScreenProps<"Bluetooth Device">) {
+ const { colors } = useTheme()
+ const { t } = useTranslation()
+ const pickedDevice = route.params?.selected
+ const [btPermission, setBtPermission] = useState<BluetoothPermissionResult | null>(null)
+ const [pairedDevices, setPairedDevices] = useState<BluetoothDeviceInfo[]>([])
+ const [bluetoothOff, setBluetoothOff] = useState(false)
+ const bluetoothReread = useTimeout()
+
+ const refreshPairedDevices = useCallback(async () => {
+ const granted = await checkBluetoothPermission()
+ const devices = granted ? await NativeLocationService.getBondedBluetoothDevices() : []
+ // A denial already seen stays "blocked", so the button keeps pointing at app settings.
+ setBtPermission((prev) => (granted ? "granted" : prev === "blocked" ? "blocked" : "denied"))
+ setBluetoothOff(devices === null)
+ setPairedDevices(devices ?? [])
+ }, [])
+
+ useEffect(() => {
+ // Opening the picker is the moment to ask, so a first visit shows the dialog instead of a denial.
+ requestBluetoothPermission().then((result) => {
+ setBtPermission(result)
+ refreshPairedDevices()
+ })
+ // Pairing a device or granting the permission in settings and coming back should list it.
+ const sub = AppState.addEventListener("change", (state) => {
+ if (state === "active") refreshPairedDevices()
+ })
+ // Quick Settings opens over the app without pausing it, so only a focus event follows a toggle there.
+ const focusSub = AppState.addEventListener("focus", () => {
+ refreshPairedDevices()
+ bluetoothReread.set(refreshPairedDevices, BLUETOOTH_REREAD_MS)
+ })
+ return () => {
+ sub.remove()
+ focusSub.remove()
+ bluetoothReread.clear()
+ }
+ }, [refreshPairedDevices, bluetoothReread])
+
+ const handleDevice = (device: BluetoothDeviceInfo) =>
+ navigation.popTo("Profile Editor", { bluetoothDevice: device }, { merge: true })
+
+ // A picked device that was unpaired since still shows, so the profile never loses it silently.
+ const deviceRows =
+ pickedDevice && !pairedDevices.some((d) => d.address === pickedDevice.address)
+ ? [
+ { ...pickedDevice, unpaired: btPermission === "granted" && !bluetoothOff },
+ ...pairedDevices.map((d) => ({ ...d, unpaired: false }))
+ ]
+ : pairedDevices.map((d) => ({ ...d, unpaired: false }))
+
+ const handleAllowBluetooth = async () => {
+ if (btPermission === "blocked") {
+ Linking.openSettings()
+ return
+ }
+ const result = await requestBluetoothPermission()
+ setBtPermission(result)
+ if (result === "granted") refreshPairedDevices()
+ }
+
+ // The centred shape is for a state that owns the screen; above a stored device it stays one line.
+ const emptyIcon = (icon: typeof Bluetooth) => (deviceRows.length === 0 ? icon : undefined)
+
+ return (
+ <Container>
+ <ScrollView contentContainerStyle={styles.scrollContent}>
+ <Text style={[styles.intro, { color: colors.textSecondary }]}>{t("profileEditor.bluetooth.hint")}</Text>
+ {btPermission !== null && btPermission !== "granted" && (
+ <EmptyState
+ icon={emptyIcon(Bluetooth)}
+ title={t("profileEditor.bluetooth.permission.title")}
+ hint={t("profileEditor.bluetooth.permission")}
+ action={{
+ label:
+ btPermission === "blocked"
+ ? t("profileEditor.bluetooth.openSettings")
+ : t("profileEditor.bluetooth.allow"),
+ onPress: handleAllowBluetooth
+ }}
+ />
+ )}
+ {btPermission === "granted" && bluetoothOff && (
+ <EmptyState
+ icon={emptyIcon(BluetoothOff)}
+ title={t("profileEditor.bluetooth.off")}
+ hint={t("profileEditor.bluetooth.off.hint")}
+ action={{ label: t("profileEditor.bluetooth.openBluetoothSettings"), onPress: openBluetoothSettings }}
+ />
+ )}
+ {btPermission === "granted" && !bluetoothOff && pairedDevices.length === 0 && (
+ <EmptyState
+ icon={emptyIcon(Bluetooth)}
+ title={t("profileEditor.bluetooth.noDevices")}
+ hint={t("profileEditor.bluetooth.noDevices.hint")}
+ action={{ label: t("profileEditor.bluetooth.openBluetoothSettings"), onPress: openBluetoothSettings }}
+ />
+ )}
+ {deviceRows.length > 0 && (
+ <Card rows>
+ <View accessibilityRole="radiogroup">
+ {deviceRows.map((device) => (
+ <RadioRow
+ key={device.address}
+ testID={`bluetooth-device-${device.address}`}
+ label={device.name}
+ sub={device.unpaired ? t("profileEditor.bluetooth.unpaired") : device.address}
+ selected={pickedDevice?.address === device.address}
+ onPress={() => handleDevice({ name: device.name, address: device.address })}
+ />
+ ))}
+ </View>
+ </Card>
+ )}
+ </ScrollView>
+ </Container>
+ )
+}
+
+const styles = StyleSheet.create({
+ scrollContent: { paddingHorizontal: space.lg, paddingTop: space.lg, paddingBottom: space.xxl },
+ intro: { fontSize: fontSizes.body, ...fonts.regular, lineHeight: lineHeights.body, marginBottom: space.lg }
+})
diff --git a/apps/mobile/src/screens/ProfileEditorScreen.tsx b/apps/mobile/src/screens/ProfileEditorScreen.tsx
index 7b0cbf82..8629ddee 100644
--- a/apps/mobile/src/screens/ProfileEditorScreen.tsx
+++ b/apps/mobile/src/screens/ProfileEditorScreen.tsx
@@ -4,17 +4,13 @@
*/
import React, { useState, useEffect, useLayoutEffect, useCallback } from "react"
-import { View, Text, StyleSheet, ScrollView, AppState, Linking } from "react-native"
+import { View, Text, StyleSheet, ScrollView, AppState } from "react-native"
import { useTheme } from "../hooks/useTheme"
import { useTracking } from "../contexts/TrackingProvider"
import { useTimeout } from "../hooks/useTimeout"
import { ProfileService } from "../services/ProfileService"
import NativeLocationService from "../services/NativeLocationService"
-import {
- checkBluetoothPermission,
- requestBluetoothPermission,
- type BluetoothPermissionResult
-} from "../services/LocationServicePermission"
+import { checkBluetoothPermission } from "../services/LocationServicePermission"
import { showAlert, showConfirm } from "../services/modalService"
import { TrackingProfile, ProfileConditionType, BluetoothDeviceInfo } from "../types/global"
import { fontSizes, fonts, lineHeights } from "../styles/typography"
@@ -28,6 +24,7 @@ import {
NumericInput,
RadioRow,
SectionTitle,
+ SelectField,
SettingRow,
TextField
} from "../components"
@@ -37,14 +34,7 @@ import { shortDistanceUnit, inputToMeters, metersToInput, getSpeedUnit, speedToI
import { formatDuration, syncIntervalLabel } from "../utils/dashboardState"
import { conditionOf, profileSentence } from "../utils/profileRow"
import { parseWholeNumber, wholeNumberError } from "../utils/settingsValidation"
-import {
- BLUETOOTH_REREAD_MS,
- PROFILE_CONDITIONS,
- SAVE_SUCCESS_DISPLAY_MS,
- defaultProfileDelays,
- size,
- space
-} from "../constants"
+import { PROFILE_CONDITIONS, SAVE_SUCCESS_DISPLAY_MS, defaultProfileDelays, size, space } from "../constants"
import type { RootScreenProps } from "../types/navigation"
import { useTranslation } from "../i18n/useTranslation"
@@ -77,11 +67,9 @@ export function ProfileEditorScreen({ navigation, route }: RootScreenProps<"Prof
})
const [saving, setSaving] = useState(false)
const [currentSsid, setCurrentSsid] = useState("")
- const [btPermission, setBtPermission] = useState<BluetoothPermissionResult | null>(null)
- const [pairedDevices, setPairedDevices] = useState<BluetoothDeviceInfo[]>([])
- const [bluetoothOff, setBluetoothOff] = useState(false)
// Survives a switch to another condition and back, like the typed network name.
const [pickedDevice, setPickedDevice] = useState<BluetoothDeviceInfo | null>(null)
+ const [btAllowed, setBtAllowed] = useState(true)
const [text, setText] = useState({
interval: String(settings.interval),
distance: String(metersToInput(settings.distance)),
@@ -93,7 +81,6 @@ export function ProfileEditorScreen({ navigation, route }: RootScreenProps<"Prof
})
const [note, setNote] = useState<{ key: NumericKey; text: string } | null>(null)
const noteTimer = useTimeout()
- const bluetoothReread = useTimeout()
// Only fetched while the SSID field is open; the fallback keeps the offer button hidden.
useEffect(() => {
@@ -112,34 +99,17 @@ export function ProfileEditorScreen({ navigation, route }: RootScreenProps<"Prof
return () => sub.remove()
}, [profile.condition.type])
- const refreshPairedDevices = useCallback(async () => {
- const granted = await checkBluetoothPermission()
- // A denial already seen stays "blocked", so the button keeps pointing at app settings.
- setBtPermission((prev) => (granted ? "granted" : prev === "blocked" ? "blocked" : "denied"))
- const devices = granted ? await NativeLocationService.getBondedBluetoothDevices() : []
- setBluetoothOff(devices === null)
- setPairedDevices(devices ?? [])
- }, [])
-
+ // Without Nearby devices the profile never matches, so the device field says so.
useEffect(() => {
if (profile.condition.type !== "bluetooth_device") return
- refreshPairedDevices()
- // Pairing a device or granting the permission in settings and coming back should list it.
+ const readPermission = () => checkBluetoothPermission().then(setBtAllowed)
+ readPermission()
const sub = AppState.addEventListener("change", (state) => {
- if (state === "active") refreshPairedDevices()
- })
- // Quick Settings opens over the app without pausing it, so only a focus event follows a toggle there.
- const focusSub = AppState.addEventListener("focus", () => {
- refreshPairedDevices()
- bluetoothReread.set(refreshPairedDevices, BLUETOOTH_REREAD_MS)
+ if (state === "active") readPermission()
})
- return () => {
- sub.remove()
- focusSub.remove()
- bluetoothReread.clear()
- }
- }, [profile.condition.type, refreshPairedDevices, bluetoothReread])
+ return () => sub.remove()
+ }, [profile.condition.type])
useLayoutEffect(() => {
navigation.setOptions({ headerTitle: isEditing ? t("profileEditor.titleEdit") : t("profileEditor.titleNew") })
@@ -233,33 +203,22 @@ export function ProfileEditorScreen({ navigation, route }: RootScreenProps<"Prof
const ssidError = isWifiSsid && text.ssid.trim() === "" ? t("profileEditor.wifi.empty") : undefined
const offerCurrentSsid = currentSsid !== "" && currentSsid.trim().toLowerCase() !== text.ssid.trim().toLowerCase()
- const handleDevice = (device: BluetoothDeviceInfo) => {
+ const handleDevice = useCallback((device: BluetoothDeviceInfo) => {
setPickedDevice(device)
setProfile((prev) => ({
...prev,
condition: { ...prev.condition, bluetoothAddress: device.address, bluetoothName: device.name }
}))
- }
- const deviceError = isBluetooth && !pickedDevice ? t("profileEditor.bluetooth.empty") : undefined
- // A picked device that was unpaired since still shows, so the profile never loses it silently.
- const deviceRows =
- pickedDevice && !pairedDevices.some((d) => d.address === pickedDevice.address)
- ? [
- { ...pickedDevice, unpaired: btPermission === "granted" && !bluetoothOff },
- ...pairedDevices.map((d) => ({ ...d, unpaired: false }))
- ]
- : pairedDevices.map((d) => ({ ...d, unpaired: false }))
-
- const handleAllowBluetooth = async () => {
- if (btPermission === "blocked") {
- Linking.openSettings()
- return
- }
- const result = await requestBluetoothPermission()
- setBtPermission(result)
- if (result === "granted") refreshPairedDevices()
- }
+ }, [])
+ // The device screen hands its pick back through the route; clearing it stops a re-apply.
+ const incomingDevice = route?.params?.bluetoothDevice
+ useEffect(() => {
+ if (!incomingDevice) return
+ handleDevice(incomingDevice)
+ navigation.setParams({ bluetoothDevice: undefined })
+ }, [incomingDevice, handleDevice, navigation])
+ const deviceError = isBluetooth && !pickedDevice ? t("profileEditor.bluetooth.empty") : undefined
const priorityError =
text.priority !== "" && parseWholeNumber(text.priority) === null ? t("validation.wholeNumber") : undefined
const handlePriority = (value: string) => {
@@ -432,46 +391,14 @@ export function ProfileEditorScreen({ navigation, route }: RootScreenProps<"Prof
)}
{opt.type === "bluetooth_device" && type === opt.type && (
<View style={styles.reveal}>
- {btPermission !== null && btPermission !== "granted" && (
- <>
- <FieldMessage>{t("profileEditor.bluetooth.permission")}</FieldMessage>
- <Button
- variant="secondary"
- title={
- btPermission === "blocked"
- ? t("profileEditor.bluetooth.openSettings")
- : t("profileEditor.bluetooth.allow")
- }
- testID="bluetooth-allow"
- onPress={handleAllowBluetooth}
- style={styles.ssidUse}
- />
- </>
- )}
- {btPermission === "granted" && bluetoothOff && (
- <FieldMessage>{t("profileEditor.bluetooth.off")}</FieldMessage>
- )}
- {btPermission === "granted" && !bluetoothOff && pairedDevices.length === 0 && (
- <FieldMessage>{t("profileEditor.bluetooth.noDevices")}</FieldMessage>
- )}
- {deviceRows.length > 0 && (
- <View accessibilityRole="radiogroup">
- {deviceRows.map((device) => (
- <RadioRow
- key={device.address}
- testID={`bluetooth-device-${device.address}`}
- label={device.name}
- sub={device.unpaired ? t("profileEditor.bluetooth.unpaired") : device.address}
- selected={pickedDevice?.address === device.address}
- onPress={() => handleDevice({ name: device.name, address: device.address })}
- />
- ))}
- </View>
- )}
- {deviceError && btPermission === "granted" && pairedDevices.length > 0 ? (
- <FieldMessage variant="error">{deviceError}</FieldMessage>
- ) : null}
- <FieldMessage>{t("profileEditor.bluetooth.hint")}</FieldMessage>
+ <SelectField
+ label={t("profileEditor.bluetooth.device")}
+ testID="nav-bluetooth-device"
+ value={pickedDevice?.name}
+ placeholder={t("profileEditor.bluetooth.pick")}
+ error={deviceError ?? (btAllowed ? undefined : t("profileEditor.bluetooth.permission.title"))}
+ onPress={() => navigation.navigate("Bluetooth Device", { selected: pickedDevice ?? undefined })}
+ />
</View>
)}
</React.Fragment>
diff --git a/apps/mobile/src/screens/__tests__/BluetoothDeviceScreen.test.tsx b/apps/mobile/src/screens/__tests__/BluetoothDeviceScreen.test.tsx
new file mode 100644
index 00000000..ef844bf0
--- /dev/null
+++ b/apps/mobile/src/screens/__tests__/BluetoothDeviceScreen.test.tsx
@@ -0,0 +1,190 @@
+import React from "react"
+import { render, fireEvent, act } from "@testing-library/react-native"
+import { BLUETOOTH_REREAD_MS } from "../../constants"
+
+const mockGetBondedBluetoothDevices = jest.fn()
+jest.mock("../../services/NativeLocationService", () => ({
+ __esModule: true,
+ default: {
+ getBondedBluetoothDevices: () => mockGetBondedBluetoothDevices()
+ }
+}))
+
+const mockCheckBluetoothPermission = jest.fn()
+const mockRequestBluetoothPermission = jest.fn()
+jest.mock("../../services/LocationServicePermission", () => ({
+ checkBluetoothPermission: () => mockCheckBluetoothPermission(),
+ requestBluetoothPermission: () => mockRequestBluetoothPermission()
+}))
+
+const mockOpenSettings = jest.fn()
+jest.spyOn(require("react-native").Linking, "openSettings").mockImplementation(() => mockOpenSettings())
+
+jest.mock("../../hooks/useTheme", () => ({
+ useTheme: () => ({ colors: require("@colota/shared").lightColors })
+}))
+
+jest.mock("../../components", () => {
+ const R = require("react")
+ const { View, Text, Pressable } = require("react-native")
+ return {
+ Container: ({ children }: any) => R.createElement(View, null, children),
+ Card: ({ children }: any) => R.createElement(View, null, children),
+ RadioRow: ({ testID, label, sub, selected, onPress }: any) =>
+ R.createElement(
+ Pressable,
+ { testID, onPress, accessibilityRole: "radio", accessibilityState: { checked: selected } },
+ R.createElement(Text, null, label),
+ sub ? R.createElement(Text, null, sub) : null
+ ),
+ EmptyState: ({ title, hint, action }: any) =>
+ R.createElement(
+ View,
+ null,
+ R.createElement(Text, null, title),
+ hint ? R.createElement(Text, null, hint) : null,
+ action
+ ? R.createElement(
+ Pressable,
+ { testID: "empty-action", onPress: action.onPress },
+ R.createElement(Text, null, action.label)
+ )
+ : null
+ )
+ }
+})
+
+import { BluetoothDeviceScreen } from "../BluetoothDeviceScreen"
+
+const PAIRED = [
+ { name: "My Car", address: "AA:BB:CC:DD:EE:FF" },
+ { name: "Earbuds", address: "11:22:33:44:55:66" }
+]
+const OLD_CAR = { name: "Old Car", address: "00:11:22:33:44:55" }
+
+describe("BluetoothDeviceScreen", () => {
+ const mockPopTo = jest.fn()
+ const navigation = { popTo: mockPopTo }
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ mockCheckBluetoothPermission.mockResolvedValue(true)
+ mockRequestBluetoothPermission.mockResolvedValue("granted")
+ mockGetBondedBluetoothDevices.mockResolvedValue(PAIRED)
+ })
+
+ const renderScreen = (selected?: { name: string; address: string }) =>
+ render(
+ <BluetoothDeviceScreen
+ navigation={navigation as any}
+ route={{ params: selected ? { selected } : undefined } as any}
+ />
+ )
+
+ it("lists the paired devices and hands the pick back to the editor", async () => {
+ const { findByTestId, getByText } = renderScreen()
+
+ fireEvent.press(await findByTestId("bluetooth-device-AA:BB:CC:DD:EE:FF"))
+
+ expect(getByText("Earbuds")).toBeTruthy()
+ expect(mockPopTo).toHaveBeenCalledWith(
+ "Profile Editor",
+ { bluetoothDevice: { name: "My Car", address: "AA:BB:CC:DD:EE:FF" } },
+ { merge: true }
+ )
+ })
+
+ it("keeps a stored device that is no longer paired", async () => {
+ const { findByTestId, getByText } = renderScreen(OLD_CAR)
+
+ const stored = await findByTestId("bluetooth-device-00:11:22:33:44:55")
+ expect(stored.props.accessibilityState.checked).toBe(true)
+ expect(getByText("No longer paired")).toBeTruthy()
+ })
+
+ // Opening the picker is the in-context moment, so the dialog comes before any denial is shown.
+ it("asks for the Nearby devices permission before it can list anything", async () => {
+ mockCheckBluetoothPermission.mockResolvedValueOnce(false)
+ mockRequestBluetoothPermission.mockResolvedValueOnce("denied")
+ const { findByText, findByTestId, getByTestId, queryByTestId } = renderScreen()
+
+ expect(await findByText("Nearby devices not allowed")).toBeTruthy()
+ expect(mockRequestBluetoothPermission).toHaveBeenCalledTimes(1)
+ expect(mockGetBondedBluetoothDevices).not.toHaveBeenCalled()
+
+ fireEvent.press(getByTestId("empty-action"))
+ await findByTestId("bluetooth-device-AA:BB:CC:DD:EE:FF")
+ expect(mockRequestBluetoothPermission).toHaveBeenCalledTimes(2)
+ expect(queryByTestId("empty-action")).toBeNull()
+ })
+
+ it("sends a blocked permission to app settings", async () => {
+ mockCheckBluetoothPermission.mockResolvedValue(false)
+ mockRequestBluetoothPermission.mockResolvedValue("blocked")
+ const { findByText, getByTestId } = renderScreen()
+
+ await findByText("Open app settings")
+ fireEvent.press(getByTestId("empty-action"))
+ expect(mockOpenSettings).toHaveBeenCalled()
+ })
+
+ // Closing the dialog resumes the app before the request resolves, so a refresh can land after "blocked".
+ it("keeps pointing at app settings when a refresh follows the blocked answer", async () => {
+ const { AppState } = require("react-native")
+ mockCheckBluetoothPermission.mockResolvedValue(false)
+ mockRequestBluetoothPermission.mockResolvedValue("blocked")
+ const { findByText, getByText } = renderScreen()
+ await findByText("Open app settings")
+
+ const onChange = (AppState.addEventListener as jest.Mock).mock.calls
+ .filter((call: unknown[]) => call[0] === "change")
+ .at(-1)[1]
+ await act(async () => onChange("active"))
+
+ expect(getByText("Open app settings")).toBeTruthy()
+ })
+
+ it("says how to pair a device when none is paired", async () => {
+ const { Linking } = require("react-native")
+ mockGetBondedBluetoothDevices.mockResolvedValue([])
+ const { findByText, getByText, getByTestId } = renderScreen()
+
+ expect(await findByText("No paired devices")).toBeTruthy()
+ expect(getByText("Pair one in Bluetooth settings, then come back.")).toBeTruthy()
+ fireEvent.press(getByTestId("empty-action"))
+ expect(Linking.sendIntent).toHaveBeenCalledWith("android.settings.BLUETOOTH_SETTINGS")
+ })
+
+ // null is the bridge's answer while Bluetooth is off.
+ it("shows Bluetooth as off, not the stored device as unpaired", async () => {
+ mockGetBondedBluetoothDevices.mockResolvedValue(null)
+ const { findByText, getByTestId, getByText, queryByText } = renderScreen(OLD_CAR)
+
+ expect(await findByText("Bluetooth is off")).toBeTruthy()
+ expect(getByTestId("bluetooth-device-00:11:22:33:44:55").props.accessibilityState.checked).toBe(true)
+ expect(queryByText("No longer paired")).toBeNull()
+ expect(queryByText("No paired devices")).toBeNull()
+ expect(getByText("Open Bluetooth settings")).toBeTruthy()
+ })
+
+ // The shade closes while Bluetooth is still turning on, so the read on focus still finds it off.
+ it("reads the paired devices again after Quick Settings closes", async () => {
+ const { AppState } = require("react-native")
+ mockGetBondedBluetoothDevices.mockResolvedValueOnce(null).mockResolvedValueOnce(null)
+ const { findByText, findByTestId, queryByTestId } = renderScreen()
+ await findByText("Bluetooth is off")
+
+ jest.useFakeTimers()
+ const onFocus = (AppState.addEventListener as jest.Mock).mock.calls
+ .filter((call: unknown[]) => call[0] === "focus")
+ .at(-1)[1]
+ await act(async () => onFocus())
+ expect(queryByTestId("bluetooth-device-AA:BB:CC:DD:EE:FF")).toBeNull()
+
+ await act(async () => {
+ jest.advanceTimersByTime(BLUETOOTH_REREAD_MS)
+ })
+ jest.useRealTimers()
+ expect(await findByTestId("bluetooth-device-AA:BB:CC:DD:EE:FF")).toBeTruthy()
+ })
+})
diff --git a/apps/mobile/src/screens/__tests__/ProfileEditorScreen.test.tsx b/apps/mobile/src/screens/__tests__/ProfileEditorScreen.test.tsx
index aa8dfc60..51c1482d 100644
--- a/apps/mobile/src/screens/__tests__/ProfileEditorScreen.test.tsx
+++ b/apps/mobile/src/screens/__tests__/ProfileEditorScreen.test.tsx
@@ -1,7 +1,7 @@
import React from "react"
import { render, fireEvent, waitFor, act } from "@testing-library/react-native"
import { TrackingProfile } from "../../types/global"
-import { BLUETOOTH_REREAD_MS, SAVE_SUCCESS_DISPLAY_MS } from "../../constants"
+import { SAVE_SUCCESS_DISPLAY_MS } from "../../constants"
const mockProfiles: TrackingProfile[] = [
{
@@ -57,30 +57,18 @@ jest.mock("../../services/ProfileService", () => ({
}))
const mockGetCurrentSsid = jest.fn().mockResolvedValue("HomeNet")
-const mockGetBondedBluetoothDevices = jest.fn()
jest.mock("../../services/NativeLocationService", () => ({
__esModule: true,
default: {
- getCurrentSsid: () => mockGetCurrentSsid(),
- getBondedBluetoothDevices: () => mockGetBondedBluetoothDevices()
+ getCurrentSsid: () => mockGetCurrentSsid()
}
}))
const mockCheckBluetoothPermission = jest.fn()
-const mockRequestBluetoothPermission = jest.fn()
jest.mock("../../services/LocationServicePermission", () => ({
- checkBluetoothPermission: () => mockCheckBluetoothPermission(),
- requestBluetoothPermission: () => mockRequestBluetoothPermission()
+ checkBluetoothPermission: () => mockCheckBluetoothPermission()
}))
-const mockOpenSettings = jest.fn()
-jest.spyOn(require("react-native").Linking, "openSettings").mockImplementation(() => mockOpenSettings())
-
-const PAIRED = [
- { name: "My Car", address: "AA:BB:CC:DD:EE:FF" },
- { name: "Earbuds", address: "11:22:33:44:55:66" }
-]
-
const mockShowAlert = jest.fn()
const mockShowConfirm = jest.fn()
jest.mock("../../services/modalService", () => ({
@@ -147,6 +135,21 @@ jest.mock("../../components", () => {
R.createElement(Text, null, label),
sub ? R.createElement(Text, null, sub) : null
),
+ ListItem: ({ testID, label, sub, onPress }: any) =>
+ R.createElement(
+ Pressable,
+ { testID, onPress },
+ R.createElement(Text, null, label),
+ sub ? R.createElement(Text, null, sub) : null
+ ),
+ SelectField: ({ testID, label, value, placeholder, error, onPress }: any) =>
+ R.createElement(
+ Pressable,
+ { testID, onPress },
+ R.createElement(Text, null, label),
+ R.createElement(Text, null, value ?? placeholder),
+ error ? R.createElement(Text, null, error) : null
+ ),
Button: ({ title, onPress, disabled, testID }: any) =>
R.createElement(
Pressable,
@@ -184,21 +187,33 @@ jest.mock("../../utils/logger", () => ({ logger: { error: jest.fn() } }))
const mockGoBack = jest.fn()
const mockSetOptions = jest.fn()
-const mockNavigation = { goBack: mockGoBack, setOptions: mockSetOptions }
+const mockNavigate = jest.fn()
+const mockNavigation = { goBack: mockGoBack, setOptions: mockSetOptions, navigate: mockNavigate, setParams: jest.fn() }
import { ProfileEditorScreen } from "../ProfileEditorScreen"
+import type { BluetoothDeviceInfo } from "../../types/global"
describe("ProfileEditorScreen", () => {
beforeEach(() => {
jest.clearAllMocks()
mockSettings = { isOfflineMode: false, interval: 5, distance: 0, syncInterval: 0 }
mockGetProfiles.mockResolvedValue(mockProfiles)
+ mockCheckBluetoothPermission.mockResolvedValue(true)
})
- const renderNew = () =>
- render(<ProfileEditorScreen navigation={mockNavigation as any} route={{ params: {} } as any} />)
- const renderEdit = (profileId = 1) =>
- render(<ProfileEditorScreen navigation={mockNavigation as any} route={{ params: { profileId } } as any} />)
+ // The device screen hands its pick back by merging it into the editor's params.
+ const renderAt = (params: Record<string, unknown>) => {
+ const screen = (p: Record<string, unknown>) => (
+ <ProfileEditorScreen navigation={mockNavigation as any} route={{ params: p } as any} />
+ )
+ const utils = render(screen(params))
+ return {
+ ...utils,
+ pickDevice: (bluetoothDevice: BluetoothDeviceInfo) => utils.rerender(screen({ ...params, bluetoothDevice }))
+ }
+ }
+ const renderNew = () => renderAt({})
+ const renderEdit = (profileId = 1) => renderAt({ profileId })
describe("the sentence", () => {
it("reads the draft back as the rule and follows every edit", () => {
@@ -338,39 +353,32 @@ describe("ProfileEditorScreen", () => {
})
describe("bluetooth device", () => {
- beforeEach(() => {
- mockCheckBluetoothPermission.mockResolvedValue(true)
- mockRequestBluetoothPermission.mockResolvedValue("granted")
- mockGetBondedBluetoothDevices.mockResolvedValue(PAIRED)
- })
-
- it("lists the paired devices and blocks Save until one is picked", async () => {
- const { getByTestId, findByTestId, getByText } = renderNew()
-
+ it("blocks Save until a device is picked and opens the device screen for it", () => {
+ const { getByTestId, getByText } = renderNew()
fireEvent.press(getByTestId("condition-bluetooth_device"))
- await findByTestId("bluetooth-device-AA:BB:CC:DD:EE:FF")
- expect(getByText("Earbuds")).toBeTruthy()
+ expect(getByText("Pick a device")).toBeTruthy()
expect(getByText("Pick a device or the profile can't match")).toBeTruthy()
expect(getByTestId("profile-sentence").props.children).toBe(
"When connected to a Bluetooth device, track every 5 s, any movement and sync each fix."
)
expect(getByTestId("save-profile-btn").props.accessibilityState.disabled).toBe(true)
- fireEvent.press(getByTestId("bluetooth-device-AA:BB:CC:DD:EE:FF"))
- expect(getByTestId("bluetooth-device-AA:BB:CC:DD:EE:FF").props.accessibilityState.checked).toBe(true)
- expect(getByTestId("profile-sentence").props.children).toBe(
- 'Connected to "My Car", track every 5 s, any movement and sync each fix.'
- )
- expect(getByTestId("save-profile-btn").props.accessibilityState.disabled).toBe(false)
+ fireEvent.press(getByTestId("nav-bluetooth-device"))
+ expect(mockNavigate).toHaveBeenCalledWith("Bluetooth Device", { selected: undefined })
})
it("saves the picked device's address and name", async () => {
- const { getByTestId, findByTestId } = renderNew()
+ const { getByTestId, getByText, pickDevice } = renderNew()
fireEvent.press(getByTestId("condition-bluetooth_device"))
- fireEvent.press(await findByTestId("bluetooth-device-AA:BB:CC:DD:EE:FF"))
- fireEvent.press(getByTestId("save-profile-btn"))
+ pickDevice({ name: "My Car", address: "AA:BB:CC:DD:EE:FF" })
+ expect(getByText("My Car")).toBeTruthy()
+ expect(getByTestId("profile-sentence").props.children).toBe(
+ 'Connected to "My Car", track every 5 s, any movement and sync each fix.'
+ )
+
+ fireEvent.press(getByTestId("save-profile-btn"))
await waitFor(() =>
expect(mockCreateProfile).toHaveBeenCalledWith(
expect.objectContaining({
@@ -380,91 +388,33 @@ describe("ProfileEditorScreen", () => {
)
})
- it("asks for the Nearby devices permission before it can list anything", async () => {
- mockCheckBluetoothPermission.mockResolvedValueOnce(false)
- const { getByTestId, findByTestId, queryByTestId } = renderNew()
+ it("keeps the pick across a condition round trip and opens the device screen on it", async () => {
+ const { findByText, getByText, getByTestId } = renderEdit(3)
+ expect(await findByText("Old Car")).toBeTruthy()
- fireEvent.press(getByTestId("condition-bluetooth_device"))
- const allow = await findByTestId("bluetooth-allow")
- expect(queryByTestId("bluetooth-device-AA:BB:CC:DD:EE:FF")).toBeNull()
- expect(mockGetBondedBluetoothDevices).not.toHaveBeenCalled()
-
- fireEvent.press(allow)
- await findByTestId("bluetooth-device-AA:BB:CC:DD:EE:FF")
- expect(mockRequestBluetoothPermission).toHaveBeenCalled()
- expect(queryByTestId("bluetooth-allow")).toBeNull()
- })
-
- it("sends a blocked permission to app settings", async () => {
- mockCheckBluetoothPermission.mockResolvedValue(false)
- mockRequestBluetoothPermission.mockResolvedValue("blocked")
- const { getByTestId, findByTestId, findByText } = renderNew()
-
- fireEvent.press(getByTestId("condition-bluetooth_device"))
- fireEvent.press(await findByTestId("bluetooth-allow"))
- await findByText("Open app settings")
-
- fireEvent.press(getByTestId("bluetooth-allow"))
- expect(mockOpenSettings).toHaveBeenCalled()
- })
-
- it("says how to pair a device when none is paired", async () => {
- mockGetBondedBluetoothDevices.mockResolvedValue([])
- const { getByTestId, findByText } = renderNew()
-
- fireEvent.press(getByTestId("condition-bluetooth_device"))
- expect(await findByText("No paired devices. Pair one in Bluetooth settings, then come back.")).toBeTruthy()
- })
-
- // null is the bridge's answer while Bluetooth is off.
- it("shows Bluetooth as off, not the saved device as unpaired", async () => {
- mockGetBondedBluetoothDevices.mockResolvedValue(null)
- const { findByText, getByTestId, queryByText } = renderEdit(3)
-
- expect(await findByText("Bluetooth is off. Turn it on to see your paired devices.")).toBeTruthy()
- expect(getByTestId("bluetooth-device-00:11:22:33:44:55").props.accessibilityState.checked).toBe(true)
- expect(queryByText("No longer paired")).toBeNull()
- expect(queryByText("No paired devices. Pair one in Bluetooth settings, then come back.")).toBeNull()
- })
+ fireEvent.press(getByTestId("nav-bluetooth-device"))
+ expect(mockNavigate).toHaveBeenCalledWith("Bluetooth Device", {
+ selected: { address: "00:11:22:33:44:55", name: "Old Car" }
+ })
- // The shade closes while Bluetooth is still turning on, so the read on focus still finds it off.
- it("reads the paired devices again after Quick Settings closes", async () => {
- const { AppState } = require("react-native")
- mockGetBondedBluetoothDevices.mockResolvedValueOnce(null).mockResolvedValueOnce(null)
- const { getByTestId, findByText, findByTestId, queryByTestId } = renderNew()
+ fireEvent.press(getByTestId("condition-charging"))
fireEvent.press(getByTestId("condition-bluetooth_device"))
- await findByText("Bluetooth is off. Turn it on to see your paired devices.")
-
- jest.useFakeTimers()
- const onFocus = (AppState.addEventListener as jest.Mock).mock.calls
- .filter((call: unknown[]) => call[0] === "focus")
- .at(-1)[1]
- await act(async () => onFocus())
- expect(queryByTestId("bluetooth-device-AA:BB:CC:DD:EE:FF")).toBeNull()
-
- await act(async () => {
- jest.advanceTimersByTime(BLUETOOTH_REREAD_MS)
- })
- jest.useRealTimers()
- expect(await findByTestId("bluetooth-device-AA:BB:CC:DD:EE:FF")).toBeTruthy()
+ expect(getByText("Old Car")).toBeTruthy()
+ expect(getByTestId("save-profile-btn").props.accessibilityState.disabled).toBe(false)
})
- it("keeps a stored device that is no longer paired, and the pick across a condition round trip", async () => {
- const { getByTestId, findByTestId, getByText } = renderEdit(3)
- const stored = await findByTestId("bluetooth-device-00:11:22:33:44:55")
- expect(stored.props.accessibilityState.checked).toBe(true)
- expect(getByText("No longer paired")).toBeTruthy()
+ // A setup link or a revoked permission leaves a saved profile that can never match.
+ it("flags a saved device the service cannot see without the Nearby devices permission", async () => {
+ mockCheckBluetoothPermission.mockResolvedValue(false)
+ const { findByText, getByTestId } = renderEdit(3)
- fireEvent.press(getByTestId("condition-charging"))
- fireEvent.press(getByTestId("condition-bluetooth_device"))
- await findByTestId("bluetooth-device-AA:BB:CC:DD:EE:FF")
- expect(getByTestId("bluetooth-device-00:11:22:33:44:55").props.accessibilityState.checked).toBe(true)
+ expect(await findByText("Nearby devices not allowed")).toBeTruthy()
expect(getByTestId("save-profile-btn").props.accessibilityState.disabled).toBe(false)
})
it("clears the stored device when saved under another condition", async () => {
- const { findByTestId, getByTestId } = renderEdit(3)
- await findByTestId("bluetooth-device-00:11:22:33:44:55")
+ const { findByText, getByTestId } = renderEdit(3)
+ await findByText("Old Car")
fireEvent.press(getByTestId("condition-charging"))
fireEvent.press(getByTestId("save-profile-btn"))
diff --git a/apps/mobile/src/screens/index.ts b/apps/mobile/src/screens/index.ts
index 5d5a314a..b4e5cbc4 100644
--- a/apps/mobile/src/screens/index.ts
+++ b/apps/mobile/src/screens/index.ts
@@ -19,6 +19,7 @@ export { LocationSummaryScreen } from "./LocationSummaryScreen"
export { SettingsScreen } from "./SettingsScreen"
export { TrackingProfilesScreen } from "./TrackingProfilesScreen"
export { ProfileEditorScreen } from "./ProfileEditorScreen"
+export { BluetoothDeviceScreen } from "./BluetoothDeviceScreen"
export { AboutScreen } from "./AboutScreen"
export { AppearanceScreen } from "./AppearanceScreen"
export { LanguageScreen } from "./LanguageScreen"
diff --git a/apps/mobile/src/types/navigation.ts b/apps/mobile/src/types/navigation.ts
index 52bbca06..8551a7dd 100644
--- a/apps/mobile/src/types/navigation.ts
+++ b/apps/mobile/src/types/navigation.ts
@@ -1,4 +1,4 @@
-import type { ApiTemplateName } from "./global"
+import type { ApiTemplateName, BluetoothDeviceInfo } from "./global"
/**
* Copyright (C) 2026 Max Dietrich
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
@@ -29,7 +29,8 @@ export type RootStackParamList = {
"Auto-Export": undefined
"Data Management": undefined
"Tracking Profiles": undefined
- "Profile Editor": { profileId?: number } | undefined
+ "Profile Editor": { profileId?: number; bluetoothDevice?: BluetoothDeviceInfo } | undefined
+ "Bluetooth Device": { selected?: BluetoothDeviceInfo } | undefined
"About Colota": undefined
"Setup Import": undefined
"Share Setup": undefined