Colota - Android GPS Location tracker
feat: show today's tracked route on dashboard map with toggle
Max Dietrich057c0ec9595f
diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.mdindex 751e1c4b..5fca800b 100644--- a/apps/docs/docs/development/architecture.md+++ b/apps/docs/docs/development/architecture.md@@ -225,7 +225,7 @@ The app uses [MapLibre GL Native](https://github.com/maplibre/maplibre-react-nat| Component | Purpose || --- | --- || `ColotaMapView` | Shared base map component wrapping MapLibre's `MapView` with OpenFreeMap vector tiles, dark mode style transformation, custom compass, and attribution |-| `DashboardMap` | Live tracking map with user marker, accuracy circle, geofence polygons with labels, auto-center, and center button |+| `DashboardMap` | Live tracking map with user marker, accuracy circle, today's track overlay with toggle button, geofence polygons with labels, auto-center, and center button || `TrackMap` | Location history map with trip-colored track segments, tappable point markers with detail popups, fit-to-track bounds, and trip legend || `CalendarPicker` | Day picker with month navigation, dot indicators for days with data, and daily distance/count display || `TripList` | Segmented trip cards with distance, duration, avg speed, elevation gain/loss, and per-trip or bulk export |diff --git a/apps/docs/docs/introduction.md b/apps/docs/docs/introduction.mdindex 38b5baa1..050d4eeb 100644--- a/apps/docs/docs/introduction.md+++ b/apps/docs/docs/introduction.md@@ -30,7 +30,7 @@ Colota has eighteen screens, each focused on a specific task:| Screen | Purpose || --- | --- |-| **Dashboard** | Live map with current coordinates, tracking controls, database stats, and geofence status |+| **Dashboard** | Live map with current coordinates, today's track overlay, tracking controls, database stats, and geofence status || **Settings** | GPS polling interval, distance filter, sync strategy, offline mode, accuracy threshold, unit system, time format || **API Config** | Endpoint field mapping with templates for Dawarich, OwnTracks, PhoneTrack, Reitti, Traccar, or custom backends || **Auth Settings** | Endpoint authentication (None, Basic Auth, Bearer Token) and custom HTTP headers |diff --git a/apps/mobile/src/components/features/dashboard/DashboardMap.tsx b/apps/mobile/src/components/features/dashboard/DashboardMap.tsxindex 33990b86..6fb8f15e 100644--- a/apps/mobile/src/components/features/dashboard/DashboardMap.tsx+++ b/apps/mobile/src/components/features/dashboard/DashboardMap.tsx@@ -12,10 +12,13 @@ import { fonts } from "../../../styles/typography"import NativeLocationService from "../../../services/NativeLocationService"import { MAP_ANIMATION_DURATION_MS, MAX_MAP_ZOOM } from "../../../constants"import { MapCenterButton } from "../map/MapCenterButton"+import { TrackToggleButton } from "../map/TrackToggleButton"import { ColotaMapView, ColotaMapRef } from "../map/ColotaMapView"import { buildGeofencesGeoJSON } from "../map/mapUtils"import { GeofenceLayers } from "../map/GeofenceLayers"+import { CurrentTrackLayers } from "../map/CurrentTrackLayers"import { UserLocationOverlay } from "../map/UserLocationOverlay"+import { useTodayTrack } from "../../../hooks/useTodayTrack"import icon from "../../../assets/icons/icon.png"import { logger } from "../../../utils/logger"@@ -37,6 +40,18 @@ export function DashboardMap({ tracking, activeZoneName, pauseReason, activeProfconst { colors } = useTheme()const [geofences, setGeofences] = useState<any[]>([])const [isCentered, setIsCentered] = useState(true)+ const [showTrack, setShowTrack] = useState<boolean | null>(null)+ const { locations: trackLocations, version: trackVersion } = useTodayTrack(tracking, coords)++ // Restore persisted track toggle+ useEffect(() => {+ NativeLocationService.getSetting("showTrack")+ .then((val) => setShowTrack(val === "true"))+ .catch((err) => {+ logger.error("[DashboardMap] Failed to load showTrack setting:", err)+ setShowTrack(false)+ })+ }, [])const isCenteredRef = useRef(true)const initialCoords = useRef<LocationCoords | null>(null)const [hasInitialCoords, setHasInitialCoords] = useState(false)@@ -109,6 +124,13 @@ export function DashboardMap({ tracking, activeZoneName, pauseReason, activeProfinitialCenter={[initialCoords.current.longitude, initialCoords.current.latitude]}onRegionDidChange={handleRegionChange}>+ <CurrentTrackLayers+ locations={trackLocations}+ version={trackVersion}+ visible={!!showTrack}+ colors={colors}+ />+<GeofenceLayers fills={geofenceData.fills} labels={geofenceData.labels} haloColor={colors.card} />{/* Always keep overlay mounted to avoid MapLibre/Fabric unmount race condition */}@@ -154,6 +176,18 @@ export function DashboardMap({ tracking, activeZoneName, pauseReason, activeProf)}{showMap && <MapCenterButton visible={!isCentered} onPress={handleCenterMe} />}+ {showMap && showTrack !== null && (+ <TrackToggleButton+ active={!!showTrack}+ onPress={() => {+ const next = !showTrack+ setShowTrack(next)+ NativeLocationService.saveSetting("showTrack", String(next)).catch((err) =>+ logger.error("[DashboardMap] Failed to save showTrack setting:", err)+ )+ }}+ />+ )}{showMap && activeZoneName && (<View style={[styles.statusBar, { backgroundColor: colors.warning + "DD" }]}>diff --git a/apps/mobile/src/components/features/dashboard/__tests__/DashboardMap.test.tsx b/apps/mobile/src/components/features/dashboard/__tests__/DashboardMap.test.tsxindex ece6d587..93ccd3a3 100644--- a/apps/mobile/src/components/features/dashboard/__tests__/DashboardMap.test.tsx+++ b/apps/mobile/src/components/features/dashboard/__tests__/DashboardMap.test.tsx@@ -58,6 +58,10 @@ jest.mock("../../../../contexts/TrackingProvider", () => ({useCoords: () => mockCoords}))+jest.mock("../../../../hooks/useTodayTrack", () => ({+ useTodayTrack: () => ({ locations: [], version: 0 })+}))+jest.mock("../../../../assets/icons/icon.png", () => "mock-icon")jest.mock("../../map/MapCenterButton", () => {diff --git a/apps/mobile/src/components/features/inspector/TrackMap.tsx b/apps/mobile/src/components/features/inspector/TrackMap.tsxindex ffb9c88b..985d4997 100644--- a/apps/mobile/src/components/features/inspector/TrackMap.tsx+++ b/apps/mobile/src/components/features/inspector/TrackMap.tsx@@ -137,7 +137,7 @@ export function TrackMap({ locations, selectedPoint, colors, trips, fitVersion }// GeoJSON dataconst segmentsGeoJSON = useMemo(- () => buildTrackSegmentsGeoJSON(locations, colors, skipIndices, locationColors),+ () => buildTrackSegmentsGeoJSON(locations, colors, { skipIndices, locationColors }),[locations, colors, skipIndices, locationColors])const pointsGeoJSON = useMemo(diff --git a/apps/mobile/src/components/features/map/CurrentTrackLayers.tsx b/apps/mobile/src/components/features/map/CurrentTrackLayers.tsxnew file mode 100644index 00000000..44a03959--- /dev/null+++ b/apps/mobile/src/components/features/map/CurrentTrackLayers.tsx@@ -0,0 +1,40 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import React, { useMemo } from "react"+import { ShapeSource, LineLayer } from "@maplibre/maplibre-react-native"+import { buildTrackSegmentsGeoJSON, type TrackLocation } from "./mapUtils"+import type { ThemeColors } from "../../../types/global"++const trackLineStyle = {+ lineColor: ["get", "color"] as const,+ lineWidth: 3,+ lineCap: "round" as const,+ lineJoin: "round" as const+}++interface Props {+ locations: TrackLocation[]+ version: number+ visible: boolean+ colors: ThemeColors+}++export function CurrentTrackLayers({ locations, version, visible, colors }: Props) {+ const geoJSON = useMemo(+ () => buildTrackSegmentsGeoJSON(locations, colors),+ // locations is a stable ref array - version is the change signal for rebuilds+ // eslint-disable-next-line react-hooks/exhaustive-deps+ [version, colors]+ )++ if (!visible || locations.length < 2) return null++ return (+ <ShapeSource id="current-track-segments" shape={geoJSON}>+ <LineLayer id="current-track-line" style={trackLineStyle} />+ </ShapeSource>+ )+}diff --git a/apps/mobile/src/components/features/map/MapActionButton.tsx b/apps/mobile/src/components/features/map/MapActionButton.tsxnew file mode 100644index 00000000..d6a51b1a--- /dev/null+++ b/apps/mobile/src/components/features/map/MapActionButton.tsx@@ -0,0 +1,51 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import React from "react"+import { Pressable, StyleSheet, ViewStyle, StyleProp } from "react-native"+import { useTheme } from "../../../hooks/useTheme"++interface Props {+ onPress: () => void+ style?: StyleProp<ViewStyle>+ children: React.ReactNode+}++export function MapActionButton({ onPress, style, children }: Props) {+ const { colors } = useTheme()++ return (+ <Pressable+ style={({ pressed }) => [+ styles.button,+ { backgroundColor: colors.card, borderColor: colors.border },+ style,+ pressed && { opacity: colors.pressedOpacity }+ ]}+ onPress={onPress}+ >+ {children}+ </Pressable>+ )+}++const styles = StyleSheet.create({+ button: {+ position: "absolute",+ bottom: 30,+ width: 40,+ height: 40,+ borderRadius: 20,+ justifyContent: "center",+ alignItems: "center",+ elevation: 5,+ shadowColor: "#000",+ shadowOffset: { width: 0, height: 2 },+ shadowOpacity: 0.25,+ shadowRadius: 3.84,+ borderWidth: 1,+ zIndex: 10+ }+})diff --git a/apps/mobile/src/components/features/map/MapCenterButton.tsx b/apps/mobile/src/components/features/map/MapCenterButton.tsxindex 4ca9ff95..b59249bb 100644--- a/apps/mobile/src/components/features/map/MapCenterButton.tsx+++ b/apps/mobile/src/components/features/map/MapCenterButton.tsx@@ -4,9 +4,10 @@*/import React from "react"-import { Pressable, StyleSheet, ViewStyle, StyleProp } from "react-native"+import { ViewStyle, StyleProp } from "react-native"import { LocateFixed } from "lucide-react-native"import { useTheme } from "../../../hooks/useTheme"+import { MapActionButton } from "./MapActionButton"interface Props {onPress: () => void@@ -20,36 +21,8 @@ export const MapCenterButton: React.FC<Props> = ({ onPress, visible, style }) =>if (!visible) return nullreturn (- <Pressable- style={({ pressed }) => [- styles.centerButton,- { backgroundColor: colors.card, borderColor: colors.border },- style,- pressed && { opacity: colors.pressedOpacity }- ]}- onPress={onPress}- >+ <MapActionButton onPress={onPress} style={[{ right: 16 }, style]}><LocateFixed size={24} color={colors.text} />- </Pressable>+ </MapActionButton>)}--const styles = StyleSheet.create({- centerButton: {- position: "absolute",- bottom: 30,- right: 16,- width: 40,- height: 40,- borderRadius: 20,- justifyContent: "center",- alignItems: "center",- elevation: 5,- shadowColor: "#000",- shadowOffset: { width: 0, height: 2 },- shadowOpacity: 0.25,- shadowRadius: 3.84,- borderWidth: 1,- zIndex: 10- }-})diff --git a/apps/mobile/src/components/features/map/TrackToggleButton.tsx b/apps/mobile/src/components/features/map/TrackToggleButton.tsxnew file mode 100644index 00000000..a19d847c--- /dev/null+++ b/apps/mobile/src/components/features/map/TrackToggleButton.tsx@@ -0,0 +1,24 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import React from "react"+import { Route } from "lucide-react-native"+import { useTheme } from "../../../hooks/useTheme"+import { MapActionButton } from "./MapActionButton"++interface Props {+ onPress: () => void+ active: boolean+}++export function TrackToggleButton({ onPress, active }: Props) {+ const { colors } = useTheme()++ return (+ <MapActionButton onPress={onPress} style={{ left: 16 }}>+ <Route size={24} color={active ? colors.primary : colors.text} />+ </MapActionButton>+ )+}diff --git a/apps/mobile/src/components/features/map/__tests__/mapUtils.test.ts b/apps/mobile/src/components/features/map/__tests__/mapUtils.test.tsindex 236c46cc..e6e9d33a 100644--- a/apps/mobile/src/components/features/map/__tests__/mapUtils.test.ts+++ b/apps/mobile/src/components/features/map/__tests__/mapUtils.test.ts@@ -172,7 +172,7 @@ describe("buildTrackSegmentsGeoJSON", () => {{ latitude: 52.55, longitude: 13.408, speed: 1 }]// Skip index 2 → no segment from point 1 to point 2- const result = buildTrackSegmentsGeoJSON(locs, colors, new Set([2]))+ const result = buildTrackSegmentsGeoJSON(locs, colors, { skipIndices: new Set([2]) })expect(result.features).toHaveLength(2) // segments 0→1 and 2→3, not 1→2})@@ -181,7 +181,7 @@ describe("buildTrackSegmentsGeoJSON", () => {{ latitude: 52.52, longitude: 13.405, speed: 0 },{ latitude: 52.53, longitude: 13.406, speed: 0 }]- const result = buildTrackSegmentsGeoJSON(locs, colors, undefined, ["#FF0000", "#00FF00"])+ const result = buildTrackSegmentsGeoJSON(locs, colors, { locationColors: ["#FF0000", "#00FF00"] })expect(result.features[0].properties?.color).toBe("#00FF00")})})diff --git a/apps/mobile/src/components/features/map/mapUtils.ts b/apps/mobile/src/components/features/map/mapUtils.tsindex 5ac23c81..b3f949bc 100644--- a/apps/mobile/src/components/features/map/mapUtils.ts+++ b/apps/mobile/src/components/features/map/mapUtils.ts@@ -83,21 +83,29 @@ export interface TrackLocation {altitude?: number}+interface TrackSegmentOptions {+ skipIndices?: Set<number>+ locationColors?: string[]+ defaultColor?: string+}+/** Build per-segment LineString features with a pre-computed `color` property.* Pass `skipIndices` to leave gaps between trips (indices where a new trip starts).* Pass `locationColors` to override speed-based coloring with per-location colors. */export function buildTrackSegmentsGeoJSON(locations: TrackLocation[],colors: ThemeColors,- skipIndices?: Set<number>,- locationColors?: string[]+ options?: TrackSegmentOptions): GeoJSON.FeatureCollection {+ const { skipIndices, locationColors, defaultColor } = options ?? {}const features: GeoJSON.Feature[] = []for (let i = 1; i < locations.length; i++) {if (skipIndices?.has(i)) continue- const color = locationColors- ? locationColors[i]- : getSpeedColor(((locations[i - 1].speed ?? 0) + (locations[i].speed ?? 0)) / 2, colors)+ const color = defaultColor+ ? defaultColor+ : locationColors+ ? locationColors[i]+ : getSpeedColor(((locations[i - 1].speed ?? 0) + (locations[i].speed ?? 0)) / 2, colors)features.push({type: "Feature",properties: { color },diff --git a/apps/mobile/src/hooks/__tests__/useTodayTrack.test.ts b/apps/mobile/src/hooks/__tests__/useTodayTrack.test.tsnew file mode 100644index 00000000..36d64b87--- /dev/null+++ b/apps/mobile/src/hooks/__tests__/useTodayTrack.test.ts@@ -0,0 +1,261 @@+import { renderHook, act } from "@testing-library/react-native"++// Mock logger+jest.mock("../../utils/logger", () => ({+ logger: { error: jest.fn() }+}))++// Mock NativeLocationService+const mockGetLocationsByDateRange = jest.fn().mockResolvedValue([])++jest.mock("../../services/NativeLocationService", () => ({+ getLocationsByDateRange: (...args: any[]) => mockGetLocationsByDateRange(...args)+}))++import { useTodayTrack } from "../useTodayTrack"+import { logger } from "../../utils/logger"++let appStateCallback: ((state: string) => void) | null = null+const mockAppStateRemove = jest.fn()++beforeEach(() => {+ jest.clearAllMocks()+ jest.useFakeTimers()+ appStateCallback = null+ mockGetLocationsByDateRange.mockResolvedValue([])++ const { AppState } = require("react-native")+ ;(AppState.addEventListener as jest.Mock).mockImplementation((_: string, cb: (state: string) => void) => {+ appStateCallback = cb+ return { remove: mockAppStateRemove }+ })+})++afterEach(() => {+ jest.useRealTimers()+})++function makeCoords(ts: number, lat = 48.1, lon = 11.5) {+ return { latitude: lat, longitude: lon, timestamp: ts, accuracy: 10, speed: 2, altitude: 500 }+}++describe("useTodayTrack", () => {+ describe("initial state", () => {+ it("returns empty locations when not tracking", () => {+ const { result } = renderHook(() => useTodayTrack(false, null))+ expect(result.current.locations).toEqual([])+ })++ it("loads locations from DB when tracking starts", async () => {+ const dbRows = [+ { latitude: 48.1, longitude: 11.5, timestamp: 1000, accuracy: 10, speed: 2, altitude: 500 },+ { latitude: 48.2, longitude: 11.6, timestamp: 1010, accuracy: 10, speed: 3, altitude: 510 }+ ]+ mockGetLocationsByDateRange.mockResolvedValueOnce(dbRows)++ const { result } = renderHook(() => useTodayTrack(true, null))++ await act(async () => {})++ expect(mockGetLocationsByDateRange).toHaveBeenCalled()+ expect(result.current.locations).toHaveLength(2)+ expect(result.current.locations[0].latitude).toBe(48.1)+ expect(result.current.locations[1].latitude).toBe(48.2)+ })+ })++ describe("clearing on tracking stop", () => {+ it("clears locations when tracking becomes false", async () => {+ const dbRows = [{ latitude: 48.1, longitude: 11.5, timestamp: 1000, accuracy: 10, speed: 2, altitude: 500 }]+ mockGetLocationsByDateRange.mockResolvedValueOnce(dbRows)++ const { result, rerender } = renderHook(({ tracking }: { tracking: boolean }) => useTodayTrack(tracking, null), {+ initialProps: { tracking: true }+ })++ await act(async () => {})+ expect(result.current.locations).toHaveLength(1)++ rerender({ tracking: false })+ expect(result.current.locations).toEqual([])+ })+ })++ describe("appending coords", () => {+ it("appends new coords with newer timestamp", async () => {+ mockGetLocationsByDateRange.mockResolvedValueOnce([])++ // Start with no coords so DB load completes first+ const { result, rerender } = renderHook(+ ({ coords }: { coords: ReturnType<typeof makeCoords> | null }) => useTodayTrack(true, coords),+ { initialProps: { coords: null as ReturnType<typeof makeCoords> | null } }+ )++ await act(async () => {})++ rerender({ coords: makeCoords(2000) })+ expect(result.current.locations).toHaveLength(1)++ rerender({ coords: makeCoords(2010, 48.2, 11.6) })+ expect(result.current.locations).toHaveLength(2)+ })++ it("skips coords with duplicate timestamp", async () => {+ mockGetLocationsByDateRange.mockResolvedValueOnce([])++ const { result, rerender } = renderHook(+ ({ coords }: { coords: ReturnType<typeof makeCoords> | null }) => useTodayTrack(true, coords),+ { initialProps: { coords: null as ReturnType<typeof makeCoords> | null } }+ )++ await act(async () => {})++ rerender({ coords: makeCoords(2000) })+ expect(result.current.locations).toHaveLength(1)++ // Same timestamp - should be skipped+ rerender({ coords: makeCoords(2000, 48.2, 11.6) })+ expect(result.current.locations).toHaveLength(1)+ })++ it("skips coords with no timestamp", async () => {+ mockGetLocationsByDateRange.mockResolvedValueOnce([])++ const coords = { latitude: 48.1, longitude: 11.5, timestamp: 0, accuracy: 10, speed: 2, altitude: 500 }+ const { result } = renderHook(() => useTodayTrack(true, coords))++ await act(async () => {})+ expect(result.current.locations).toHaveLength(0)+ })+ })++ describe("flush batching", () => {+ it("bumps version after flush interval when coords are appended", async () => {+ mockGetLocationsByDateRange.mockResolvedValueOnce([])++ const coords1 = makeCoords(3000)+ const { result, rerender } = renderHook(+ ({ coords }: { coords: ReturnType<typeof makeCoords> | null }) => useTodayTrack(true, coords),+ {+ initialProps: { coords: coords1 }+ }+ )++ await act(async () => {})+ const versionAfterLoad = result.current.version++ const coords2 = makeCoords(3010, 48.2, 11.6)+ rerender({ coords: coords2 })++ const versionBeforeFlush = result.current.version+ expect(versionBeforeFlush).toBe(versionAfterLoad)++ await act(async () => {+ jest.advanceTimersByTime(5000)+ })++ expect(result.current.version).toBeGreaterThan(versionBeforeFlush)+ })+ })++ describe("foreground catch-up", () => {+ it("does incremental load when app comes to foreground", async () => {+ const dbRows = [{ latitude: 48.1, longitude: 11.5, timestamp: 1000, accuracy: 10, speed: 2, altitude: 500 }]+ mockGetLocationsByDateRange.mockResolvedValueOnce(dbRows)++ renderHook(() => useTodayTrack(true, null))+ await act(async () => {})++ expect(mockGetLocationsByDateRange).toHaveBeenCalledTimes(1)++ const catchUpRows = [{ latitude: 48.3, longitude: 11.7, timestamp: 1020, accuracy: 10, speed: 4, altitude: 520 }]+ mockGetLocationsByDateRange.mockResolvedValueOnce(catchUpRows)++ await act(async () => {+ appStateCallback?.("active")+ })++ expect(mockGetLocationsByDateRange).toHaveBeenCalledTimes(2)+ // Second call should use lastTimestamp as the since param+ expect(mockGetLocationsByDateRange.mock.calls[1][0]).toBe(1000)+ })++ it("does full load when app comes to foreground with no prior data", async () => {+ mockGetLocationsByDateRange.mockResolvedValue([])++ renderHook(() => useTodayTrack(true, null))+ await act(async () => {})++ await act(async () => {+ appStateCallback?.("active")+ })++ const calls = mockGetLocationsByDateRange.mock.calls+ expect(calls).toHaveLength(2)+ // Both calls are full loads (startOfDayUnix) - much larger than a typical "since" value+ expect(calls[0][0]).toBeGreaterThan(1000000)+ expect(calls[1][0]).toBeGreaterThan(1000000)+ })++ it("does not subscribe to AppState when not tracking", async () => {+ renderHook(() => useTodayTrack(false, null))+ await act(async () => {})++ expect(appStateCallback).toBeNull()+ })+ })++ describe("error handling", () => {+ it("logs error when DB load fails", async () => {+ mockGetLocationsByDateRange.mockRejectedValueOnce(new Error("DB corrupt"))++ renderHook(() => useTodayTrack(true, null))+ await act(async () => {})++ expect(logger.error).toHaveBeenCalledWith("[useTodayTrack] Failed to load locations:", expect.any(Error))+ })++ it("still works after a failed load", async () => {+ mockGetLocationsByDateRange.mockRejectedValueOnce(new Error("DB corrupt"))++ const { result } = renderHook(() => useTodayTrack(true, makeCoords(5000)))+ await act(async () => {})++ expect(result.current.locations).toHaveLength(1)+ expect(result.current.locations[0].timestamp).toBe(5000)+ })+ })++ describe("cleanup", () => {+ it("clears flush timer on unmount", async () => {+ mockGetLocationsByDateRange.mockResolvedValueOnce([])++ const coords = makeCoords(6000)+ const { unmount, rerender } = renderHook(+ ({ c }: { c: ReturnType<typeof makeCoords> }) => useTodayTrack(true, c),+ {+ initialProps: { c: coords }+ }+ )++ await act(async () => {})++ rerender({ c: makeCoords(6010, 48.2, 11.6) })++ const clearTimeoutSpy = jest.spyOn(globalThis, "clearTimeout")+ unmount()+ expect(clearTimeoutSpy).toHaveBeenCalled()+ clearTimeoutSpy.mockRestore()+ })++ it("removes AppState listener on unmount", async () => {+ mockGetLocationsByDateRange.mockResolvedValueOnce([])++ const { unmount } = renderHook(() => useTodayTrack(true, null))+ await act(async () => {})++ unmount()+ expect(mockAppStateRemove).toHaveBeenCalled()+ })+ })+})diff --git a/apps/mobile/src/hooks/useTodayTrack.ts b/apps/mobile/src/hooks/useTodayTrack.tsnew file mode 100644index 00000000..9574cd59--- /dev/null+++ b/apps/mobile/src/hooks/useTodayTrack.ts@@ -0,0 +1,164 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import { useEffect, useRef, useState, useCallback } from "react"+import { AppState } from "react-native"+import NativeLocationService from "../services/NativeLocationService"+import type { TrackLocation } from "../components/features/map/mapUtils"+import type { LocationCoords } from "../types/global"+import { logger } from "../utils/logger"++/** How often to bump the version counter (ms) to batch GeoJSON rebuilds. */+const FLUSH_INTERVAL_MS = 5000++function startOfDayUnix(): number {+ const d = new Date()+ d.setHours(0, 0, 0, 0)+ return Math.floor(d.getTime() / 1000)+}++function todayDateStr(): string {+ const d = new Date()+ const m = d.getMonth() + 1+ const day = d.getDate()+ return `${d.getFullYear()}-${m < 10 ? "0" : ""}${m}-${day < 10 ? "0" : ""}${day}`+}++/**+ * Loads today's tracked locations and incrementally appends new ones+ * from the coords context. Returns a stable ref array + a version+ * counter for memoization.+ */+export function useTodayTrack(tracking: boolean, coords: LocationCoords | null) {+ const locationsRef = useRef<TrackLocation[]>([])+ const [version, setVersion] = useState(0)+ const flushTimer = useRef<ReturnType<typeof setTimeout> | null>(null)+ const hasPendingPoints = useRef(false)+ const lastTimestampRef = useRef(0)+ const loadedDayRef = useRef("")++ const flush = useCallback(() => {+ flushTimer.current = null+ if (hasPendingPoints.current) {+ hasPendingPoints.current = false+ setVersion((v) => v + 1)+ }+ }, [])++ const scheduleFlush = useCallback(() => {+ hasPendingPoints.current = true+ if (!flushTimer.current) {+ flushTimer.current = setTimeout(flush, FLUSH_INTERVAL_MS)+ }+ }, [flush])++ // Load today's locations from DB+ const loadFromDb = useCallback(async (since?: number) => {+ try {+ const start = since ?? startOfDayUnix()+ const end = Math.floor(Date.now() / 1000)+ const rows = await NativeLocationService.getLocationsByDateRange(start, end)+ const mapped: TrackLocation[] = (rows || []).map((r: any) => ({+ latitude: r.latitude,+ longitude: r.longitude,+ timestamp: r.timestamp,+ accuracy: r.accuracy,+ speed: r.speed,+ altitude: r.altitude+ }))++ if (since) {+ // Incremental: append only points newer than the cutoff.+ const cutoff = since+ for (const loc of mapped) {+ if (loc.timestamp && loc.timestamp > cutoff) {+ locationsRef.current.push(loc)+ }+ }+ } else {+ // Full load: merge any points appended by coords during the await+ const pendingCutoff = mapped.length > 0 ? (mapped[mapped.length - 1].timestamp ?? 0) : 0+ const pendingPoints = locationsRef.current.filter((loc) => (loc.timestamp ?? 0) > pendingCutoff)+ locationsRef.current = mapped.concat(pendingPoints)+ loadedDayRef.current = todayDateStr()+ }++ if (locationsRef.current.length > 0) {+ const last = locationsRef.current[locationsRef.current.length - 1]+ lastTimestampRef.current = last.timestamp ?? end+ }++ setVersion((v) => v + 1)+ } catch (err) {+ logger.error("[useTodayTrack] Failed to load locations:", err)+ }+ }, [])++ // Initial load + day rollover check+ useEffect(() => {+ if (!tracking) {+ locationsRef.current = []+ lastTimestampRef.current = 0+ loadedDayRef.current = ""+ setVersion((v) => v + 1)+ return+ }+ loadFromDb()+ }, [tracking, loadFromDb])++ // Append new points from coords context changes+ useEffect(() => {+ if (!tracking || !coords || !coords.timestamp) return++ // Day rollover: reset if date changed+ const today = todayDateStr()+ if (loadedDayRef.current && loadedDayRef.current !== today) {+ locationsRef.current = []+ lastTimestampRef.current = 0+ loadedDayRef.current = today+ }++ // Skip if this timestamp was already recorded+ if (coords.timestamp <= lastTimestampRef.current) return++ locationsRef.current.push({+ latitude: coords.latitude,+ longitude: coords.longitude,+ timestamp: coords.timestamp,+ accuracy: coords.accuracy,+ speed: coords.speed,+ altitude: coords.altitude+ })+ lastTimestampRef.current = coords.timestamp+ scheduleFlush()+ }, [tracking, coords, scheduleFlush])++ // Catch up on locations missed while backgrounded (incremental)+ useEffect(() => {+ if (!tracking) return++ const sub = AppState.addEventListener("change", (state) => {+ if (state === "active" && lastTimestampRef.current > 0) {+ loadFromDb(lastTimestampRef.current)+ } else if (state === "active") {+ loadFromDb()+ }+ })++ return () => sub.remove()+ }, [tracking, loadFromDb])++ // Cleanup flush timer on unmount+ useEffect(() => {+ return () => {+ if (flushTimer.current) {+ clearTimeout(flushTimer.current)+ flushTimer.current = null+ }+ }+ }, [])++ return { locations: locationsRef.current, version }+}