Colota - Android GPS Location tracker
refactor(dashboard): the map is the screen, the state reads as one line (#851)
Max Dietrich94fa7a7917dc
diff --git a/apps/mobile/src/components/features/dashboard/ConnectionStatus.tsx b/apps/mobile/src/components/features/dashboard/ConnectionStatus.tsxindex 9ad00855..e6fc08ba 100644--- a/apps/mobile/src/components/features/dashboard/ConnectionStatus.tsx+++ b/apps/mobile/src/components/features/dashboard/ConnectionStatus.tsx@@ -3,22 +3,27 @@* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.*/-import React, { useState, useCallback, useMemo } from "react"+import React, { useState, useCallback } from "react"import { StyleSheet, View, Text, Pressable, DeviceEventEmitter } from "react-native"import { ChevronRight } from "lucide-react-native"import { useFocusEffect } from "@react-navigation/native"import { useTheme } from "../../../hooks/useTheme"import { useTracking } from "../../../contexts/TrackingProvider"-import { ServerStatus, ConnectionStatusProps } from "../../../types/global"-import { fonts } from "../../../styles/typography"+import { ConnectionStatusProps, DatabaseStats } from "../../../types/global"+import { fontSizes, fonts } from "../../../styles/typography"import NativeLocationService from "../../../services/NativeLocationService"+import { size, space, STATE_LAYER_ALPHA } from "../../../constants"+import { describeServer, endpointHost, type ServerTone } from "../../../utils/serverState"+import { formatCount } from "../../../utils/format"+import { radius } from "@colota/shared"export function ConnectionStatus({ endpoint, navigation }: ConnectionStatusProps) {const { colors } = useTheme()const { settings } = useTracking()const isOffline = settings.isOfflineMode- const [serverStatus, setServerStatus] = useState<ServerStatus | "offline" | "deviceOffline" | null>(null)+ const [stats, setStats] = useState<DatabaseStats | null>(null)+ const [deviceOnline, setDeviceOnline] = useState(true)useFocusEffect(useCallback(() => {@@ -26,104 +31,115 @@ export function ConnectionStatus({ endpoint, navigation }: ConnectionStatusPropslet cancelled = falseconst refresh = async () => {- if (isOffline) {- setServerStatus("offline")- return- }-+ if (isOffline) returnconst networkAvailable = await NativeLocationService.isNetworkAvailable()if (cancelled) return- if (!networkAvailable) {- setServerStatus("deviceOffline")- return- }-- if (!endpoint) {- setServerStatus("notConfigured")- return- }-+ setDeviceOnline(networkAvailable)+ if (!endpoint) returntry {- const stats = await NativeLocationService.getStats()- if (cancelled) return- // Empty queue plus a prior successful send (sent = retained synced rows) means caught up.- if (stats.queued === 0 && stats.sent > 0) {- setServerStatus("connected")- }+ const next = await NativeLocationService.getStats()+ if (!cancelled) setStats(next)} catch {// getStats is a local DB read; a failure here says nothing about the server.}}refresh()- const sub = DeviceEventEmitter.addListener("onSyncError", () => setServerStatus("error"))+ // The queue grows on a fix and drains or fails on a sync, so those events are exactly when the row changes.+ const subs = ["onSyncError", "onSyncProgress", "onLocationUpdate"].map((event) =>+ DeviceEventEmitter.addListener(event, refresh)+ )return () => {cancelled = true- sub.remove()+ subs.forEach((sub) => sub.remove())}}, [endpoint, isOffline]))- const displayUrl = endpoint ? endpoint.replace(/^https?:\/\//, "").split("/")[0] : ""+ const tone = (t: ServerTone) =>+ t === "success"+ ? colors.success+ : t === "error"+ ? colors.error+ : t === "warning"+ ? colors.warning+ : t === "light"+ ? colors.textLight+ : colors.textSecondary- const config = useMemo(() => {- const statusMap = {- connected: { color: colors.success, label: "Connected" },- error: { color: colors.error, label: "Unreachable" },- notConfigured: { color: colors.warning, label: "No endpoint" },- deviceOffline: { color: colors.textSecondary, label: "Device offline" },- offline: { color: colors.textSecondary, label: "Offline Mode" },- loading: { color: colors.textLight, label: "Checking" }- }+ const known = isOffline || !endpoint || !deviceOnline || stats !== null+ const server = describeServer({+ offline: isOffline,+ endpoint: endpoint ?? "",+ deviceOnline,+ queued: stats?.queued ?? 0,+ today: stats?.today ?? 0,+ lastSyncTime: stats?.lastSyncTime ?? 0,+ lastSyncError: stats?.lastSyncError ?? ""+ })+ const word = known ? server.word : "Checking"+ const dotColor = known ? tone(server.tone) : colors.textLight- if (serverStatus === null) return statusMap.loading- if (isOffline) return statusMap.offline- if (serverStatus === "deviceOffline") return statusMap.deviceOffline- return statusMap[serverStatus as ServerStatus] || statusMap.error- }, [serverStatus, colors, isOffline])+ const hostLabel = isOffline ? "Offline mode" : endpoint ? endpointHost(endpoint) : "Server"+ const queued = stats?.queued ?? 0+ const queueLabel = queued > 0 ? `${formatCount(queued)} queued` : ""+ const spokenStatus = [word, queueLabel].filter(Boolean).join(" · ")+ // A healthy server says nothing; the word is for a screen reader, which cannot see the dot.+ const statusLabel = known && server.tone === "success" ? queueLabel : spokenStatusreturn (<Pressable+ accessibilityRole="button"+ accessibilityLabel={isOffline ? hostLabel : `${hostLabel}, ${spokenStatus}`}onPress={() => navigation.navigate("Connection")}- style={({ pressed }) => [- styles.container,- { backgroundColor: colors.card, borderColor: colors.border },- pressed && { opacity: colors.pressedOpacity }- ]}+ android_ripple={{ color: colors.text + STATE_LAYER_ALPHA }}+ style={styles.row}>- <View style={[styles.dot, { backgroundColor: config.color }]} />+ <View style={styles.glyph}>+ <View style={[styles.dot, { backgroundColor: dotColor }]} />+ </View><Text style={[styles.host, { color: colors.text }]} numberOfLines={1}>- {isOffline ? "Offline Mode" : displayUrl || "Server"}+ {hostLabel}</Text>- {!isOffline && <Text style={[styles.status, { color: config.color }]}>{config.label}</Text>}- <ChevronRight size={16} color={colors.textLight} />+ {/* The endpoint can answer while the backlog grows, held by the sync condition or a 429, so the queue shows on its own. */}+ {!isOffline && statusLabel !== "" && (+ <Text style={[styles.status, { color: colors.textSecondary }]} numberOfLines={1}>+ {statusLabel}+ </Text>+ )}+ <ChevronRight size={size.icon.sm} color={colors.textLight} /></Pressable>)}const styles = StyleSheet.create({- container: {+ row: {flexDirection: "row",alignItems: "center",- padding: 14,- borderRadius: 12,- borderWidth: 1,- marginBottom: 22+ gap: space.lg,+ minHeight: size.row,+ paddingVertical: space.md,+ marginHorizontal: -space.lg,+ paddingHorizontal: space.lg+ },+ glyph: {+ width: size.icon.md,+ alignItems: "center"},dot: {width: 8,height: 8,- borderRadius: 4,- marginRight: 12+ borderRadius: radius.pill},host: {- flex: 1,- fontSize: 14,+ flexGrow: 1,+ flexShrink: 1,+ fontSize: fontSizes.body,...fonts.medium},status: {- fontSize: 12,- ...fonts.medium,- marginRight: 8+ flexShrink: 1,+ fontSize: fontSizes.caption,+ ...fonts.medium}})diff --git a/apps/mobile/src/components/features/dashboard/CoordinateDisplay.tsx b/apps/mobile/src/components/features/dashboard/CoordinateDisplay.tsxdeleted file mode 100644index d4101b8d..00000000--- a/apps/mobile/src/components/features/dashboard/CoordinateDisplay.tsx+++ /dev/null@@ -1,83 +0,0 @@-/**- * Copyright (C) 2026 Max Dietrich- * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.- */--import React from "react"-import { View, Text, StyleSheet } from "react-native"-import { useTheme } from "../../../hooks/useTheme"-import { useCoords } from "../../../contexts/TrackingProvider"-import { fonts } from "../../../styles/typography"-import { SectionTitle } from "../../ui/SectionTitle"-import { Card } from "../../ui/Card"--export function CoordinateDisplay() {- const coords = useCoords()- const { colors } = useTheme()-- if (!coords) return null-- const latitude = coords.latitude?.toFixed(6) ?? "0.000000"- const longitude = coords.longitude?.toFixed(6) ?? "0.000000"- const altitude = Math.round(coords.altitude ?? 0).toLocaleString()- const accuracy = coords.accuracy?.toFixed(1) ?? "0.0"-- /**- * Renders a single coordinate metric card- */- const renderCard = (label: string, value: string, unit: string) => (- <Card variant="elevated">- <Text style={[styles.coordLabel, { color: colors.textSecondary }]}>{label}</Text>- <Text style={[styles.coordValue, { color: colors.text }]}>- {value}- <Text style={styles.coordUnit}> {unit}</Text>- </Text>- </Card>- )-- return (- <>- <SectionTitle>CURRENT LOCATION DATA</SectionTitle>- <View style={styles.container}>- {/* First Row: Latitude and Longitude */}- <View style={styles.row}>- {renderCard("Latitude", latitude, "°")}- {renderCard("Longitude", longitude, "°")}- </View>-- {/* Second Row: Altitude and Accuracy */}- <View style={styles.row}>- {renderCard("Altitude", altitude, "m")}- {renderCard("Accuracy", `±${accuracy}`, "m")}- </View>- </View>- </>- )-}--const styles = StyleSheet.create({- container: {- gap: 10- },- row: {- flexDirection: "row",- gap: 10- },- coordLabel: {- fontSize: 10,- ...fonts.semiBold,- marginBottom: 4,- letterSpacing: 0.5,- textTransform: "uppercase"- },- coordValue: {- fontSize: 15,- ...fonts.bold,- letterSpacing: -0.3- },- coordUnit: {- fontSize: 12,- ...fonts.medium,- opacity: 0.6- }-})diff --git a/apps/mobile/src/components/features/dashboard/DashboardBanner.tsx b/apps/mobile/src/components/features/dashboard/DashboardBanner.tsxnew file mode 100644index 00000000..f7314edf--- /dev/null+++ b/apps/mobile/src/components/features/dashboard/DashboardBanner.tsx@@ -0,0 +1,78 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import React from "react"+import { LayoutChangeEvent, StyleSheet, Text, View } from "react-native"+import { BatteryWarning, CircleAlert, TriangleAlert, type LucideIcon } from "lucide-react-native"+import { radius } from "@colota/shared"+import { useTheme } from "../../../hooks/useTheme"+import { fontSizes, fonts, lineHeights } from "../../../styles/typography"+import { elevation, size, space } from "../../../constants"+import { Button } from "../../ui/Button"++export type BannerCondition = "permission" | "background" | "locationOff" | "battery"++type Props = {+ condition: BannerCondition+ onAction: () => void+ top: number+ left: number+ right: number+ onLayout?: (event: LayoutChangeEvent) => void+}++const CONTENT: Record<+ BannerCondition,+ { icon: LucideIcon; tone: "error" | "warning"; text: string; action: string | null }+> = {+ permission: { icon: CircleAlert, tone: "error", text: "Location permission missing", action: "Grant" },+ background: { icon: CircleAlert, tone: "error", text: "Background location not allowed", action: "Grant" },+ locationOff: { icon: TriangleAlert, tone: "warning", text: "Location services are off", action: "Settings" },+ battery: { icon: BatteryWarning, tone: "error", text: "Battery critically low. Charge to track.", action: null }+}++export function DashboardBanner({ condition, onAction, top, left, right, onLayout }: Props) {+ const { colors } = useTheme()+ const { icon: Icon, tone, text, action } = CONTENT[condition]++ return (+ <View+ accessibilityRole="alert"+ accessibilityLiveRegion="polite"+ onLayout={onLayout}+ style={[styles.container, { top, left, right, backgroundColor: colors.surfaceRaised }]}+ testID="dashboard-banner"+ >+ <Icon size={size.icon.md} color={colors[tone]} />+ <Text style={[styles.text, { color: colors.text }]}>{text}</Text>+ {action !== null && (+ <Button title={action} variant="ghost" shape="rounded" color={colors.primary} onPress={onAction} />+ )}+ </View>+ )+}++const styles = StyleSheet.create({+ container: {+ position: "absolute",+ zIndex: 1,+ minHeight: size.row,+ borderRadius: radius.md,+ elevation: elevation.floating,+ overflow: "hidden",+ flexDirection: "row",+ alignItems: "center",+ gap: space.md,+ paddingStart: space.lg,+ paddingEnd: space.sm,+ paddingVertical: space.xs+ },+ text: {+ flex: 1,+ fontSize: fontSizes.body,+ lineHeight: lineHeights.body,+ ...fonts.medium+ }+})diff --git a/apps/mobile/src/components/features/dashboard/DashboardDock.tsx b/apps/mobile/src/components/features/dashboard/DashboardDock.tsxnew file mode 100644index 00000000..f891f14a--- /dev/null+++ b/apps/mobile/src/components/features/dashboard/DashboardDock.tsx@@ -0,0 +1,129 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import React from "react"+import { ScrollView } from "react-native"+import { CircleAlert, CircleDashed, CircleDot, CirclePause, Timer, type LucideIcon } from "lucide-react-native"+import { useTheme } from "../../../hooks/useTheme"+import { Settings, ThemeColors } from "../../../types/global"+import { describeState, type StateIcon, type StateTone } from "../../../utils/dashboardState"+import { size } from "../../../constants"+import { MapDock } from "../../ui/MapDock"+import { Divider } from "../../ui/Divider"+import { SpinningLoader } from "../../ui/SpinningLoader"+import { StatRow } from "../../ui/StatRow"+import { ConnectionStatus } from "./ConnectionStatus"+import { StateLine } from "../../ui/StateLine"+import { WelcomeCard } from "./WelcomeCard"++type DashboardDockProps = {+ tracking: boolean+ hasFix: boolean+ locationEnabled: boolean+ activeZoneName: string | null+ pauseReason: string | null+ activeProfileName: string | null+ coords: { accuracy: number; timestamp: number } | null+ lastKnown: { timestamp: number } | null+ stoppedByBattery: boolean+ intervalText: string+ endpoint: string | null+ isOfflineMode: boolean+ navigation: any+ maxHeight: number+ firstRun: boolean+ settings: Settings+ colors: ThemeColors+ onDismiss: () => void+ onStartTracking: () => void+ onNavigateToConnection: () => void+ onNavigateToTrackingSync: () => void+ onNavigateToRequestFormat: () => void+}++const GLYPHS: Record<Exclude<StateIcon, "loader">, LucideIcon> = {+ dashed: CircleDashed,+ circleDot: CircleDot,+ pause: CirclePause,+ alert: CircleAlert+}++export function DashboardDock({+ tracking,+ hasFix,+ locationEnabled,+ activeZoneName,+ pauseReason,+ activeProfileName,+ coords,+ lastKnown,+ stoppedByBattery,+ intervalText,+ endpoint,+ isOfflineMode,+ navigation,+ maxHeight,+ firstRun,+ settings,+ colors: welcomeColors,+ onDismiss,+ onStartTracking,+ onNavigateToConnection,+ onNavigateToTrackingSync,+ onNavigateToRequestFormat+}: DashboardDockProps) {+ const { colors } = useTheme()++ if (firstRun) {+ return (+ <ScrollView style={{ maxHeight }} showsVerticalScrollIndicator={false}>+ <WelcomeCard+ settings={settings}+ tracking={tracking}+ colors={welcomeColors}+ onDismiss={onDismiss}+ onStartTracking={onStartTracking}+ onNavigateToConnection={onNavigateToConnection}+ onNavigateToTrackingSync={onNavigateToTrackingSync}+ onNavigateToRequestFormat={onNavigateToRequestFormat}+ />+ </ScrollView>+ )+ }++ const state = describeState({+ tracking,+ hasFix,+ locationEnabled,+ activeZoneName,+ pauseReason,+ activeProfileName,+ coords,+ lastKnown,+ stoppedByBattery+ })+ const tones: Record<StateTone, string> = {+ secondary: colors.textSecondary,+ primary: colors.primary,+ success: colors.success,+ error: colors.error+ }+ const iconColor = tones[state.tone]+ const icon = state.icon === "loader" ? <SpinningLoader size={size.icon.md} color={iconColor} /> : GLYPHS[state.icon]++ return (+ <MapDock maxHeight={maxHeight}>+ <StateLine icon={icon} iconColor={iconColor} label={state.label} caption={state.caption} testID="dock-state" />+ <Divider tight inset />+ <StatRow icon={Timer} label="Interval" value={intervalText} testID="dock-interval" />+ {!isOfflineMode && (+ <>+ <Divider tight inset />+ <ConnectionStatus endpoint={endpoint} navigation={navigation} />+ </>+ )}+ </MapDock>+ )+}diff --git a/apps/mobile/src/components/features/dashboard/DashboardMap.tsx b/apps/mobile/src/components/features/dashboard/DashboardMap.tsxindex 5d1d69bf..0239b231 100644--- a/apps/mobile/src/components/features/dashboard/DashboardMap.tsx+++ b/apps/mobile/src/components/features/dashboard/DashboardMap.tsx@@ -4,72 +4,83 @@*/import React, { useRef, useEffect, useMemo, useCallback, useState } from "react"-import { View, StyleSheet, Text, ActivityIndicator, DeviceEventEmitter, Image, Pressable } from "react-native"-import { AlertTriangle } from "lucide-react-native"-import { LocationCoords } from "../../../types/global"+import { View, StyleSheet, DeviceEventEmitter } from "react-native"+import type { ViewPadding } from "@maplibre/maplibre-react-native"+import { Geofence, LocationCoords } from "../../../types/global"import { useTheme } from "../../../hooks/useTheme"import { useCoords } from "../../../contexts/TrackingProvider"-import { fonts } from "../../../styles/typography"import NativeLocationService from "../../../services/NativeLocationService"-import { MAP_ANIMATION_DURATION_MS, MAX_MAP_ZOOM } from "../../../constants"+import {+ DEFAULT_MAP_ZOOM,+ GEOFENCE_ZOOM_PADDING,+ MAP_ANIMATION_DURATION_MS,+ WORLD_MAP_ZOOM,+ size,+ space+} from "../../../constants"import { MapCenterButton } from "../map/MapCenterButton"-import { TrackToggleButton } from "../map/TrackToggleButton"import { ColotaMapView, ColotaMapRef } from "../map/ColotaMapView"-import { buildGeofencesGeoJSON } from "../map/mapUtils"+import { buildGeofencesGeoJSON, geofenceBounds } 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"+const isValidCoords = (c: LocationCoords | null): c is LocationCoords => {+ return c !== null && c.latitude !== 0 && c.longitude !== 0+}++export type LastKnownLocation = {+ latitude: number+ longitude: number+ accuracy: number+ timestamp: number+}+type Props = {tracking: booleanactiveZoneName: string | null- pauseReason: string | null- activeProfileName: string | null- isBatteryCritical: boolean- locationEnabled: boolean-}--const isValidCoords = (c: LocationCoords | null): c is LocationCoords => {- return c !== null && c.latitude !== 0 && c.longitude !== 0+ /** `undefined` until the screen has read the database, `null` when it holds no fix. */+ lastKnown: LastKnownLocation | null | undefined+ cameraPadding: ViewPadding+ controlsBottom: number+ controlsEnd: number+ showTrack: boolean+ onHasTrackChange: (hasTrack: boolean) => void+ /** Bumped by the screen on Start, so the map reacts to the tap and not to the first fix. */+ recentreSignal: number}+const WORLD_CENTER: [number, number] = [0, 20]export function DashboardMap({tracking,activeZoneName,- pauseReason,- activeProfileName,- isBatteryCritical,- locationEnabled+ lastKnown,+ cameraPadding,+ controlsBottom,+ controlsEnd,+ showTrack,+ onHasTrackChange,+ recentreSignal}: Props) {const coords = useCoords()const mapRef = useRef<ColotaMapRef>(null)const { colors } = useTheme()- const [geofences, setGeofences] = useState<any[]>([])+ const [geofences, setGeofences] = useState<Geofence[] | null>(null)const [isCentered, setIsCentered] = useState(true)- const [showTrack, setShowTrack] = useState<boolean | null>(null)+ const isCenteredRef = useRef(true)+ const placedRef = useRef(false)+ const recentredRef = useRef(0)+ const flyUntilRef = useRef(0)+ const firstLoadRef = useRef(true)+ const initialRef = useRef<LastKnownLocation | LocationCoords | null | undefined>(undefined)+ const [mapLoads, setMapLoads] = useState(0)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)useEffect(() => {- if (!initialCoords.current && coords) {- initialCoords.current = coords- setHasInitialCoords(true)- }- }, [coords])+ onHasTrackChange(trackLocations.length > 0)+ }, [trackLocations, trackVersion, onHasTrackChange])const loadGeofences = useCallback(async () => {try {@@ -77,6 +88,7 @@ export function DashboardMap({setGeofences(data)} catch (err) {logger.error("[DashboardMap] Failed to load geofences:", err)+ setGeofences([])}}, [])@@ -89,28 +101,86 @@ export function DashboardMap({return () => listener.remove()}, [loadGeofences])- // Auto-center camera when position changes (only if currently centered).- // Uses ref to avoid re-triggering when isCentered flips (which would- // override the setCamera zoom from handleCenterMe with a pan-only moveTo).+ const liveFix = tracking && isValidCoords(coords) ? coords : null+ const position = liveFix ?? lastKnown ?? null++ // A stop sent before the style loads can be reset to its default, so placement runs again on the first map load.+ useEffect(() => {+ if (!position) placedRef.current = false+ if (placedRef.current || !mapRef.current?.camera) return+ if (position) {+ placedRef.current = true+ mapRef.current.camera.setStop({+ center: [position.longitude, position.latitude],+ zoom: DEFAULT_MAP_ZOOM,+ padding: cameraPadding,+ duration: 0+ })+ return+ }+ if (lastKnown === null && geofences && geofences.length > 0) {+ placedRef.current = true+ const [top, right, bottom, left] = GEOFENCE_ZOOM_PADDING+ mapRef.current.camera.fitBounds(geofenceBounds(geofences), {+ padding: {+ top: top + (cameraPadding.top ?? 0),+ right: right + (cameraPadding.right ?? 0),+ bottom: bottom + (cameraPadding.bottom ?? 0),+ left: left + (cameraPadding.left ?? 0)+ },+ duration: 0+ })+ }+ }, [mapLoads, position, lastKnown, geofences, cameraPadding])++ // The event fires again on every style load (a theme flip, the saved style URL resolving), which must not snap the viewport.+ const handleMapReady = useCallback(() => {+ if (!firstLoadRef.current) return+ firstLoadRef.current = false+ placedRef.current = false+ setMapLoads((n) => n + 1)+ }, [])++ // An ease issued mid-flight cancels the fly at whatever zoom it has reached, and it lands on the same point anyway.useEffect(() => {- if (!coords || !isCenteredRef.current || !mapRef.current?.camera) return+ if (!liveFix || !isCenteredRef.current || !mapRef.current?.camera) return+ if (Date.now() < flyUntilRef.current) returnmapRef.current.camera.easeTo({- center: [coords.longitude, coords.latitude],+ center: [liveFix.longitude, liveFix.latitude],+ padding: cameraPadding,+ duration: MAP_ANIMATION_DURATION_MS+ })+ }, [liveFix, cameraPadding])++ useEffect(() => {+ if (recentreSignal === recentredRef.current) return+ recentredRef.current = recentreSignal+ if (!position || !mapRef.current?.camera) return+ placedRef.current = true+ flyUntilRef.current = Date.now() + MAP_ANIMATION_DURATION_MS+ mapRef.current.camera.flyTo({+ center: [position.longitude, position.latitude],+ zoom: DEFAULT_MAP_ZOOM,+ padding: cameraPadding,duration: MAP_ANIMATION_DURATION_MS})- }, [coords])+ isCenteredRef.current = true+ setIsCentered(true)+ }, [recentreSignal, position, cameraPadding])const handleCenterMe = useCallback(() => {- if (coords && mapRef.current?.camera) {+ if (position && mapRef.current?.camera) {+ flyUntilRef.current = Date.now() + MAP_ANIMATION_DURATION_MSmapRef.current.camera.flyTo({- center: [coords.longitude, coords.latitude],- zoom: MAX_MAP_ZOOM,+ center: [position.longitude, position.latitude],+ zoom: DEFAULT_MAP_ZOOM,+ padding: cameraPadding,duration: MAP_ANIMATION_DURATION_MS})isCenteredRef.current = truesetIsCentered(true)}- }, [coords])+ }, [position, cameraPadding])const handleRegionChange = useCallback((payload: { isUserInteraction: boolean }) => {if (payload.isUserInteraction) {@@ -119,171 +189,47 @@ export function DashboardMap({}}, [])- // Geofence GeoJSON- const geofenceData = useMemo(() => buildGeofencesGeoJSON(geofences, colors), [geofences, colors])-- const showMap = tracking && isValidCoords(coords)- const waitingForFix = tracking && !isValidCoords(coords)- const locationOff = tracking && !locationEnabled-- return (- <View style={[styles.container, { borderRadius: colors.borderRadius }]}>- {/* Keep map mounted to avoid MapLibre/Fabric unmount race condition.- Hide it behind the placeholder when not tracking. */}- {hasInitialCoords && initialCoords.current ? (- <View style={showMap ? styles.mapVisible : styles.mapHidden} pointerEvents={showMap ? "auto" : "none"}>- <ColotaMapView- ref={mapRef}- initialCenter={[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 */}- {coords && <UserLocationOverlay coords={coords} isPaused={!!activeZoneName} colors={colors} />}- </ColotaMapView>- </View>- ) : null}-- {!tracking && (- <View- style={[- styles.stateContainer,- styles.overlay,- { backgroundColor: colors.card, borderRadius: colors.borderRadius }- ]}- >- <View style={[styles.iconCircle, { backgroundColor: colors.border }]}>- <Image source={icon} style={styles.icon} />- </View>- <Text style={[styles.stateTitle, { color: isBatteryCritical ? colors.error : colors.text }]}>- {isBatteryCritical ? "Tracking Stopped" : "Tracking Disabled"}- </Text>- <Text style={[styles.stateSubtext, { color: colors.textSecondary }]}>- {isBatteryCritical- ? "Battery critically low. Charge your device to resume."- : "Start tracking to see the map."}- </Text>- </View>- )}-- {waitingForFix && locationOff && (- <Pressable- onPress={() => NativeLocationService.openLocationSettings()}- style={[- styles.stateContainer,- styles.overlay,- { backgroundColor: colors.card, borderRadius: colors.borderRadius }- ]}- >- <View style={[styles.iconCircle, { backgroundColor: colors.warning + "20" }]}>- <AlertTriangle size={32} color={colors.warning} />- </View>- <Text style={[styles.stateTitle, { color: colors.warning }]}>Location Services Off</Text>- <Text style={[styles.stateSubtext, { color: colors.textSecondary }]}>- Tracking can't get GPS fixes. Tap to open Settings.- </Text>- </Pressable>- )}+ const geofenceData = useMemo(() => buildGeofencesGeoJSON(geofences ?? [], colors), [geofences, colors])- {waitingForFix && !locationOff && (- <View- style={[- styles.stateContainer,- styles.overlay,- { backgroundColor: colors.card, borderRadius: colors.borderRadius }- ]}- >- <ActivityIndicator size="large" color={colors.primary} />- <Text style={[styles.stateTitle, styles.stateTitleSpaced, { color: colors.text }]}>Searching GPS...</Text>- <Text style={[styles.stateSubtext, { color: colors.textSecondary }]}>Waiting for GPS signal.</Text>- </View>- )}-- {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 && locationOff && (- <Pressable- onPress={() => NativeLocationService.openLocationSettings()}- style={[styles.statusBar, { backgroundColor: colors.error + "DD" }]}- >- <Text style={styles.barText}>Location off - tap to enable</Text>- </Pressable>- )}+ // The tiles wait for the database, so the map never opens on the world view and jumps to the fix a frame later.+ const settled = liveFix != null || lastKnown !== undefined+ if (settled && initialRef.current === undefined) initialRef.current = liveFix ?? lastKnown ?? null+ const initial = initialRef.current+ const staleCoords = useMemo<LocationCoords | null>(+ () => (lastKnown ? { latitude: lastKnown.latitude, longitude: lastKnown.longitude, accuracy: 0 } : null),+ [lastKnown]+ )- {showMap && !locationOff && activeZoneName && (- <View style={[styles.statusBar, { backgroundColor: colors.warning + "DD" }]}>- <Text style={styles.barText}>- Paused in {activeZoneName}- {pauseReason === "wifi" ? " - WiFi" : pauseReason === "motionless" ? " - Motionless" : ""}- </Text>- </View>- )}+ if (!settled) return <View style={StyleSheet.absoluteFill} testID="dashboard-map-pending" />- {showMap && !locationOff && !activeZoneName && activeProfileName && (- <View style={[styles.statusBar, { backgroundColor: colors.primary + "DD" }]}>- <Text style={styles.barText}>{activeProfileName}</Text>- </View>- )}+ return (+ <View style={StyleSheet.absoluteFill}>+ <ColotaMapView+ ref={mapRef}+ initialCenter={initial ? [initial.longitude, initial.latitude] : WORLD_CENTER}+ initialZoom={initial ? DEFAULT_MAP_ZOOM : WORLD_MAP_ZOOM}+ cameraPadding={cameraPadding}+ controlsBottom={controlsBottom}+ controlsEnd={controlsEnd}+ onRegionDidChange={handleRegionChange}+ onMapReady={handleMapReady}+ >+ <CurrentTrackLayers locations={trackLocations} version={trackVersion} visible={showTrack} colors={colors} />++ <GeofenceLayers fills={geofenceData.fills} labels={geofenceData.labels} haloColor={colors.card} />++ {liveFix ? (+ <UserLocationOverlay coords={liveFix} isPaused={!!activeZoneName} colors={colors} />+ ) : (+ staleCoords && <UserLocationOverlay coords={staleCoords} isPaused colors={colors} />+ )}+ </ColotaMapView>++ <MapCenterButton+ visible={!isCentered && position !== null}+ onPress={handleCenterMe}+ style={{ bottom: controlsBottom + size.iconColumn + space.lg, right: controlsEnd }}+ /></View>)}--const styles = StyleSheet.create({- container: { flex: 1, width: "100%", overflow: "hidden" },- mapVisible: { flex: 1 },- mapHidden: { flex: 1, opacity: 0 },- overlay: { position: "absolute", top: 0, left: 0, right: 0, bottom: 0, zIndex: 1 },- stateContainer: {- flex: 1,- justifyContent: "center",- alignItems: "center",- padding: 24- },- icon: { width: 64, height: 64 },- iconCircle: {- width: 80,- height: 80,- borderRadius: 40,- justifyContent: "center",- alignItems: "center",- marginBottom: 16- },- stateTitle: { fontSize: 18, ...fonts.bold, textAlign: "center" },- stateTitleSpaced: { marginTop: 20 },- stateSubtext: {- fontSize: 14,- textAlign: "center",- marginTop: 8,- lineHeight: 20- },- statusBar: {- position: "absolute",- top: 0,- left: 0,- right: 0,- paddingVertical: 6,- alignItems: "center",- zIndex: 5- },- barText: { fontSize: 13, ...fonts.semiBold, color: "#fff" }-})diff --git a/apps/mobile/src/components/features/dashboard/DatabaseStatistics.tsx b/apps/mobile/src/components/features/dashboard/DatabaseStatistics.tsxdeleted file mode 100644index 67f67e50..00000000--- a/apps/mobile/src/components/features/dashboard/DatabaseStatistics.tsx+++ /dev/null@@ -1,100 +0,0 @@-/**- * Copyright (C) 2026 Max Dietrich- * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.- */-import React from "react"-import { Text, StyleSheet, View } from "react-native"-import { SectionTitle, Card } from "../.."-import { useTheme } from "../../../hooks/useTheme"-import { useTracking } from "../../../contexts/TrackingProvider"-import { fonts } from "../../../styles/typography"-import { DatabaseStats } from "../../../types/global"-import { getQueueColor } from "../../../utils/queueStatus"--type DatabaseStatisticsProps = {- stats: DatabaseStats-}--export const DatabaseStatistics = React.memo(function DatabaseStatistics({ stats }: DatabaseStatisticsProps) {- const { settings } = useTracking()- const isOfflineMode = settings.isOfflineMode- const { colors } = useTheme()- const queuedColor = getQueueColor(stats.queued, colors)-- return (- <>- {/* Database Statistics */}- <View style={styles.metricsSection}>- <SectionTitle>DATABASE STATISTICS</SectionTitle>- {!isOfflineMode ? (- <View style={styles.statsGrid}>- <Card variant="elevated" style={styles.statCard}>- <Text style={[styles.statLabel, { color: colors.textSecondary }]}>Queued</Text>- <Text style={[styles.statValue, { color: queuedColor }]}>{stats.queued.toLocaleString()}</Text>- <Text style={[styles.statUnit, { color: colors.textLight }]}>pending</Text>- </Card>- <Card variant="elevated" style={styles.statCard}>- <Text style={[styles.statLabel, { color: colors.textSecondary }]}>Sent</Text>- <Text style={[styles.statValue, { color: colors.success }]}>{stats.sent.toLocaleString()}</Text>- <Text style={[styles.statUnit, { color: colors.textLight }]}>synced</Text>- </Card>- </View>- ) : (- <View style={styles.statsGrid}>- <Card variant="elevated" style={styles.statCard}>- <Text style={[styles.statLabel, { color: colors.textSecondary }]}>Total</Text>- <Text style={[styles.statValue, { color: colors.primary }]}>{stats.total.toLocaleString()}</Text>- <Text style={[styles.statUnit, { color: colors.textLight }]}>locations</Text>- </Card>- </View>- )}- <View style={[styles.statsGrid, styles.statsGridSpaced]}>- <Card variant="elevated" style={styles.statCard}>- <Text style={[styles.statLabel, { color: colors.textSecondary }]}>Today</Text>- <Text style={[styles.statValue, { color: colors.info }]}>{stats.today.toLocaleString()}</Text>- <Text style={[styles.statUnit, { color: colors.textLight }]}>tracked</Text>- </Card>- <Card variant="elevated" style={styles.statCard}>- <Text style={[styles.statLabel, { color: colors.textSecondary }]}>Storage</Text>- <Text style={[styles.statValue, { color: colors.primaryDark }]}>{stats.databaseSizeMB.toFixed(1)}</Text>- <Text style={[styles.statUnit, { color: colors.textLight }]}>MB</Text>- </Card>- </View>- </View>- </>- )-})--const styles = StyleSheet.create({- metricsSection: {- marginBottom: 24- },- statsGrid: {- flexDirection: "row",- gap: 12- },- statsGridSpaced: {- marginTop: 12- },- statCard: {- flex: 1,- alignItems: "center"- },- statUnit: {- fontSize: 11,- ...fonts.medium- },- statLabel: {- fontSize: 10,- ...fonts.semiBold,- marginBottom: 6,- letterSpacing: 0.5,- textTransform: "uppercase"- },- statValue: {- fontSize: 24,- ...fonts.bold,- letterSpacing: -0.5,- marginBottom: 2- }-})diff --git a/apps/mobile/src/components/features/dashboard/WelcomeCard.tsx b/apps/mobile/src/components/features/dashboard/WelcomeCard.tsxindex b1146149..ad4e7487 100644--- a/apps/mobile/src/components/features/dashboard/WelcomeCard.tsx+++ b/apps/mobile/src/components/features/dashboard/WelcomeCard.tsx@@ -8,8 +8,11 @@ import { Text, StyleSheet, View, Pressable } from "react-native"import { Check, ChevronRight } from "lucide-react-native"import { Settings, ThemeColors } from "../../../types/global"import { useTracking } from "../../../contexts/TrackingProvider"-import { fonts } from "../../../styles/typography"+import { fontSizes, fonts, type } from "../../../styles/typography"+import { Button } from "../../ui/Button"import { Card } from "../../ui/Card"+import { size, space, STATE_LAYER_ALPHA } from "../../../constants"+import { radius } from "@colota/shared"interface WelcomeCardProps {settings: Settings@@ -19,7 +22,7 @@ interface WelcomeCardProps {onStartTracking: () => voidonNavigateToConnection: () => voidonNavigateToTrackingSync: () => void- onNavigateToApiConfig: () => void+ onNavigateToRequestFormat: () => void}interface ChecklistItemProps {@@ -32,17 +35,8 @@ interface ChecklistItemProps {function ChecklistItem({ label, completed, colors, onPress }: ChecklistItemProps) {const content = (<View style={styles.checklistItem}>- <View- style={[- styles.checkCircle,- // eslint-disable-next-line react-native/no-inline-styles- {- borderColor: completed ? colors.success : colors.border,- backgroundColor: completed ? colors.success + "20" : "transparent"- }- ]}- >- {completed && <Check size={13} color={colors.success} />}+ <View style={[styles.checkCircle, { borderColor: colors.border }]}>+ {completed && <Check size={size.icon.sm} color={colors.success} />}</View><Textstyle={[@@ -53,13 +47,17 @@ function ChecklistItem({ label, completed, colors, onPress }: ChecklistItemProps>{label}</Text>- {onPress && !completed && <ChevronRight size={18} color={colors.textLight} />}+ {onPress && !completed && <ChevronRight size={size.icon.md} color={colors.textLight} />}</View>)if (onPress && !completed) {return (- <Pressable onPress={onPress} style={({ pressed }) => pressed && { opacity: colors.pressedOpacity }}>+ <Pressable+ accessibilityRole="button"+ onPress={onPress}+ android_ripple={{ color: colors.text + STATE_LAYER_ALPHA }}+ >{content}</Pressable>)@@ -76,7 +74,7 @@ export function WelcomeCard({onStartTracking,onNavigateToConnection,onNavigateToTrackingSync,- onNavigateToApiConfig+ onNavigateToRequestFormat}: WelcomeCardProps) {const {settings: { isOfflineMode }@@ -84,88 +82,78 @@ export function WelcomeCard({const hasEndpoint = settings.endpoint.trim().length > 0return (- <View style={styles.container}>- <Card variant="outlined" style={{ borderColor: colors.primary }}>- <Text style={[styles.title, { color: colors.text }]}>Welcome to Colota</Text>- <Text style={[styles.subtitle, { color: colors.textSecondary }]}>Get started by completing these steps:</Text>+ <Card variant="elevated">+ <Text style={[styles.title, { color: colors.text }]}>Welcome to Colota</Text>+ <Text style={[styles.subtitle, { color: colors.textSecondary }]}>Get started by completing these steps:</Text>- <View style={styles.checklist}>- <ChecklistItem label="1. Start tracking" completed={tracking} colors={colors} onPress={onStartTracking} />- {!isOfflineMode && (- <ChecklistItem- label="2. Configure your server endpoint"- completed={hasEndpoint}- colors={colors}- onPress={onNavigateToConnection}- />- )}- </View>+ <View style={styles.checklist}>+ <ChecklistItem label="1. Start tracking" completed={tracking} colors={colors} onPress={onStartTracking} />+ {!isOfflineMode && (+ <ChecklistItem+ label="2. Configure your server endpoint"+ completed={hasEndpoint}+ colors={colors}+ onPress={onNavigateToConnection}+ />+ )}+ </View>- <View style={styles.linkRow}>- {!isOfflineMode && (- <Pressable- onPress={onNavigateToApiConfig}- style={({ pressed }) => pressed && { opacity: colors.pressedOpacity }}- >- <Text style={[styles.link, { color: colors.primaryDark }]}>API field mapping</Text>- </Pressable>- )}+ <View style={styles.linkRow}>+ {!isOfflineMode && (<Pressable- onPress={onNavigateToTrackingSync}- style={({ pressed }) => pressed && { opacity: colors.pressedOpacity }}+ accessibilityRole="button"+ onPress={onNavigateToRequestFormat}+ android_ripple={{ color: colors.text + STATE_LAYER_ALPHA }}+ style={styles.linkTarget}>- <Text style={[styles.link, { color: colors.primaryDark }]}>Tracking presets</Text>+ <Text style={[styles.link, { color: colors.link }]}>Request format</Text></Pressable>- </View>-+ )}<Pressable- style={({ pressed }) => [- styles.dismissButton,- { borderColor: colors.border },- pressed && { opacity: colors.pressedOpacity }- ]}- onPress={onDismiss}+ accessibilityRole="button"+ onPress={onNavigateToTrackingSync}+ android_ripple={{ color: colors.text + STATE_LAYER_ALPHA }}+ style={styles.linkTarget}>- <Text style={[styles.dismissText, { color: colors.textSecondary }]}>Got it</Text>+ <Text style={[styles.link, { color: colors.link }]}>Tracking presets</Text></Pressable>- </Card>- </View>+ </View>++ <Button title="Got it" variant="secondary" onPress={onDismiss} />+ </Card>)}const styles = StyleSheet.create({- container: {- marginBottom: 16- },title: {- fontSize: 20,- ...fonts.bold,- marginBottom: 4+ ...type.title,+ marginBottom: space.xs},subtitle: {- fontSize: 14,+ fontSize: fontSizes.body,...fonts.regular,- marginBottom: 16+ marginBottom: space.lg},checklist: {- gap: 12,- marginBottom: 16+ gap: space.md,+ marginBottom: space.lg},checklistItem: {flexDirection: "row",- alignItems: "center"+ alignItems: "center",+ minHeight: size.touch},checkCircle: {width: 24,height: 24,- borderRadius: 12,+ borderRadius: radius.pill,borderWidth: 2,justifyContent: "center",alignItems: "center",- marginRight: 12+ marginEnd: space.md},checklistLabel: {- fontSize: 15,+ fontSize: fontSizes.input,...fonts.medium,flex: 1},@@ -174,21 +162,15 @@ const styles = StyleSheet.create({},linkRow: {flexDirection: "row",- gap: 16,- marginBottom: 16- },- link: {- fontSize: 14,- ...fonts.semiBold+ gap: space.lg,+ marginBottom: space.lg},- dismissButton: {- paddingVertical: 10,- alignItems: "center",- borderRadius: 10,- borderWidth: 1.5+ linkTarget: {+ minHeight: size.touch,+ justifyContent: "center"},- dismissText: {- fontSize: 14,+ link: {+ fontSize: fontSizes.body,...fonts.semiBold}})diff --git a/apps/mobile/src/components/features/dashboard/__tests__/ConnectionStatus.test.tsx b/apps/mobile/src/components/features/dashboard/__tests__/ConnectionStatus.test.tsxindex fc199f2e..b6c0524f 100644--- a/apps/mobile/src/components/features/dashboard/__tests__/ConnectionStatus.test.tsx+++ b/apps/mobile/src/components/features/dashboard/__tests__/ConnectionStatus.test.tsx@@ -1,21 +1,11 @@import React from "react"import { render, waitFor, act } from "@testing-library/react-native"-import { DeviceEventEmitter } from "react-native"+import { DeviceEventEmitter, StyleSheet } from "react-native"+import { lightColors } from "@colota/shared"+import { size, space } from "../../../../constants"jest.mock("../../../../hooks/useTheme", () => ({- useTheme: () => ({- colors: {- success: "#22c55e",- error: "#ef4444",- warning: "#f59e0b",- textSecondary: "#6b7280",- textLight: "#9ca3af",- text: "#000",- card: "#fff",- border: "#e5e7eb",- pressedOpacity: 0.6- }- })+ useTheme: () => ({ colors: require("@colota/shared").lightColors })}))const mockSettings = { isOfflineMode: false }@@ -48,7 +38,15 @@ const mockFetch = jest.fn()import { ConnectionStatus } from "../ConnectionStatus"const mockNavigation = { navigate: jest.fn() }-const stats = (queued: number, sent: number) => ({ queued, sent, total: sent, today: 0, databaseSizeMB: 0 })+const stats = (queued: number, sent: number, lastSyncTime = sent > 0 ? Date.now() : 0, lastSyncError = "") => ({+ queued,+ sent,+ total: sent,+ today: 0,+ databaseSizeMB: 0,+ lastSyncTime,+ lastSyncError+})const emit = (event: string, payload: object) =>act(() => {DeviceEventEmitter.emit(event, payload)@@ -64,40 +62,62 @@ beforeEach(() => {describe("ConnectionStatus", () => {const url = "https://example.com/api/locations"- it("shows 'Checking' until a sync result is known", async () => {- const { getByText } = render(<ConnectionStatus endpoint={url} navigation={mockNavigation} />)+ it("shows 'Checking' until the first read lands, rather than a verdict it does not have", async () => {+ let resolveStats: (v: unknown) => void = () => {}+ mockGetStats.mockImplementationOnce(() => new Promise((r) => (resolveStats = r)))+ const { getByText, getByRole } = render(<ConnectionStatus endpoint={url} navigation={mockNavigation} />)- expect(getByText("Checking")).toBeTruthy()await waitFor(() => expect(mockGetStats).toHaveBeenCalled())expect(getByText("Checking")).toBeTruthy()++ resolveStats(stats(0, 5))+ await waitFor(() => expect(getByRole("button").props.accessibilityLabel).toBe("example.com, Synced"))})- it("shows 'Connected' when the queue is empty and locations have synced", async () => {+ it("a healthy server shows the dot and host alone, while a screen reader still hears Connected", async () => {mockGetStats.mockResolvedValue(stats(0, 5))- const { getByText } = render(<ConnectionStatus endpoint={url} navigation={mockNavigation} />)+ const { getByRole, queryByText } = render(<ConnectionStatus endpoint={url} navigation={mockNavigation} />)++ await waitFor(() => expect(getByRole("button").props.accessibilityLabel).toBe("example.com, Synced"))+ expect(queryByText(/Synced/)).toBeNull()+ expect(queryByText(/Checking/)).toBeNull()+ })++ it("a backlog on a reachable server shows only the count, because the count is the news", async () => {+ mockGetStats.mockResolvedValue(stats(0, 400))+ const { getByRole, getByText, queryByText } = render(+ <ConnectionStatus endpoint="https://tracks.example.org" navigation={mockNavigation} />+ )+ await waitFor(() => expect(getByRole("button").props.accessibilityLabel).toBe("tracks.example.org, Synced"))++ mockGetStats.mockResolvedValue(stats(12, 400))+ emit("onLocationUpdate", {})- await waitFor(() => expect(getByText("Connected")).toBeTruthy())+ await waitFor(() => expect(getByText("12 queued")).toBeTruthy())+ expect(queryByText(/Synced/)).toBeNull()+ expect(getByRole("button").props.accessibilityLabel).toBe("tracks.example.org, Synced · 12 queued")})- it("stays 'Checking' on a backlog with no sync event yet (does not fabricate a status)", async () => {+ it("says 'Not synced yet' on a backlog before the first success rather than fabricating a verdict", async () => {mockGetStats.mockResolvedValue(stats(3, 0))- const { getByText, queryByText } = render(<ConnectionStatus endpoint={url} navigation={mockNavigation} />)+ const { findByText, queryByText } = render(<ConnectionStatus endpoint={url} navigation={mockNavigation} />)- await waitFor(() => expect(mockGetStats).toHaveBeenCalled())- expect(getByText("Checking")).toBeTruthy()- expect(queryByText("Connected")).toBeNull()- expect(queryByText("Unreachable")).toBeNull()+ // The queue rides on the same line, so the status is a prefix rather than the whole string.+ expect(await findByText(/^Not synced yet/)).toBeTruthy()+ expect(queryByText(/Synced$/)).toBeNull()+ expect(queryByText(/Sync failing/)).toBeNull()})- it("shows 'Unreachable' on a sync error event", async () => {+ it("shows 'Sync failing' once native records a failure and a sync error event arrives", async () => {const { getByText } = render(<ConnectionStatus endpoint={url} navigation={mockNavigation} />)await waitFor(() => expect(mockGetStats).toHaveBeenCalled())+ mockGetStats.mockResolvedValue(stats(3, 400, Date.now(), "send failed"))emit("onSyncError", { message: "send failed", queuedCount: 3 })- await waitFor(() => expect(getByText("Unreachable")).toBeTruthy())+ await waitFor(() => expect(getByText(/^Sync failing/)).toBeTruthy())})it("never performs a network request itself", async () => {@@ -117,24 +137,25 @@ describe("ConnectionStatus", () => {.mockResolvedValue(true)mockGetStats.mockResolvedValue(stats(0, 5))- const { getByText, rerender } = render(<ConnectionStatus endpoint="" navigation={mockNavigation} />)+ const { getByRole, rerender } = render(<ConnectionStatus endpoint="" navigation={mockNavigation} />)rerender(<ConnectionStatus endpoint={url} navigation={mockNavigation} />)- await waitFor(() => expect(getByText("Connected")).toBeTruthy())+ const connected = "example.com, Synced"+ await waitFor(() => expect(getByRole("button").props.accessibilityLabel).toBe(connected))await act(async () => resolveStale(true))- expect(getByText("Connected")).toBeTruthy()+ expect(getByRole("button").props.accessibilityLabel).toBe(connected)})it("shows 'No endpoint' when endpoint is empty", async () => {const { getByText } = render(<ConnectionStatus endpoint="" navigation={mockNavigation} />)- await waitFor(() => expect(getByText("No endpoint")).toBeTruthy())+ await waitFor(() => expect(getByText("No server")).toBeTruthy())})it("shows 'No endpoint' when endpoint is null", async () => {const { getByText } = render(<ConnectionStatus endpoint={null} navigation={mockNavigation} />)- await waitFor(() => expect(getByText("No endpoint")).toBeTruthy())+ await waitFor(() => expect(getByText("No server")).toBeTruthy())})it("shows 'Offline Mode' when offline mode is enabled", async () => {@@ -142,7 +163,7 @@ describe("ConnectionStatus", () => {const { getByText } = render(<ConnectionStatus endpoint={url} navigation={mockNavigation} />)- await waitFor(() => expect(getByText("Offline Mode")).toBeTruthy())+ await waitFor(() => expect(getByText("Offline mode")).toBeTruthy())})it("shows 'Device offline' when the device has no network", async () => {@@ -150,7 +171,7 @@ describe("ConnectionStatus", () => {const { getByText } = render(<ConnectionStatus endpoint={url} navigation={mockNavigation} />)- await waitFor(() => expect(getByText("Device offline")).toBeTruthy())+ await waitFor(() => expect(getByText("No network")).toBeTruthy())})it("displays the host portion of the endpoint URL", async () => {@@ -166,6 +187,79 @@ describe("ConnectionStatus", () => {const { getByText } = render(<ConnectionStatus endpoint="" navigation={mockNavigation} />)expect(getByText("Server")).toBeTruthy()- await waitFor(() => expect(getByText("No endpoint")).toBeTruthy())+ await waitFor(() => expect(getByText("No server")).toBeTruthy())+ })++ it("carries the queue on the row, because a reachable server can still be falling behind", async () => {+ mockGetStats.mockResolvedValue(stats(12, 400))+ const { getByText } = render(<ConnectionStatus endpoint="https://tracks.example.org" navigation={mockNavigation} />)++ await waitFor(() => expect(getByText(/12 queued/)).toBeTruthy())+ })++ it("says nothing about the queue when there is none, so the count means something when it appears", async () => {+ mockGetStats.mockResolvedValue(stats(0, 400))+ const { queryByText } = render(+ <ConnectionStatus endpoint="https://tracks.example.org" navigation={mockNavigation} />+ )++ await waitFor(() => expect(queryByText(/queued/)).toBeNull())+ })++ it("paints no surface of its own, because the dock card it sits in is the surface", async () => {+ const { getByRole } = render(<ConnectionStatus endpoint={url} navigation={mockNavigation} />)++ const style = StyleSheet.flatten(getByRole("button").props.style)+ expect(style.backgroundColor).toBeUndefined()+ expect(style.borderRadius).toBeUndefined()+ expect(style.borderWidth).toBeUndefined()+ expect(style.marginBottom).toBeUndefined()+ await waitFor(() => expect(mockGetStats).toHaveBeenCalled())+ })++ it("paints the state on the dot alone and prints the word in the secondary text colour, which clears 4.5 on the dock in dark mode where the hues do not", async () => {+ const { getByText, UNSAFE_getAllByType } = render(<ConnectionStatus endpoint={url} navigation={mockNavigation} />)+ await waitFor(() => expect(mockGetStats).toHaveBeenCalled())++ mockGetStats.mockResolvedValue(stats(0, 400, Date.now(), "send failed"))+ emit("onSyncError", { message: "send failed", queuedCount: 0 })+ await waitFor(() => expect(getByText("Sync failing")).toBeTruthy())++ const { View } = require("react-native")+ const dot = UNSAFE_getAllByType(View).find((v: any) => StyleSheet.flatten(v.props.style)?.width === 8)+ expect(StyleSheet.flatten(dot?.props.style).backgroundColor).toBe(lightColors.error)+ expect(StyleSheet.flatten(getByText("Sync failing").props.style).color).toBe(lightColors.textSecondary)+ })++ it("centres the dot in ListItem's icon column, so the host starts where the rows above it do", async () => {+ const { getByRole, UNSAFE_getAllByType } = render(<ConnectionStatus endpoint={url} navigation={mockNavigation} />)+ await waitFor(() => expect(mockGetStats).toHaveBeenCalled())++ const { View } = require("react-native")+ const box = UNSAFE_getAllByType(View).find((v: any) => StyleSheet.flatten(v.props.style)?.width === size.icon.md)+ expect(StyleSheet.flatten(box?.props.style).alignItems).toBe("center")+ expect(StyleSheet.flatten(getByRole("button").props.style).gap).toBe(space.lg)+ })++ it("lets both the host and the status give way at a large font scale, so neither collapses to nothing", async () => {+ mockGetStats.mockResolvedValue(stats(12345, 5))++ const { getByText } = render(<ConnectionStatus endpoint={url} navigation={mockNavigation} />)+ await waitFor(() => expect(getByText(/queued/)).toBeTruthy())++ const host = StyleSheet.flatten(getByText("example.com").props.style)+ const status = StyleSheet.flatten(getByText(/queued/).props.style)+ expect(host.flexGrow).toBe(1)+ expect(host.flexShrink).toBe(1)+ expect(status.flexShrink).toBe(1)+ })++ it("reads host and status as one row to a screen reader, so the tap target names what it opens", async () => {+ mockGetStats.mockResolvedValue(stats(12, 0))+ const { getByRole } = render(<ConnectionStatus endpoint="https://tracks.example.org" navigation={mockNavigation} />)++ await waitFor(() =>+ expect(getByRole("button").props.accessibilityLabel).toBe("tracks.example.org, Not synced yet · 12 queued")+ )})})diff --git a/apps/mobile/src/components/features/dashboard/__tests__/DashboardBanner.test.tsx b/apps/mobile/src/components/features/dashboard/__tests__/DashboardBanner.test.tsxnew file mode 100644index 00000000..f97d5149--- /dev/null+++ b/apps/mobile/src/components/features/dashboard/__tests__/DashboardBanner.test.tsx@@ -0,0 +1,98 @@+import React from "react"+import { render, fireEvent } from "@testing-library/react-native"+import { StyleSheet } from "react-native"+import { lightColors } from "@colota/shared"++jest.mock("../../../../hooks/useTheme", () => ({+ useTheme: () => ({ colors: require("@colota/shared").lightColors })+}))++import { DashboardBanner } from "../DashboardBanner"++const flat = (el: any) => StyleSheet.flatten(el.props.style)++const renderBanner = (condition: React.ComponentProps<typeof DashboardBanner>["condition"], onAction = jest.fn()) =>+ render(<DashboardBanner condition={condition} onAction={onAction} top={36} left={16} right={64} />)++describe("DashboardBanner", () => {+ it.each([+ ["permission", "Location permission missing", "Grant", "icon-CircleAlert", lightColors.error],+ ["background", "Background location not allowed", "Grant", "icon-CircleAlert", lightColors.error],+ ["locationOff", "Location services are off", "Settings", "icon-TriangleAlert", lightColors.warning]+ ] as const)(+ "%s names the problem, offers its one fix and tints only the glyph",+ (condition, text, action, glyph, hue) => {+ const { getByText, getByRole, getByTestId } = renderBanner(condition)++ expect(getByText(text)).toBeTruthy()+ expect(getByRole("button", { name: action })).toBeTruthy()+ expect(getByTestId(glyph).props.color).toBe(hue)+ }+ )++ it("battery has no action because charging is the only fix", () => {+ const { getByText, queryByRole, getByTestId } = renderBanner("battery")++ expect(getByText("Battery critically low. Charge to track.")).toBeTruthy()+ expect(queryByRole("button")).toBeNull()+ expect(getByTestId("icon-BatteryWarning").props.color).toBe(lightColors.error)+ })++ it("carries the alert role without swallowing its button into one accessible node", () => {+ const { getByTestId, getByRole } = renderBanner("permission")++ const banner = getByTestId("dashboard-banner")+ expect(banner.props.accessibilityRole).toBe("alert")+ expect(banner.props.accessible).toBeUndefined()+ expect(getByRole("button", { name: "Grant" })).toBeTruthy()+ })++ it("is a live region, so TalkBack announces a warning that appears while the user is elsewhere on the screen", () => {+ const { getByTestId } = renderBanner("locationOff")++ expect(getByTestId("dashboard-banner").props.accessibilityLiveRegion).toBe("polite")+ })++ it("reports its height to the screen, which lifts the camera padding by it", () => {+ const onLayout = jest.fn()+ const { getByTestId } = render(+ <DashboardBanner condition="permission" onAction={jest.fn()} top={36} left={16} right={16} onLayout={onLayout} />+ )++ fireEvent(getByTestId("dashboard-banner"), "layout", { nativeEvent: { layout: { height: 56 } } })++ expect(onLayout).toHaveBeenCalledWith(expect.objectContaining({ nativeEvent: { layout: { height: 56 } } }))+ })++ it("keeps the hue on the glyph, because white on the dark-mode semantic hues fails 4.5:1", () => {+ const { getByTestId } = renderBanner("locationOff")++ const style = flat(getByTestId("dashboard-banner"))+ expect(style.backgroundColor).toBe(lightColors.surfaceRaised)+ expect(style.backgroundColor).not.toBe(lightColors.warning)+ })++ it("labels its button in the primary hue, because the ghost default fails 4.5 on the elevated fill in dark mode", () => {+ const { getByText } = renderBanner("permission")++ expect(flat(getByText("Grant")).color).toBe(lightColors.primary)+ })++ it("sits where the screen puts it, below the status inset and inside the side insets", () => {+ const { getByTestId } = renderBanner("permission")++ const style = flat(getByTestId("dashboard-banner"))+ expect(style.top).toBe(36)+ expect(style.left).toBe(16)+ expect(style.right).toBe(64)+ })++ it("runs the action the screen handed it", () => {+ const onAction = jest.fn()+ const { getByRole } = renderBanner("locationOff", onAction)++ fireEvent.press(getByRole("button", { name: "Settings" }))++ expect(onAction).toHaveBeenCalledTimes(1)+ })+})diff --git a/apps/mobile/src/components/features/dashboard/__tests__/DashboardDock.test.tsx b/apps/mobile/src/components/features/dashboard/__tests__/DashboardDock.test.tsxnew file mode 100644index 00000000..fe0fe72f--- /dev/null+++ b/apps/mobile/src/components/features/dashboard/__tests__/DashboardDock.test.tsx@@ -0,0 +1,176 @@+import React from "react"+import { render } from "@testing-library/react-native"+import { ScrollView, StyleSheet } from "react-native"+import { lightColors } from "@colota/shared"+import { DEFAULT_SETTINGS } from "../../../../types/global"+import { size } from "../../../../constants"+import { loadDisplayPreferences } from "../../../../utils/geo"+import { Card } from "../../../ui/Card"+import { Divider } from "../../../ui/Divider"++jest.mock("../../../../hooks/useTheme", () => ({+ useTheme: () => ({ colors: require("@colota/shared").lightColors })+}))++const mockGetSetting = jest.fn()+jest.mock("../../../../services/NativeLocationService", () => ({+ __esModule: true,+ default: {+ getSetting: (...args: string[]) => mockGetSetting(...args)+ }+}))++jest.mock("../ConnectionStatus", () => {+ const R = require("react")+ const { View } = require("react-native")+ return {+ ConnectionStatus: (props: any) => R.createElement(View, { testID: "ConnectionStatus", ...props })+ }+})++jest.mock("../WelcomeCard", () => {+ const R = require("react")+ const { View } = require("react-native")+ return {+ WelcomeCard: (props: any) => R.createElement(View, { testID: "WelcomeCard", ...props })+ }+})++import { DashboardDock } from "../DashboardDock"++beforeAll(async () => {+ mockGetSetting.mockImplementation((key: string) => {+ if (key === "unitSystem") return Promise.resolve("metric")+ if (key === "timeFormat") return Promise.resolve("24h")+ return Promise.resolve("")+ })+ await loadDisplayPreferences()+})++const idleProps = {+ tracking: false,+ hasFix: false,+ locationEnabled: true,+ activeZoneName: null,+ pauseReason: null,+ activeProfileName: null,+ coords: null,+ lastKnown: null,+ stoppedByBattery: false,+ intervalText: "Every 30 s · Balanced",+ endpoint: "https://tracks.example.org/api",+ isOfflineMode: false,+ navigation: { navigate: jest.fn() },+ maxHeight: 390,+ firstRun: false,+ settings: DEFAULT_SETTINGS,+ colors: lightColors,+ onDismiss: jest.fn(),+ onStartTracking: jest.fn(),+ onNavigateToConnection: jest.fn(),+ onNavigateToTrackingSync: jest.fn(),+ onNavigateToRequestFormat: jest.fn()+}++const trackingProps = {+ ...idleProps,+ tracking: true,+ hasFix: true,+ coords: { accuracy: 4.2, timestamp: 1_700_000_000 }+}++const renderDock = (props: Partial<React.ComponentProps<typeof DashboardDock>> = {}) =>+ render(<DashboardDock {...idleProps} {...props} />)++describe("DashboardDock", () => {+ it("keeps the same three rows and two seams idle and tracking, so starting never shifts the dock", () => {+ const idle = renderDock()+ const idleShape = [+ idle.getByTestId("dock-state"),+ idle.getByTestId("dock-interval"),+ idle.getByTestId("ConnectionStatus")+ ].length+ expect(idleShape).toBe(3)+ expect(idle.UNSAFE_getAllByType(Divider)).toHaveLength(2)+ for (const divider of idle.UNSAFE_getAllByType(Divider)) {+ expect(divider.props.tight).toBe(true)+ expect(divider.props.inset).toBe(true)+ }+ expect(idle.getByLabelText("Ready, No fixes yet")).toBeTruthy()+ expect(idle.getByLabelText("Interval, Every 30 s · Balanced")).toBeTruthy()+ idle.unmount()++ const live = renderDock(trackingProps)+ expect(live.getByTestId("dock-state")).toBeTruthy()+ expect(live.getByTestId("dock-interval")).toBeTruthy()+ expect(live.getByTestId("ConnectionStatus")).toBeTruthy()+ expect(live.UNSAFE_getAllByType(Divider)).toHaveLength(2)+ expect(live.getByText("Tracking")).toBeTruthy()+ expect(live.getByText(/^±4 m · /)).toBeTruthy()+ expect(live.getByTestId("icon-CircleDot").props.color).toBe(lightColors.success)+ })++ it("drops the server row and its seam in offline mode, because there is no server to report", () => {+ const { queryByTestId, UNSAFE_getAllByType, getByTestId } = renderDock({ isOfflineMode: true })++ expect(queryByTestId("ConnectionStatus")).toBeNull()+ expect(UNSAFE_getAllByType(Divider)).toHaveLength(1)+ expect(getByTestId("dock-interval")).toBeTruthy()+ })++ it("hands the server row its endpoint and navigation, so a tap still opens Connection", () => {+ const { getByTestId } = renderDock()++ expect(getByTestId("ConnectionStatus").props.endpoint).toBe(idleProps.endpoint)+ expect(getByTestId("ConnectionStatus").props.navigation).toBe(idleProps.navigation)+ })++ it("shows the welcome checklist instead of the rows on first run and passes its callbacks through", () => {+ const { getByTestId, queryByTestId } = renderDock({ firstRun: true })++ const welcome = getByTestId("WelcomeCard")+ expect(welcome.props.onDismiss).toBe(idleProps.onDismiss)+ expect(welcome.props.onStartTracking).toBe(idleProps.onStartTracking)+ expect(welcome.props.settings).toBe(DEFAULT_SETTINGS)+ expect(queryByTestId("dock-state")).toBeNull()+ expect(queryByTestId("dock-interval")).toBeNull()+ expect(queryByTestId("ConnectionStatus")).toBeNull()+ })++ it("names the zone and the exit condition while paused, in a neutral tone since pausing is designed", () => {+ const { getByLabelText, getByTestId } = renderDock({+ ...trackingProps,+ activeZoneName: "Home",+ pauseReason: "wifi"+ })++ expect(getByLabelText("Paused in Home, Home WiFi · resumes when you leave")).toBeTruthy()+ expect(getByTestId("icon-CirclePause").props.color).toBe(lightColors.textSecondary)+ })++ it("spins the loader in the accent while searching, so a missing fix reads as work in progress", () => {+ const { getByText, getByTestId } = renderDock({ tracking: true, hasFix: false })++ expect(getByText("Searching for GPS")).toBeTruthy()+ expect(getByText("No fix yet")).toBeTruthy()+ expect(getByTestId("icon-Loader").props.color).toBe(lightColors.primary)+ expect(getByTestId("icon-Loader").props.size).toBe(size.icon.md)+ })++ it("flags a battery stop in the error hue after the banner has cleared", () => {+ const { getByLabelText, getByTestId } = renderDock({ stoppedByBattery: true })++ expect(getByLabelText("Tracking stopped, Battery fell below 5%")).toBeTruthy()+ expect(getByTestId("icon-CircleAlert").props.color).toBe(lightColors.error)+ })++ it("sits on the elevated row surface and caps its scroll at the height it is given", () => {+ const { UNSAFE_getByType } = renderDock({ maxHeight: 320 })++ expect(UNSAFE_getByType(Card).props.variant).toBe("elevated")+ expect(UNSAFE_getByType(Card).props.rows).toBe(true)+ const scroll = UNSAFE_getByType(ScrollView)+ expect(StyleSheet.flatten(scroll.props.style).maxHeight).toBe(320)+ expect(scroll.props.showsVerticalScrollIndicator).toBe(false)+ })+})diff --git a/apps/mobile/src/components/features/dashboard/__tests__/DashboardMap.test.tsx b/apps/mobile/src/components/features/dashboard/__tests__/DashboardMap.test.tsxindex b980e023..80f2e109 100644--- a/apps/mobile/src/components/features/dashboard/__tests__/DashboardMap.test.tsx+++ b/apps/mobile/src/components/features/dashboard/__tests__/DashboardMap.test.tsx@@ -1,188 +1,453 @@import React from "react"-import { render } from "@testing-library/react-native"+import { render, act, waitFor } from "@testing-library/react-native"+import { StyleSheet } from "react-native"+import {+ DEFAULT_MAP_ZOOM,+ GEOFENCE_ZOOM_PADDING,+ MAP_ANIMATION_DURATION_MS,+ WORLD_MAP_ZOOM,+ size,+ space+} from "../../../../constants"++const mockSetStop = jest.fn()+const mockFitBounds = jest.fn()+const mockEaseTo = jest.fn()+const mockFlyTo = jest.fn()+const mockMapProps = jest.fn()++jest.mock("../../map/ColotaMapView", () => {+ const R = require("react")+ const { View } = require("react-native")+ return {+ __esModule: true,+ ColotaMapView: R.forwardRef(function MockColotaMapView(props: any, ref: any) {+ R.useImperativeHandle(ref, () => ({+ camera: { setStop: mockSetStop, fitBounds: mockFitBounds, easeTo: mockEaseTo, flyTo: mockFlyTo },+ mapView: null+ }))+ mockMapProps(props)+ return R.createElement(View, { testID: "ColotaMapView", ...props }, props.children)+ })+ }+})jest.mock("@maplibre/maplibre-react-native", () => {+ const R = require("react")+ const { View } = require("react-native")+ const stub = (name: string) => {+ const Stub = (props: any) => R.createElement(View, { testID: props.id ?? name }, props.children)+ Stub.displayName = name+ return Stub+ }+ return { GeoJSONSource: stub("GeoJSONSource"), Layer: stub("Layer"), Marker: stub("Marker") }+})++jest.mock("../../map/UserLocationOverlay", () => {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+ UserLocationOverlay: (props: any) => R.createElement(View, { testID: "user-dot", ...props })}})-jest.mock("@react-navigation/native", () => ({- useFocusEffect: jest.fn(),- useIsFocused: () => true-}))+jest.mock("../../map/MapCenterButton", () => {+ const R = require("react")+ const { View } = require("react-native")+ return {+ MapCenterButton: (props: any) => R.createElement(View, { testID: "center-button", ...props })+ }+})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"- },- mode: "light"- })+ useTheme: () => ({ colors: require("@colota/shared").lightColors, mode: "light" })}))+const mockGetGeofences = jest.fn()+const mockGetLocationsByDateRange = jest.fn()jest.mock("../../../../services/NativeLocationService", () => ({- isNetworkAvailable: jest.fn().mockResolvedValue(true),- getGeofences: jest.fn().mockResolvedValue([]),- checkCurrentPauseZone: jest.fn().mockResolvedValue(null),- getMostRecentLocation: jest.fn().mockResolvedValue(null),- getSetting: jest.fn().mockResolvedValue(null)+ __esModule: true,+ default: {+ getGeofences: (...args: unknown[]) => mockGetGeofences(...args),+ getLocationsByDateRange: (...args: unknown[]) => mockGetLocationsByDateRange(...args),+ getSetting: jest.fn().mockResolvedValue(null)+ }}))-let mockCoords: { latitude: number; longitude: number; accuracy: number } | null = {- latitude: 48.1,- longitude: 11.5,- accuracy: 10-}+let mockCoords: { latitude: number; longitude: number; accuracy: number } | null = nulljest.mock("../../../../contexts/TrackingProvider", () => ({useCoords: () => mockCoords}))+let mockTrack: { latitude: number; longitude: number }[] = []+const mockUseTodayTrack = jest.fn()jest.mock("../../../../hooks/useTodayTrack", () => ({- useTodayTrack: () => ({ locations: [], version: 0 })+ useTodayTrack: (...args: unknown[]) => mockUseTodayTrack(...args)}))-jest.mock("../../../../assets/icons/icon.png", () => "mock-icon")+import { DashboardMap } from "../DashboardMap"-jest.mock("../../map/MapCenterButton", () => {- const R = require("react")- const { View } = require("react-native")- return { MapCenterButton: () => R.createElement(View, { testID: "center-button" }) }-})+const padding = { top: 40, right: 64, bottom: 260, left: 16 }+const controlsBottom = 224+const controlsEnd = 16+const lastKnown = { latitude: 48.1, longitude: 11.5, accuracy: 12, timestamp: 1_700_000_000 }+const homeZone = {+ id: 1,+ name: "Home",+ lat: 48.1,+ lon: 11.5,+ radius: 200,+ enabled: true,+ pauseTracking: true,+ pauseOnWifi: false,+ pauseOnMotionless: false,+ motionlessTimeoutMinutes: 5,+ heartbeatEnabled: false,+ heartbeatIntervalMinutes: 15+}-import { DashboardMap } from "../DashboardMap"+const baseProps = {+ tracking: false,+ activeZoneName: null as string | null,+ lastKnown: null as typeof lastKnown | null | undefined,+ cameraPadding: padding,+ controlsBottom,+ controlsEnd,+ showTrack: false,+ onHasTrackChange: jest.fn(),+ recentreSignal: 0+}++const zonesLoaded = () => new Promise<void>((resolve) => setTimeout(() => resolve(), 0))-describe("DashboardMap info cards", () => {+describe("DashboardMap", () => {beforeEach(() => {- mockCoords = { latitude: 48.1, longitude: 11.5, accuracy: 10 }+ jest.clearAllMocks()+ mockCoords = null+ mockTrack = []+ mockUseTodayTrack.mockImplementation(() => ({ locations: mockTrack, version: 0 }))+ mockGetGeofences.mockResolvedValue([])+ mockGetLocationsByDateRange.mockResolvedValue([])})- const baseProps = {- tracking: true,- activeZoneName: null as string | null,- pauseReason: null as string | null,- activeProfileName: null as string | null,- isBatteryCritical: false,- locationEnabled: true- }+ it("draws no tiles until the database has answered, so the map never opens on the world view and jumps", async () => {+ const { queryByTestId, getByTestId, rerender } = render(<DashboardMap {...baseProps} lastKnown={undefined} />)+ await act(zonesLoaded)++ expect(queryByTestId("ColotaMapView")).toBeNull()+ expect(getByTestId("dashboard-map-pending")).toBeTruthy()- it("shows profile name when activeProfileName is set and no pause zone", () => {- const { getByText } = render(<DashboardMap {...baseProps} activeProfileName="Charging" />)+ rerender(<DashboardMap {...baseProps} lastKnown={lastKnown} />)+ await act(zonesLoaded)- expect(getByText("Charging")).toBeTruthy()+ expect(getByTestId("ColotaMapView")).toBeTruthy()+ expect(mockMapProps.mock.calls[0][0].initialCenter).toEqual([lastKnown.longitude, lastKnown.latitude])+ expect(mockMapProps.mock.calls[0][0].initialZoom).toBe(DEFAULT_MAP_ZOOM)})- it("hides profile indicator when no profile is active", () => {- const { queryByText } = render(<DashboardMap {...baseProps} activeProfileName={null} />)+ it("mounts idle with no fix on the world view", async () => {+ const { getByTestId } = render(<DashboardMap {...baseProps} />)+ await act(zonesLoaded)- expect(queryByText("Charging")).toBeNull()+ expect(getByTestId("ColotaMapView")).toBeTruthy()+ expect(mockMapProps.mock.calls[0][0].initialCenter).toEqual([0, 20])+ expect(mockMapProps.mock.calls[0][0].initialZoom).toBe(WORLD_MAP_ZOOM)})- it("shows pause zone indicator when inside a pause zone", () => {- const { getByText } = render(<DashboardMap {...baseProps} activeZoneName="Home" />)+ it("frames the last known fix at street zoom inside the camera padding", async () => {+ render(<DashboardMap {...baseProps} lastKnown={lastKnown} />)+ await act(zonesLoaded)++ expect(mockSetStop).toHaveBeenCalledWith({+ center: [lastKnown.longitude, lastKnown.latitude],+ zoom: DEFAULT_MAP_ZOOM,+ padding,+ duration: 0+ })+ expect(mockFitBounds).not.toHaveBeenCalled()+ })- expect(getByText(/Paused in Home/)).toBeTruthy()+ it("fits the zones with the dock padding added when the database holds no fix, so Home shows before Start", async () => {+ mockGetGeofences.mockResolvedValue([homeZone])++ render(<DashboardMap {...baseProps} lastKnown={null} />)+ await act(zonesLoaded)++ expect(mockSetStop).not.toHaveBeenCalled()+ const [bounds, options] = mockFitBounds.mock.calls[0]+ expect(bounds[0]).toBeLessThan(homeZone.lon)+ expect(bounds[2]).toBeGreaterThan(homeZone.lon)+ expect(bounds[1]).toBeLessThan(homeZone.lat)+ expect(bounds[3]).toBeGreaterThan(homeZone.lat)+ const [top, right, bottom, left] = GEOFENCE_ZOOM_PADDING+ expect(options).toEqual({+ padding: {+ top: top + padding.top,+ right: right + padding.right,+ bottom: bottom + padding.bottom,+ left: left + padding.left+ },+ duration: 0+ })})- it("shows pause zone indicator when both pause zone and profile are active", () => {- const { getByText, queryByText } = render(- <DashboardMap {...baseProps} activeZoneName="Home" activeProfileName="Charging" />- )+ it("waits for the database before fitting zones, so a fix that arrives late still wins", async () => {+ mockGetGeofences.mockResolvedValue([homeZone])++ const { rerender } = render(<DashboardMap {...baseProps} lastKnown={undefined} />)+ await act(zonesLoaded)+ expect(mockFitBounds).not.toHaveBeenCalled()++ rerender(<DashboardMap {...baseProps} lastKnown={lastKnown} />)- expect(getByText(/Paused in Home/)).toBeTruthy()- expect(queryByText("Charging")).toBeNull()+ expect(mockFitBounds).not.toHaveBeenCalled()+ expect(mockSetStop).toHaveBeenCalledWith(expect.objectContaining({ zoom: DEFAULT_MAP_ZOOM }))})- it("hides standalone profile indicator when pause zone is active", () => {- const { queryByText } = render(<DashboardMap {...baseProps} activeZoneName="Office" activeProfileName="Charging" />)+ it("frames the fix again once the map reports ready, because a stop sent before the style loads can be reset", async () => {+ render(<DashboardMap {...baseProps} lastKnown={lastKnown} />)+ await act(zonesLoaded)+ expect(mockSetStop).toHaveBeenCalledTimes(1)- expect(queryByText("Charging")).toBeNull()+ act(() => mockMapProps.mock.calls[0][0].onMapReady())++ expect(mockSetStop).toHaveBeenCalledTimes(2)+ expect(mockSetStop).toHaveBeenLastCalledWith({+ center: [lastKnown.longitude, lastKnown.latitude],+ zoom: DEFAULT_MAP_ZOOM,+ padding,+ duration: 0+ })})- it("shows pause zone indicator without profile in pause zone", () => {- const { getByText } = render(<DashboardMap {...baseProps} activeZoneName="Home" activeProfileName={null} />)+ it("keeps the user's viewport when a later style load reports ready, so a theme switch does not snap the map back", async () => {+ render(<DashboardMap {...baseProps} lastKnown={lastKnown} />)+ await act(zonesLoaded)+ act(() => mockMapProps.mock.calls[0][0].onMapReady())+ expect(mockSetStop).toHaveBeenCalledTimes(2)++ act(() => mockMapProps.mock.calls[0][0].onRegionDidChange({ isUserInteraction: true }))+ act(() => mockMapProps.mock.calls[0][0].onMapReady())- expect(getByText(/Paused in Home/)).toBeTruthy()+ expect(mockSetStop).toHaveBeenCalledTimes(2)})- it("shows Tracking Disabled when not tracking", () => {- const { getByText } = render(<DashboardMap {...baseProps} tracking={false} />)+ it("fits the zones again once the map reports ready", async () => {+ mockGetGeofences.mockResolvedValue([homeZone])++ render(<DashboardMap {...baseProps} lastKnown={null} />)+ await act(zonesLoaded)+ expect(mockFitBounds).toHaveBeenCalledTimes(1)++ act(() => mockMapProps.mock.calls[0][0].onMapReady())++ expect(mockFitBounds).toHaveBeenCalledTimes(2)+ expect(mockSetStop).not.toHaveBeenCalled()+ })- expect(getByText("Tracking Disabled")).toBeTruthy()+ it("frames the first live fix at street zoom after a world start, then only follows the centre", async () => {+ const { rerender } = render(<DashboardMap {...baseProps} tracking lastKnown={null} />)+ await act(zonesLoaded)+ act(() => mockMapProps.mock.calls[0][0].onMapReady())+ expect(mockSetStop).not.toHaveBeenCalled()++ mockCoords = { latitude: 48.2, longitude: 11.6, accuracy: 8 }+ rerender(<DashboardMap {...baseProps} tracking lastKnown={null} />)+ expect(mockSetStop).toHaveBeenCalledTimes(1)+ expect(mockSetStop).toHaveBeenCalledWith(expect.objectContaining({ center: [11.6, 48.2], zoom: DEFAULT_MAP_ZOOM }))++ mockCoords = { latitude: 48.3, longitude: 11.7, accuracy: 8 }+ rerender(<DashboardMap {...baseProps} tracking lastKnown={null} />)+ expect(mockSetStop).toHaveBeenCalledTimes(1)+ expect(mockEaseTo).toHaveBeenLastCalledWith(expect.objectContaining({ center: [11.7, 48.3], padding }))+ expect(mockEaseTo.mock.calls.at(-1)[0].zoom).toBeUndefined()})- it("shows battery critical message when not tracking and battery is critical", () => {- const { getByText } = render(<DashboardMap {...baseProps} tracking={false} isBatteryCritical={true} />)+ it("flies to the last known fix the moment Start is tapped, so the map reacts before a cold fix, and lets the flight land before following", async () => {+ const now = jest.spyOn(Date, "now").mockReturnValue(1_000_000)+ const { rerender, getByTestId } = render(<DashboardMap {...baseProps} lastKnown={lastKnown} />)+ await act(zonesLoaded)+ act(() => mockMapProps.mock.calls[0][0].onMapReady())+ act(() => mockMapProps.mock.calls[0][0].onRegionDidChange({ isUserInteraction: true }))+ expect(getByTestId("center-button").props.visible).toBe(true)+ const stopsBefore = mockSetStop.mock.calls.length++ rerender(<DashboardMap {...baseProps} lastKnown={lastKnown} recentreSignal={1} />)++ expect(mockFlyTo).toHaveBeenCalledTimes(1)+ expect(mockFlyTo).toHaveBeenCalledWith({+ center: [lastKnown.longitude, lastKnown.latitude],+ zoom: DEFAULT_MAP_ZOOM,+ padding,+ duration: MAP_ANIMATION_DURATION_MS+ })+ expect(getByTestId("center-button").props.visible).toBe(false)++ // The seeded fix lands inside the flight; an ease now would cancel the fly before it reaches street zoom.+ mockCoords = { latitude: 48.2, longitude: 11.6, accuracy: 8 }+ rerender(<DashboardMap {...baseProps} tracking lastKnown={lastKnown} recentreSignal={1} />)++ expect(mockSetStop).toHaveBeenCalledTimes(stopsBefore)+ expect(mockFlyTo).toHaveBeenCalledTimes(1)+ expect(mockEaseTo).not.toHaveBeenCalled()++ now.mockReturnValue(1_000_000 + MAP_ANIMATION_DURATION_MS)+ mockCoords = { latitude: 48.3, longitude: 11.7, accuracy: 8 }+ rerender(<DashboardMap {...baseProps} tracking lastKnown={lastKnown} recentreSignal={1} />)++ expect(mockFlyTo).toHaveBeenCalledTimes(1)+ expect(mockEaseTo).toHaveBeenLastCalledWith(expect.objectContaining({ center: [11.7, 48.3], padding }))+ expect(mockEaseTo.mock.calls.at(-1)[0].zoom).toBeUndefined()+ now.mockRestore()+ })- expect(getByText("Tracking Stopped")).toBeTruthy()- expect(getByText("Battery critically low. Charge your device to resume.")).toBeTruthy()+ it("lets the centre disc's flight land before a live fix follows, so the zoom it restores is not cut short", async () => {+ const now = jest.spyOn(Date, "now").mockReturnValue(1_000_000)+ mockCoords = { latitude: 48.2, longitude: 11.6, accuracy: 8 }+ const { rerender, getByTestId } = render(<DashboardMap {...baseProps} tracking />)+ await act(zonesLoaded)+ act(() => mockMapProps.mock.calls[0][0].onRegionDidChange({ isUserInteraction: true }))+ mockEaseTo.mockClear()++ act(() => getByTestId("center-button").props.onPress())+ expect(mockFlyTo).toHaveBeenCalledTimes(1)++ mockCoords = { latitude: 48.3, longitude: 11.7, accuracy: 8 }+ rerender(<DashboardMap {...baseProps} tracking />)+ expect(mockEaseTo).not.toHaveBeenCalled()++ now.mockReturnValue(1_000_000 + MAP_ANIMATION_DURATION_MS)+ mockCoords = { latitude: 48.4, longitude: 11.8, accuracy: 8 }+ rerender(<DashboardMap {...baseProps} tracking />)+ expect(mockEaseTo).toHaveBeenCalledWith(expect.objectContaining({ center: [11.8, 48.4], padding }))+ now.mockRestore()})- it("shows normal disabled message when not tracking and battery is fine", () => {- const { getByText } = render(<DashboardMap {...baseProps} tracking={false} isBatteryCritical={false} />)+ it("stays on the world view when Start is tapped with no last known fix, leaving the first fix to frame the map", async () => {+ const { rerender } = render(<DashboardMap {...baseProps} lastKnown={null} />)+ await act(zonesLoaded)+ act(() => mockMapProps.mock.calls[0][0].onMapReady())++ rerender(<DashboardMap {...baseProps} lastKnown={null} recentreSignal={1} />)+ expect(mockFlyTo).not.toHaveBeenCalled()+ expect(mockSetStop).not.toHaveBeenCalled()- expect(getByText("Tracking Disabled")).toBeTruthy()- expect(getByText("Start tracking to see the map.")).toBeTruthy()+ mockCoords = { latitude: 48.2, longitude: 11.6, accuracy: 8 }+ rerender(<DashboardMap {...baseProps} tracking lastKnown={null} recentreSignal={1} />)++ expect(mockFlyTo).not.toHaveBeenCalled()+ expect(mockSetStop).toHaveBeenCalledTimes(1)+ expect(mockSetStop).toHaveBeenCalledWith(expect.objectContaining({ center: [11.6, 48.2], zoom: DEFAULT_MAP_ZOOM }))})- it("shows Location Services Off overlay when tracking but location services are off", () => {- mockCoords = null- const { getByText, queryByText } = render(<DashboardMap {...baseProps} locationEnabled={false} />)+ it("leaves the world view when there is neither a fix nor a zone", async () => {+ render(<DashboardMap {...baseProps} lastKnown={null} />)+ await act(zonesLoaded)- expect(getByText("Location Services Off")).toBeTruthy()- expect(getByText(/Tap to open Settings/)).toBeTruthy()- // The Searching GPS spinner overlay should NOT show simultaneously- expect(queryByText("Searching GPS...")).toBeNull()+ expect(mockSetStop).not.toHaveBeenCalled()+ expect(mockFitBounds).not.toHaveBeenCalled()})- it("shows Searching GPS overlay when tracking and location services are on but no fix yet", () => {- mockCoords = null- const { getByText, queryByText } = render(<DashboardMap {...baseProps} locationEnabled={true} />)+ it("draws the last known position as a stale dot with no ring while idle", async () => {+ const { getByTestId } = render(<DashboardMap {...baseProps} lastKnown={lastKnown} />)+ await act(zonesLoaded)- expect(getByText("Searching GPS...")).toBeTruthy()- expect(queryByText("Location Services Off")).toBeNull()+ const dot = getByTestId("user-dot")+ expect(dot.props.isPaused).toBe(true)+ expect(dot.props.coords).toEqual({ latitude: lastKnown.latitude, longitude: lastKnown.longitude, accuracy: 0 })})- it("shows location-off status bar when tracking with cached coords but location services off", () => {- // Coords are valid (cached from before location was disabled), so the full- // overlay doesn't fire - the slim status bar at the top of the map does.- const { getByText, queryByText } = render(- <DashboardMap {...baseProps} activeProfileName="Charging" locationEnabled={false} />- )+ it("draws the live fix with its ring while tracking and dims it inside a pause zone", async () => {+ mockCoords = { latitude: 48.2, longitude: 11.6, accuracy: 8 }++ const live = render(<DashboardMap {...baseProps} tracking lastKnown={lastKnown} />)+ await act(zonesLoaded)+ expect(live.getByTestId("user-dot").props.isPaused).toBe(false)+ expect(live.getByTestId("user-dot").props.coords).toBe(mockCoords)+ live.unmount()++ const paused = render(<DashboardMap {...baseProps} tracking activeZoneName="Home" />)+ await act(zonesLoaded)+ expect(paused.getByTestId("user-dot").props.isPaused).toBe(true)+ })++ it("shows no dot at all when nothing is known", async () => {+ const { queryByTestId } = render(<DashboardMap {...baseProps} lastKnown={null} />)+ await act(zonesLoaded)++ expect(queryByTestId("user-dot")).toBeNull()+ })++ it("forwards the camera padding and the control column's base line and end to the map view", async () => {+ render(<DashboardMap {...baseProps} />)+ await act(zonesLoaded)- expect(getByText("Location off - tap to enable")).toBeTruthy()- // Profile chip is hidden while location is off (location-off takes priority)- expect(queryByText("Charging")).toBeNull()- // Full-screen overlay should NOT show because we have valid coords- expect(queryByText("Location Services Off")).toBeNull()+ expect(mockMapProps.mock.calls[0][0].cameraPadding).toBe(padding)+ expect(mockMapProps.mock.calls[0][0].controlsBottom).toBe(controlsBottom)+ expect(mockMapProps.mock.calls[0][0].controlsEnd).toBe(controlsEnd)})- it("hides profile and pause-zone chips when location services are off", () => {- const { queryByText } = render(- <DashboardMap {...baseProps} activeZoneName="Home" activeProfileName="Charging" locationEnabled={false} />+ it("follows a live fix inside the padding, so the dot never slides under the dock", async () => {+ mockCoords = { latitude: 48.2, longitude: 11.6, accuracy: 8 }++ render(<DashboardMap {...baseProps} tracking />)+ await act(zonesLoaded)++ expect(mockEaseTo).toHaveBeenCalledWith(expect.objectContaining({ center: [11.6, 48.2], padding }))+ })++ it("puts the centre disc one slot above the base line at the column's end and shows it only after a pan", async () => {+ const { getByTestId } = render(<DashboardMap {...baseProps} lastKnown={lastKnown} />)+ await act(zonesLoaded)++ const position = StyleSheet.flatten(getByTestId("center-button").props.style)+ expect(position.bottom).toBe(controlsBottom + size.iconColumn + space.lg)+ expect(position.right).toBe(controlsEnd)+ expect(getByTestId("center-button").props.visible).toBe(false)++ act(() => mockMapProps.mock.calls[0][0].onRegionDidChange({ isUserInteraction: true }))+ expect(getByTestId("center-button").props.visible).toBe(true)++ act(() => getByTestId("center-button").props.onPress())+ expect(mockFlyTo).toHaveBeenCalledWith(+ expect.objectContaining({ center: [lastKnown.longitude, lastKnown.latitude], zoom: DEFAULT_MAP_ZOOM, padding }))+ expect(getByTestId("center-button").props.visible).toBe(false)+ })++ it("renders no Text node while searching or idle, so the tiles are all a user sees", async () => {+ const { Text } = require("react-native")++ const searching = render(<DashboardMap {...baseProps} tracking />)+ await act(zonesLoaded)+ expect(searching.UNSAFE_queryAllByType(Text)).toHaveLength(0)+ searching.unmount()++ const idle = render(<DashboardMap {...baseProps} lastKnown={null} />)+ await act(zonesLoaded)+ expect(idle.UNSAFE_queryAllByType(Text)).toHaveLength(0)+ })++ it("tells the screen when today's track has points, so the Route toggle can appear idle", async () => {+ mockTrack = [{ latitude: 48.1, longitude: 11.5 }]+ const onHasTrackChange = jest.fn()++ render(<DashboardMap {...baseProps} onHasTrackChange={onHasTrackChange} />)+ await act(zonesLoaded)++ expect(onHasTrackChange).toHaveBeenLastCalledWith(true)+ })++ it("reads today's points from the database while idle, so the Route toggle is offered before Start", async () => {+ mockUseTodayTrack.mockImplementation(jest.requireActual("../../../../hooks/useTodayTrack").useTodayTrack)+ mockGetLocationsByDateRange.mockResolvedValue([+ { latitude: 48.1, longitude: 11.5, timestamp: 1_700_000_000, accuracy: 10, speed: 0, altitude: 500 }+ ])+ const onHasTrackChange = jest.fn()++ render(<DashboardMap {...baseProps} tracking={false} onHasTrackChange={onHasTrackChange} />)- expect(queryByText(/Paused in Home/)).toBeNull()- expect(queryByText("Charging")).toBeNull()+ await waitFor(() => expect(onHasTrackChange).toHaveBeenLastCalledWith(true))+ expect(mockGetLocationsByDateRange).toHaveBeenCalledTimes(1)})})diff --git a/apps/mobile/src/components/features/dashboard/__tests__/DatabaseStatistics.test.tsx b/apps/mobile/src/components/features/dashboard/__tests__/DatabaseStatistics.test.tsxdeleted file mode 100644index 71c660dd..00000000--- a/apps/mobile/src/components/features/dashboard/__tests__/DatabaseStatistics.test.tsx+++ /dev/null@@ -1,129 +0,0 @@-import React from "react"-import { render } from "@testing-library/react-native"--let mockSettings = { isOfflineMode: false }--jest.mock("../../../../contexts/TrackingProvider", () => ({- useTracking: () => ({- settings: mockSettings- })-}))--jest.mock("../../../../hooks/useTheme", () => ({- useTheme: () => ({- colors: {- primary: "#0d9488",- primaryDark: "#115E59",- text: "#000",- textSecondary: "#6b7280",- textLight: "#9ca3af",- success: "#22c55e",- info: "#3b82f6",- card: "#fff",- border: "#e5e7eb"- }- })-}))--jest.mock("../../../index", () => {- const R = require("react")- const { View, Text } = require("react-native")- return {- SectionTitle: ({ children }: any) => R.createElement(Text, null, children),- Card: ({ children, variant }: any) => R.createElement(View, { testID: `card-${variant || "default"}` }, children)- }-})--jest.mock("../../../../utils/queueStatus", () => ({- getQueueColor: () => "#000"-}))--import { DatabaseStatistics } from "../DatabaseStatistics"--const baseStats = {- queued: 12,- sent: 100,- total: 500,- today: 8,- databaseSizeMB: 2.5-}--describe("DatabaseStatistics", () => {- beforeEach(() => {- mockSettings = { isOfflineMode: false }- })-- it("shows section title", () => {- const { getByText } = render(<DatabaseStatistics stats={baseStats} />)-- expect(getByText("DATABASE STATISTICS")).toBeTruthy()- })-- describe("online mode (default)", () => {- it("shows Queued and Sent cards", () => {- const { getByText } = render(<DatabaseStatistics stats={baseStats} />)-- expect(getByText("Queued")).toBeTruthy()- expect(getByText("12")).toBeTruthy()- expect(getByText("pending")).toBeTruthy()- expect(getByText("Sent")).toBeTruthy()- expect(getByText("100")).toBeTruthy()- expect(getByText("synced")).toBeTruthy()- })-- it("does not show Total locations card", () => {- const { queryByText } = render(<DatabaseStatistics stats={baseStats} />)-- expect(queryByText("locations")).toBeNull()- })-- it("shows Today and Storage cards", () => {- const { getByText } = render(<DatabaseStatistics stats={baseStats} />)-- expect(getByText("Today")).toBeTruthy()- expect(getByText("8")).toBeTruthy()- expect(getByText("tracked")).toBeTruthy()- expect(getByText("Storage")).toBeTruthy()- expect(getByText("2.5")).toBeTruthy()- expect(getByText("MB")).toBeTruthy()- })- })-- describe("offline mode", () => {- beforeEach(() => {- mockSettings = { isOfflineMode: true }- })-- it("shows Total locations card instead of Queued/Sent", () => {- const { getByText } = render(<DatabaseStatistics stats={baseStats} />)-- expect(getByText("Total")).toBeTruthy()- expect(getByText("500")).toBeTruthy()- expect(getByText("locations")).toBeTruthy()- })-- it("hides Queued and Sent cards", () => {- const { queryByText } = render(<DatabaseStatistics stats={baseStats} />)-- expect(queryByText("Queued")).toBeNull()- expect(queryByText("pending")).toBeNull()- expect(queryByText("Sent")).toBeNull()- expect(queryByText("synced")).toBeNull()- })-- it("still shows Today and Storage cards", () => {- const { getByText } = render(<DatabaseStatistics stats={baseStats} />)-- expect(getByText("Today")).toBeTruthy()- expect(getByText("Storage")).toBeTruthy()- })- })-- it("formats large numbers with locale string", () => {- mockSettings = { isOfflineMode: true }- const largeStats = { ...baseStats, total: 1234567 }- const { getByText } = render(<DatabaseStatistics stats={largeStats} />)-- expect(getByText((1234567).toLocaleString())).toBeTruthy()- })-})diff --git a/apps/mobile/src/components/features/dashboard/__tests__/WelcomeCard.test.tsx b/apps/mobile/src/components/features/dashboard/__tests__/WelcomeCard.test.tsxindex de6a291f..8b8700fd 100644--- a/apps/mobile/src/components/features/dashboard/__tests__/WelcomeCard.test.tsx+++ b/apps/mobile/src/components/features/dashboard/__tests__/WelcomeCard.test.tsx@@ -1,6 +1,8 @@import React from "react"-import { render, fireEvent } from "@testing-library/react-native"+import { StyleSheet, View as RNView } from "react-native"+import { render, fireEvent, within } from "@testing-library/react-native"import { DEFAULT_SETTINGS } from "../../../../types/global"+import { size } from "../../../../constants"let mockSettings = { isOfflineMode: false }@@ -10,11 +12,17 @@ jest.mock("../../../../contexts/TrackingProvider", () => ({})}))+// Button reads the theme itself, unlike WelcomeCard, which takes colors as a prop.+jest.mock("../../../../hooks/useTheme", () => ({+ useTheme: () => ({ colors: require("@colota/shared").lightColors })+}))+jest.mock("../../../ui/Card", () => {const R = require("react")const { View } = require("react-native")return {- Card: ({ children }: any) => R.createElement(View, null, children)+ Card: ({ children, variant, style }: any) =>+ R.createElement(View, { testID: "welcome-card", variant, style }, children)}})@@ -36,6 +44,7 @@ const mockColors = {textSecondary: "#6b7280",textLight: "#9ca3af",success: "#22c55e",+ link: "#0d9488",border: "#e5e7eb"} as any@@ -47,7 +56,7 @@ const defaultProps = {onStartTracking: jest.fn(),onNavigateToConnection: jest.fn(),onNavigateToTrackingSync: jest.fn(),- onNavigateToApiConfig: jest.fn()+ onNavigateToRequestFormat: jest.fn()}describe("WelcomeCard", () => {@@ -56,6 +65,30 @@ describe("WelcomeCard", () => {mockSettings = { isOfflineMode: false }})+ it("sits over map tiles as an elevated surface with no border of its own", () => {+ const { getByTestId } = render(<WelcomeCard {...defaultProps} />)++ const card = getByTestId("welcome-card")+ expect(card.props.variant).toBe("elevated")+ expect(StyleSheet.flatten(card.props.style)?.borderColor).toBeUndefined()+ })++ it("colours its links with the link token, because primaryDark fails 4.5 on the elevated surface in dark mode", () => {+ const { getByText } = render(<WelcomeCard {...defaultProps} />)++ expect(StyleSheet.flatten(getByText("Request format").props.style).color).toBe(mockColors.link)+ expect(StyleSheet.flatten(getByText("Tracking presets").props.style).color).toBe(mockColors.link)+ })++ it("gives every checklist row and text link the 48 touch height, since a bare text line is too short to hit", () => {+ const { getByRole } = render(<WelcomeCard {...defaultProps} />)++ const row = getByRole("button", { name: "2. Configure your server endpoint" })+ expect(StyleSheet.flatten(within(row).UNSAFE_getAllByType(RNView)[0].props.style).minHeight).toBe(size.touch)+ expect(StyleSheet.flatten(getByRole("button", { name: "Request format" }).props.style).minHeight).toBe(size.touch)+ expect(StyleSheet.flatten(getByRole("button", { name: "Tracking presets" }).props.style).minHeight).toBe(size.touch)+ })+it("renders welcome title and subtitle", () => {const { getByText } = render(<WelcomeCard {...defaultProps} />)@@ -76,10 +109,10 @@ describe("WelcomeCard", () => {expect(getByText("2. Configure your server endpoint")).toBeTruthy()})- it("shows API field mapping link", () => {+ it("shows the request format link", () => {const { getByText } = render(<WelcomeCard {...defaultProps} />)- expect(getByText("API field mapping")).toBeTruthy()+ expect(getByText("Request format")).toBeTruthy()})it("shows Tracking presets link", () => {@@ -100,10 +133,10 @@ describe("WelcomeCard", () => {expect(queryByText("2. Configure your server endpoint")).toBeNull()})- it("hides API field mapping link", () => {+ it("hides the request format link", () => {const { queryByText } = render(<WelcomeCard {...defaultProps} />)- expect(queryByText("API field mapping")).toBeNull()+ expect(queryByText("Request format")).toBeNull()})it("still shows Tracking presets link", () => {@@ -143,12 +176,12 @@ describe("WelcomeCard", () => {expect(defaultProps.onNavigateToConnection).toHaveBeenCalledTimes(1)})- it("calls onNavigateToApiConfig when API field mapping is pressed", () => {+ it("calls onNavigateToRequestFormat when the request format link is pressed", () => {const { getByText } = render(<WelcomeCard {...defaultProps} />)- fireEvent.press(getByText("API field mapping"))+ fireEvent.press(getByText("Request format"))- expect(defaultProps.onNavigateToApiConfig).toHaveBeenCalledTimes(1)+ expect(defaultProps.onNavigateToRequestFormat).toHaveBeenCalledTimes(1)})it("marks Start tracking as completed when tracking is active", () => {diff --git a/apps/mobile/src/components/index.ts b/apps/mobile/src/components/index.tsindex 432934bb..f5b77f80 100644--- a/apps/mobile/src/components/index.ts+++ b/apps/mobile/src/components/index.ts@@ -71,6 +71,6 @@ export { StatRow } from "./ui/StatRow"export { Footer } from "./ui/Footer"export { FormatOption } from "./ui/FormatOption"export { FormatSelector } from "./ui/FormatSelector"-export { CoordinateDisplay } from "./features/dashboard/CoordinateDisplay"-export { DatabaseStatistics } from "./features/dashboard/DatabaseStatistics"export { StatsCard } from "./features/settings/StatsCard"+export { DashboardBanner } from "./features/dashboard/DashboardBanner"+export { DashboardDock } from "./features/dashboard/DashboardDock"diff --git a/apps/mobile/src/screens/DashboardScreen.tsx b/apps/mobile/src/screens/DashboardScreen.tsxindex 15b5dec9..fdaa6ba5 100644--- a/apps/mobile/src/screens/DashboardScreen.tsx+++ b/apps/mobile/src/screens/DashboardScreen.tsx@@ -3,49 +3,60 @@* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.*/-import React, { useEffect, useState, useCallback, useRef } from "react"-import { StyleSheet, View, ScrollView, DeviceEventEmitter, Animated, AppState } from "react-native"-import { ScreenProps, DatabaseStats } from "../types/global"+import React, { useEffect, useLayoutEffect, useState, useCallback, useMemo } from "react"+import { StyleSheet, View, DeviceEventEmitter, AppState, StatusBar, useWindowDimensions } from "react-native"+import { useSafeAreaInsets } from "react-native-safe-area-context"+import { useFocusEffect, useIsFocused } from "@react-navigation/native"+import { ScreenProps } from "../types/global"import { useTheme } from "../hooks/useTheme"+import { useActiveProfile } from "../hooks/useActiveProfile"import NativeLocationService from "../services/NativeLocationService"-import { useTracking } from "../contexts/TrackingProvider"-import { useFocusEffect } from "@react-navigation/native"+import { checkPermissions, ensurePermissions, PermissionStatus } from "../services/LocationServicePermission"+import { useTracking, useCoords } from "../contexts/TrackingProvider"import { showConfirm } from "../services/modalService"-import {- Button,- ConnectionStatus,- DashboardMap,- CoordinateDisplay,- Container,- DatabaseStatistics,- WelcomeCard-} from "../components"-import { STATS_REFRESH_IDLE, MIN_STATS_INTERVAL_MS } from "../constants"+import { Button, Container, DashboardBanner, DashboardDock, DashboardMap } from "../components"+import type { LastKnownLocation } from "../components/features/dashboard/DashboardMap"+import { TrackToggleButton } from "../components/features/map/TrackToggleButton"+import { intervalText, pickBannerCondition } from "../utils/dashboardState"+import { size, space } from "../constants"import { Square, Play } from "lucide-react-native"import { logger } from "../utils/logger"export function DashboardScreen({ navigation }: ScreenProps) {- const { settings, tracking, startTracking, stopTracking, setSettings, activeProfileName, settingsHydrated } =- useTracking()- const { colors } = useTheme()+ const {+ settings,+ tracking,+ startTracking,+ stopTracking,+ setSettings,+ activeProfileName,+ activeProfileId,+ settingsHydrated+ } = useTracking()+ const coords = useCoords()+ const { colors, isDark } = useTheme()+ const insets = useSafeAreaInsets()+ const { height: windowHeight } = useWindowDimensions()+ const isFocused = useIsFocused()- const [stats, setStats] = useState<DatabaseStats>({- queued: 0,- sent: 0,- total: 0,- today: 0,- databaseSizeMB: 0- })+ // Hiding the header is safe on a tab root: the tab bar stays as the way out.+ useLayoutEffect(() => {+ navigation.setOptions({ headerShown: false })+ }, [navigation])- const prevStats = useRef(stats)const [currentPauseZone, setCurrentPauseZone] = useState<string | null>(null)const [pauseReason, setPauseReason] = useState<string | null>(null)- const [scrollEnabled, setScrollEnabled] = useState(true)const [isBatteryCritical, setIsBatteryCritical] = useState(false)const [locationEnabled, setLocationEnabled] = useState(true)-- // Animation for button- const buttonScale = useRef(new Animated.Value(1)).current+ const [permissions, setPermissions] = useState<PermissionStatus | null>(null)+ const [lastKnown, setLastKnown] = useState<LastKnownLocation | null | undefined>(undefined)+ const [stoppedByBattery, setStoppedByBattery] = useState(false)+ const [showTrack, setShowTrack] = useState<boolean | null>(null)+ const [hasTrack, setHasTrack] = useState(false)+ const activeProfile = useActiveProfile(activeProfileId)+ const [stackHeight, setStackHeight] = useState(0)+ const [bannerHeight, setBannerHeight] = useState(0)+ const [recentreSignal, setRecentreSignal] = useState(0)const handleStart = async () => {const locationOn = await NativeLocationService.isLocationEnabled()@@ -53,67 +64,22 @@ export function DashboardScreen({ navigation }: ScreenProps) {const openSettings = await showConfirm({title: "Please enable Location Services",message: "Location Services are disabled. Tracking will not work until they are enabled in Settings.",- confirmText: "Location Settings",- cancelText: "Start Anyway"+ confirmText: "Location settings",+ cancelText: "Start anyway"})if (openSettings) {await NativeLocationService.openLocationSettings()return}}-- // Bounce animation- Animated.sequence([- Animated.spring(buttonScale, {- toValue: 0.92,- useNativeDriver: true- }),- Animated.spring(buttonScale, {- toValue: 1,- useNativeDriver: true,- friction: 3- })- ]).start()-+ setRecentreSignal((n) => n + 1)await startTracking()- setTimeout(updateStats, 500)}const handleStop = async () => {- Animated.sequence([- Animated.spring(buttonScale, {- toValue: 0.92,- useNativeDriver: true- }),- Animated.spring(buttonScale, {- toValue: 1,- useNativeDriver: true,- friction: 3- })- ]).start()-await stopTracking()- updateStats()}- const updateStats = useCallback(async () => {- try {- const nativeStats = await NativeLocationService.getStats()-- const hasChanged =- nativeStats.queued !== prevStats.current.queued ||- nativeStats.sent !== prevStats.current.sent ||- nativeStats.today !== prevStats.current.today-- if (hasChanged) {- setStats(nativeStats)- prevStats.current = nativeStats- }- } catch (err) {- logger.error("[Dashboard] Failed to update stats:", err)- }- }, [])-const updatePauseZone = useCallback(async () => {try {const result = await NativeLocationService.checkCurrentPauseZone()@@ -126,26 +92,49 @@ export function DashboardScreen({ navigation }: ScreenProps) {}}, [])+ const refreshPermissions = useCallback(() => {+ checkPermissions()+ .then(setPermissions)+ .catch((err) => logger.error("[Dashboard] Failed to check permissions:", err))+ }, [])++ useEffect(() => {+ NativeLocationService.getSetting("showTrack")+ .then((val) => setShowTrack(val === "true"))+ .catch((err) => {+ logger.error("[Dashboard] Failed to load showTrack setting:", err)+ setShowTrack(false)+ })+ }, [])+useFocusEffect(useCallback(() => {- setScrollEnabled(true)- updateStats()- if (tracking) updatePauseZone()- if (!tracking) {- NativeLocationService.isBatteryCritical().then(setIsBatteryCritical)- } else {+ if (tracking) {+ updatePauseZone()setIsBatteryCritical(false)+ } else {+ NativeLocationService.isBatteryCritical().then(setIsBatteryCritical)+ NativeLocationService.getSetting("stopped_by_battery")+ .then((val) => setStoppedByBattery(val === "true"))+ .catch((err) => logger.error("[Dashboard] Failed to read stopped_by_battery:", err))}+ NativeLocationService.getMostRecentLocation()+ .then((latest) =>+ setLastKnown(+ latest+ ? {+ latitude: latest.latitude,+ longitude: latest.longitude,+ accuracy: latest.accuracy ?? 0,+ timestamp: latest.timestamp+ }+ : null+ )+ )+ .catch((err) => logger.error("[Dashboard] Failed to read the last known location:", err))NativeLocationService.isLocationEnabled().then(setLocationEnabled)-- const interval = tracking ? Math.max(settings.interval * 1000, MIN_STATS_INTERVAL_MS) : STATS_REFRESH_IDLE-- const statsTimer = setInterval(updateStats, interval)-- return () => {- clearInterval(statsTimer)- }- }, [tracking, updateStats, updatePauseZone, settings.interval])+ refreshPermissions()+ }, [tracking, updatePauseZone, refreshPermissions]))useEffect(() => {@@ -172,13 +161,14 @@ export function DashboardScreen({ navigation }: ScreenProps) {const appStateSub = AppState.addEventListener("change", (state) => {if (state === "active") {NativeLocationService.isLocationEnabled().then(setLocationEnabled)+ refreshPermissions()}})return () => {listener.remove()appStateSub.remove()}- }, [])+ }, [refreshPermissions])useEffect(() => {const pauseZoneListener = DeviceEventEmitter.addListener(@@ -197,121 +187,144 @@ export function DashboardScreen({ navigation }: ScreenProps) {return () => pauseZoneListener.remove()}, [])- return (- <Container>- <ScrollView- contentContainerStyle={styles.scrollContent}- bounces={false}- showsVerticalScrollIndicator={false}- scrollEnabled={scrollEnabled}- >- {/* Map Section */}- <View style={styles.mapSection}>- <View- style={styles.mapWrapper}- onTouchStart={() => setScrollEnabled(false)}- onTouchEnd={() => setScrollEnabled(true)}- >- <DashboardMap- tracking={tracking}- activeZoneName={currentPauseZone}- pauseReason={pauseReason}- activeProfileName={activeProfileName}- isBatteryCritical={isBatteryCritical}- locationEnabled={locationEnabled}- />- </View>+ const bannerCondition = pickBannerCondition({ permissions, locationEnabled, isBatteryCritical, tracking })- {/* Tracking Control Button */}- <Animated.View- style={[styles.controlButtonContainer, { transform: [{ scale: buttonScale }] }]}- pointerEvents="box-none"- >- <Button- style={styles.controlButton}- variant={tracking ? "danger" : "primary"}- icon={tracking ? Square : Play}- onPress={tracking ? handleStop : handleStart}- activeOpacity={0.9}- disabled={!tracking && (isBatteryCritical || !settingsHydrated)}- title={tracking ? "Stop Tracking" : "Start Tracking"}- />- </Animated.View>- </View>+ const handleBannerAction = useCallback(() => {+ if (bannerCondition === "locationOff") {+ NativeLocationService.openLocationSettings()+ return+ }+ ensurePermissions()+ .then(refreshPermissions)+ .catch((err) => logger.error("[Dashboard] Failed to request permissions:", err))+ }, [bannerCondition, refreshPermissions])- {/* Content Section */}- <View style={[styles.content, { backgroundColor: colors.background }]}>- {/* Welcome Card (first run). Unhydrated settings read as a first run and cannot be dismissed. */}- {settingsHydrated && !settings.hasCompletedSetup && (- <WelcomeCard- settings={settings}- tracking={tracking}- colors={colors}- onDismiss={() =>- setSettings({ ...settings, hasCompletedSetup: true }).catch((err) =>- logger.error("[DashboardScreen] Failed to dismiss welcome card:", err)- )- }- onStartTracking={handleStart}- onNavigateToConnection={() => navigation.navigate("Connection")}- onNavigateToTrackingSync={() => navigation.navigate("Tracking & Sync")}- onNavigateToApiConfig={() => navigation.navigate("Request Format")}- />- )}+ const toggleTrack = useCallback(() => {+ const next = !showTrack+ setShowTrack(next)+ NativeLocationService.saveSetting("showTrack", String(next)).catch((err) =>+ logger.error("[Dashboard] Failed to save showTrack setting:", err)+ )+ }, [showTrack])- {/* Coordinates */}- {tracking && (- <View style={styles.metricsSection}>- <CoordinateDisplay />- </View>- )}+ const bannerInset = bannerCondition && bannerHeight ? bannerHeight + space.md : 0+ const edgeStart = space.lg + insets.left+ const edgeEnd = space.lg + insets.right+ const cameraPadding = useMemo(+ () => ({+ top: insets.top + bannerInset + space.lg,+ bottom: stackHeight + space.lg + space.lg,+ left: edgeStart,+ right: edgeEnd + size.iconColumn + space.lg+ }),+ [insets.top, bannerInset, stackHeight, edgeStart, edgeEnd]+ )+ const controlsBottom = space.lg + stackHeight + space.sm- {/* Stats Cards */}- <DatabaseStatistics stats={stats} />+ const hasFix = tracking && coords !== null && coords.latitude !== 0 && coords.longitude !== 0+ const dockCoords = hasFix ? { accuracy: coords.accuracy ?? 0, timestamp: coords.timestamp ?? 0 } : null+ const intervalRow = activeProfile+ ? intervalText(activeProfile.interval, activeProfile.syncInterval)+ : intervalText(settings.interval, settings.syncInterval)- {/* Server Connection */}- {!settings.isOfflineMode && <ConnectionStatus endpoint={settings.endpoint} navigation={navigation} />}+ return (+ <Container>+ {isFocused && <StatusBar barStyle={isDark ? "light-content" : "dark-content"} />}++ <DashboardMap+ tracking={tracking}+ activeZoneName={currentPauseZone}+ lastKnown={lastKnown}+ cameraPadding={cameraPadding}+ controlsBottom={controlsBottom}+ controlsEnd={edgeEnd}+ showTrack={!!showTrack}+ onHasTrackChange={setHasTrack}+ recentreSignal={recentreSignal}+ />++ {bannerCondition && (+ <DashboardBanner+ condition={bannerCondition}+ onAction={handleBannerAction}+ top={insets.top + space.md}+ left={edgeStart}+ right={edgeEnd}+ onLayout={(e) => setBannerHeight(e.nativeEvent.layout.height)}+ />+ )}++ <View+ style={[styles.stack, { left: edgeStart, right: edgeEnd }]}+ pointerEvents="box-none"+ onLayout={(e) => setStackHeight(e.nativeEvent.layout.height)}+ testID="dashboard-stack"+ >+ <View style={styles.actionRow} pointerEvents="box-none">+ <View style={styles.routeSlot} testID="route-slot">+ {showTrack !== null && (tracking || hasTrack) && (+ <TrackToggleButton anchored={false} active={showTrack} onPress={toggleTrack} />+ )}+ </View>+ <Button+ shape="pill"+ floating+ variant={tracking ? "danger" : "primary"}+ icon={tracking ? Square : Play}+ onPress={tracking ? handleStop : handleStart}+ loading={!settingsHydrated}+ disabled={!tracking && isBatteryCritical}+ title={tracking ? "Stop tracking" : "Start tracking"}+ /></View>- </ScrollView>++ <DashboardDock+ tracking={tracking}+ hasFix={hasFix}+ locationEnabled={locationEnabled}+ activeZoneName={currentPauseZone}+ pauseReason={pauseReason}+ activeProfileName={activeProfileName}+ coords={dockCoords}+ lastKnown={lastKnown ?? null}+ stoppedByBattery={stoppedByBattery}+ intervalText={intervalRow}+ endpoint={settings.endpoint}+ isOfflineMode={settings.isOfflineMode}+ navigation={navigation}+ maxHeight={windowHeight / 2}+ firstRun={settingsHydrated && !settings.hasCompletedSetup}+ settings={settings}+ colors={colors}+ onDismiss={() =>+ setSettings({ ...settings, hasCompletedSetup: true }).catch((err) =>+ logger.error("[DashboardScreen] Failed to dismiss welcome card:", err)+ )+ }+ onStartTracking={handleStart}+ onNavigateToConnection={() => navigation.navigate("Connection")}+ onNavigateToTrackingSync={() => navigation.navigate("Tracking & Sync")}+ onNavigateToRequestFormat={() => navigation.navigate("Request Format")}+ />+ </View></Container>)}const styles = StyleSheet.create({- scrollContent: {- flexGrow: 1- },- mapSection: {- height: 480,- position: "relative"- },- mapWrapper: {+ stack: {position: "absolute",- top: 0,- left: 0,- right: 0,- bottom: 0- },- controlButtonContainer: {- position: "absolute",- bottom: 24,- left: 0,- right: 0,- alignItems: "center"- },- controlButton: {- borderRadius: 28,- elevation: 4,- minWidth: 200,- shadowColor: "#000"+ bottom: space.lg,+ flexDirection: "column",+ gap: space.sm},- content: {- flex: 1,- paddingTop: 20,- paddingHorizontal: 16,- paddingBottom: 8+ actionRow: {+ flexDirection: "row",+ alignItems: "flex-end",+ justifyContent: "space-between"},- metricsSection: {- marginBottom: 20+ routeSlot: {+ width: size.iconColumn,+ marginBottom: space.sm}})diff --git a/apps/mobile/src/screens/__tests__/DashboardScreen.test.tsx b/apps/mobile/src/screens/__tests__/DashboardScreen.test.tsxindex 1f33ca9c..f1d5441b 100644--- a/apps/mobile/src/screens/__tests__/DashboardScreen.test.tsx+++ b/apps/mobile/src/screens/__tests__/DashboardScreen.test.tsx@@ -1,20 +1,39 @@import React from "react"-import { render, fireEvent, waitFor } from "@testing-library/react-native"+import { render, fireEvent, waitFor, act } from "@testing-library/react-native"+import { DeviceEventEmitter, StatusBar, StyleSheet } from "react-native"import { DEFAULT_SETTINGS, Settings } from "../../types/global"--// --- Mocks ---+import { size, space } from "../../constants"const mockStartTracking = jest.fn().mockResolvedValue(undefined)const mockStopTracking = jest.fn().mockResolvedValue(undefined)const mockSetSettings = jest.fn().mockResolvedValue(undefined)-const mockIsLocationEnabled = jest.fn().mockResolvedValue(true)-const mockOpenLocationSettings = jest.fn().mockResolvedValue(true)-const mockShowConfirm = jest.fn().mockResolvedValue(false)+const mockIsLocationEnabled = jest.fn()+const mockIsBatteryCritical = jest.fn()+const mockOpenLocationSettings = jest.fn()+const mockGetMostRecentLocation = jest.fn()+const mockGetSetting = jest.fn()+const mockSaveSetting = jest.fn()+const mockGetStats = jest.fn()+const mockGetProfiles = jest.fn()+const mockCheckPermissions = jest.fn()+const mockEnsurePermissions = jest.fn()+const mockShowConfirm = jest.fn()let mockSettings: Settings = { ...DEFAULT_SETTINGS }let mockTracking = falselet mockSettingsHydrated = true-let mockCoords: { latitude: number; longitude: number } | null = null+let mockCoords: { latitude: number; longitude: number; accuracy: number; timestamp: number } | null = null+let mockActiveProfileName: string | null = null+let mockActiveProfileId: number | null = null+let mockInsets = { top: 24, bottom: 0, left: 0, right: 0 }++const grantedPermissions = {+ location: true,+ background: true,+ notifications: true,+ batteryOptimized: true,+ localNetwork: true+}jest.mock("../../contexts/TrackingProvider", () => ({useTracking: () => ({@@ -23,85 +42,102 @@ jest.mock("../../contexts/TrackingProvider", () => ({startTracking: mockStartTracking,stopTracking: mockStopTracking,setSettings: mockSetSettings,- activeProfileName: "Default",+ activeProfileName: mockActiveProfileName,+ activeProfileId: mockActiveProfileId,settingsHydrated: mockSettingsHydrated}),useCoords: () => mockCoords}))jest.mock("../../hooks/useTheme", () => ({- useTheme: () => ({- colors: {- primary: "#0d9488",- primaryDark: "#115E59",- border: "#e5e7eb",- text: "#000",- textSecondary: "#6b7280",- textLight: "#9ca3af",- background: "#fff",- info: "#3b82f6",- success: "#22c55e",- error: "#ef4444",- card: "#fff",- backgroundElevated: "#f9fafb",- placeholder: "#9ca3af",- textOnPrimary: "#fff"- }- })+ useTheme: () => ({ colors: require("@colota/shared").lightColors, isDark: false })+}))++jest.mock("react-native-safe-area-context", () => ({+ useSafeAreaInsets: () => mockInsets}))jest.mock("@react-navigation/native", () => ({useFocusEffect: (cb: () => void | (() => void)) => {const { useEffect } = require("react")- // eslint-disable-next-line react-hooks/exhaustive-deps- useEffect(() => cb(), [])- }+ useEffect(() => cb(), [cb])+ },+ useIsFocused: () => true}))jest.mock("../../services/NativeLocationService", () => ({__esModule: true,default: {- getStats: jest.fn().mockResolvedValue({- queued: 0,- sent: 5,- total: 10,- today: 3,- databaseSizeMB: 0.5- }),+ getStats: (...args: unknown[]) => mockGetStats(...args),checkCurrentPauseZone: jest.fn().mockResolvedValue(null),- isBatteryCritical: jest.fn().mockResolvedValue(false),+ isBatteryCritical: (...args: unknown[]) => mockIsBatteryCritical(...args),isLocationEnabled: (...args: unknown[]) => mockIsLocationEnabled(...args),- openLocationSettings: (...args: unknown[]) => mockOpenLocationSettings(...args)+ openLocationSettings: (...args: unknown[]) => mockOpenLocationSettings(...args),+ getMostRecentLocation: (...args: unknown[]) => mockGetMostRecentLocation(...args),+ getSetting: (...args: unknown[]) => mockGetSetting(...args),+ saveSetting: (...args: unknown[]) => mockSaveSetting(...args),+ getProfiles: (...args: unknown[]) => mockGetProfiles(...args)}}))+jest.mock("../../services/LocationServicePermission", () => ({+ checkPermissions: (...args: unknown[]) => mockCheckPermissions(...args),+ ensurePermissions: (...args: unknown[]) => mockEnsurePermissions(...args)+}))+jest.mock("../../services/modalService", () => ({showConfirm: (...args: unknown[]) => mockShowConfirm(...args)}))+jest.mock("../../components/features/map/TrackToggleButton", () => {+ const R = require("react")+ const { Pressable } = require("react-native")+ return {+ TrackToggleButton: (props: any) =>+ R.createElement(Pressable, {+ testID: "track-toggle",+ accessibilityRole: "button",+ onPress: props.onPress,+ active: props.active,+ anchored: props.anchored+ })+ }+})+jest.mock("../../components", () => {const R = require("react")const { View, Text, Pressable } = require("react-native")return {- DashboardMap: () => R.createElement(View, { testID: "DashboardMap" }),- CoordinateDisplay: () => R.createElement(View, { testID: "CoordinateDisplay" }),- DatabaseStatistics: () => R.createElement(View, { testID: "DatabaseStatistics" }),- ConnectionStatus: () => R.createElement(View, { testID: "ConnectionStatus" }),- QuickAccess: () => R.createElement(View, { testID: "QuickAccess" }),- WelcomeCard: () => R.createElement(View, { testID: "WelcomeCard" }),+ DashboardMap: (props: any) => R.createElement(View, { testID: "DashboardMap", ...props }),+ DashboardBanner: (props: any) =>+ R.createElement(+ View,+ { testID: "DashboardBanner", ...props },+ R.createElement(Pressable, { testID: "banner-action", accessibilityRole: "button", onPress: props.onAction })+ ),+ DashboardDock: (props: any) => R.createElement(View, { testID: "DashboardDock", ...props }),Container: ({ children }: any) => R.createElement(View, null, children),- Button: ({ title, onPress, disabled }: any) =>+ Button: ({ title, onPress, disabled, variant, loading, floating, shape, icon }: any) =>R.createElement(- Pressable,- { onPress, disabled, accessibilityState: { disabled: !!disabled } },- R.createElement(Text, null, title)+ View,+ { testID: "pill", variant, loading, floating, shape, icon },+ R.createElement(+ Pressable,+ { onPress, disabled, accessibilityRole: "button", accessibilityState: { disabled: !!disabled } },+ R.createElement(Text, null, title)+ ))}})import { DashboardScreen } from "../DashboardScreen"-const mockNavigation = { navigate: jest.fn() } as any+const mockSetOptions = jest.fn()+const mockNavigation = { navigate: jest.fn(), setOptions: mockSetOptions } as any++const renderScreen = () => render(<DashboardScreen navigation={mockNavigation} />)++const settle = () => waitFor(() => expect(mockCheckPermissions).toHaveBeenCalled())describe("DashboardScreen", () => {beforeEach(() => {@@ -110,165 +146,500 @@ describe("DashboardScreen", () => {mockTracking = falsemockSettingsHydrated = truemockCoords = null+ mockActiveProfileName = null+ mockActiveProfileId = null+ mockInsets = { top: 24, bottom: 0, left: 0, right: 0 }mockIsLocationEnabled.mockResolvedValue(true)+ mockIsBatteryCritical.mockResolvedValue(false)mockOpenLocationSettings.mockResolvedValue(true)+ mockGetMostRecentLocation.mockResolvedValue(null)+ mockGetSetting.mockResolvedValue("false")+ mockSaveSetting.mockResolvedValue(undefined)+ mockGetStats.mockResolvedValue({ queued: 0, sent: 0, total: 0, today: 0, databaseSizeMB: 0 })+ mockGetProfiles.mockResolvedValue([])+ mockCheckPermissions.mockResolvedValue(grantedPermissions)+ mockEnsurePermissions.mockResolvedValue(true)mockShowConfirm.mockResolvedValue(false)})- it("shows Start Tracking button when not tracking", () => {- mockTracking = false+ it("hides the header, because the map is the screen's own chrome and a tab root cannot be stranded", async () => {+ renderScreen()+ await settle()- const { getByText } = render(<DashboardScreen navigation={mockNavigation} />)+ expect(mockSetOptions).toHaveBeenCalledWith({ headerShown: false })+ })++ it("offers Start as the teal pill with the Play glyph while idle", async () => {+ const { getByText, getByTestId } = renderScreen()+ await settle()- expect(getByText("Start Tracking")).toBeTruthy()+ expect(getByText("Start tracking")).toBeTruthy()+ expect(getByTestId("pill").props.variant).toBe("primary")+ expect(getByTestId("pill").props.shape).toBe("pill")+ expect(getByTestId("pill").props.floating).toBe(true)+ expect(getByTestId("pill").props.icon.displayName).toBe("Play")})- it("shows Stop Tracking button when tracking", () => {+ it("turns the pill to the danger hue with the Square glyph while tracking, so a mis-tap reads as a stop", async () => {mockTracking = true- const { getByText } = render(<DashboardScreen navigation={mockNavigation} />)+ const { getByText, getByTestId } = renderScreen()+ await settle()- expect(getByText("Stop Tracking")).toBeTruthy()+ expect(getByText("Stop tracking")).toBeTruthy()+ expect(getByTestId("pill").props.variant).toBe("danger")+ expect(getByTestId("pill").props.icon.displayName).toBe("Square")})- it("shows CoordinateDisplay when tracking with valid coords", () => {- mockTracking = true- mockCoords = { latitude: 52.52, longitude: 13.405 }+ it("shows Start as loading rather than disabled until the settings have been read", async () => {+ // start() sends every key, and fromReadableMap prefers a present empty endpoint over the stored one.+ mockSettingsHydrated = false- const { getByTestId } = render(<DashboardScreen navigation={mockNavigation} />)+ const { getByText, getByTestId } = renderScreen()+ await settle()- expect(getByTestId("CoordinateDisplay")).toBeTruthy()+ expect(getByTestId("pill").props.loading).toBe(true)+ expect(getByText("Start tracking")).not.toBeDisabled()})- it("hides CoordinateDisplay when not tracking", () => {- mockTracking = false- mockCoords = { latitude: 52.52, longitude: 13.405 }+ it("disables Start only for a critical battery, with the banner as its reason", async () => {+ mockIsBatteryCritical.mockResolvedValue(true)- const { queryByTestId } = render(<DashboardScreen navigation={mockNavigation} />)+ const { getByText, getByTestId } = renderScreen()+ await waitFor(() => expect(getByText("Start tracking")).toBeDisabled())- expect(queryByTestId("CoordinateDisplay")).toBeNull()+ expect(getByTestId("DashboardBanner").props.condition).toBe("battery")})- it("disables Start Tracking while settings have not been read", () => {- // start() sends every key, and fromReadableMap prefers a present empty endpoint over the stored one.- mockSettingsHydrated = false+ it("keeps Stop enabled while tracking even if the battery reads critical, because the service is already running", async () => {+ mockTracking = true+ mockIsBatteryCritical.mockResolvedValue(true)++ const { getByText, queryByTestId } = renderScreen()+ await settle()- const { getByText } = render(<DashboardScreen navigation={mockNavigation} />)+ await act(async () => {+ DeviceEventEmitter.emit("onChargingStateChanged", {})+ })+ await waitFor(() => expect(mockIsBatteryCritical).toHaveBeenCalled())- expect(getByText("Start Tracking")).toBeDisabled()+ expect(getByText("Stop tracking")).not.toBeDisabled()+ expect(queryByTestId("DashboardBanner")).toBeNull()})- it("hides WelcomeCard while settings have not been read", () => {- // Unhydrated settings read as a first run, and dismissing the card would save the defaults.+ it("hands the dock the first-run flag only once settings are read, since unhydrated settings look like a first run", async () => {mockSettings = { ...DEFAULT_SETTINGS, hasCompletedSetup: false }mockSettingsHydrated = false- const { queryByTestId } = render(<DashboardScreen navigation={mockNavigation} />)+ const { getByTestId } = renderScreen()+ await settle()- expect(queryByTestId("WelcomeCard")).toBeNull()+ expect(getByTestId("DashboardDock").props.firstRun).toBe(false)})- it("shows WelcomeCard when hasCompletedSetup is false", () => {+ it("marks the dock as first run while setup is incomplete and drops it once it is done", async () => {mockSettings = { ...DEFAULT_SETTINGS, hasCompletedSetup: false }+ const fresh = renderScreen()+ await settle()+ expect(fresh.getByTestId("DashboardDock").props.firstRun).toBe(true)+ fresh.unmount()- const { getByTestId } = render(<DashboardScreen navigation={mockNavigation} />)-- expect(getByTestId("WelcomeCard")).toBeTruthy()- })-- it("hides WelcomeCard when hasCompletedSetup is true", () => {mockSettings = { ...DEFAULT_SETTINGS, hasCompletedSetup: true }-- const { queryByTestId } = render(<DashboardScreen navigation={mockNavigation} />)-- expect(queryByTestId("WelcomeCard")).toBeNull()+ const done = renderScreen()+ await settle()+ expect(done.getByTestId("DashboardDock").props.firstRun).toBe(false)})- it("renders DatabaseStatistics component", () => {- const { getByTestId } = render(<DashboardScreen navigation={mockNavigation} />)-- expect(getByTestId("DatabaseStatistics")).toBeTruthy()- })+ it("tells the dock to drop the server row in offline mode", async () => {+ mockSettings = { ...DEFAULT_SETTINGS, isOfflineMode: true }- it("renders ConnectionStatus component", () => {- const { getByTestId } = render(<DashboardScreen navigation={mockNavigation} />)+ const { getByTestId } = renderScreen()+ await settle()- expect(getByTestId("ConnectionStatus")).toBeTruthy()+ expect(getByTestId("DashboardDock").props.isOfflineMode).toBe(true)+ expect(getByTestId("DashboardDock").props.endpoint).toBe(DEFAULT_SETTINGS.endpoint)})- it("hides ConnectionStatus when offline mode is enabled", () => {- mockSettings = { ...DEFAULT_SETTINGS, isOfflineMode: true }-- const { queryByTestId } = render(<DashboardScreen navigation={mockNavigation} />)+ it("labels the interval row with the fix and sync cadence from settings while no profile is active", async () => {+ mockSettings = { ...DEFAULT_SETTINGS, interval: 30, syncInterval: 300 }+ const batched = renderScreen()+ await settle()+ expect(batched.getByTestId("DashboardDock").props.intervalText).toBe("Every 30 s · Sync 5 min")+ batched.unmount()++ mockSettings = { ...DEFAULT_SETTINGS, interval: 5, syncInterval: 0 }+ const instant = renderScreen()+ await settle()+ expect(instant.getByTestId("DashboardDock").props.intervalText).toBe("Every 5 s · Instant sync")+ expect(mockGetProfiles).not.toHaveBeenCalled()+ })- expect(queryByTestId("ConnectionStatus")).toBeNull()+ it("labels the interval row with the active profile's fix and sync cadence, since the state line already names it", async () => {+ mockTracking = true+ mockSettings = { ...DEFAULT_SETTINGS, interval: 30, syncInterval: 300 }+ mockActiveProfileName = "Night"+ mockActiveProfileId = 7+ mockGetProfiles.mockResolvedValue([+ { id: 3, name: "Driving", interval: 10, syncInterval: 60 },+ { id: 7, name: "Night", interval: 300, syncInterval: 900 }+ ])++ const { getByTestId } = renderScreen()+ await waitFor(() => expect(getByTestId("DashboardDock").props.intervalText).toBe("Every 5 min · Sync 15 min"))})- it("still renders DatabaseStatistics when offline mode is enabled", () => {- mockSettings = { ...DEFAULT_SETTINGS, isOfflineMode: true }+ it("falls back to the settings pair when the active profile id matches no saved profile", async () => {+ mockTracking = true+ mockSettings = { ...DEFAULT_SETTINGS, interval: 30, syncInterval: 300 }+ mockActiveProfileId = 99+ mockGetProfiles.mockResolvedValue([{ id: 7, name: "Night", interval: 300, syncInterval: 900 }])- const { getByTestId } = render(<DashboardScreen navigation={mockNavigation} />)+ const { getByTestId } = renderScreen()+ await waitFor(() => expect(mockGetProfiles).toHaveBeenCalled())- expect(getByTestId("DatabaseStatistics")).toBeTruthy()+ expect(getByTestId("DashboardDock").props.intervalText).toBe("Every 30 s · Sync 5 min")})- // ── Start Tracking + Location Services check (#312) ────────────────────────-it("starts tracking directly when location services are enabled", async () => {- mockTracking = false- mockIsLocationEnabled.mockResolvedValue(true)-- const { getByText } = render(<DashboardScreen navigation={mockNavigation} />)- fireEvent.press(getByText("Start Tracking"))+ const { getByText } = renderScreen()+ await settle()+ fireEvent.press(getByText("Start tracking"))await waitFor(() => expect(mockStartTracking).toHaveBeenCalled())expect(mockShowConfirm).not.toHaveBeenCalled()expect(mockOpenLocationSettings).not.toHaveBeenCalled()})- it("opens location settings and skips start when user picks 'Location Settings'", async () => {- mockTracking = false+ it("opens location settings and skips start when the user picks Location settings", async () => {mockIsLocationEnabled.mockResolvedValue(false)- mockShowConfirm.mockResolvedValue(true) // user taps "Location Settings"+ mockShowConfirm.mockResolvedValue(true)- const { getByText } = render(<DashboardScreen navigation={mockNavigation} />)- fireEvent.press(getByText("Start Tracking"))+ const { getByText, getByTestId } = renderScreen()+ await settle()+ fireEvent.press(getByText("Start tracking"))await waitFor(() => expect(mockOpenLocationSettings).toHaveBeenCalled())expect(mockStartTracking).not.toHaveBeenCalled()+ expect(getByTestId("DashboardMap").props.recentreSignal).toBe(0)})- it("starts tracking anyway when user dismisses the location warning", async () => {- mockTracking = false+ it("signals the map to recentre on each Start, so the tap shows on the map before the first fix does", async () => {+ const { getByText, getByTestId } = renderScreen()+ await settle()+ expect(getByTestId("DashboardMap").props.recentreSignal).toBe(0)++ fireEvent.press(getByText("Start tracking"))+ await waitFor(() => expect(mockStartTracking).toHaveBeenCalled())++ expect(getByTestId("DashboardMap").props.recentreSignal).toBe(1)+ })++ it("starts tracking anyway when the user dismisses the location warning", async () => {mockIsLocationEnabled.mockResolvedValue(false)- mockShowConfirm.mockResolvedValue(false) // user taps "Close"+ mockShowConfirm.mockResolvedValue(false)- const { getByText } = render(<DashboardScreen navigation={mockNavigation} />)- fireEvent.press(getByText("Start Tracking"))+ const { getByText } = renderScreen()+ await settle()+ fireEvent.press(getByText("Start tracking"))await waitFor(() => expect(mockStartTracking).toHaveBeenCalled())expect(mockOpenLocationSettings).not.toHaveBeenCalled()})- it("revalidates locationEnabled when AppState transitions to active", async () => {+ it("stops tracking from the pill", async () => {+ mockTracking = true++ const { getByText } = renderScreen()+ await settle()+ fireEvent.press(getByText("Stop tracking"))++ await waitFor(() => expect(mockStopTracking).toHaveBeenCalled())+ })++ it("revalidates location services and permissions when the app returns to the foreground, never per fix", async () => {const { AppState } = require("react-native")const addSpy = jest.spyOn(AppState, "addEventListener")- render(<DashboardScreen navigation={mockNavigation} />)-- // Wait for the initial isLocationEnabled call from useFocusEffect+ renderScreen()+ await settle()await waitFor(() => expect(mockIsLocationEnabled).toHaveBeenCalled())- const callsAfterMount = mockIsLocationEnabled.mock.calls.length+ const locationCalls = mockIsLocationEnabled.mock.calls.length+ const permissionCalls = mockCheckPermissions.mock.calls.lengthconst changeHandler = addSpy.mock.calls.find(([event]) => event === "change")?.[1] as (s: string) => voidexpect(changeHandler).toBeDefined()- changeHandler("background")- expect(mockIsLocationEnabled).toHaveBeenCalledTimes(callsAfterMount)+ await act(async () => changeHandler("background"))+ expect(mockIsLocationEnabled).toHaveBeenCalledTimes(locationCalls)+ expect(mockCheckPermissions).toHaveBeenCalledTimes(permissionCalls)++ await act(async () => changeHandler("active"))+ expect(mockIsLocationEnabled).toHaveBeenCalledTimes(locationCalls + 1)+ expect(mockCheckPermissions).toHaveBeenCalledTimes(permissionCalls + 1)+ })++ it("checks permissions once on focus so a revoked grant shows before the tap", async () => {+ renderScreen()+ await settle()++ expect(mockCheckPermissions).toHaveBeenCalledTimes(1)+ })++ it("never asks for database statistics, because nothing on the dashboard prints them", async () => {+ renderScreen()+ await settle()++ expect(mockGetStats).not.toHaveBeenCalled()+ })++ it("reads the last known fix on focus while idle and hands it to the map and the dock", async () => {+ mockGetMostRecentLocation.mockResolvedValue({+ latitude: 48.1,+ longitude: 11.5,+ accuracy: 12.5,+ timestamp: 1_700_000_000+ })++ const { getByTestId } = renderScreen()+ const expected = { latitude: 48.1, longitude: 11.5, accuracy: 12.5, timestamp: 1_700_000_000 }+ await waitFor(() => expect(getByTestId("DashboardMap").props.lastKnown).toEqual(expected))++ expect(getByTestId("DashboardDock").props.lastKnown).toEqual(expected)+ })++ it("hands the map an unread marker before the database answers, so a zone fit cannot beat a fix", async () => {+ mockGetMostRecentLocation.mockReturnValue(new Promise(() => {}))++ const { getByTestId } = renderScreen()+ await settle()++ expect(getByTestId("DashboardMap").props.lastKnown).toBeUndefined()+ expect(getByTestId("DashboardDock").props.lastKnown).toBeNull()+ })++ it("reads the last known fix while tracking too, so the map opens where the service last was instead of on the world", async () => {+ mockTracking = true+ mockGetMostRecentLocation.mockResolvedValue({+ latitude: 48.1,+ longitude: 11.5,+ accuracy: 4,+ timestamp: 1_700_000_000+ })++ const { getByTestId } = renderScreen()++ await waitFor(() =>+ expect(getByTestId("DashboardMap").props.lastKnown).toEqual({+ latitude: 48.1,+ longitude: 11.5,+ accuracy: 4,+ timestamp: 1_700_000_000+ })+ )+ })++ it("reads the battery-stop flag while idle so the state line stays honest after the banner clears", async () => {+ mockGetSetting.mockImplementation((key: string) => Promise.resolve(key === "stopped_by_battery" ? "true" : "false"))++ const { getByTestId } = renderScreen()+ await waitFor(() => expect(getByTestId("DashboardDock").props.stoppedByBattery).toBe(true))+ })++ it("hands the dock the live fix's accuracy and time while tracking", async () => {+ mockTracking = true+ mockCoords = { latitude: 48.1, longitude: 11.5, accuracy: 4.2, timestamp: 1_700_000_000 }++ const { getByTestId } = renderScreen()+ await settle()++ expect(getByTestId("DashboardDock").props.hasFix).toBe(true)+ expect(getByTestId("DashboardDock").props.coords).toEqual({ accuracy: 4.2, timestamp: 1_700_000_000 })+ })++ describe("banner", () => {+ it("shows nothing while every prerequisite holds", async () => {+ const { queryByTestId } = renderScreen()+ await settle()++ expect(queryByTestId("DashboardBanner")).toBeNull()+ })++ it("puts a missing location grant above location services and battery, because nothing works without it", async () => {+ mockCheckPermissions.mockResolvedValue({ ...grantedPermissions, location: false })+ mockIsLocationEnabled.mockResolvedValue(false)+ mockIsBatteryCritical.mockResolvedValue(true)++ const { getByTestId } = renderScreen()+ await waitFor(() => expect(getByTestId("DashboardBanner").props.condition).toBe("permission"))+ })++ it("puts location services above battery", async () => {+ mockIsLocationEnabled.mockResolvedValue(false)+ mockIsBatteryCritical.mockResolvedValue(true)++ const { getByTestId } = renderScreen()+ await waitFor(() => expect(getByTestId("DashboardBanner").props.condition).toBe("locationOff"))+ })++ it("names a missing background grant only while tracking, when it actually costs fixes", async () => {+ mockCheckPermissions.mockResolvedValue({ ...grantedPermissions, background: false })++ const idle = renderScreen()+ await settle()+ expect(idle.queryByTestId("DashboardBanner")).toBeNull()+ idle.unmount()++ mockTracking = true+ const live = renderScreen()+ await waitFor(() => expect(live.getByTestId("DashboardBanner").props.condition).toBe("background"))+ })++ it("sits below the status inset, never over the clock", async () => {+ mockIsLocationEnabled.mockResolvedValue(false)++ const { getByTestId } = renderScreen()+ await waitFor(() => expect(getByTestId("DashboardBanner")).toBeTruthy())++ expect(getByTestId("DashboardBanner").props.top).toBe(24 + 12)+ })++ it("opens the location settings from the location-off action", async () => {+ mockIsLocationEnabled.mockResolvedValue(false)++ const { getByTestId } = renderScreen()+ await waitFor(() => expect(getByTestId("DashboardBanner")).toBeTruthy())+ fireEvent.press(getByTestId("banner-action"))++ expect(mockOpenLocationSettings).toHaveBeenCalled()+ expect(mockEnsurePermissions).not.toHaveBeenCalled()+ })++ it("runs the disclosure-gated permission flow from Grant and re-reads the grants after it", async () => {+ mockCheckPermissions.mockResolvedValue({ ...grantedPermissions, location: false })++ const { getByTestId } = renderScreen()+ await waitFor(() => expect(getByTestId("DashboardBanner").props.condition).toBe("permission"))+ const checksBefore = mockCheckPermissions.mock.calls.length++ fireEvent.press(getByTestId("banner-action"))++ await waitFor(() => expect(mockEnsurePermissions).toHaveBeenCalled())+ await waitFor(() => expect(mockCheckPermissions).toHaveBeenCalledTimes(checksBefore + 1))+ expect(mockOpenLocationSettings).not.toHaveBeenCalled()+ })++ it("disappears the moment its condition clears", async () => {+ const { AppState } = require("react-native")+ const addSpy = jest.spyOn(AppState, "addEventListener")+ mockIsLocationEnabled.mockResolvedValue(false)++ const { getByTestId, queryByTestId } = renderScreen()+ await waitFor(() => expect(getByTestId("DashboardBanner")).toBeTruthy())++ mockIsLocationEnabled.mockResolvedValue(true)+ const changeHandler = addSpy.mock.calls.find(([event]) => event === "change")?.[1] as (s: string) => void+ await act(async () => changeHandler("active"))++ expect(queryByTestId("DashboardBanner")).toBeNull()+ })+ })++ describe("map framing", () => {+ it("keeps the position dot out from under the dock, the banner and the disc column", async () => {+ const { getByTestId } = renderScreen()+ await settle()++ act(() => {+ fireEvent(getByTestId("dashboard-stack"), "layout", { nativeEvent: { layout: { height: 200 } } })+ })++ expect(getByTestId("DashboardMap").props.cameraPadding).toEqual({+ top: 24 + 16,+ bottom: 200 + 16 + 16,+ left: 16,+ right: 16 + 40 + 16+ })+ expect(getByTestId("DashboardMap").props.controlsBottom).toBe(16 + 200 + 8)+ expect(getByTestId("DashboardMap").props.controlsEnd).toBe(16)+ })++ it("pads the stack, the banner and the disc column by the side insets, so a landscape navigation bar covers none of them", async () => {+ mockInsets = { top: 24, bottom: 0, left: 0, right: 48 }+ mockIsLocationEnabled.mockResolvedValue(false)++ const { getByTestId } = renderScreen()+ await waitFor(() => expect(getByTestId("DashboardBanner")).toBeTruthy())++ const stack = StyleSheet.flatten(getByTestId("dashboard-stack").props.style)+ expect(stack.left).toBe(16)+ expect(stack.right).toBe(16 + 48)+ expect(getByTestId("DashboardBanner").props.left).toBe(16)+ expect(getByTestId("DashboardBanner").props.right).toBe(16 + 48)+ expect(getByTestId("DashboardMap").props.controlsEnd).toBe(16 + 48)+ expect(getByTestId("DashboardMap").props.cameraPadding.right).toBe(16 + 48 + 40 + 16)+ })++ it("adds the banner's height to the top inset only while a banner is up", async () => {+ mockIsLocationEnabled.mockResolvedValue(false)++ const { getByTestId } = renderScreen()+ await waitFor(() => expect(getByTestId("DashboardBanner")).toBeTruthy())++ act(() => {+ fireEvent(getByTestId("DashboardBanner"), "layout", { nativeEvent: { layout: { height: 56 } } })+ })++ expect(getByTestId("DashboardMap").props.cameraPadding.top).toBe(24 + 56 + 12 + 16)+ })+ })++ describe("today's track", () => {+ it("holds the Route slot empty idle with no points, so the pill never moves", async () => {+ const { queryByTestId, getByTestId } = renderScreen()+ await settle()++ expect(queryByTestId("track-toggle")).toBeNull()+ expect(StyleSheet.flatten(getByTestId("route-slot").props.style).width).toBe(size.iconColumn)+ })++ it("lifts the Route disc and the pill 16 above the dock and 16 apart, one rhythm for every floating control", async () => {+ const { getByTestId } = renderScreen()+ await settle()++ expect(StyleSheet.flatten(getByTestId("route-slot").props.style).marginBottom).toBe(space.sm)+ expect(StyleSheet.flatten(getByTestId("dashboard-stack").props.style).gap).toBe(space.sm)+ })++ it("offers the Route toggle in the action row while tracking and persists a flip", async () => {+ mockTracking = true+ mockGetSetting.mockImplementation((key: string) => Promise.resolve(key === "showTrack" ? "true" : "false"))++ const { getByTestId } = renderScreen()+ await waitFor(() => expect(getByTestId("track-toggle")).toBeTruthy())+ expect(getByTestId("track-toggle").props.anchored).toBe(false)+ expect(getByTestId("track-toggle").props.active).toBe(true)+ expect(getByTestId("DashboardMap").props.showTrack).toBe(true)++ fireEvent.press(getByTestId("track-toggle"))++ expect(mockSaveSetting).toHaveBeenCalledWith("showTrack", "false")+ expect(getByTestId("DashboardMap").props.showTrack).toBe(false)+ })++ it("offers the Route toggle idle once the map reports today's points", async () => {+ const { getByTestId } = renderScreen()+ await settle()++ act(() => getByTestId("DashboardMap").props.onHasTrackChange(true))++ expect(getByTestId("track-toggle")).toBeTruthy()+ })+ })- changeHandler("active")- await waitFor(() => expect(mockIsLocationEnabled).toHaveBeenCalledTimes(callsAfterMount + 1))+ it("paints dark status icons over the light map style while focused", async () => {+ const { UNSAFE_getByType } = renderScreen()+ await settle()- addSpy.mockRestore()+ expect(UNSAFE_getByType(StatusBar).props.barStyle).toBe("dark-content")})})diff --git a/apps/mobile/src/utils/__tests__/dashboardState.test.ts b/apps/mobile/src/utils/__tests__/dashboardState.test.tsnew file mode 100644index 00000000..db37ac34--- /dev/null+++ b/apps/mobile/src/utils/__tests__/dashboardState.test.ts@@ -0,0 +1,274 @@+import {+ describeState,+ formatDuration,+ formatInterval,+ formatLastFix,+ intervalText,+ pickBannerCondition,+ recordingSummary,+ syncSummary,+ trackingSummary,+ type StateInput+} from "../dashboardState"+import { formatDate, formatTime, loadDisplayPreferences } from "../geo"++const mockGetSetting = jest.fn()++jest.mock("../../services/NativeLocationService", () => ({+ __esModule: true,+ default: {+ getSetting: (...args: string[]) => mockGetSetting(...args)+ }+}))++beforeAll(async () => {+ mockGetSetting.mockImplementation((key: string) => {+ if (key === "unitSystem") return Promise.resolve("metric")+ if (key === "timeFormat") return Promise.resolve("24h")+ return Promise.resolve("")+ })+ await loadDisplayPreferences()+})++const NOW = new Date(2026, 1, 28, 12, 0, 0)+const TODAY_AT_18_42 = Math.floor(new Date(2026, 1, 28, 18, 42, 0).getTime() / 1000)+const YESTERDAY_AT_18_42 = Math.floor(new Date(2026, 1, 27, 18, 42, 0).getTime() / 1000)++const granted = { location: true, background: true }++describe("pickBannerCondition", () => {+ const calm = { permissions: granted, locationEnabled: true, isBatteryCritical: false, tracking: false }++ it("shows nothing when every prerequisite holds", () => {+ expect(pickBannerCondition(calm)).toBeNull()+ expect(pickBannerCondition({ ...calm, tracking: true })).toBeNull()+ })++ it("a missing location grant outranks everything else because nothing can record without it", () => {+ expect(+ pickBannerCondition({+ permissions: { location: false, background: false },+ locationEnabled: false,+ isBatteryCritical: true,+ tracking: true+ })+ ).toBe("permission")+ })++ it("a missing background grant matters only while the service is running", () => {+ const partial = { ...calm, permissions: { location: true, background: false } }+ expect(pickBannerCondition({ ...partial, tracking: true })).toBe("background")+ expect(pickBannerCondition({ ...partial, tracking: false })).toBeNull()+ })++ it("a missing background grant outranks location services being off", () => {+ expect(+ pickBannerCondition({+ permissions: { location: true, background: false },+ locationEnabled: false,+ isBatteryCritical: false,+ tracking: true+ })+ ).toBe("background")+ })++ it("location services off outranks a critical battery", () => {+ expect(pickBannerCondition({ ...calm, locationEnabled: false, isBatteryCritical: true })).toBe("locationOff")+ })++ it("a critical battery only blocks a start, so it is silent while tracking", () => {+ expect(pickBannerCondition({ ...calm, isBatteryCritical: true })).toBe("battery")+ expect(pickBannerCondition({ ...calm, isBatteryCritical: true, tracking: true })).toBeNull()+ })++ it("an unread permission status never claims a grant is missing", () => {+ expect(pickBannerCondition({ ...calm, permissions: null })).toBeNull()+ expect(pickBannerCondition({ ...calm, permissions: null, locationEnabled: false })).toBe("locationOff")+ })+})++describe("describeState", () => {+ const idle: StateInput = {+ tracking: false,+ hasFix: false,+ locationEnabled: true,+ activeZoneName: null,+ pauseReason: null,+ activeProfileName: null,+ coords: null,+ lastKnown: null,+ stoppedByBattery: false,+ now: NOW+ }+ const live: StateInput = {+ ...idle,+ tracking: true,+ hasFix: true,+ coords: { accuracy: 4.3, timestamp: TODAY_AT_18_42 }+ }++ it("idle with a fix from today tells the user when they were last seen", () => {+ expect(describeState({ ...idle, lastKnown: { timestamp: TODAY_AT_18_42 } })).toEqual({+ icon: "dashed",+ tone: "secondary",+ label: "Ready",+ caption: `Last fix ${formatTime(TODAY_AT_18_42)}`+ })+ })++ it("idle with an older fix adds the date so the time is not mistaken for today", () => {+ expect(describeState({ ...idle, lastKnown: { timestamp: YESTERDAY_AT_18_42 } }).caption).toBe(+ `Last fix ${formatDate(YESTERDAY_AT_18_42)} · ${formatTime(YESTERDAY_AT_18_42)}`+ )+ })++ it("a fresh install is Ready with no fix to report", () => {+ expect(describeState(idle)).toEqual({ icon: "dashed", tone: "secondary", label: "Ready", caption: "No fixes yet" })+ })++ it("a battery stop stays visible after the banner clears so the user knows why recording ended", () => {+ expect(describeState({ ...idle, stoppedByBattery: true, lastKnown: { timestamp: TODAY_AT_18_42 } })).toEqual({+ icon: "alert",+ tone: "error",+ label: "Tracking stopped",+ caption: "Battery fell below 5%"+ })+ })++ it("a battery stop is forgotten once tracking runs again", () => {+ expect(describeState({ ...live, stoppedByBattery: true }).label).toBe("Tracking")+ })++ it("tracking without a fix is searching, not an error", () => {+ expect(describeState({ ...idle, tracking: true })).toEqual({+ icon: "loader",+ tone: "primary",+ label: "Searching for GPS",+ caption: "No fix yet"+ })+ })++ it("searching with location services off names the cause the banner offers to fix", () => {+ expect(describeState({ ...idle, tracking: true, locationEnabled: false }).caption).toBe("Location services are off")+ })++ it("a fix flag without coordinates has nothing to print, so it still reads as searching", () => {+ expect(describeState({ ...idle, tracking: true, hasFix: true }).label).toBe("Searching for GPS")+ })++ it("a live fix leads with accuracy and time in the user's units", () => {+ expect(describeState(live)).toEqual({+ icon: "circleDot",+ tone: "success",+ label: "Tracking",+ caption: `±4 m · ${formatTime(TODAY_AT_18_42)}`+ })+ })++ it("an active profile is named on the label so the user sees what is overriding their settings", () => {+ expect(describeState({ ...live, activeProfileName: "Night" }).label).toBe("Tracking · Night")+ })++ it("a WiFi pause names the network the zone is bound to", () => {+ expect(describeState({ ...live, activeZoneName: "Home", pauseReason: "wifi" })).toEqual({+ icon: "pause",+ tone: "secondary",+ label: "Paused in Home",+ caption: "Home WiFi · resumes when you leave"+ })+ })++ it("a motionless pause says movement, not leaving, ends it", () => {+ expect(describeState({ ...live, activeZoneName: "Home", pauseReason: "motionless" }).caption).toBe(+ "No movement · resumes when you move"+ )+ })++ it("a plain zone pause says leaving the zone ends it", () => {+ expect(describeState({ ...live, activeZoneName: "Work", pauseReason: null }).caption).toBe(+ "Inside zone · resumes when you leave"+ )+ })++ it("a pause outranks the live fix because recording is what the user cares about", () => {+ expect(describeState({ ...live, activeZoneName: "Home", activeProfileName: "Night" }).label).toBe("Paused in Home")+ })+})++describe("formatInterval", () => {+ it("keeps sub-minute intervals in seconds", () => {+ expect(formatInterval(5)).toBe("Every 5 s")+ expect(formatInterval(30)).toBe("Every 30 s")+ })++ it("promotes whole minutes so 300 does not have to be divided in the head", () => {+ expect(formatInterval(60)).toBe("Every 1 min")+ expect(formatInterval(300)).toBe("Every 5 min")+ })++ it("promotes whole hours", () => {+ expect(formatInterval(3600)).toBe("Every 1 h")+ expect(formatInterval(7200)).toBe("Every 2 h")+ })++ it("falls back to seconds when neither unit divides evenly, so nothing is rounded away", () => {+ expect(formatInterval(90)).toBe("Every 90 s")+ expect(formatInterval(5400)).toBe("Every 90 min")+ })+})++describe("intervalText", () => {+ it.each([+ [5, 900, "Every 5 s · Sync 15 min"],+ [30, 300, "Every 30 s · Sync 5 min"],+ [5, 90, "Every 5 s · Sync 90 s"],+ [3600, 7200, "Every 1 h · Sync 2 h"]+ ])("pairs the fix cadence %i s with the sync cadence %i s in the same units", (interval, sync, expected) => {+ expect(intervalText(interval, sync)).toBe(expected)+ })++ it("calls a zero sync interval instant, since every fix is sent as it lands", () => {+ expect(intervalText(5, 0)).toBe("Every 5 s · Instant sync")+ })+})++describe("trackingSummary", () => {+ it("prints a preset as fix rate, movement gate and sync cadence in one grammar", () => {+ expect(trackingSummary(5, 0, 0, false)).toBe("Every 5 s, any movement · syncs each fix")+ expect(trackingSummary(30, 2, 300, false)).toBe("Every 30 s after 2 m · syncs every 5 min")+ expect(trackingSummary(60, 2, 900, false)).toBe("Every 1 min after 2 m · syncs every 15 min")+ })++ it("keeps a custom value in seconds when no unit divides it", () => {+ expect(trackingSummary(20, 5, 90, false)).toBe("Every 20 s after 5 m · syncs every 90 s")+ })++ it("drops the sync clause offline, since nothing syncs", () => {+ expect(trackingSummary(30, 2, 300, true)).toBe("Every 30 s after 2 m")+ })++ it("exposes the two halves so a caption can carry one of them", () => {+ expect(recordingSummary(5, 20)).toBe("Every 5 s after 20 m")+ expect(syncSummary(0)).toBe("syncs each fix")+ expect(syncSummary(900)).toBe("syncs every 15 min")+ expect(formatDuration(90)).toBe("90 s")+ })+})++describe("formatLastFix", () => {+ it("has nothing to date when no fix was ever recorded", () => {+ expect(formatLastFix(null, NOW)).toBe("No fixes yet")+ })++ it("drops the date for a fix from today", () => {+ expect(formatLastFix(TODAY_AT_18_42, NOW)).toBe(`Last fix ${formatTime(TODAY_AT_18_42)}`)+ })++ it("keeps the date for a fix from another day, even one just past midnight", () => {+ const lateLastNight = Math.floor(new Date(2026, 1, 27, 23, 59, 0).getTime() / 1000)+ const earlyToday = new Date(2026, 1, 28, 0, 1, 0)+ expect(formatLastFix(lateLastNight, earlyToday)).toBe(+ `Last fix ${formatDate(lateLastNight)} · ${formatTime(lateLastNight)}`+ )+ })+})diff --git a/apps/mobile/src/utils/dashboardState.ts b/apps/mobile/src/utils/dashboardState.tsnew file mode 100644index 00000000..11af959e--- /dev/null+++ b/apps/mobile/src/utils/dashboardState.ts@@ -0,0 +1,146 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import { formatTime, formatWhen, metersToInput, shortDistanceUnit } from "./geo"++export type BannerCondition = "permission" | "background" | "locationOff" | "battery"++export interface BannerInput {+ permissions: { location: boolean; background: boolean } | null+ locationEnabled: boolean+ isBatteryCritical: boolean+ tracking: boolean+}++export function pickBannerCondition({+ permissions,+ locationEnabled,+ isBatteryCritical,+ tracking+}: BannerInput): BannerCondition | null {+ if (permissions && !permissions.location) return "permission"+ if (permissions && tracking && !permissions.background) return "background"+ if (!locationEnabled) return "locationOff"+ if (isBatteryCritical && !tracking) return "battery"+ return null+}++export type StateIcon = "dashed" | "loader" | "circleDot" | "pause" | "alert"+export type StateTone = "secondary" | "primary" | "success" | "error"++export interface StateDescription {+ icon: StateIcon+ tone: StateTone+ label: string+ caption: string+}++export interface StateInput {+ tracking: boolean+ hasFix: boolean+ locationEnabled: boolean+ activeZoneName: string | null+ pauseReason: string | null+ activeProfileName: string | null+ coords: { accuracy: number; timestamp: number } | null+ lastKnown: { timestamp: number } | null+ stoppedByBattery: boolean+ now?: Date+}++const STOPPED_BY_BATTERY = "Battery fell below 5%"+const NO_FIX_YET = "No fix yet"+const LOCATION_OFF = "Location services are off"++function pauseCaption(zoneName: string, pauseReason: string | null): string {+ if (pauseReason === "wifi") return `${zoneName} WiFi · resumes when you leave`+ if (pauseReason === "motionless") return "No movement · resumes when you move"+ return "Inside zone · resumes when you leave"+}++export function describeState(input: StateInput): StateDescription {+ const { tracking, hasFix, locationEnabled, activeZoneName, pauseReason, activeProfileName, coords } = input++ if (!tracking) {+ if (input.stoppedByBattery) {+ return { icon: "alert", tone: "error", label: "Tracking stopped", caption: STOPPED_BY_BATTERY }+ }+ return {+ icon: "dashed",+ tone: "secondary",+ label: "Ready",+ caption: formatLastFix(input.lastKnown?.timestamp ?? null, input.now)+ }+ }++ if (activeZoneName) {+ return {+ icon: "pause",+ tone: "secondary",+ label: `Paused in ${activeZoneName}`,+ caption: pauseCaption(activeZoneName, pauseReason)+ }+ }++ if (!hasFix || !coords) {+ return {+ icon: "loader",+ tone: "primary",+ label: "Searching for GPS",+ caption: locationEnabled ? NO_FIX_YET : LOCATION_OFF+ }+ }++ const accuracy = Math.round(metersToInput(coords.accuracy))+ return {+ icon: "circleDot",+ tone: "success",+ label: activeProfileName ? `Tracking · ${activeProfileName}` : "Tracking",+ caption: `±${accuracy} ${shortDistanceUnit()} · ${formatTime(coords.timestamp)}`+ }+}++export function formatDuration(seconds: number): string {+ if (seconds >= 3600 && seconds % 3600 === 0) return `${seconds / 3600} h`+ if (seconds >= 60 && seconds % 60 === 0) return `${seconds / 60} min`+ return `${seconds} s`+}++export function formatInterval(seconds: number): string {+ return `Every ${formatDuration(seconds)}`+}++/** "Every 30 s after 2 m", or ", any movement" when no distance gates a fix. */+export function recordingSummary(intervalSeconds: number, distanceMeters: number): string {+ const gate =+ distanceMeters === 0 ? ", any movement" : ` after ${metersToInput(distanceMeters)} ${shortDistanceUnit()}`+ return `${formatInterval(intervalSeconds)}${gate}`+}++/** "syncs each fix" or "syncs every 5 min", lower case so a caption can carry it. */+export function syncSummary(syncIntervalSeconds: number): string {+ return syncIntervalSeconds === 0 ? "syncs each fix" : `syncs every ${formatDuration(syncIntervalSeconds)}`+}++/** The one line a preset row, the Custom row and the Settings row all print for a configuration. */+export function trackingSummary(+ intervalSeconds: number,+ distanceMeters: number,+ syncIntervalSeconds: number,+ isOfflineMode: boolean+): string {+ const recording = recordingSummary(intervalSeconds, distanceMeters)+ return isOfflineMode ? recording : `${recording} · ${syncSummary(syncIntervalSeconds)}`+}++export function intervalText(intervalSeconds: number, syncIntervalSeconds: number): string {+ const sync = syncIntervalSeconds === 0 ? "Instant sync" : `Sync ${formatDuration(syncIntervalSeconds)}`+ return `${formatInterval(intervalSeconds)} · ${sync}`+}++export function formatLastFix(timestampSeconds: number | null, now: Date = new Date()): string {+ if (timestampSeconds === null) return "No fixes yet"+ return `Last fix ${formatWhen(timestampSeconds, now)}`+}