Skip to content

Colota - Android GPS Location tracker

feat(geofences): mark the user's position on the place-zone map (#893)

Max Dietrich0bc8d55b0b1e
diff --git a/apps/docs/docs/guides/geofencing.md b/apps/docs/docs/guides/geofencing.md
index c1a47903..9276d965 100644
--- a/apps/docs/docs/guides/geofencing.md
+++ b/apps/docs/docs/guides/geofencing.md
@@ -16,7 +16,7 @@ Create zones where location recording stops automatically. These "pause zones" s
1. Go to the **Geofences** tab
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
+3. Give the zone a name and a radius, then tap **Location** and pick a point on the map. The dot marks where you are; while tracking, the locate button places the zone at your position
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.
diff --git a/apps/mobile/src/screens/PlaceZoneScreen.tsx b/apps/mobile/src/screens/PlaceZoneScreen.tsx
index da3238b5..bc49f189 100644
--- a/apps/mobile/src/screens/PlaceZoneScreen.tsx
+++ b/apps/mobile/src/screens/PlaceZoneScreen.tsx
@@ -3,23 +3,30 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
-import React, { useCallback, useMemo, useRef, useState } from "react"
+import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"
import { View, Text, StyleSheet } from "react-native"
+import { LocateFixed } from "lucide-react-native"
import { useTheme } from "../hooks/useTheme"
-import { useCoords } from "../contexts/TrackingProvider"
+import { useTracking, useCoords } from "../contexts/TrackingProvider"
+import NativeLocationService from "../services/NativeLocationService"
import { Button, Container } from "../components"
import { ColotaMapView, ColotaMapRef } from "../components/features/map/ColotaMapView"
import { GeofenceLayers } from "../components/features/map/GeofenceLayers"
+import { UserLocationOverlay } from "../components/features/map/UserLocationOverlay"
+import { MapActionButton, mapActionStyles } from "../components/features/map/MapActionButton"
import { buildGeofencesGeoJSON } from "../components/features/map/mapUtils"
import { fontSizes, fonts } from "../styles/typography"
-import { space } from "../constants"
+import { DEFAULT_MAP_ZOOM, MAP_ANIMATION_DURATION_MS, WORLD_MAP_ZOOM, size, space } from "../constants"
import { formatShortDistance } from "../utils/geo"
+import { logger } from "../utils/logger"
import { RootScreenProps } from "../types/navigation"
+import type { LocationCoords } from "../types/global"
const WORLD_CENTER: [number, number] = [0, 0]
export function PlaceZoneScreen({ navigation, route }: RootScreenProps<"Place Zone">) {
const { colors } = useTheme()
+ const { tracking } = useTracking()
const coords = useCoords()
const mapRef = useRef<ColotaMapRef>(null)
@@ -27,12 +34,37 @@ export function PlaceZoneScreen({ navigation, route }: RootScreenProps<"Place Zo
const [picked, setPicked] = useState<{ lat: number; lon: number } | null>(
lat != null && lon != null ? { lat, lon } : null
)
+ // `undefined` until the database has answered, so the map never opens on [0, 0] at street zoom and jumps.
+ const [savedFix, setSavedFix] = useState<LocationCoords | null | undefined>(undefined)
+
+ const liveFix = tracking && coords ? coords : null
+
+ useEffect(() => {
+ if (liveFix) return
+ let active = true
+ NativeLocationService.getMostRecentLocation()
+ .then((latest) => {
+ if (!active) return
+ setSavedFix(latest ? { latitude: latest.latitude, longitude: latest.longitude, accuracy: 0 } : null)
+ })
+ .catch((err) => {
+ logger.error("[PlaceZoneScreen] Failed to read the last known location:", err)
+ if (active) setSavedFix(null)
+ })
+ return () => {
+ active = false
+ }
+ }, [liveFix])
+
+ const position = liveFix ?? savedFix ?? null
+ const hasZoneCoord = lat != null && lon != null
+ const ready = hasZoneCoord || liveFix !== null || savedFix !== undefined
const initialCenter = useMemo<[number, number] | undefined>(() => {
if (lat != null && lon != null) return [lon, lat]
- if (coords) return [coords.longitude, coords.latitude]
+ if (position) return [position.longitude, position.latitude]
return undefined
- }, [lat, lon, coords])
+ }, [lat, lon, position])
// Drawn through the list's own builder, so this circle is the circle the zone gets.
const draft = useMemo(
@@ -46,6 +78,16 @@ export function PlaceZoneScreen({ navigation, route }: RootScreenProps<"Place Zo
[picked, name, radius, colors]
)
+ const handlePlaceAtFix = useCallback(() => {
+ if (!liveFix) return
+ setPicked({ lat: liveFix.latitude, lon: liveFix.longitude })
+ mapRef.current?.camera?.flyTo({
+ center: [liveFix.longitude, liveFix.latitude],
+ zoom: DEFAULT_MAP_ZOOM,
+ duration: MAP_ANIMATION_DURATION_MS
+ })
+ }, [liveFix])
+
const handleConfirm = useCallback(() => {
if (!picked) return
navigation.popTo("Geofence Editor", { lat: picked.lat, lon: picked.lon }, { merge: true })
@@ -54,14 +96,33 @@ export function PlaceZoneScreen({ navigation, route }: RootScreenProps<"Place Zo
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>
+ {ready && (
+ <ColotaMapView
+ ref={mapRef}
+ initialCenter={initialCenter ?? WORLD_CENTER}
+ initialZoom={initialCenter ? DEFAULT_MAP_ZOOM : WORLD_MAP_ZOOM}
+ 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} />
+ {liveFix ? (
+ <UserLocationOverlay coords={liveFix} isPaused={false} colors={colors} />
+ ) : (
+ savedFix && <UserLocationOverlay coords={savedFix} isPaused colors={colors} />
+ )}
+ </ColotaMapView>
+ )}
+ {liveFix && (
+ <MapActionButton
+ style={[mapActionStyles.right, styles.locate]}
+ accessibilityRole="button"
+ accessibilityLabel="Place zone at my position"
+ onPress={handlePlaceAtFix}
+ testID="place-at-fix-btn"
+ >
+ <LocateFixed size={size.icon.md} color={colors.textLight} />
+ </MapActionButton>
+ )}
</View>
<View style={styles.footer}>
@@ -79,6 +140,7 @@ export function PlaceZoneScreen({ navigation, route }: RootScreenProps<"Place Zo
const styles = StyleSheet.create({
mapWrap: { flex: 1 },
map: { flex: 1 },
+ locate: { bottom: space.xxl + size.iconColumn + space.lg },
footer: { padding: space.lg, gap: space.sm },
readout: { fontSize: fontSizes.description, ...fonts.regular }
})
diff --git a/apps/mobile/src/screens/__tests__/PlaceZoneScreen.test.tsx b/apps/mobile/src/screens/__tests__/PlaceZoneScreen.test.tsx
index 293ddc92..d1db533e 100644
--- a/apps/mobile/src/screens/__tests__/PlaceZoneScreen.test.tsx
+++ b/apps/mobile/src/screens/__tests__/PlaceZoneScreen.test.tsx
@@ -1,12 +1,24 @@
import React from "react"
-import { render, fireEvent } from "@testing-library/react-native"
+import { render, fireEvent, waitFor } from "@testing-library/react-native"
+import { DEFAULT_MAP_ZOOM, WORLD_MAP_ZOOM } from "../../constants"
jest.mock("../../hooks/useTheme", () => ({
useTheme: () => ({ colors: jest.requireActual("@colota/shared").lightColors })
}))
+let mockTracking = true
+let mockCoords: { latitude: number; longitude: number; accuracy: number } | null = null
jest.mock("../../contexts/TrackingProvider", () => ({
- useCoords: () => ({ latitude: 52.5, longitude: 13.4 })
+ useTracking: () => ({ tracking: mockTracking }),
+ useCoords: () => mockCoords
+}))
+
+const mockGetMostRecentLocation = jest.fn()
+jest.mock("../../services/NativeLocationService", () => ({
+ __esModule: true,
+ default: {
+ getMostRecentLocation: (...args: any[]) => mockGetMostRecentLocation(...args)
+ }
}))
jest.mock("../../components", () => {
@@ -23,21 +35,25 @@ jest.mock("../../components", () => {
}
})
+const mockFlyTo = jest.fn()
+const mockMapProps = jest.fn()
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(
+ ColotaMapView: R.forwardRef((props: any, ref: any) => {
+ R.useImperativeHandle(ref, () => ({ camera: { flyTo: mockFlyTo }, mapView: null }))
+ mockMapProps(props)
+ return R.createElement(
View,
- null,
+ { testID: "colota-map" },
R.createElement(Pressable, {
testID: "map-press",
- onPress: () => onPress?.({ latitude: 48.1, longitude: 11.6 })
+ onPress: () => props.onPress?.({ latitude: 48.1, longitude: 11.6 })
}),
- children
+ props.children
)
- )
+ })
}
})
@@ -45,15 +61,46 @@ jest.mock("../../components/features/map/GeofenceLayers", () => ({
GeofenceLayers: () => null
}))
+jest.mock("../../components/features/map/UserLocationOverlay", () => {
+ const R = require("react")
+ const { View } = require("react-native")
+ return { UserLocationOverlay: (props: any) => R.createElement(View, { testID: "user-location-overlay", ...props }) }
+})
+
+jest.mock("../../components/features/map/MapActionButton", () => {
+ const R = require("react")
+ const { Pressable } = require("react-native")
+ return {
+ MapActionButton: (props: any) =>
+ R.createElement(Pressable, {
+ testID: props.testID,
+ accessibilityLabel: props.accessibilityLabel,
+ onPress: props.onPress
+ }),
+ mapActionStyles: { right: {} }
+ }
+})
+
import { PlaceZoneScreen } from "../PlaceZoneScreen"
import { formatShortDistance } from "../../utils/geo"
+const LIVE_FIX = { latitude: 52.5, longitude: 13.4, accuracy: 20 }
+
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 }
}
+const lastMapProps = () => mockMapProps.mock.calls[mockMapProps.mock.calls.length - 1][0]
+
+beforeEach(() => {
+ jest.clearAllMocks()
+ mockTracking = true
+ mockCoords = LIVE_FIX
+ mockGetMostRecentLocation.mockResolvedValue(null)
+})
+
describe("PlaceZoneScreen", () => {
it("cannot confirm until somewhere is picked", () => {
const { getByTestId, getByText } = renderScreen()
@@ -83,5 +130,77 @@ describe("PlaceZoneScreen", () => {
const { getByText } = renderScreen({ name: "Home", radius: 50, lat: 40.7, lon: -74 })
expect(getByText(`40.70000, -74.00000 · ${formatShortDistance(50)} radius`)).toBeTruthy()
+ expect(lastMapProps().initialCenter).toEqual([-74, 40.7])
+ })
+
+ it("marks where the user stands while tracking, so the zone is placed against a position and not a guess", () => {
+ const { getByTestId } = renderScreen()
+
+ const dot = getByTestId("user-location-overlay")
+ expect(dot.props.coords).toEqual(LIVE_FIX)
+ expect(dot.props.isPaused).toBe(false)
+ expect(lastMapProps().initialCenter).toEqual([13.4, 52.5])
+ expect(mockGetMostRecentLocation).not.toHaveBeenCalled()
+ })
+
+ it("places the zone at the live fix in one tap and confirms that coordinate", () => {
+ const { getByTestId, getByText, popTo } = renderScreen()
+
+ fireEvent.press(getByTestId("place-at-fix-btn"))
+
+ expect(getByText(`52.50000, 13.40000 · ${formatShortDistance(100)} radius`)).toBeTruthy()
+ expect(mockFlyTo).toHaveBeenCalledWith(expect.objectContaining({ center: [13.4, 52.5] }))
+
+ fireEvent.press(getByTestId("use-location-btn"))
+ expect(popTo).toHaveBeenCalledWith("Geofence Editor", { lat: 52.5, lon: 13.4 }, { merge: true })
+ })
+
+ it("greys the last recorded fix while tracking is off and never offers to place the zone on it, since it may be a city away", async () => {
+ mockTracking = false
+ mockGetMostRecentLocation.mockResolvedValue({ latitude: 48.2, longitude: 16.37, accuracy: 12 })
+
+ const { findByTestId, queryByTestId } = renderScreen()
+
+ const dot = await findByTestId("user-location-overlay")
+ expect(dot.props.isPaused).toBe(true)
+ expect(dot.props.coords).toEqual({ latitude: 48.2, longitude: 16.37, accuracy: 0 })
+ expect(lastMapProps().initialCenter).toEqual([16.37, 48.2])
+ expect(queryByTestId("place-at-fix-btn")).toBeNull()
+ })
+
+ it("draws no map until the saved fix is read, so it never opens on the ocean and jumps", async () => {
+ mockTracking = false
+ let resolve: (v: any) => void = () => {}
+ mockGetMostRecentLocation.mockReturnValue(new Promise((r) => (resolve = r)))
+
+ const { queryByTestId, findByTestId } = renderScreen()
+ expect(queryByTestId("colota-map")).toBeNull()
+
+ resolve({ latitude: 48.2, longitude: 16.37 })
+
+ await findByTestId("colota-map")
+ expect(mockMapProps.mock.calls[0][0].initialCenter).toEqual([16.37, 48.2])
+ expect(mockMapProps.mock.calls[0][0].initialZoom).toBe(DEFAULT_MAP_ZOOM)
+ })
+
+ it("opens on the whole world rather than a street-level patch of sea when there is no fix at all", async () => {
+ mockTracking = false
+ mockCoords = null
+
+ const { findByTestId, queryByTestId } = renderScreen()
+
+ await findByTestId("colota-map")
+ expect(lastMapProps().initialZoom).toBe(WORLD_MAP_ZOOM)
+ expect(queryByTestId("user-location-overlay")).toBeNull()
+ })
+
+ it("still opens the map when the saved fix cannot be read", async () => {
+ mockTracking = false
+ mockGetMostRecentLocation.mockRejectedValue(new Error("db closed"))
+
+ const { findByTestId } = renderScreen()
+
+ await findByTestId("colota-map")
+ await waitFor(() => expect(lastMapProps().initialZoom).toBe(WORLD_MAP_ZOOM))
})
})
diff --git a/fastlane/metadata/android/en-US/changelogs/51.txt b/fastlane/metadata/android/en-US/changelogs/51.txt
index 2e3363e9..153a2326 100644
--- a/fastlane/metadata/android/en-US/changelogs/51.txt
+++ b/fastlane/metadata/android/en-US/changelogs/51.txt
@@ -1,2 +1,3 @@
- A tracking profile keeps its deactivation delay when a lower-priority profile starts to match
- Setup links show the full server address with its host on its own line, name the server they replace and are rejected as a whole when the address hides its host
+- Placing a geofence shows where you are and the locate button puts the zone there