Skip to content

Colota - Android GPS Location tracker

refactor(geofences): the same bones as the other tabs (#854)

Max Dietrichb0997ec65d98
diff --git a/apps/docs/docs/guides/geofencing.md b/apps/docs/docs/guides/geofencing.md
index f9ca6b60..aefca288 100644
--- a/apps/docs/docs/guides/geofencing.md
+++ b/apps/docs/docs/guides/geofencing.md
@@ -15,17 +15,19 @@ Create zones where location recording stops automatically. These "pause zones" s
## Setup
1. Go to the **Geofences** tab
-2. Enter a name and radius
-3. Tap **Place Geofence**, then tap the map to place it
-4. Tap the **›** arrow on any geofence to open the editor and configure pause options
+2. Tap **+** in the top bar
+3. Give the zone a name and a radius, then tap **Location** and pick a point on the map
+4. Set the pause options, then tap **Save geofence**
+
+Tap any zone in the list, or its circle on the map, to reopen the editor. Every field can be changed there, **Location** included. The zone you are paused in reads **Paused here** in the list.
import ScreenshotGallery from '@site/src/components/ScreenshotGallery'
-<ScreenshotGallery screenshots={[ { src: "/img/screenshots/Geofences.png", label: "Geofences" }, { src: "/img/screenshots/GeofenceEditor.png", label: "Geofence Editor" }, ]} />
+<ScreenshotGallery screenshots={[ { src: "/img/screenshots/Geofences.png", label: "Geofences" }, { src: "/img/screenshots/GeofenceEditor.png", label: "Geofence editor" }, ]} />
## GPS Pause Options
-Each geofence has independent pause settings, configured in the editor (tap **›**):
+Each geofence has independent pause settings, configured in the editor:
### Don't record in zone
@@ -64,7 +66,7 @@ Changes made in the editor take effect immediately, even when you are already in
You can share all your geofences with another device or another user via a setup link instead of recreating zones by hand.
1. Open the **Geofences** screen
-2. Tap the share icon next to "Active Geofences"
+2. Tap the share icon in the top bar
3. The system share sheet opens with a `colota://setup?config=...` link
4. Send the link through any messenger, email or as a QR code
@@ -72,7 +74,7 @@ When the recipient opens the link, Colota shows the import confirmation screen l
The share button is all-or-nothing - every zone in the list is included. The `id`, `createdAt` and `enabled` fields are stripped, so imported zones always start enabled and get fresh database entries on the recipient's device.
-To share zones together with your tracking, sync and API settings in a single link, use **Settings -> Share Setup** instead (see [Deep Link Setup](deep-link-setup.md#sharing-from-the-app)).
+To share zones together with your tracking, sync and API settings in a single link, use **Settings -> Share setup** instead (see [Deep Link Setup](deep-link-setup.md#sharing-from-the-app)).
See the [Deep Link Setup](deep-link-setup.md#geofences) guide for the full payload format.
diff --git a/apps/mobile/App.tsx b/apps/mobile/App.tsx
index 7a9f184b..6e77d2fc 100644
--- a/apps/mobile/App.tsx
+++ b/apps/mobile/App.tsx
@@ -26,6 +26,7 @@ import {
AutoExportScreen,
GeofenceScreen,
GeofenceEditorScreen,
+ PlaceZoneScreen,
DataManagementScreen,
LocationHistoryScreen,
LocationSummaryScreen,
@@ -97,6 +98,11 @@ const SCREEN_CONFIG: readonly ScreenConfig[] = [
component: GeofenceEditorScreen,
title: "Geofence editor"
},
+ {
+ name: "Place Zone",
+ component: PlaceZoneScreen,
+ title: "Place zone"
+ },
{
name: "Location History",
component: LocationHistoryScreen,
diff --git a/apps/mobile/src/screens/GeofenceEditorScreen.tsx b/apps/mobile/src/screens/GeofenceEditorScreen.tsx
index e6ec9d63..80508cc0 100644
--- a/apps/mobile/src/screens/GeofenceEditorScreen.tsx
+++ b/apps/mobile/src/screens/GeofenceEditorScreen.tsx
@@ -4,17 +4,28 @@
*/
import React, { useState, useEffect, useCallback, useRef, useMemo } from "react"
-import { View, Text, StyleSheet, ScrollView, Switch, TextInput, DeviceEventEmitter } from "react-native"
+import { View, Text, StyleSheet, ScrollView, DeviceEventEmitter } from "react-native"
import { useTheme } from "../hooks/useTheme"
import NativeLocationService from "../services/NativeLocationService"
import { showAlert, showConfirm } from "../services/modalService"
-import { fonts } from "../styles/typography"
-import { Container, SectionTitle, Card, SettingRow, Button, FieldMessage } from "../components"
+import { fontSizes, fonts, lineHeights } from "../styles/typography"
+import {
+ Button,
+ Card,
+ Container,
+ FieldMessage,
+ ListItem,
+ SectionTitle,
+ SettingRow,
+ Toggle,
+ TextField
+} from "../components"
import { Check, Trash2 } from "lucide-react-native"
import { logger } from "../utils/logger"
import { shortDistanceUnit, inputToMeters, metersToInput } from "../utils/geo"
import { parsePositiveInt, isPositiveInt } from "../utils/settingsValidation"
import type { RootScreenProps } from "../types/navigation"
+import { size, space } from "../constants"
declare function requestIdleCallback(callback: () => void): number
declare function cancelIdleCallback(handle: number): void
@@ -35,6 +46,10 @@ export function GeofenceEditorScreen({ navigation, route }: RootScreenProps<"Geo
const [heartbeatEnabled, setHeartbeatEnabled] = useState(false)
const [heartbeatIntervalStr, setHeartbeatIntervalStr] = useState("15")
const [saving, setSaving] = useState(false)
+ const placedOnEntry = useRef(route?.params?.lat != null)
+ const [coord, setCoord] = useState<{ lat: number; lon: number } | null>(
+ route?.params?.lat != null && route?.params?.lon != null ? { lat: route.params.lat, lon: route.params.lon } : null
+ )
const savedState = useRef({
name: route?.params?.name ?? ("" as string),
@@ -44,13 +59,16 @@ export function GeofenceEditorScreen({ navigation, route }: RootScreenProps<"Geo
pauseOnMotionless: false,
motionlessTimeoutStr: "1",
heartbeatEnabled: false,
- heartbeatIntervalStr: "15"
+ heartbeatIntervalStr: "15",
+ coord: null as { lat: number; lon: number } | null
})
const hasChanges = useMemo(() => {
const s = savedState.current
return (
name !== s.name ||
+ coord?.lat !== s.coord?.lat ||
+ coord?.lon !== s.coord?.lon ||
radius !== s.radius ||
pauseTracking !== s.pauseTracking ||
pauseOnWifi !== s.pauseOnWifi ||
@@ -61,6 +79,7 @@ export function GeofenceEditorScreen({ navigation, route }: RootScreenProps<"Geo
)
}, [
name,
+ coord,
radius,
pauseTracking,
pauseOnWifi,
@@ -84,6 +103,8 @@ export function GeofenceEditorScreen({ navigation, route }: RootScreenProps<"Geo
setName(existing.name)
setRadiusStr(String(metersToInput(existing.radius)))
setRadius(existing.radius)
+ // A coordinate carried in is newer than the stored one, so the load must not undo it.
+ if (!placedOnEntry.current) setCoord({ lat: existing.lat, lon: existing.lon })
setPauseTracking(existing.pauseTracking)
setPauseOnWifi(existing.pauseOnWifi)
setPauseOnMotionless(existing.pauseOnMotionless)
@@ -98,7 +119,8 @@ export function GeofenceEditorScreen({ navigation, route }: RootScreenProps<"Geo
pauseOnMotionless: existing.pauseOnMotionless,
motionlessTimeoutStr: String(existing.motionlessTimeoutMinutes),
heartbeatEnabled: existing.heartbeatEnabled ?? false,
- heartbeatIntervalStr: String(existing.heartbeatIntervalMinutes ?? 15)
+ heartbeatIntervalStr: String(existing.heartbeatIntervalMinutes ?? 15),
+ coord: { lat: existing.lat, lon: existing.lon }
}
}
})
@@ -116,6 +138,11 @@ export function GeofenceEditorScreen({ navigation, route }: RootScreenProps<"Geo
}
}, [geofenceId, navigation])
+ useEffect(() => {
+ const { lat, lon } = route?.params ?? {}
+ if (lat != null && lon != null) setCoord({ lat, lon })
+ }, [route?.params])
+
const handleRadiusChange = useCallback((val: string) => {
setRadiusStr(val)
const num = Number(val)
@@ -140,6 +167,8 @@ export function GeofenceEditorScreen({ navigation, route }: RootScreenProps<"Geo
await NativeLocationService.updateGeofence({
id: geofenceId,
name: name.trim(),
+ lat: coord?.lat,
+ lon: coord?.lon,
radius,
pauseTracking,
pauseOnWifi,
@@ -149,12 +178,15 @@ export function GeofenceEditorScreen({ navigation, route }: RootScreenProps<"Geo
heartbeatIntervalMinutes: effectiveHeartbeat
})
} else {
- const lat = route?.params?.lat as number
- const lon = route?.params?.lon as number
+ if (!coord) {
+ showAlert("No location", "Place the zone on the map first.", "warning")
+ setSaving(false)
+ return
+ }
await NativeLocationService.createGeofence({
name: name.trim(),
- lat,
- lon,
+ lat: coord.lat,
+ lon: coord.lon,
radius,
enabled: true,
pauseTracking,
@@ -175,6 +207,7 @@ export function GeofenceEditorScreen({ navigation, route }: RootScreenProps<"Geo
}
}, [
name,
+ coord,
radius,
pauseTracking,
pauseOnWifi,
@@ -184,14 +217,13 @@ export function GeofenceEditorScreen({ navigation, route }: RootScreenProps<"Geo
heartbeatIntervalStr,
isEditing,
geofenceId,
- navigation,
- route
+ navigation
])
const handleDelete = useCallback(async () => {
if (!geofenceId) return
const confirmed = await showConfirm({
- title: "Delete Geofence",
+ title: "Delete geofence",
message: `Delete "${name}"?`,
confirmText: "Delete",
destructive: true
@@ -207,91 +239,90 @@ export function GeofenceEditorScreen({ navigation, route }: RootScreenProps<"Geo
}
}, [geofenceId, name, navigation])
- const inputStyle = [
- styles.input,
- { backgroundColor: colors.background, color: colors.text, borderColor: colors.border }
- ]
-
return (
<Container>
<ScrollView contentContainerStyle={styles.content} showsVerticalScrollIndicator={false}>
<SectionTitle>General</SectionTitle>
- <Card style={styles.card}>
+ <Card rows style={styles.card}>
<SettingRow label="Name">
- <TextInput
+ <TextField
testID="geofence-name-input"
- style={[inputStyle, styles.nameInput]}
+ accessibilityLabel="Name"
+ style={styles.nameInput}
value={name}
onChangeText={setName}
placeholder="Home, Work..."
- placeholderTextColor={colors.placeholder}
/>
</SettingRow>
<SettingRow label={`Radius (${shortDistanceUnit()})`}>
- <TextInput
+ <TextField
testID="geofence-radius-input"
- style={[inputStyle, styles.numInput]}
+ accessibilityLabel="Radius"
+ figure
+ style={styles.numInput}
value={radiusStr}
onChangeText={handleRadiusChange}
placeholder="50"
- placeholderTextColor={colors.placeholder}
keyboardType="numeric"
/>
</SettingRow>
+ <ListItem
+ testID="place-zone-row"
+ label="Location"
+ sub={coord ? `${coord.lat.toFixed(5)}, ${coord.lon.toFixed(5)}` : "Not placed yet"}
+ onPress={() =>
+ navigation.navigate("Place Zone", {
+ name: name.trim() || "New zone",
+ radius,
+ lat: coord?.lat,
+ lon: coord?.lon
+ })
+ }
+ />
</Card>
- <SectionTitle>GPS Pause Options</SectionTitle>
- <Card style={styles.card}>
- <SettingRow label="Don't record in zone" hint="Pause saving and syncing" style={styles.toggleRow}>
- <Switch
+ <SectionTitle>GPS pause options</SectionTitle>
+ <Card rows style={[styles.card, styles.cardTail]}>
+ <SettingRow label="Don't record in zone" hint="Pause saving and syncing">
+ <Toggle
+ accessibilityLabel="Don't record in zone"
testID="pause-tracking-toggle"
value={pauseTracking}
onValueChange={setPauseTracking}
- trackColor={{ false: colors.border, true: colors.warning + "80" }}
- thumbColor={pauseTracking ? colors.warning : colors.border}
/>
</SettingRow>
- <SettingRow
- label="WiFi/Ethernet pause"
- hint="Stop GPS on unmetered networks"
- style={[styles.toggleRow, !pauseTracking && styles.disabledRow]}
- >
- <Switch
+ <SettingRow label="WiFi/Ethernet pause" hint="Stop GPS on unmetered networks" disabled={!pauseTracking}>
+ <Toggle
+ accessibilityLabel="WiFi/Ethernet pause"
testID="pause-wifi-toggle"
value={pauseOnWifi}
onValueChange={setPauseOnWifi}
disabled={!pauseTracking}
- trackColor={{ false: colors.border, true: colors.primary + "80" }}
- thumbColor={pauseOnWifi ? colors.primary : colors.border}
/>
</SettingRow>
- <SettingRow
- label="Motionless pause"
- hint="Stop GPS after no motion for a set time"
- style={[styles.toggleRow, !pauseTracking && styles.disabledRow]}
- >
- <Switch
+ <SettingRow label="Motionless pause" hint="Stop GPS after no motion for a set time" disabled={!pauseTracking}>
+ <Toggle
+ accessibilityLabel="Motionless pause"
testID="pause-motionless-toggle"
value={pauseOnMotionless}
onValueChange={setPauseOnMotionless}
disabled={!pauseTracking}
- trackColor={{ false: colors.border, true: colors.primary + "80" }}
- thumbColor={pauseOnMotionless ? colors.primary : colors.border}
/>
</SettingRow>
{pauseTracking && pauseOnMotionless && (
- <View style={[styles.nestedSetting, { borderLeftColor: colors.border }]}>
+ <View style={styles.nestedSetting}>
<SettingRow label="Timeout (min)" hint="Minutes without motion before GPS stops">
- <TextInput
+ <TextField
testID="motionless-timeout-input"
- style={[inputStyle, styles.numInput]}
+ accessibilityLabel="Timeout in minutes"
+ figure
+ style={styles.numInput}
value={motionlessTimeoutStr}
onChangeText={setMotionlessTimeoutStr}
placeholder="1"
- placeholderTextColor={colors.placeholder}
keyboardType="number-pad"
/>
</SettingRow>
@@ -304,28 +335,28 @@ export function GeofenceEditorScreen({ navigation, route }: RootScreenProps<"Geo
<SettingRow
label="Stationary heartbeat"
hint="Periodic point at the zone center while paused"
- style={[styles.toggleRow, !pauseTracking && styles.disabledRow]}
+ disabled={!pauseTracking}
>
- <Switch
+ <Toggle
+ accessibilityLabel="Stationary heartbeat"
testID="heartbeat-toggle"
value={heartbeatEnabled}
onValueChange={setHeartbeatEnabled}
disabled={!pauseTracking}
- trackColor={{ false: colors.border, true: colors.primary + "80" }}
- thumbColor={heartbeatEnabled ? colors.primary : colors.border}
/>
</SettingRow>
{pauseTracking && heartbeatEnabled && (
- <View style={[styles.nestedSetting, { borderLeftColor: colors.border }]}>
+ <View style={styles.nestedSetting}>
<SettingRow label="Interval (min)" hint="How often to record a point">
- <TextInput
+ <TextField
testID="heartbeat-interval-input"
- style={[inputStyle, styles.numInput]}
+ accessibilityLabel="Interval in minutes"
+ figure
+ style={styles.numInput}
value={heartbeatIntervalStr}
onChangeText={setHeartbeatIntervalStr}
placeholder="15"
- placeholderTextColor={colors.placeholder}
keyboardType="number-pad"
/>
</SettingRow>
@@ -336,7 +367,7 @@ export function GeofenceEditorScreen({ navigation, route }: RootScreenProps<"Geo
)}
{pauseTracking && pauseOnWifi && pauseOnMotionless && (
- <View style={[styles.combinedNote, { borderTopColor: colors.border }]}>
+ <View style={[styles.combinedNote, { borderTopColor: colors.divider }]}>
<Text style={[styles.combinedNoteText, { color: colors.textSecondary }]}>
GPS resumes only when both WiFi is disconnected and motion is detected
</Text>
@@ -345,7 +376,8 @@ export function GeofenceEditorScreen({ navigation, route }: RootScreenProps<"Geo
</Card>
<Button
- title={saving ? "Saving..." : "Save Geofence"}
+ title="Save geofence"
+ loading={saving}
onPress={handleSave}
disabled={
saving ||
@@ -355,35 +387,31 @@ export function GeofenceEditorScreen({ navigation, route }: RootScreenProps<"Geo
}
icon={Check}
/>
- {isEditing && <Button title="Delete Geofence" onPress={handleDelete} variant="danger" icon={Trash2} />}
+ {isEditing && <Button title="Delete geofence" onPress={handleDelete} variant="danger" icon={Trash2} />}
</ScrollView>
</Container>
)
}
const styles = StyleSheet.create({
- content: { padding: 20, paddingBottom: 40 },
- card: { marginBottom: 16 },
- input: {
- padding: 10,
- borderWidth: 1.5,
- borderRadius: 8,
- fontSize: 15
- },
+ cardTail: { paddingBottom: space.lg },
+ content: { padding: space.lg, paddingBottom: space.xxl },
+ card: { marginBottom: space.lg },
nameInput: { flex: 1 },
- numInput: { width: 80, textAlign: "center" },
- toggleRow: { paddingVertical: 10 },
- disabledRow: { opacity: 0.45 },
- nestedSetting: { marginLeft: 16, paddingLeft: 12, borderLeftWidth: 3, marginTop: 4, marginBottom: 4 },
+ numInput: { width: size.numericField },
+ nestedSetting: {
+ marginTop: space.md,
+ marginStart: space.lg
+ },
combinedNote: {
- marginTop: 8,
- paddingTop: 12,
+ marginTop: space.sm,
+ paddingTop: space.md,
borderTopWidth: StyleSheet.hairlineWidth
},
combinedNoteText: {
- fontSize: 12,
+ fontSize: fontSizes.caption,
...fonts.regular,
- lineHeight: 17,
+ lineHeight: lineHeights.caption,
fontStyle: "italic"
}
})
diff --git a/apps/mobile/src/screens/GeofenceScreen.tsx b/apps/mobile/src/screens/GeofenceScreen.tsx
index 109f5cc3..fe5e2c0b 100644
--- a/apps/mobile/src/screens/GeofenceScreen.tsx
+++ b/apps/mobile/src/screens/GeofenceScreen.tsx
@@ -3,235 +3,152 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
-import React, { useState, useEffect, useRef, useMemo, useCallback } from "react"
-import { View, Text, StyleSheet, TextInput, Pressable, FlatList, DeviceEventEmitter, Share } from "react-native"
+import React, { useState, useEffect, useRef, useMemo, useCallback, useLayoutEffect } from "react"
+import { View, StyleSheet, ScrollView, DeviceEventEmitter, Share, useWindowDimensions } from "react-native"
+import { useSafeAreaInsets } from "react-native-safe-area-context"
+import { useFocusEffect } from "@react-navigation/native"
import { useTheme } from "../hooks/useTheme"
import NativeLocationService from "../services/NativeLocationService"
import { showAlert } from "../services/modalService"
import { Geofence, ScreenProps } from "../types/global"
import { useTracking, useCoords } from "../contexts/TrackingProvider"
-import { fonts } from "../styles/typography"
-import { ChevronRight, Wifi, PersonStanding, MapPinHouse, Share2 } from "lucide-react-native"
-import { Container, SectionTitle, Card } from "../components"
+import { MapPinHouse, MapPinCheck, Share2, Plus, LocateFixed } from "lucide-react-native"
+import { Card, Container, Divider, EmptyState, HeaderAction, ListItem } from "../components"
import {
DEFAULT_MAP_ZOOM,
- WORLD_MAP_ZOOM,
GEOFENCE_ZOOM_PADDING,
MAP_ANIMATION_DURATION_MS,
- MAX_MAP_ZOOM,
- HIT_SLOP_MD
+ WORLD_MAP_ZOOM,
+ size,
+ space
} from "../constants"
-import { MapCenterButton } from "../components/features/map/MapCenterButton"
+import { MapActionButton } from "../components/features/map/MapActionButton"
import { ColotaMapView, ColotaMapRef } from "../components/features/map/ColotaMapView"
-import { buildGeofencesGeoJSON } from "../components/features/map/mapUtils"
+import { buildGeofencesGeoJSON, geofenceBounds } from "../components/features/map/mapUtils"
import { GeofenceLayers } from "../components/features/map/GeofenceLayers"
import { UserLocationOverlay } from "../components/features/map/UserLocationOverlay"
import { logger } from "../utils/logger"
-import { formatShortDistance, shortDistanceUnit, inputToMeters } from "../utils/geo"
+import { zoneRowSub } from "../utils/geofenceRow"
import { buildGeofencesLink } from "../utils/setupLink"
-const GeofenceMap = React.memo(function GeofenceMap({
- tracking,
- geofenceData,
- currentPauseZone,
- onMapPress,
- focusRequest
-}: {
- tracking: boolean
- geofenceData: ReturnType<typeof buildGeofencesGeoJSON>
- currentPauseZone: string | null
- onMapPress: (coords: { latitude: number; longitude: number }) => void
- focusRequest: { geofence: Geofence; key: number } | null
-}) {
- const coords = useCoords()
- const { colors } = useTheme()
-
- const mapRef = useRef<ColotaMapRef>(null)
- const isCenteredRef = useRef(true)
- const [isCentered, setIsCentered] = useState(true)
- const [hasInitialCoords, setHasInitialCoords] = useState(false)
- const initialCenter = useRef<{ latitude: number; longitude: number; accuracy: number } | null>(null)
+const MAP_VIEWPORT_SHARE = 0.5
+const WORLD_CENTER: [number, number] = [0, 20]
- useEffect(() => {
- if (hasInitialCoords) return
- if (coords) {
- initialCenter.current = { latitude: coords.latitude, longitude: coords.longitude, accuracy: coords.accuracy ?? 0 }
- setHasInitialCoords(true)
- return
- }
- NativeLocationService.getMostRecentLocation().then((latest) => {
- if (initialCenter.current) return
- initialCenter.current = latest
- ? { latitude: latest.latitude, longitude: latest.longitude, accuracy: latest.accuracy ?? 0 }
- : { latitude: 0, longitude: 0, accuracy: 0 }
- setHasInitialCoords(true)
- })
- }, [coords, hasInitialCoords])
-
- useEffect(() => {
- if (!coords || !isCenteredRef.current || !tracking || !mapRef.current?.camera) return
- mapRef.current.camera.easeTo({
- center: [coords.longitude, coords.latitude],
- duration: MAP_ANIMATION_DURATION_MS
- })
- }, [coords, tracking])
-
- useEffect(() => {
- if (!focusRequest || !mapRef.current?.camera) return
- const { geofence } = focusRequest
- const latDelta = (geofence.radius / 111320) * 1.5
- const lonDelta = (geofence.radius / (111320 * Math.cos((geofence.lat * Math.PI) / 180))) * 1.5
- mapRef.current.camera.fitBounds(
- [geofence.lon - lonDelta, geofence.lat - latDelta, geofence.lon + lonDelta, geofence.lat + latDelta],
- {
- padding: {
- top: GEOFENCE_ZOOM_PADDING[0],
- right: GEOFENCE_ZOOM_PADDING[1],
- bottom: GEOFENCE_ZOOM_PADDING[2],
- left: GEOFENCE_ZOOM_PADDING[3]
- },
- duration: 600
- }
- )
- }, [focusRequest])
-
- const handleCenterMe = useCallback(() => {
- if (coords && mapRef.current?.camera) {
- mapRef.current.camera.flyTo({
- center: [coords.longitude, coords.latitude],
- zoom: MAX_MAP_ZOOM,
- duration: MAP_ANIMATION_DURATION_MS
- })
- isCenteredRef.current = true
- setIsCentered(true)
- }
- }, [coords])
-
- const handleRegionChange = useCallback((payload: { isUserInteraction: boolean }) => {
- if (payload.isUserInteraction) {
- isCenteredRef.current = false
- setIsCentered(false)
- }
- }, [])
-
- const hasRealCoords =
- initialCenter.current && (initialCenter.current.latitude !== 0 || initialCenter.current.longitude !== 0)
- const initialZoom = hasRealCoords ? DEFAULT_MAP_ZOOM : WORLD_MAP_ZOOM
-
- return (
- <View style={[styles.map, { borderRadius: colors.borderRadius }]}>
- {hasInitialCoords && initialCenter.current ? (
- <ColotaMapView
- ref={mapRef}
- initialCenter={[initialCenter.current.longitude, initialCenter.current.latitude]}
- initialZoom={initialZoom}
- onPress={onMapPress}
- onRegionDidChange={handleRegionChange}
- >
- <GeofenceLayers fills={geofenceData.fills} labels={geofenceData.labels} haloColor={colors.card} />
- {coords && tracking && <UserLocationOverlay coords={coords} isPaused={!!currentPauseZone} colors={colors} />}
- </ColotaMapView>
- ) : null}
- <MapCenterButton visible={!isCentered && tracking} onPress={handleCenterMe} />
- </View>
- )
-})
+type Fix = { latitude: number; longitude: number; accuracy: number }
export function GeofenceScreen({ navigation }: ScreenProps) {
+ const { height: viewportHeight } = useWindowDimensions()
+ const insets = useSafeAreaInsets()
+ const mapHeight = Math.round(viewportHeight * MAP_VIEWPORT_SHARE)
const { tracking } = useTracking()
+ const coords = useCoords()
const { colors } = useTheme()
- const [geofences, setGeofences] = useState<Geofence[]>([])
- const [newName, setNewName] = useState("")
- const [newRadius, setNewRadius] = useState("50")
- const [placingGeofence, setPlacingGeofence] = useState(false)
+ const [geofences, setGeofences] = useState<Geofence[] | null>(null)
const [currentPauseZone, setCurrentPauseZone] = useState<string | null>(null)
-
- const [focusRequest, setFocusRequest] = useState<{ geofence: Geofence; key: number } | null>(null)
+ // `undefined` until the database has answered, so the tiles never open on the world view and jump.
+ const [lastFix, setLastFix] = useState<Fix | null | undefined>(undefined)
+ const [mapReady, setMapReady] = useState(false)
+ const [panned, setPanned] = useState(false)
+ const mapRef = useRef<ColotaMapRef>(null)
+ const fittedRef = useRef<string | null>(null)
const loadGeofences = useCallback(async () => {
try {
- const data = await NativeLocationService.getGeofences()
- setGeofences(data)
+ setGeofences(await NativeLocationService.getGeofences())
} catch (err) {
logger.error("[GeofenceScreen] Failed to load geofences:", err)
}
}, [])
- useEffect(() => {
- loadGeofences()
- }, [loadGeofences])
-
- useEffect(() => {
- const checkPauseZone = async () => {
- try {
- const result = await NativeLocationService.checkCurrentPauseZone()
- setCurrentPauseZone(result?.zoneName ?? null)
- } catch (err) {
- logger.error("[GeofenceScreen] Failed to check pause zone:", err)
- }
+ const checkPauseZone = useCallback(async () => {
+ try {
+ const result = await NativeLocationService.checkCurrentPauseZone()
+ setCurrentPauseZone(result?.zoneName ?? null)
+ } catch (err) {
+ logger.error("[GeofenceScreen] Failed to check pause zone:", err)
}
+ }, [])
- checkPauseZone()
- const listener = DeviceEventEmitter.addListener("geofenceUpdated", () => {
+ useFocusEffect(
+ useCallback(() => {
+ loadGeofences()
checkPauseZone()
+ }, [loadGeofences, checkPauseZone])
+ )
+
+ useEffect(() => {
+ const updated = DeviceEventEmitter.addListener("geofenceUpdated", () => {
loadGeofences()
+ checkPauseZone()
})
- return () => listener.remove()
- }, [loadGeofences])
-
- const handleMapPress = useCallback(
- async (pressCoords: { latitude: number; longitude: number }) => {
- if (!placingGeofence) return
- setPlacingGeofence(false)
- try {
- await NativeLocationService.createGeofence({
- name: newName.trim(),
- lat: pressCoords.latitude,
- lon: pressCoords.longitude,
- radius: inputToMeters(Number(newRadius)),
- enabled: true,
- pauseTracking: true,
- pauseOnWifi: false,
- pauseOnMotionless: false,
- motionlessTimeoutMinutes: 1,
- heartbeatEnabled: false,
- heartbeatIntervalMinutes: 15
- })
- await loadGeofences()
- DeviceEventEmitter.emit("geofenceUpdated")
- } catch (err) {
- logger.error("[GeofenceScreen] Failed to create geofence:", err)
- showAlert("Error", "Failed to create geofence.", "error")
- }
- setNewName("")
- setNewRadius("50")
- },
- [placingGeofence, newName, newRadius, loadGeofences]
- )
+ const zone = DeviceEventEmitter.addListener(
+ "onPauseZoneChange",
+ (data: { entered: boolean; zoneName: string | null }) => setCurrentPauseZone(data.entered ? data.zoneName : null)
+ )
+ return () => {
+ updated.remove()
+ zone.remove()
+ }
+ }, [loadGeofences, checkPauseZone])
- const startPlacingGeofence = useCallback(() => {
- if (!newName.trim()) {
- showAlert("Missing Name", "Please enter a name.", "warning")
+ useEffect(() => {
+ if (coords) {
+ setLastFix({ latitude: coords.latitude, longitude: coords.longitude, accuracy: coords.accuracy ?? 0 })
return
}
+ let active = true
+ NativeLocationService.getMostRecentLocation()
+ .then((latest) => {
+ if (!active) return
+ setLastFix(
+ latest ? { latitude: latest.latitude, longitude: latest.longitude, accuracy: latest.accuracy ?? 0 } : null
+ )
+ })
+ .catch((err) => {
+ logger.error("[GeofenceScreen] Failed to read the last known location:", err)
+ if (active) setLastFix(null)
+ })
+ return () => {
+ active = false
+ }
+ }, [coords])
- const radius = Number(newRadius)
- if (!radius || radius <= 0) {
- showAlert("Invalid Radius", "Please enter a valid radius.", "warning")
- return
+ const edgeStart = space.lg + insets.left
+ const edgeEnd = space.lg + insets.right
+ const controlsBottom = space.lg + space.sm
+ const cameraPadding = useMemo(
+ () => ({ top: space.lg, bottom: space.lg, left: edgeStart, right: edgeEnd + size.iconColumn + space.lg }),
+ [edgeStart, edgeEnd]
+ )
+ const fitPadding = useMemo(() => {
+ const [top, right, bottom, left] = GEOFENCE_ZOOM_PADDING
+ return {
+ top: top + cameraPadding.top,
+ right: right + cameraPadding.right,
+ bottom: bottom + cameraPadding.bottom,
+ left: left + cameraPadding.left
}
+ }, [cameraPadding])
- setPlacingGeofence(true)
- }, [newName, newRadius])
+ const fitZones = useCallback(
+ (zones: Geofence[], duration: number) => {
+ mapRef.current?.camera?.fitBounds(geofenceBounds(zones), { padding: fitPadding, duration })
+ setPanned(false)
+ },
+ [fitPadding]
+ )
- const focusKeyRef = useRef(0)
- const handleZoomToGeofence = useCallback((item: Geofence) => {
- setFocusRequest({ geofence: item, key: ++focusKeyRef.current })
- }, [])
+ const zoneKey = geofences?.map((z) => z.id).join(",") ?? null
+ useEffect(() => {
+ if (!mapReady || !geofences || geofences.length === 0 || zoneKey === fittedRef.current) return
+ // The first fit lands before the tiles show; a changed zone set animates so the eye can follow.
+ fitZones(geofences, fittedRef.current === null ? 0 : MAP_ANIMATION_DURATION_MS)
+ fittedRef.current = zoneKey
+ }, [mapReady, geofences, zoneKey, fitZones])
const handleShareGeofences = useCallback(async () => {
- if (geofences.length === 0) return
+ if (!geofences || geofences.length === 0) return
try {
await Share.share({ message: buildGeofencesLink(geofences) })
} catch (err) {
@@ -240,203 +157,140 @@ export function GeofenceScreen({ navigation }: ScreenProps) {
}
}, [geofences])
- const geofenceData = useMemo(() => buildGeofencesGeoJSON(geofences, colors), [geofences, colors])
+ const openEditor = useCallback(
+ (geofenceId?: number) => {
+ navigation.navigate("Geofence Editor", geofenceId === undefined ? {} : { geofenceId })
+ },
+ [navigation]
+ )
- const renderItem = useCallback(
- ({ item }: { item: Geofence }) => (
- <Card style={styles.card}>
- <View style={styles.row}>
- <Pressable
- onPress={() => handleZoomToGeofence(item)}
- hitSlop={HIT_SLOP_MD}
- style={({ pressed }) => [styles.zoomBtn, pressed && { opacity: colors.pressedOpacity }]}
- >
- <MapPinHouse size={20} color={colors.textSecondary} />
- </Pressable>
- <Pressable
- testID={`edit-geofence-${item.id}`}
- style={({ pressed }) => [styles.editBtn, pressed && { opacity: colors.pressedOpacity }]}
- onPress={() => navigation.navigate("Geofence Editor", { geofenceId: item.id })}
- >
- <View style={styles.info}>
- <Text style={[styles.name, { color: colors.text }]}>{item.name}</Text>
- <View style={styles.radiusRow}>
- <Text style={[styles.radius, { color: colors.textSecondary }]}>
- {formatShortDistance(item.radius)} radius
- </Text>
- {item.pauseOnWifi && <Wifi size={12} color={colors.textSecondary} />}
- {item.pauseOnMotionless && <PersonStanding size={12} color={colors.textSecondary} />}
- </View>
- </View>
- <ChevronRight size={20} color={colors.textSecondary} />
- </Pressable>
- </View>
- </Card>
+ const hasZones = (geofences?.length ?? 0) > 0
+ const renderHeaderActions = useCallback(
+ () => (
+ <View style={styles.headerRow}>
+ {hasZones && (
+ <HeaderAction
+ icon={Share2}
+ label="Share all geofences"
+ onPress={handleShareGeofences}
+ testID="share-geofences-btn"
+ />
+ )}
+ <HeaderAction icon={Plus} label="Create geofence" onPress={() => openEditor()} testID="add-geofence-btn" />
+ </View>
),
- [colors, handleZoomToGeofence, navigation]
+ [hasZones, handleShareGeofences, openEditor]
)
+ useLayoutEffect(() => {
+ navigation.setOptions({ headerRight: renderHeaderActions })
+ }, [navigation, renderHeaderActions])
- return (
- <Container>
- <GeofenceMap
- tracking={tracking}
- geofenceData={geofenceData}
- currentPauseZone={currentPauseZone}
- onMapPress={handleMapPress}
- focusRequest={focusRequest}
- />
-
- <FlatList
- data={geofences}
- keyExtractor={(item) => item.id!.toString()}
- contentContainerStyle={styles.list}
- showsVerticalScrollIndicator={false}
- ListHeaderComponent={
- <>
- <View style={styles.section}>
- <SectionTitle>Create Geofence</SectionTitle>
- <Card>
- <Text style={[styles.hint, { color: colors.textSecondary }]}>
- Enter a name and radius, then tap the map to place
- </Text>
-
- <View style={styles.inputRow}>
- <View style={[styles.inputGroup, styles.inputGroupName]}>
- <Text style={[styles.label, { color: colors.textSecondary }]}>Name</Text>
- <TextInput
- testID="geofence-name-input"
- style={[
- styles.input,
- {
- backgroundColor: colors.background,
- color: colors.text,
- borderColor: colors.border
- }
- ]}
- placeholder="Home, Work..."
- placeholderTextColor={colors.placeholder}
- value={newName}
- onChangeText={setNewName}
- />
- </View>
+ const handleRegionChange = useCallback((payload: { isUserInteraction: boolean }) => {
+ if (payload.isUserInteraction) setPanned(true)
+ }, [])
- <View style={[styles.inputGroup, styles.inputGroupRadius]}>
- <Text style={[styles.label, { color: colors.textSecondary }]}>Radius ({shortDistanceUnit()})</Text>
- <TextInput
- testID="geofence-radius-input"
- style={[
- styles.input,
- styles.inputCentered,
- {
- backgroundColor: colors.background,
- color: colors.text,
- borderColor: colors.border
- }
- ]}
- placeholder="50"
- placeholderTextColor={colors.placeholder}
- value={newRadius}
- keyboardType="numeric"
- onChangeText={setNewRadius}
- />
- </View>
- </View>
+ const handleFit = useCallback(() => {
+ if (geofences && geofences.length > 0) {
+ fitZones(geofences, MAP_ANIMATION_DURATION_MS)
+ } else if (lastFix) {
+ mapRef.current?.camera?.flyTo({
+ center: [lastFix.longitude, lastFix.latitude],
+ zoom: DEFAULT_MAP_ZOOM,
+ padding: cameraPadding,
+ duration: MAP_ANIMATION_DURATION_MS
+ })
+ setPanned(false)
+ }
+ }, [geofences, lastFix, fitZones, cameraPadding])
- <Pressable
- testID="place-geofence-btn"
- style={({ pressed }) => [
- styles.placeBtn,
- { backgroundColor: colors.primary },
- pressed && { opacity: colors.pressedOpacity }
- ]}
- onPress={startPlacingGeofence}
- disabled={placingGeofence}
- >
- <Text style={[styles.placeBtnText, { color: colors.textOnPrimary }]}>
- {placingGeofence ? "Tap Map to Place..." : "Place Geofence"}
- </Text>
- </Pressable>
- </Card>
- </View>
+ const geofenceData = useMemo(() => buildGeofencesGeoJSON(geofences ?? [], colors), [geofences, colors])
+ const liveFix = tracking && coords ? coords : null
+ const showDisc = panned && (hasZones || lastFix !== null)
- {geofences.length > 0 && (
- <View style={styles.activeHeader}>
- <SectionTitle>Active Geofences ({geofences.length})</SectionTitle>
- <Pressable
- testID="share-geofences-btn"
- onPress={handleShareGeofences}
- hitSlop={HIT_SLOP_MD}
- style={({ pressed }) => [styles.shareBtn, pressed && { opacity: colors.pressedOpacity }]}
- >
- <Share2 size={20} color={colors.textSecondary} />
- </Pressable>
- </View>
- )}
- </>
- }
- ListEmptyComponent={
- geofences.length === 0 ? (
- <View style={styles.empty}>
- <Text style={[styles.emptyText, { color: colors.textSecondary }]}>No geofences yet</Text>
- <Text style={[styles.emptyHint, { color: colors.textLight }]}>
- Create a geofence to stop recording locations in specific areas
- </Text>
- </View>
- ) : undefined
- }
- renderItem={renderItem}
- />
+ return (
+ <Container>
+ <View style={{ height: mapHeight }}>
+ {lastFix !== undefined && (
+ <ColotaMapView
+ ref={mapRef}
+ initialCenter={lastFix ? [lastFix.longitude, lastFix.latitude] : WORLD_CENTER}
+ initialZoom={lastFix ? DEFAULT_MAP_ZOOM : WORLD_MAP_ZOOM}
+ cameraPadding={cameraPadding}
+ controlsBottom={controlsBottom}
+ controlsEnd={edgeEnd}
+ onRegionDidChange={handleRegionChange}
+ onMapReady={() => setMapReady(true)}
+ >
+ <GeofenceLayers
+ fills={geofenceData.fills}
+ labels={geofenceData.labels}
+ haloColor={colors.card}
+ onPressZone={openEditor}
+ />
+ {liveFix && <UserLocationOverlay coords={liveFix} isPaused={!!currentPauseZone} colors={colors} />}
+ </ColotaMapView>
+ )}
+ {showDisc && (
+ <MapActionButton
+ anchored={false}
+ style={[styles.disc, { bottom: controlsBottom + size.iconColumn + space.lg, right: edgeEnd }]}
+ accessibilityRole="button"
+ accessibilityLabel={hasZones ? "Fit geofences" : "Centre map on my position"}
+ onPress={handleFit}
+ testID="fit-geofences-btn"
+ >
+ <LocateFixed size={size.icon.md} color={colors.textLight} />
+ </MapActionButton>
+ )}
+ </View>
+
+ <ScrollView contentContainerStyle={styles.content}>
+ {geofences === null ? null : hasZones ? (
+ <Card rows>
+ {geofences.map((zone, i) => {
+ const pausedHere = tracking && currentPauseZone === zone.name
+ return (
+ <React.Fragment key={zone.id}>
+ {i > 0 && <Divider tight inset />}
+ <ListItem
+ testID={`edit-geofence-${zone.id}`}
+ icon={pausedHere ? MapPinCheck : MapPinHouse}
+ label={zone.name}
+ sub={zoneRowSub(zone, pausedHere)}
+ onPress={() => openEditor(zone.id)}
+ />
+ </React.Fragment>
+ )
+ })}
+ </Card>
+ ) : (
+ <EmptyState
+ icon={MapPinHouse}
+ title="No geofences yet"
+ hint="A geofence stops recording while you are inside it."
+ action={{ label: "Create geofence", onPress: () => openEditor() }}
+ style={styles.empty}
+ />
+ )}
+ </ScrollView>
</Container>
)
}
const styles = StyleSheet.create({
- map: { height: 450, overflow: "hidden" },
- list: { padding: 20, paddingBottom: 40 },
- section: { marginBottom: 16 },
- hint: { fontSize: 13, ...fonts.regular, lineHeight: 18, marginBottom: 16 },
- inputRow: { flexDirection: "row", gap: 12, marginBottom: 16 },
- inputGroup: { flex: 1 },
- inputGroupName: {
- flex: 2
- },
- inputGroupRadius: {
- flex: 0,
- minWidth: 90
- },
- label: {
- fontSize: 12,
- ...fonts.semiBold,
- marginBottom: 6,
- textTransform: "uppercase",
- letterSpacing: 0.5
+ headerRow: {
+ flexDirection: "row"
},
- input: { padding: 14, borderWidth: 1.5, borderRadius: 10, fontSize: 15 },
- inputCentered: {
- textAlign: "center"
+ disc: {
+ position: "absolute"
},
- placeBtn: { padding: 16, borderRadius: 12, alignItems: "center" },
- placeBtnText: { fontSize: 15, ...fonts.semiBold },
- card: { marginBottom: 12 },
- row: {
- flexDirection: "row",
- alignItems: "center",
- justifyContent: "space-between"
+ content: {
+ flexGrow: 1,
+ paddingHorizontal: space.lg,
+ paddingTop: space.lg,
+ paddingBottom: space.xxl
},
- zoomBtn: { padding: 4, marginRight: 16 },
- activeHeader: { flexDirection: "row", alignItems: "center", justifyContent: "space-between" },
- shareBtn: { padding: 4, marginBottom: 12 },
- editBtn: { flex: 1, flexDirection: "row", alignItems: "center" },
- info: { flex: 1, marginRight: 12 },
- name: { fontSize: 15, ...fonts.semiBold, marginBottom: 2 },
- radiusRow: { flexDirection: "row", alignItems: "center", gap: 4 },
- radius: { fontSize: 12 },
- empty: { alignItems: "center", paddingVertical: 20 },
- emptyText: { fontSize: 15, ...fonts.semiBold, marginBottom: 6 },
- emptyHint: {
- fontSize: 13,
- textAlign: "center",
- maxWidth: 260,
- lineHeight: 18
+ empty: {
+ paddingHorizontal: 0
}
})
diff --git a/apps/mobile/src/screens/PlaceZoneScreen.tsx b/apps/mobile/src/screens/PlaceZoneScreen.tsx
new file mode 100644
index 00000000..da3238b5
--- /dev/null
+++ b/apps/mobile/src/screens/PlaceZoneScreen.tsx
@@ -0,0 +1,84 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+import React, { useCallback, useMemo, useRef, useState } from "react"
+import { View, Text, StyleSheet } from "react-native"
+import { useTheme } from "../hooks/useTheme"
+import { useCoords } from "../contexts/TrackingProvider"
+import { Button, Container } from "../components"
+import { ColotaMapView, ColotaMapRef } from "../components/features/map/ColotaMapView"
+import { GeofenceLayers } from "../components/features/map/GeofenceLayers"
+import { buildGeofencesGeoJSON } from "../components/features/map/mapUtils"
+import { fontSizes, fonts } from "../styles/typography"
+import { space } from "../constants"
+import { formatShortDistance } from "../utils/geo"
+import { RootScreenProps } from "../types/navigation"
+
+const WORLD_CENTER: [number, number] = [0, 0]
+
+export function PlaceZoneScreen({ navigation, route }: RootScreenProps<"Place Zone">) {
+ const { colors } = useTheme()
+ const coords = useCoords()
+ const mapRef = useRef<ColotaMapRef>(null)
+
+ const { name, radius, lat, lon } = route.params
+ const [picked, setPicked] = useState<{ lat: number; lon: number } | null>(
+ lat != null && lon != null ? { lat, lon } : null
+ )
+
+ const initialCenter = useMemo<[number, number] | undefined>(() => {
+ if (lat != null && lon != null) return [lon, lat]
+ if (coords) return [coords.longitude, coords.latitude]
+ return undefined
+ }, [lat, lon, coords])
+
+ // Drawn through the list's own builder, so this circle is the circle the zone gets.
+ const draft = useMemo(
+ () =>
+ picked
+ ? buildGeofencesGeoJSON(
+ [{ id: -1, name, lat: picked.lat, lon: picked.lon, radius, enabled: true } as never],
+ colors
+ )
+ : { fills: { type: "FeatureCollection", features: [] }, labels: { type: "FeatureCollection", features: [] } },
+ [picked, name, radius, colors]
+ )
+
+ const handleConfirm = useCallback(() => {
+ if (!picked) return
+ navigation.popTo("Geofence Editor", { lat: picked.lat, lon: picked.lon }, { merge: true })
+ }, [navigation, picked])
+
+ return (
+ <Container>
+ <View style={styles.mapWrap}>
+ <ColotaMapView
+ ref={mapRef}
+ initialCenter={initialCenter ?? WORLD_CENTER}
+ onPress={(c) => setPicked({ lat: c.latitude, lon: c.longitude })}
+ style={styles.map}
+ >
+ <GeofenceLayers fills={draft.fills as never} labels={draft.labels as never} haloColor={colors.background} />
+ </ColotaMapView>
+ </View>
+
+ <View style={styles.footer}>
+ <Text style={[styles.readout, { color: picked ? colors.text : colors.textSecondary }]}>
+ {picked
+ ? `${picked.lat.toFixed(5)}, ${picked.lon.toFixed(5)} · ${formatShortDistance(radius)} radius`
+ : "Tap the map to place the zone"}
+ </Text>
+ <Button title="Use this location" onPress={handleConfirm} disabled={!picked} />
+ </View>
+ </Container>
+ )
+}
+
+const styles = StyleSheet.create({
+ mapWrap: { flex: 1 },
+ map: { flex: 1 },
+ footer: { padding: space.lg, gap: space.sm },
+ readout: { fontSize: fontSizes.description, ...fonts.regular }
+})
diff --git a/apps/mobile/src/screens/__tests__/GeofenceEditorScreen.test.tsx b/apps/mobile/src/screens/__tests__/GeofenceEditorScreen.test.tsx
index 7315c972..f1c1be36 100644
--- a/apps/mobile/src/screens/__tests__/GeofenceEditorScreen.test.tsx
+++ b/apps/mobile/src/screens/__tests__/GeofenceEditorScreen.test.tsx
@@ -48,9 +48,7 @@ jest.mock("../../hooks/useTheme", () => ({
error: "#ef4444",
warning: "#f59e0b",
success: "#22c55e",
- placeholder: "#9ca3af",
- borderRadius: 12,
- pressedOpacity: 0.7
+ placeholder: "#9ca3af"
}
})
}))
@@ -69,10 +67,27 @@ jest.mock("../../components", () => {
const R = require("react")
const { View, Text, Pressable } = require("react-native")
return {
+ TextField: require("../../testing/componentStubs").TextFieldStub,
+ Toggle: function (props: any) {
+ return require("react").createElement(require("react-native").Switch, {
+ testID: props.testID,
+ value: props.value,
+ onValueChange: props.onValueChange,
+ disabled: props.disabled,
+ accessibilityLabel: props.accessibilityLabel
+ })
+ },
Container: ({ children }: any) => R.createElement(View, null, children),
SectionTitle: ({ children }: any) => R.createElement(Text, null, children),
Card: ({ children }: any) => R.createElement(View, null, children),
SettingRow: ({ label, children }: any) => R.createElement(View, null, R.createElement(Text, null, label), children),
+ ListItem: ({ label, sub, onPress, testID }: any) =>
+ R.createElement(
+ Pressable,
+ { testID, onPress, accessibilityRole: "button" },
+ R.createElement(Text, null, label),
+ R.createElement(Text, null, sub)
+ ),
Button: ({ title, onPress, disabled }: any) =>
R.createElement(
Pressable,
@@ -97,7 +112,8 @@ jest.mock("lucide-react-native", () => {
})
const mockGoBack = jest.fn()
-const mockNavigation = { goBack: mockGoBack }
+const mockNavigate = jest.fn()
+const mockNavigation = { goBack: mockGoBack, navigate: mockNavigate }
const mockExistingGeofence: Geofence = {
id: 1,
@@ -127,6 +143,12 @@ describe("GeofenceEditorScreen", () => {
mockUpdateGeofence.mockResolvedValue(true)
})
+ function renderEditAt(lat: number, lon: number) {
+ return render(
+ <GeofenceEditorScreen navigation={mockNavigation as any} route={{ params: { geofenceId: 1, lat, lon } } as any} />
+ )
+ }
+
function renderEdit(geofenceId = 1) {
return render(<GeofenceEditorScreen navigation={mockNavigation as any} route={{ params: { geofenceId } } as any} />)
}
@@ -221,7 +243,7 @@ describe("GeofenceEditorScreen", () => {
await waitFor(() => {
expect(mockShowConfirm).toHaveBeenCalledWith(
expect.objectContaining({
- title: "Delete Geofence",
+ title: "Delete geofence",
message: 'Delete "Home"?',
confirmText: "Delete",
destructive: true
@@ -264,4 +286,27 @@ describe("GeofenceEditorScreen", () => {
expect(mockGoBack).toHaveBeenCalled()
})
})
+
+ it("saves a moved zone, which delete-and-recreate was the only way to do before", async () => {
+ const { getByText } = renderEditAt(40.7, -74)
+
+ await waitFor(() => expect(getByText("Save geofence")).toBeTruthy())
+ fireEvent.press(getByText("Save geofence"))
+
+ await waitFor(() =>
+ expect(mockUpdateGeofence).toHaveBeenCalledWith(expect.objectContaining({ id: 1, lat: 40.7, lon: -74 }))
+ )
+ })
+
+ it("opens Place Zone carrying the draft, so the radius is drawn as it will be", async () => {
+ const { getByTestId } = renderEdit()
+
+ await waitFor(() => expect(getByTestId("place-zone-row")).toBeTruthy())
+ fireEvent.press(getByTestId("place-zone-row"))
+
+ expect(mockNavigate).toHaveBeenCalledWith(
+ "Place Zone",
+ expect.objectContaining({ name: "Home", lat: 48.1, lon: 11.5 })
+ )
+ })
})
diff --git a/apps/mobile/src/screens/__tests__/GeofenceScreen.test.tsx b/apps/mobile/src/screens/__tests__/GeofenceScreen.test.tsx
index b4017188..18c031d0 100644
--- a/apps/mobile/src/screens/__tests__/GeofenceScreen.test.tsx
+++ b/apps/mobile/src/screens/__tests__/GeofenceScreen.test.tsx
@@ -1,385 +1,348 @@
import React from "react"
-import { render, fireEvent, waitFor } from "@testing-library/react-native"
-import { Share } from "react-native"
+import { render, fireEvent, waitFor, act } from "@testing-library/react-native"
+import { DeviceEventEmitter, Share } from "react-native"
import { Geofence } from "../../types/global"
+import { GEOFENCE_ZOOM_PADDING, size, space } from "../../constants"
-// --- Mocks ---
-
-jest.mock("@maplibre/maplibre-react-native", () => {
- const R = require("react")
- const { View } = require("react-native")
- return {
- __esModule: true,
- Map: (props: any) => R.createElement(View, { testID: "mapview", ...props }),
- Camera: () => null,
- GeoJSONSource: ({ children }: any) => children,
- Layer: () => null,
- Marker: ({ children }: any) => children
+jest.mock("@react-navigation/native", () => ({
+ useFocusEffect: (cb: () => (() => void) | void) => {
+ const R = require("react")
+ R.useEffect(() => {
+ const cleanup = cb()
+ return typeof cleanup === "function" ? cleanup : undefined
+ }, [cb])
}
-})
+}))
-jest.mock("@react-navigation/native", () => ({
- useFocusEffect: jest.fn()
+jest.mock("react-native-safe-area-context", () => ({
+ useSafeAreaInsets: () => ({ top: 0, bottom: 0, left: 0, right: 0 })
}))
jest.mock("../../hooks/useTheme", () => ({
- useTheme: () => ({
- colors: {
- primary: "#0d9488",
- text: "#000",
- textSecondary: "#6b7280",
- textDisabled: "#d1d5db",
- card: "#fff",
- warning: "#f59e0b",
- info: "#3b82f6",
- background: "#fff",
- border: "#e5e7eb",
- borderRadius: 12,
- success: "#22c55e",
- error: "#ef4444",
- link: "#0d9488",
- textLight: "#9ca3af",
- textOnPrimary: "#fff",
- placeholder: "#d1d5db",
- primaryDark: "#0d9488",
- backgroundElevated: "#f9fafb",
- surface: "#fff",
- overlay: "rgba(0,0,0,0.5)"
- },
- mode: "light"
- })
+ useTheme: () => ({ colors: require("@colota/shared").lightColors, mode: "light" })
}))
+let mockTracking = true
+let mockCoords: { latitude: number; longitude: number; accuracy: number } | null = null
jest.mock("../../contexts/TrackingProvider", () => ({
- useTracking: () => ({ tracking: true }),
- useCoords: () => ({ latitude: 48.1, longitude: 11.5, accuracy: 10 })
+ useTracking: () => ({ tracking: mockTracking }),
+ useCoords: () => mockCoords
}))
-const mockGetGeofences = jest.fn().mockResolvedValue([])
-const mockCreateGeofence = jest.fn().mockResolvedValue(undefined)
-const mockUpdateGeofence = jest.fn().mockResolvedValue(undefined)
-const mockDeleteGeofence = jest.fn().mockResolvedValue(undefined)
-const mockCheckCurrentPauseZone = jest.fn().mockResolvedValue(null)
-const mockIsNetworkAvailable = jest.fn().mockResolvedValue(true)
-const mockRecheckZoneSettings = jest.fn().mockResolvedValue(undefined)
-const mockGetMostRecentLocation = jest.fn().mockResolvedValue(null)
-
+const mockGetGeofences = jest.fn()
+const mockCheckCurrentPauseZone = jest.fn()
+const mockGetMostRecentLocation = jest.fn()
jest.mock("../../services/NativeLocationService", () => ({
__esModule: true,
default: {
getGeofences: (...args: any[]) => mockGetGeofences(...args),
- createGeofence: (...args: any[]) => mockCreateGeofence(...args),
- updateGeofence: (...args: any[]) => mockUpdateGeofence(...args),
- deleteGeofence: (...args: any[]) => mockDeleteGeofence(...args),
checkCurrentPauseZone: (...args: any[]) => mockCheckCurrentPauseZone(...args),
- isNetworkAvailable: (...args: any[]) => mockIsNetworkAvailable(...args),
- recheckZoneSettings: (...args: any[]) => mockRecheckZoneSettings(...args),
- getMostRecentLocation: (...args: any[]) => mockGetMostRecentLocation(...args),
- getSetting: jest.fn().mockResolvedValue(null)
+ getMostRecentLocation: (...args: any[]) => mockGetMostRecentLocation(...args)
}
}))
const mockShowAlert = jest.fn()
-
jest.mock("../../services/modalService", () => ({
showAlert: (...args: any[]) => mockShowAlert(...args)
}))
+const mockFitBounds = jest.fn()
+const mockFlyTo = jest.fn()
+const mockMapProps = jest.fn()
jest.mock("../../components/features/map/ColotaMapView", () => {
const R = require("react")
- const { View } = require("react-native")
+ const { View, Pressable } = require("react-native")
return {
- ColotaMapView: R.forwardRef(({ children }: any, _ref: any) =>
- R.createElement(View, { testID: "colota-map" }, children)
- )
+ ColotaMapView: R.forwardRef((props: any, ref: any) => {
+ R.useImperativeHandle(ref, () => ({ camera: { fitBounds: mockFitBounds, flyTo: mockFlyTo }, mapView: null }))
+ mockMapProps(props)
+ return R.createElement(
+ View,
+ { testID: "colota-map" },
+ R.createElement(Pressable, { testID: "map-ready", onPress: () => props.onMapReady?.() }),
+ R.createElement(Pressable, {
+ testID: "map-pan",
+ onPress: () => props.onRegionDidChange?.({ isUserInteraction: true })
+ }),
+ props.children
+ )
+ })
}
})
jest.mock("../../components/features/map/GeofenceLayers", () => {
const R = require("react")
- const { View } = require("react-native")
+ const { View, Pressable } = require("react-native")
return {
- GeofenceLayers: () => R.createElement(View, { testID: "geofence-layers" })
+ GeofenceLayers: (props: any) =>
+ R.createElement(
+ View,
+ { testID: "geofence-layers", ...props },
+ props.onPressZone && R.createElement(Pressable, { testID: "tap-zone-2", onPress: () => props.onPressZone(2) })
+ )
}
})
jest.mock("../../components/features/map/UserLocationOverlay", () => {
const R = require("react")
const { View } = require("react-native")
- return {
- UserLocationOverlay: () => R.createElement(View, { testID: "user-location-overlay" })
- }
+ return { UserLocationOverlay: (props: any) => R.createElement(View, { testID: "user-location-overlay", ...props }) }
})
-jest.mock("../../components/features/map/MapCenterButton", () => {
+jest.mock("../../components/features/map/MapActionButton", () => {
const R = require("react")
- const { View } = require("react-native")
+ const { Pressable } = require("react-native")
return {
- MapCenterButton: () => R.createElement(View, { testID: "center-button" })
+ MapActionButton: (props: any) =>
+ R.createElement(Pressable, {
+ testID: props.testID,
+ accessibilityRole: "button",
+ accessibilityLabel: props.accessibilityLabel,
+ onPress: props.onPress,
+ style: props.style
+ })
}
})
-jest.mock("../../components/features/map/mapUtils", () => ({
- buildGeofencesGeoJSON: jest.fn().mockReturnValue({ fills: null, labels: null })
-}))
-
jest.mock("../../components", () => {
const R = require("react")
- const { View, Text } = require("react-native")
+ const { View, Text, Pressable } = require("react-native")
return {
Container: ({ children }: any) => R.createElement(View, null, children),
- SectionTitle: ({ children }: any) => R.createElement(Text, null, children),
- Card: ({ children, style }: any) => R.createElement(View, { style }, children)
- }
-})
-
-jest.mock("../../assets/icons/icon.png", () => "mock-icon")
-
-jest.mock("lucide-react-native", () => {
- const R = require("react")
- const { Text } = require("react-native")
- return {
- ChevronRight: (props: any) => R.createElement(Text, props, "ChevronRight"),
- Wifi: (props: any) => R.createElement(Text, props, "Wifi"),
- PersonStanding: (props: any) => R.createElement(Text, props, "PersonStanding"),
- MapPinHouse: (props: any) => R.createElement(Text, props, "MapPinHouse"),
- Share2: (props: any) => R.createElement(Text, props, "Share2")
+ HeaderAction: ({ label, hint, disabled, onPress, testID }: any) =>
+ R.createElement(Pressable, {
+ testID,
+ onPress,
+ disabled,
+ accessibilityRole: "button",
+ accessibilityLabel: label,
+ accessibilityHint: hint,
+ accessibilityState: { disabled: !!disabled }
+ }),
+ Card: ({ children }: any) => R.createElement(View, { testID: "zone-card" }, children),
+ Divider: () => null,
+ EmptyState: ({ title, hint, action }: any) =>
+ R.createElement(
+ View,
+ { testID: "EmptyState" },
+ R.createElement(Text, null, title),
+ R.createElement(Text, null, hint),
+ action &&
+ R.createElement(
+ Pressable,
+ { testID: "empty-action", onPress: action.onPress },
+ R.createElement(Text, null, action.label)
+ )
+ ),
+ ListItem: ({ label, sub, onPress, testID, icon }: any) =>
+ R.createElement(
+ Pressable,
+ { accessibilityRole: "button", onPress, testID, accessibilityLabel: `${label}, ${sub}` },
+ R.createElement(Text, null, label),
+ R.createElement(Text, null, sub),
+ R.createElement(Text, { testID: `${testID}-glyph` }, icon?.displayName ?? icon?.name ?? "icon")
+ )
}
})
jest.mock("../../utils/logger", () => ({
- logger: { debug: jest.fn(), error: jest.fn(), warn: jest.fn(), info: jest.fn() }
+ logger: { error: jest.fn(), warn: jest.fn(), info: jest.fn(), debug: jest.fn() }
}))
jest.mock("../../utils/geo", () => ({
- formatShortDistance: (meters: number) => `${Math.round(meters)}m`,
- shortDistanceUnit: () => "m",
- inputToMeters: (value: number) => value
+ ...jest.requireActual("../../utils/geo"),
+ formatShortDistance: (m: number) => `${m}m`
}))
import { GeofenceScreen } from "../GeofenceScreen"
-// --- Test data ---
-
-const mockGeofences: Geofence[] = [
- {
- id: 1,
- name: "Home",
- lat: 48.1,
- lon: 11.5,
- radius: 100,
- enabled: true,
- pauseTracking: true,
- pauseOnWifi: false,
- pauseOnMotionless: false,
- motionlessTimeoutMinutes: 10,
- heartbeatEnabled: false,
- heartbeatIntervalMinutes: 15
- },
- {
- id: 2,
- name: "Office",
- lat: 48.2,
- lon: 11.6,
- radius: 200,
- enabled: true,
- pauseTracking: false,
- pauseOnWifi: false,
- pauseOnMotionless: false,
- motionlessTimeoutMinutes: 10,
- heartbeatEnabled: false,
- heartbeatIntervalMinutes: 15
- }
-]
+const zone = (id: number, name: string, overrides: Partial<Geofence> = {}): Geofence => ({
+ id,
+ name,
+ lat: 48.1 + id * 0.01,
+ lon: 11.5,
+ radius: 100 * id,
+ enabled: true,
+ pauseTracking: true,
+ pauseOnWifi: id === 1,
+ pauseOnMotionless: false,
+ motionlessTimeoutMinutes: 5,
+ heartbeatEnabled: false,
+ heartbeatIntervalMinutes: 15,
+ ...overrides
+})
+const zones = [zone(1, "Home"), zone(2, "Office", { pauseTracking: false })]
+
+const lastOptions = (props: any) => props.navigation.setOptions.mock.calls.at(-1)[0]
+const headerRight = (props: any) => render(lastOptions(props).headerRight())
-// --- Tests ---
+function createProps() {
+ return { navigation: { navigate: jest.fn(), setOptions: jest.fn() } } as any
+}
+
+async function renderReady(props = createProps()) {
+ const utils = render(<GeofenceScreen {...props} />)
+ await waitFor(() => expect(utils.getByTestId("colota-map")).toBeTruthy())
+ fireEvent.press(utils.getByTestId("map-ready"))
+ await act(async () => {})
+ return { ...utils, props }
+}
describe("GeofenceScreen", () => {
beforeEach(() => {
jest.clearAllMocks()
- mockGetGeofences.mockResolvedValue([])
+ mockTracking = true
+ mockCoords = null
+ mockGetGeofences.mockResolvedValue(zones)
+ mockCheckCurrentPauseZone.mockResolvedValue(null)
+ mockGetMostRecentLocation.mockResolvedValue({ latitude: 48.1, longitude: 11.5, accuracy: 8 })
})
- function renderScreen() {
- return render(<GeofenceScreen navigation={{} as any} />)
- }
+ it("lists every geofence as a row that says what it does, with no header counting them", async () => {
+ const { getByText, queryByText, getByTestId } = await renderReady()
- it("shows empty state when no geofences exist", async () => {
- const { getByText } = renderScreen()
-
- await waitFor(() => {
- expect(getByText("No geofences yet")).toBeTruthy()
- })
+ expect(getByTestId("zone-card")).toBeTruthy()
+ expect(getByText("Home")).toBeTruthy()
+ expect(getByText("100m · WiFi pause")).toBeTruthy()
+ expect(getByText("200m · recording continues")).toBeTruthy()
+ expect(queryByText(/Active geofences/)).toBeNull()
+ expect(queryByText("Create geofence")).toBeNull()
})
- it("renders geofence list with name and radius", async () => {
- mockGetGeofences.mockResolvedValue(mockGeofences)
+ it("opens the editor from a row, from a circle on the map and from the header Create", async () => {
+ const { getByTestId, props } = await renderReady()
- const { getByText } = renderScreen()
+ fireEvent.press(getByTestId("edit-geofence-1"))
+ expect(props.navigation.navigate).toHaveBeenCalledWith("Geofence Editor", { geofenceId: 1 })
- await waitFor(() => {
- expect(getByText("Home")).toBeTruthy()
- expect(getByText("100m radius")).toBeTruthy()
- expect(getByText("Office")).toBeTruthy()
- expect(getByText("200m radius")).toBeTruthy()
- })
- })
-
- it("shows validation alert when name is empty", async () => {
- const { getByText } = renderScreen()
-
- await waitFor(() => {
- expect(getByText("Place Geofence")).toBeTruthy()
- })
+ fireEvent.press(getByTestId("tap-zone-2"))
+ expect(props.navigation.navigate).toHaveBeenLastCalledWith("Geofence Editor", { geofenceId: 2 })
- fireEvent.press(getByText("Place Geofence"))
-
- expect(mockShowAlert).toHaveBeenCalledWith("Missing Name", "Please enter a name.", "warning")
+ fireEvent.press(headerRight(props).getByLabelText("Create geofence"))
+ expect(props.navigation.navigate).toHaveBeenLastCalledWith("Geofence Editor", {})
})
- it("shows validation alert when radius is invalid (0 or negative)", async () => {
- const { getByText, getByPlaceholderText, getByDisplayValue } = renderScreen()
-
- await waitFor(() => {
- expect(getByText("Place Geofence")).toBeTruthy()
- })
+ it("shares every geofence from the header, only once there is one to share", async () => {
+ const shareSpy = jest.spyOn(Share, "share").mockResolvedValue({ action: "sharedAction", activityType: undefined })
+ const { props } = await renderReady()
- fireEvent.changeText(getByPlaceholderText("Home, Work..."), "Test Zone")
- fireEvent.changeText(getByDisplayValue("50"), "0")
- fireEvent.press(getByText("Place Geofence"))
+ const bar = headerRight(props)
+ fireEvent.press(bar.getByLabelText("Share all geofences"))
+ await waitFor(() => expect(shareSpy).toHaveBeenCalledWith({ message: expect.stringContaining("colota://setup") }))
- expect(mockShowAlert).toHaveBeenCalledWith("Invalid Radius", "Please enter a valid radius.", "warning")
+ mockGetGeofences.mockResolvedValue([])
+ const emptyProps = createProps()
+ await renderReady(emptyProps)
+ expect(headerRight(emptyProps).queryByLabelText("Share all geofences")).toBeNull()
+ shareSpy.mockRestore()
})
- it("enters placing mode on valid name and radius", async () => {
- const { getByText, getByPlaceholderText, getByDisplayValue } = renderScreen()
-
- await waitFor(() => {
- expect(getByText("Place Geofence")).toBeTruthy()
- })
+ it("says so when the share sheet fails", async () => {
+ const shareSpy = jest.spyOn(Share, "share").mockRejectedValue(new Error("no sheet"))
+ const { props } = await renderReady()
- fireEvent.changeText(getByPlaceholderText("Home, Work..."), "Test Zone")
- fireEvent.changeText(getByDisplayValue("50"), "100")
- fireEvent.press(getByText("Place Geofence"))
+ fireEvent.press(headerRight(props).getByLabelText("Share all geofences"))
- expect(mockShowAlert).not.toHaveBeenCalled()
- expect(getByText("Tap Map to Place...")).toBeTruthy()
+ await waitFor(() => expect(mockShowAlert).toHaveBeenCalledWith("Error", "Failed to share geofences.", "error"))
+ shareSpy.mockRestore()
})
- it("tapping ChevronRight navigates to editor with geofence id", async () => {
- mockGetGeofences.mockResolvedValue(mockGeofences)
- const mockNavigate = jest.fn()
+ it("marks the geofence you stand in with a check and the words Paused here, and clears it when you leave", async () => {
+ mockCheckCurrentPauseZone.mockResolvedValue({ zoneName: "Home", pauseReason: "wifi" })
+ const { getByText, queryByText, getByTestId } = await renderReady()
- const { getAllByText } = render(<GeofenceScreen navigation={{ navigate: mockNavigate } as any} />)
+ await waitFor(() => expect(getByText("Paused here · 100m · WiFi pause")).toBeTruthy())
+ expect(getByTestId("edit-geofence-1-glyph").props.children).toBe("MapPinCheck")
+ expect(getByTestId("edit-geofence-2-glyph").props.children).toBe("MapPinHouse")
- await waitFor(() => {
- expect(getAllByText("ChevronRight").length).toBeGreaterThanOrEqual(1)
+ act(() => {
+ DeviceEventEmitter.emit("onPauseZoneChange", { entered: false, zoneName: null, pauseReason: null })
})
+ await waitFor(() => expect(queryByText(/Paused here/)).toBeNull())
- fireEvent.press(getAllByText("ChevronRight")[0])
-
- expect(mockNavigate).toHaveBeenCalledWith("Geofence Editor", { geofenceId: 1 })
- })
-
- describe("share geofences", () => {
- let shareSpy: jest.SpyInstance
-
- beforeEach(() => {
- shareSpy = jest.spyOn(Share, "share").mockResolvedValue({ action: "sharedAction", activityType: undefined })
+ act(() => {
+ DeviceEventEmitter.emit("onPauseZoneChange", { entered: true, zoneName: "Home", pauseReason: "wifi" })
})
+ await waitFor(() => expect(getByText(/^Paused here/)).toBeTruthy())
+ })
- afterEach(() => {
- shareSpy.mockRestore()
+ it("fits the camera to every geofence once the map is ready, inside the control column, and again only when the set changes", async () => {
+ const { getByTestId } = await renderReady()
+
+ expect(mockFitBounds).toHaveBeenCalledTimes(1)
+ const [bounds, options] = mockFitBounds.mock.calls[0]
+ expect(bounds[1]).toBeLessThan(48.11)
+ expect(bounds[3]).toBeGreaterThan(48.12)
+ expect(options.padding).toEqual({
+ top: GEOFENCE_ZOOM_PADDING[0] + space.lg,
+ right: GEOFENCE_ZOOM_PADDING[1] + space.lg + size.iconColumn + space.lg,
+ bottom: GEOFENCE_ZOOM_PADDING[2] + space.lg,
+ left: GEOFENCE_ZOOM_PADDING[3] + space.lg
})
+ expect(options.duration).toBe(0)
- it("does not render the share button when there are no geofences", async () => {
- const { queryByTestId, getByText } = renderScreen()
-
- await waitFor(() => {
- expect(getByText("No geofences yet")).toBeTruthy()
- })
-
- expect(queryByTestId("share-geofences-btn")).toBeNull()
+ act(() => {
+ DeviceEventEmitter.emit("geofenceUpdated")
})
+ await act(async () => {})
+ expect(mockFitBounds).toHaveBeenCalledTimes(1)
- it("renders the share button when at least one geofence exists", async () => {
- mockGetGeofences.mockResolvedValue(mockGeofences)
- const { getByTestId } = renderScreen()
-
- await waitFor(() => {
- expect(getByTestId("share-geofences-btn")).toBeTruthy()
- })
+ mockGetGeofences.mockResolvedValue([...zones, zone(3, "Gym")])
+ act(() => {
+ DeviceEventEmitter.emit("geofenceUpdated")
})
+ await waitFor(() => expect(mockFitBounds).toHaveBeenCalledTimes(2))
+ expect(mockFitBounds.mock.calls[1][1].duration).toBeGreaterThan(0)
+ expect(getByTestId("colota-map")).toBeTruthy()
+ })
- it("opens the share sheet with a colota://setup link on press", async () => {
- mockGetGeofences.mockResolvedValue(mockGeofences)
- const { getByTestId } = renderScreen()
-
- await waitFor(() => {
- expect(getByTestId("share-geofences-btn")).toBeTruthy()
- })
-
- fireEvent.press(getByTestId("share-geofences-btn"))
-
- await waitFor(() => {
- expect(shareSpy).toHaveBeenCalledTimes(1)
- })
-
- const arg = shareSpy.mock.calls[0][0]
- expect(arg.message).toMatch(/^colota:\/\/setup\?config=/)
- })
-
- it("encodes geofences without id, createdAt, or enabled fields", async () => {
- mockGetGeofences.mockResolvedValue(mockGeofences)
- const { getByTestId } = renderScreen()
-
- await waitFor(() => {
- expect(getByTestId("share-geofences-btn")).toBeTruthy()
- })
-
- fireEvent.press(getByTestId("share-geofences-btn"))
+ it("offers a fit disc only after a pan, and hides it again once pressed", async () => {
+ const { getByTestId, queryByTestId, getByLabelText } = await renderReady()
- await waitFor(() => {
- expect(shareSpy).toHaveBeenCalledTimes(1)
- })
+ expect(queryByTestId("fit-geofences-btn")).toBeNull()
+ fireEvent.press(getByTestId("map-pan"))
+ const disc = getByLabelText("Fit geofences")
+ expect(disc.props.style).toEqual(
+ expect.arrayContaining([expect.objectContaining({ bottom: space.lg + space.sm + size.iconColumn + space.lg })])
+ )
- const link = shareSpy.mock.calls[0][0].message as string
- const encoded = link.split("config=")[1]
- const decoded = JSON.parse(atob(encoded))
-
- expect(decoded.geofences).toHaveLength(2)
- expect(decoded.geofences[0]).toEqual({
- name: "Home",
- lat: 48.1,
- lon: 11.5,
- radius: 100,
- pauseTracking: true,
- pauseOnWifi: false,
- pauseOnMotionless: false,
- motionlessTimeoutMinutes: 10,
- heartbeatEnabled: false,
- heartbeatIntervalMinutes: 15
- })
- expect(decoded.geofences[0]).not.toHaveProperty("id")
- expect(decoded.geofences[0]).not.toHaveProperty("createdAt")
- expect(decoded.geofences[0]).not.toHaveProperty("enabled")
- })
+ fireEvent.press(disc)
+ expect(mockFitBounds).toHaveBeenCalledTimes(2)
+ expect(queryByTestId("fit-geofences-btn")).toBeNull()
+ })
- it("shows an error alert when sharing fails", async () => {
- mockGetGeofences.mockResolvedValue(mockGeofences)
- shareSpy.mockRejectedValueOnce(new Error("share failed"))
+ it("shows the empty tab under a map on the last fix, with one action, and the disc centres on the fix after a pan", async () => {
+ mockGetGeofences.mockResolvedValue([])
+ const { getByText, getByTestId, queryByTestId, getByLabelText, props } = await renderReady()
+
+ expect(queryByTestId("zone-card")).toBeNull()
+ expect(getByText("No geofences yet")).toBeTruthy()
+ expect(mockMapProps.mock.calls[0][0].initialCenter).toEqual([11.5, 48.1])
+ fireEvent.press(getByTestId("empty-action"))
+ expect(props.navigation.navigate).toHaveBeenCalledWith("Geofence Editor", {})
+
+ fireEvent.press(getByTestId("map-pan"))
+ fireEvent.press(getByLabelText("Centre map on my position"))
+ expect(mockFlyTo).toHaveBeenCalledWith(expect.objectContaining({ center: [11.5, 48.1] }))
+ expect(mockFitBounds).not.toHaveBeenCalled()
+ })
- const { getByTestId } = renderScreen()
+ it("draws no tiles until the database has answered, so the map never opens on the world view and jumps", async () => {
+ mockGetMostRecentLocation.mockReturnValue(new Promise(() => {}))
+ const { queryByTestId } = render(<GeofenceScreen {...createProps()} />)
+ await act(async () => {})
- await waitFor(() => {
- expect(getByTestId("share-geofences-btn")).toBeTruthy()
- })
+ expect(queryByTestId("colota-map")).toBeNull()
+ })
- fireEvent.press(getByTestId("share-geofences-btn"))
+ it("draws the live dot only while tracking, greyed inside the geofence you are paused in", async () => {
+ mockCoords = { latitude: 48.1, longitude: 11.5, accuracy: 4 }
+ mockCheckCurrentPauseZone.mockResolvedValue({ zoneName: "Home", pauseReason: null })
+ const { getByTestId } = await renderReady()
+ await waitFor(() => expect(getByTestId("user-location-overlay").props.isPaused).toBe(true))
- await waitFor(() => {
- expect(mockShowAlert).toHaveBeenCalledWith("Error", "Failed to share geofences.", "error")
- })
- })
+ mockTracking = false
+ const { queryByTestId } = await renderReady()
+ expect(queryByTestId("user-location-overlay")).toBeNull()
})
})
diff --git a/apps/mobile/src/screens/__tests__/PlaceZoneScreen.test.tsx b/apps/mobile/src/screens/__tests__/PlaceZoneScreen.test.tsx
new file mode 100644
index 00000000..293ddc92
--- /dev/null
+++ b/apps/mobile/src/screens/__tests__/PlaceZoneScreen.test.tsx
@@ -0,0 +1,87 @@
+import React from "react"
+import { render, fireEvent } from "@testing-library/react-native"
+
+jest.mock("../../hooks/useTheme", () => ({
+ useTheme: () => ({ colors: jest.requireActual("@colota/shared").lightColors })
+}))
+
+jest.mock("../../contexts/TrackingProvider", () => ({
+ useCoords: () => ({ latitude: 52.5, longitude: 13.4 })
+}))
+
+jest.mock("../../components", () => {
+ const R = require("react")
+ const { View, Text, Pressable } = require("react-native")
+ return {
+ Container: ({ children }: any) => R.createElement(View, null, children),
+ Button: ({ title, onPress, disabled }: any) =>
+ R.createElement(
+ Pressable,
+ { testID: "use-location-btn", onPress, disabled, accessibilityState: { disabled } },
+ R.createElement(Text, null, title)
+ )
+ }
+})
+
+jest.mock("../../components/features/map/ColotaMapView", () => {
+ const R = require("react")
+ const { View, Pressable } = require("react-native")
+ return {
+ ColotaMapView: R.forwardRef(({ children, onPress }: any, _ref: any) =>
+ R.createElement(
+ View,
+ null,
+ R.createElement(Pressable, {
+ testID: "map-press",
+ onPress: () => onPress?.({ latitude: 48.1, longitude: 11.6 })
+ }),
+ children
+ )
+ )
+ }
+})
+
+jest.mock("../../components/features/map/GeofenceLayers", () => ({
+ GeofenceLayers: () => null
+}))
+
+import { PlaceZoneScreen } from "../PlaceZoneScreen"
+import { formatShortDistance } from "../../utils/geo"
+
+function renderScreen(params: any = { name: "Home", radius: 100 }) {
+ const popTo = jest.fn()
+ const view = render(<PlaceZoneScreen navigation={{ popTo } as any} route={{ params } as any} />)
+ return { ...view, popTo }
+}
+
+describe("PlaceZoneScreen", () => {
+ it("cannot confirm until somewhere is picked", () => {
+ const { getByTestId, getByText } = renderScreen()
+
+ expect(getByTestId("use-location-btn").props.accessibilityState.disabled).toBe(true)
+ expect(getByText("Tap the map to place the zone")).toBeTruthy()
+ })
+
+ it("reads the picked point back with the radius it will have", () => {
+ const { getByTestId, getByText } = renderScreen()
+
+ fireEvent.press(getByTestId("map-press"))
+
+ expect(getByText(`48.10000, 11.60000 · ${formatShortDistance(100)} radius`)).toBeTruthy()
+ })
+
+ it("merges the coordinate into the editor rather than opening a second one", () => {
+ const { getByTestId, popTo } = renderScreen()
+
+ fireEvent.press(getByTestId("map-press"))
+ fireEvent.press(getByTestId("use-location-btn"))
+
+ expect(popTo).toHaveBeenCalledWith("Geofence Editor", { lat: 48.1, lon: 11.6 }, { merge: true })
+ })
+
+ it("opens on the zone being edited, not the user, when it already has a place", () => {
+ const { getByText } = renderScreen({ name: "Home", radius: 50, lat: 40.7, lon: -74 })
+
+ expect(getByText(`40.70000, -74.00000 · ${formatShortDistance(50)} radius`)).toBeTruthy()
+ })
+})
diff --git a/apps/mobile/src/screens/index.ts b/apps/mobile/src/screens/index.ts
index 073a6971..65760100 100644
--- a/apps/mobile/src/screens/index.ts
+++ b/apps/mobile/src/screens/index.ts
@@ -29,3 +29,4 @@ export { TripDetailScreen } from "./TripDetailScreen"
export { OfflineMapsScreen } from "./OfflineMapsScreen"
export { BackupRestoreScreen } from "./BackupRestoreScreen"
export { BackendTemplateScreen } from "./BackendTemplateScreen"
+export { PlaceZoneScreen } from "./PlaceZoneScreen"
diff --git a/apps/mobile/src/types/navigation.ts b/apps/mobile/src/types/navigation.ts
index 5558d558..bf70ef57 100644
--- a/apps/mobile/src/types/navigation.ts
+++ b/apps/mobile/src/types/navigation.ts
@@ -21,6 +21,7 @@ export type RootStackParamList = {
"mTLS Settings": undefined
Geofences: undefined
"Geofence Editor": { geofenceId?: number; name?: string; radius?: number; lat?: number; lon?: number } | undefined
+ "Place Zone": { name: string; radius: number; lat?: number; lon?: number }
"Location History": { initialTab?: InspectorTab; initialDate?: string } | undefined
"Location Summary": undefined
"Export Locations": undefined
diff --git a/apps/mobile/src/utils/__tests__/geofenceRow.test.ts b/apps/mobile/src/utils/__tests__/geofenceRow.test.ts
new file mode 100644
index 00000000..466e93a7
--- /dev/null
+++ b/apps/mobile/src/utils/__tests__/geofenceRow.test.ts
@@ -0,0 +1,42 @@
+import { zoneRowSub } from "../geofenceRow"
+import type { Geofence } from "../../types/global"
+
+jest.mock("../geo", () => ({
+ formatShortDistance: (m: number) => `${m}m`
+}))
+
+const zone = (overrides: Partial<Geofence> = {}): Geofence => ({
+ id: 1,
+ name: "Home",
+ lat: 48.1,
+ lon: 11.5,
+ radius: 50,
+ enabled: true,
+ pauseTracking: true,
+ pauseOnWifi: false,
+ pauseOnMotionless: false,
+ motionlessTimeoutMinutes: 5,
+ heartbeatEnabled: false,
+ heartbeatIntervalMinutes: 15,
+ ...overrides
+})
+
+describe("zoneRowSub", () => {
+ it("names the radius and every pause mode that is on, so the row says what the zone does", () => {
+ expect(zoneRowSub(zone({ pauseOnWifi: true, pauseOnMotionless: true }), false)).toBe(
+ "50m · WiFi pause · motionless pause"
+ )
+ expect(zoneRowSub(zone({ pauseOnWifi: true }), false)).toBe("50m · WiFi pause")
+ expect(zoneRowSub(zone(), false)).toBe("50m")
+ })
+
+ it("says recording continues when the master switch is off, since the modes do nothing then", () => {
+ expect(zoneRowSub(zone({ pauseTracking: false, pauseOnWifi: true, pauseOnMotionless: true }), false)).toBe(
+ "50m · recording continues"
+ )
+ })
+
+ it("leads with Paused here for the zone you stand in, so the state survives an ellipsis", () => {
+ expect(zoneRowSub(zone({ pauseOnWifi: true }), true)).toBe("Paused here · 50m · WiFi pause")
+ })
+})
diff --git a/apps/mobile/src/utils/geofenceRow.ts b/apps/mobile/src/utils/geofenceRow.ts
new file mode 100644
index 00000000..6a7fe9e3
--- /dev/null
+++ b/apps/mobile/src/utils/geofenceRow.ts
@@ -0,0 +1,22 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+import type { Geofence } from "../types/global"
+import { formatShortDistance } from "./geo"
+
+/** The caption under a zone's name: what it does, and "Paused here" first when you stand in it. */
+export function zoneRowSub(zone: Geofence, pausedHere: boolean): string {
+ const parts: string[] = []
+ if (pausedHere) parts.push("Paused here")
+ parts.push(formatShortDistance(zone.radius))
+ if (!zone.pauseTracking) {
+ // The pause modes are inert without the master switch, so naming them would promise a pause that never comes.
+ parts.push("recording continues")
+ } else {
+ if (zone.pauseOnWifi) parts.push("WiFi pause")
+ if (zone.pauseOnMotionless) parts.push("motionless pause")
+ }
+ return parts.join(" · ")
+}