Colota - Android GPS Location tracker
feat: add configurable unit system and time format settings
Max Dietrichb2289072736f
diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.mdindex 87047f00..8f912596 100644--- a/apps/docs/docs/development/architecture.md+++ b/apps/docs/docs/development/architecture.md@@ -172,7 +172,7 @@ Wraps Android's `EncryptedSharedPreferences` for encrypted credential storage (A| Screen | Purpose || --- | --- || `DashboardScreen` | Live map with tracking controls, coordinates, database stats, geofence and profile status |-| `SettingsScreen` | GPS interval, distance filter, sync strategy, offline mode, accuracy threshold |+| `SettingsScreen` | GPS interval, distance filter, sync strategy, offline mode, accuracy threshold, unit system, time format || `ApiSettingsScreen` | Endpoint URL, HTTP method, field mapping with backend templates || `AuthSettingsScreen` | Authentication method (None, Basic Auth, Bearer Token) and custom HTTP headers || `GeofenceScreen` | Create, edit, and delete pause zones on an interactive map |@@ -228,7 +228,7 @@ Supporting utilities in `mapUtils.ts`:| Utility | Purpose || --- | --- || `logger` | Environment-aware logging - suppresses debug/info in production via `__DEV__`, always logs warn/error |-| `geo` | Haversine distance, speed/distance/duration/time formatting with locale-aware unit selection (km/h vs mph) |+| `geo` | Haversine distance, speed/distance/duration/time formatting with configurable unit system (metric/imperial) and time format (12h/24h), auto-detected from locale on first use || `exportConverters` | Converts location data to CSV, GeoJSON, GPX, and KML export formats (flat and trip-aware variants) || `trips` | Trip segmentation via time-gap detection (15-min threshold) with distance computation, trip stats (avg speed, elevation gain/loss), and trip color assignment || `queueStatus` | Maps sync queue size to color indicators for the dashboard |diff --git a/apps/docs/docs/introduction.md b/apps/docs/docs/introduction.mdindex 0bc58391..bc59aa09 100644--- a/apps/docs/docs/introduction.md+++ b/apps/docs/docs/introduction.md@@ -19,6 +19,7 @@ Colota is a self-hosted GPS tracking app for Android. It sends your location to- **Data Export** - Export location history in CSV, GeoJSON, GPX, or KML formats.- **Authentication** - Basic Auth, Bearer Token, or custom HTTP headers with AES-256-GCM encrypted storage.- **Quick Setup** - Configure devices instantly via `colota://setup` deep links or QR codes. No manual typing required.+- **Display Settings** - Choose between metric and imperial units, 12h or 24h time format. Auto-detected from device locale on first use.- **Dark Mode** - Full light and dark theme support.## App Screens@@ -28,7 +29,7 @@ Colota has fourteen screens, each focused on a specific task:| Screen | Purpose || --- | --- || **Dashboard** | Live map with current coordinates, tracking controls, database stats, and geofence status |-| **Settings** | GPS polling interval, distance filter, sync strategy, offline mode, accuracy threshold |+| **Settings** | GPS polling interval, distance filter, sync strategy, offline mode, accuracy threshold, unit system, time format || **API Config** | Endpoint field mapping with templates for Dawarich, OwnTracks, PhoneTrack, Reitti, Traccar, or custom backends || **Auth Settings** | Endpoint authentication (None, Basic Auth, Bearer Token) and custom HTTP headers || **Geofences** | Create, edit, and delete pause zones on an interactive map |diff --git a/apps/mobile/App.tsx b/apps/mobile/App.tsxindex da5b9df4..661645ec 100644--- a/apps/mobile/App.tsx+++ b/apps/mobile/App.tsx@@ -29,11 +29,13 @@ import {TripDetailScreen} from "./src/screens/"import NativeLocationService from "./src/services/NativeLocationService"+import { loadDisplayPreferences } from "./src/utils/geo"import { setLogCollecting } from "./src/utils/logger"MapLibreGL.setAccessToken(null)-// Enable log collection early if debug mode was previously enabled+// Load display preferences and enable log collection early+loadDisplayPreferences()NativeLocationService.getSetting("debug_mode_enabled", "false").then((v) => {if (v === "true") setLogCollecting(true)})diff --git a/apps/mobile/src/components/features/settings/SyncStrategySettings.tsx b/apps/mobile/src/components/features/settings/SyncStrategySettings.tsxindex ff499255..accb9fd4 100644--- a/apps/mobile/src/components/features/settings/SyncStrategySettings.tsx+++ b/apps/mobile/src/components/features/settings/SyncStrategySettings.tsx@@ -11,6 +11,7 @@ import { fonts, fontSizes } from "../../../styles/typography"import { SYNC_INTERVAL_PRESETS, SYNC_INTERVAL_LABELS } from "../../../constants"import { SectionTitle, Card, Divider, NumericInput, SettingRow } from "../../index"import { PresetOption } from "./PresetOption"+import { shortDistanceUnit, inputToMeters, metersToInput } from "../../../utils/geo"interface SyncStrategySettingsProps {settings: Settings@@ -28,8 +29,10 @@ export function SyncStrategySettings({colors}: SyncStrategySettingsProps) {const [intervalInput, setIntervalInput] = useState(settings.interval.toString())- const [distanceInput, setDistanceInput] = useState(settings.distance?.toString() || "0")- const [accuracyThresholdInput, setAccuracyTresholdInput] = useState(settings.accuracyThreshold.toString())+ const [distanceInput, setDistanceInput] = useState(metersToInput(settings.distance ?? 0).toString())+ const [accuracyThresholdInput, setAccuracyThresholdInput] = useState(+ metersToInput(settings.accuracyThreshold).toString()+ )const [syncIntervalInput, setSyncIntervalInput] = useState(settings.syncInterval.toString())const [showAdvanced, setShowAdvanced] = useState(false)@@ -38,8 +41,8 @@ export function SyncStrategySettings({// Sync inputs with settings changes (e.g. preset selection)useEffect(() => {setIntervalInput(settings.interval.toString())- setDistanceInput(settings.distance?.toString() || "0")- setAccuracyTresholdInput(settings.accuracyThreshold.toString())+ setDistanceInput(metersToInput(settings.distance ?? 0).toString())+ setAccuracyThresholdInput(metersToInput(settings.accuracyThreshold).toString())setSyncIntervalInput(settings.syncInterval.toString())}, [settings.interval, settings.distance, settings.accuracyThreshold, settings.syncInterval])@@ -47,11 +50,12 @@ export function SyncStrategySettings({(key: "interval" | "distance" | "accuracyThreshold", value: string, min: number = 0) => {if (key === "interval") setIntervalInput(value)if (key === "distance") setDistanceInput(value)- if (key === "accuracyThreshold") setAccuracyTresholdInput(value)+ if (key === "accuracyThreshold") setAccuracyThresholdInput(value)const num = Number(value)if (!isNaN(num) && num >= min) {- const next = { ...settings, [key]: num, syncPreset: "custom" as const }+ const stored = key === "distance" || key === "accuracyThreshold" ? inputToMeters(num) : num+ const next = { ...settings, [key]: stored, syncPreset: "custom" as const }onDebouncedSave(next)}},@@ -68,9 +72,10 @@ export function SyncStrategySettings({val = minif (key === "interval") setIntervalInput(min.toString())if (key === "distance") setDistanceInput(min.toString())- if (key === "accuracyThreshold") setAccuracyTresholdInput(min.toString())+ if (key === "accuracyThreshold") setAccuracyThresholdInput(min.toString())- const next = { ...settings, [key]: val }+ const stored = key === "distance" || key === "accuracyThreshold" ? inputToMeters(val) : val+ const next = { ...settings, [key]: stored }onSettingsChange(next)onImmediateSave(next)}@@ -183,7 +188,7 @@ export function SyncStrategySettings({value={distanceInput}onChange={(val) => handleNumericChange("distance", val, 0)}onBlur={() => handleNumericBlur("distance", 0)}- unit="meters"+ unit={shortDistanceUnit()}placeholder="10"hint="Only record if moved more than this distance"colors={colors}@@ -372,7 +377,7 @@ export function SyncStrategySettings({value={accuracyThresholdInput}onChange={(val) => handleNumericChange("accuracyThreshold", val, 1)}onBlur={() => handleNumericBlur("accuracyThreshold", 1)}- unit="meters"+ unit={shortDistanceUnit()}placeholder="50"hint="Reject readings with accuracy worse than this"colors={colors}diff --git a/apps/mobile/src/screens/GeofenceScreen.tsx b/apps/mobile/src/screens/GeofenceScreen.tsxindex f629c20f..f6cb6e5b 100644--- a/apps/mobile/src/screens/GeofenceScreen.tsx+++ b/apps/mobile/src/screens/GeofenceScreen.tsx@@ -28,6 +28,7 @@ import { buildGeofencesGeoJSON } from "../components/features/map/mapUtils"import { GeofenceLayers } from "../components/features/map/GeofenceLayers"import { UserLocationOverlay } from "../components/features/map/UserLocationOverlay"import { logger } from "../utils/logger"+import { formatShortDistance, shortDistanceUnit, inputToMeters } from "../utils/geo"export function GeofenceScreen({}: ScreenProps) {const { tracking } = useTracking()@@ -134,7 +135,7 @@ export function GeofenceScreen({}: ScreenProps) {name: newName,lat: pressCoords.latitude,lon: pressCoords.longitude,- radius: Number(newRadius),+ radius: inputToMeters(Number(newRadius)),enabled: true,pauseTracking: true})@@ -255,7 +256,9 @@ export function GeofenceScreen({}: ScreenProps) {onPress={() => handleZoomToGeofence(item)}><Text style={[styles.name, { color: colors.text }]}>{item.name}</Text>- <Text style={[styles.radius, { color: colors.textSecondary }]}>{item.radius}m radius</Text>+ <Text style={[styles.radius, { color: colors.textSecondary }]}>+ {formatShortDistance(item.radius)} radius+ </Text></Pressable><View style={styles.actions}>@@ -355,7 +358,7 @@ export function GeofenceScreen({}: ScreenProps) {</View><View style={[styles.inputGroup, styles.inputGroupRadius]}>- <Text style={[styles.label, { color: colors.textSecondary }]}>Radius (m)</Text>+ <Text style={[styles.label, { color: colors.textSecondary }]}>Radius ({shortDistanceUnit()})</Text><TextInputstyle={[styles.input,diff --git a/apps/mobile/src/screens/ProfileEditorScreen.tsx b/apps/mobile/src/screens/ProfileEditorScreen.tsxindex 12210c9c..ee578023 100644--- a/apps/mobile/src/screens/ProfileEditorScreen.tsx+++ b/apps/mobile/src/screens/ProfileEditorScreen.tsx@@ -13,6 +13,7 @@ import { fonts } from "../styles/typography"import { Container, SectionTitle, Card, Divider, SettingRow, NumericInput } from "../components"import { Check } from "lucide-react-native"import { logger } from "../utils/logger"+import { shortDistanceUnit, inputToMeters, metersToInput } from "../utils/geo"import { MS_TO_KMH, PROFILE_CONDITIONS, SYNC_INTERVAL_PRESETS, SYNC_INTERVAL_LABELS } from "../constants"const DEFAULT_PROFILE: Omit<TrackingProfile, "id" | "createdAt"> = {@@ -60,7 +61,7 @@ export function ProfileEditorScreen({ navigation, route }: any) {enabled: existing.enabled})setIntervalStr(String(existing.interval))- setDistanceStr(String(existing.distance))+ setDistanceStr(String(metersToInput(existing.distance)))setPriorityStr(String(existing.priority))setDelayStr(String(existing.deactivationDelay))setSyncIntervalStr(String(existing.syncInterval))@@ -81,7 +82,8 @@ export function ProfileEditorScreen({ navigation, route }: any) {setter(value)const num = Number(value)if (!isNaN(num) && num >= min) {- setProfile((prev) => ({ ...prev, [field]: num }))+ const stored = field === "distance" ? inputToMeters(num) : num+ setProfile((prev) => ({ ...prev, [field]: stored }))}},[]@@ -273,7 +275,7 @@ export function ProfileEditorScreen({ navigation, route }: any) {placeholder="0"placeholderTextColor={colors.placeholder}/>- <Text style={[styles.unit, { color: colors.textSecondary }]}>m</Text>+ <Text style={[styles.unit, { color: colors.textSecondary }]}>{shortDistanceUnit()}</Text></View></SettingRow>diff --git a/apps/mobile/src/screens/SettingsScreen.tsx b/apps/mobile/src/screens/SettingsScreen.tsxindex 1693875f..ec5dbd0d 100644--- a/apps/mobile/src/screens/SettingsScreen.tsx+++ b/apps/mobile/src/screens/SettingsScreen.tsx@@ -13,12 +13,14 @@ import NativeLocationService from "../services/NativeLocationService"import { useTracking } from "../contexts/TrackingProvider"import { FloatingSaveIndicator } from "../components/ui/FloatingSaveIndicator"import { fonts } from "../styles/typography"-import { SectionTitle, Card, Container, Divider } from "../components"+import { SectionTitle, Card, Container, Divider, SettingRow } from "../components"import { ChevronRight } from "lucide-react-native"import { StatsCard } from "../components"import { logger } from "../utils/logger"import { ConnectionSettings } from "../components/features/settings/ConnectionSettings"import { SyncStrategySettings } from "../components/features/settings/SyncStrategySettings"+import { loadDisplayPreferences, getUnitSystem, getTimeFormat } from "../utils/geo"+import type { UnitSystem, TimeFormat } from "../utils/geo"/*** Settings screen for configuring location tracking.@@ -36,6 +38,40 @@ export function SettingsScreen({ navigation }: ScreenProps) {// Endpoint input (managed here since ConnectionSettings needs it and we sync with settings)const [endpointInput, setEndpointInput] = useState(settings.endpoint || "")+ // Display preferences (preselect from locale if not yet saved)+ const [unitSystem, setUnitSystem] = useState<UnitSystem>(getUnitSystem)+ const [timeFormat, setTimeFormat] = useState<TimeFormat>(getTimeFormat)++ const toggleUnitSystem = useCallback(+ async (imperial: boolean) => {+ const value: UnitSystem = imperial ? "imperial" : "metric"+ const prev = unitSystem+ setUnitSystem(value)+ try {+ await NativeLocationService.saveSetting("unitSystem", value)+ await loadDisplayPreferences()+ } catch {+ setUnitSystem(prev)+ }+ },+ [unitSystem]+ )++ const toggleTimeFormat = useCallback(+ async (use12h: boolean) => {+ const value: TimeFormat = use12h ? "12h" : "24h"+ const prev = timeFormat+ setTimeFormat(value)+ try {+ await NativeLocationService.saveSetting("timeFormat", value)+ await loadDisplayPreferences()+ } catch {+ setTimeFormat(prev)+ }+ },+ [timeFormat]+ )+// Sync endpoint input with settings changesuseEffect(() => {setEndpointInput(settings.endpoint || "")@@ -126,10 +162,7 @@ export function SettingsScreen({ navigation }: ScreenProps) {<View style={styles.section}><SectionTitle>Appearance</SectionTitle><Card>- <View style={styles.settingRow}>- <View style={styles.settingContent}>- <Text style={[styles.settingLabel, { color: colors.text }]}>Dark Mode</Text>- </View>+ <SettingRow label="Dark Mode"><Switchvalue={mode === "dark"}onValueChange={toggleTheme}@@ -139,7 +172,35 @@ export function SettingsScreen({ navigation }: ScreenProps) {}}thumbColor={mode === "dark" ? colors.primary : colors.border}/>- </View>+ </SettingRow>++ <Divider />++ <SettingRow label="Imperial Units" hint="Use miles, feet, and mph">+ <Switch+ value={unitSystem === "imperial"}+ onValueChange={toggleUnitSystem}+ trackColor={{+ false: colors.border,+ true: colors.primary + "80"+ }}+ thumbColor={unitSystem === "imperial" ? colors.primary : colors.border}+ />+ </SettingRow>++ <Divider />++ <SettingRow label="12-Hour Time" hint="Use AM/PM instead of 24-hour format">+ <Switch+ value={timeFormat === "12h"}+ onValueChange={toggleTimeFormat}+ trackColor={{+ false: colors.border,+ true: colors.primary + "80"+ }}+ thumbColor={timeFormat === "12h" ? colors.primary : colors.border}+ />+ </SettingRow></Card></View>@@ -211,21 +272,6 @@ const styles = StyleSheet.create({section: {marginBottom: 24},- settingRow: {- flexDirection: "row",- justifyContent: "space-between",- alignItems: "center",- paddingVertical: 4- },- settingContent: {- flex: 1,- marginRight: 16- },- settingLabel: {- fontSize: 16,- ...fonts.semiBold,- marginBottom: 2- },linkRow: {flexDirection: "row",justifyContent: "space-between",diff --git a/apps/mobile/src/utils/__tests__/geo.test.ts b/apps/mobile/src/utils/__tests__/geo.test.tsindex 43587ec3..e2c22178 100644--- a/apps/mobile/src/utils/__tests__/geo.test.ts+++ b/apps/mobile/src/utils/__tests__/geo.test.ts@@ -1,4 +1,44 @@-import { computeTotalDistance, formatDistance, formatSpeed } from "../geo"+import {+ computeTotalDistance,+ formatDistance,+ formatShortDistance,+ formatSpeed,+ formatTime,+ shortDistanceUnit,+ inputToMeters,+ metersToInput,+ getSpeedUnit,+ loadDisplayPreferences,+ getUnitSystem,+ getTimeFormat+} from "../geo"++const mockGetSetting = jest.fn()++jest.mock("../../services/NativeLocationService", () => ({+ __esModule: true,+ default: {+ getSetting: (...args) => mockGetSetting(...args)+ }+}))++/** Helper to set cached preferences via loadDisplayPreferences */+async function setPreferences(unit, time) {+ mockGetSetting.mockImplementation((key) => {+ if (key === "unitSystem") return Promise.resolve(unit)+ if (key === "timeFormat") return Promise.resolve(time)+ return Promise.resolve("")+ })+ await loadDisplayPreferences()+}++/** Helper to mock locale */+function mockLocale(locale) {+ // @ts-ignore - mock Intl+ Intl.NumberFormat = jest.fn(() => ({+ resolvedOptions: () => ({ locale })+ }))+}describe("computeTotalDistance", () => {it("returns 0 for empty array", () => {@@ -10,7 +50,7 @@ describe("computeTotalDistance", () => {})it("calculates distance between two known points", () => {- // Berlin (52.52, 13.405) → Munich (48.1351, 11.582) ≈ 504 km+ // Berlin (52.52, 13.405) -> Munich (48.1351, 11.582) ~ 504 kmconst locations = [{ latitude: 52.52, longitude: 13.405 },{ latitude: 48.1351, longitude: 11.582 }@@ -26,7 +66,6 @@ describe("computeTotalDistance", () => {{ latitude: 52.53, longitude: 13.405 },{ latitude: 52.54, longitude: 13.405 }]- // Two hops of ~1.11 km each ≈ 2.22 km totalconst meters = computeTotalDistance(locations)expect(meters).toBeGreaterThan(2000)expect(meters).toBeLessThan(2500)@@ -42,51 +81,42 @@ describe("computeTotalDistance", () => {})describe("formatDistance", () => {- let originalNumberFormat: typeof Intl.NumberFormat+ let originalNumberFormatbeforeEach(() => {originalNumberFormat = Intl.NumberFormat})- afterEach(() => {- // @ts-ignore – restore original+ afterEach(async () => {+ // @ts-ignore - restore originalIntl.NumberFormat = originalNumberFormat+ await setPreferences("", "")})- it("formats as km for non-US locales", () => {- // @ts-ignore – mock Intl- Intl.NumberFormat = jest.fn(() => ({- resolvedOptions: () => ({ locale: "de-DE" })- }))+ it("formats as km for metric", async () => {+ await setPreferences("metric", "")expect(formatDistance(12345)).toBe("12.3 km")})- it("formats as miles for en-US locale", () => {- // @ts-ignore – mock Intl- Intl.NumberFormat = jest.fn(() => ({- resolvedOptions: () => ({ locale: "en-US" })- }))+ it("formats as miles for imperial", async () => {+ await setPreferences("imperial", "")expect(formatDistance(1609.344)).toBe("1.0 mi")})- it("formats as miles for en-GB locale", () => {- // @ts-ignore – mock Intl- Intl.NumberFormat = jest.fn(() => ({- resolvedOptions: () => ({ locale: "en-GB" })- }))- expect(formatDistance(8046.72)).toBe("5.0 mi")+ it("falls back to locale when no preference saved", async () => {+ await setPreferences("", "")+ mockLocale("en-US")+ expect(formatDistance(1609.344)).toBe("1.0 mi")})- it("formats 0 meters correctly", () => {- // @ts-ignore – mock Intl- Intl.NumberFormat = jest.fn(() => ({- resolvedOptions: () => ({ locale: "de-DE" })- }))+ it("formats 0 meters correctly", async () => {+ await setPreferences("metric", "")expect(formatDistance(0)).toBe("0.0 km")})- it("falls back to km if Intl throws", () => {- // @ts-ignore – mock Intl to throw+ it("falls back to km if Intl throws and no preference", async () => {+ await setPreferences("", "")+ // @ts-ignore - mock Intl to throwIntl.NumberFormat = jest.fn(() => {throw new Error("unsupported")})@@ -94,49 +124,165 @@ describe("formatDistance", () => {})})-describe("formatSpeed", () => {- let originalNumberFormat: typeof Intl.NumberFormat+describe("formatShortDistance", () => {+ afterEach(async () => {+ await setPreferences("", "")+ })- beforeEach(() => {- originalNumberFormat = Intl.NumberFormat+ it("formats as meters for metric", async () => {+ await setPreferences("metric", "")+ expect(formatShortDistance(50)).toBe("50m")})- afterEach(() => {- // @ts-ignore – restore original- Intl.NumberFormat = originalNumberFormat+ it("formats as feet for imperial", async () => {+ await setPreferences("imperial", "")+ expect(formatShortDistance(50)).toBe("164 ft")+ })++ it("rounds to nearest foot", async () => {+ await setPreferences("imperial", "")+ expect(formatShortDistance(1)).toBe("3 ft")+ })+})++describe("formatSpeed", () => {+ afterEach(async () => {+ await setPreferences("", "")})- it("formats as km/h for non-US locales", () => {- // @ts-ignore – mock Intl- Intl.NumberFormat = jest.fn(() => ({- resolvedOptions: () => ({ locale: "de-DE" })- }))- // 2 m/s = 7.2 km/h+ it("formats as km/h for metric", async () => {+ await setPreferences("metric", "")expect(formatSpeed(2)).toBe("7.2 km/h")})- it("formats as mph for en-US locale", () => {- // @ts-ignore – mock Intl- Intl.NumberFormat = jest.fn(() => ({- resolvedOptions: () => ({ locale: "en-US" })- }))- // 2 m/s ≈ 4.5 mph+ it("formats as mph for imperial", async () => {+ await setPreferences("imperial", "")expect(formatSpeed(2)).toBe("4.5 mph")})- it("formats 0 m/s correctly", () => {- // @ts-ignore – mock Intl- Intl.NumberFormat = jest.fn(() => ({- resolvedOptions: () => ({ locale: "de-DE" })- }))+ it("formats 0 m/s correctly", async () => {+ await setPreferences("metric", "")expect(formatSpeed(0)).toBe("0.0 km/h")})+})- it("falls back to km/h if Intl throws", () => {- // @ts-ignore – mock Intl to throw- Intl.NumberFormat = jest.fn(() => {- throw new Error("unsupported")- })- expect(formatSpeed(8)).toBe("28.8 km/h")+describe("getSpeedUnit", () => {+ afterEach(async () => {+ await setPreferences("", "")+ })++ it("returns km/h for metric", async () => {+ await setPreferences("metric", "")+ expect(getSpeedUnit()).toEqual({ factor: 3.6, unit: "km/h" })+ })++ it("returns mph for imperial", async () => {+ await setPreferences("imperial", "")+ expect(getSpeedUnit()).toEqual({ factor: 2.23694, unit: "mph" })+ })+})++describe("shortDistanceUnit", () => {+ afterEach(async () => {+ await setPreferences("", "")+ })++ it("returns m for metric", async () => {+ await setPreferences("metric", "")+ expect(shortDistanceUnit()).toBe("m")+ })++ it("returns ft for imperial", async () => {+ await setPreferences("imperial", "")+ expect(shortDistanceUnit()).toBe("ft")+ })+})++describe("inputToMeters", () => {+ afterEach(async () => {+ await setPreferences("", "")+ })++ it("returns value unchanged for metric", async () => {+ await setPreferences("metric", "")+ expect(inputToMeters(50)).toBe(50)+ })++ it("converts feet to meters for imperial", async () => {+ await setPreferences("imperial", "")+ const result = inputToMeters(164)+ expect(result).toBeCloseTo(49.987, 1)+ })+})++describe("metersToInput", () => {+ afterEach(async () => {+ await setPreferences("", "")+ })++ it("returns value unchanged for metric", async () => {+ await setPreferences("metric", "")+ expect(metersToInput(50)).toBe(50)+ })++ it("converts meters to feet for imperial", async () => {+ await setPreferences("imperial", "")+ expect(metersToInput(50)).toBe(164)+ })++ it("round-trips without significant drift", async () => {+ await setPreferences("imperial", "")+ const feet = metersToInput(50)+ const backToMeters = inputToMeters(feet)+ expect(backToMeters).toBeCloseTo(50, 0)+ })+})++describe("loadDisplayPreferences", () => {+ afterEach(async () => {+ await setPreferences("", "")+ })++ it("loads metric/24h", async () => {+ await setPreferences("metric", "24h")+ expect(getUnitSystem()).toBe("metric")+ expect(getTimeFormat()).toBe("24h")+ })++ it("loads imperial/12h", async () => {+ await setPreferences("imperial", "12h")+ expect(getUnitSystem()).toBe("imperial")+ expect(getTimeFormat()).toBe("12h")+ })++ it("falls back to locale for invalid values", async () => {+ await setPreferences("invalid", "invalid")+ const unit = getUnitSystem()+ expect(unit === "metric" || unit === "imperial").toBe(true)+ })++ it("handles native storage error gracefully", async () => {+ mockGetSetting.mockRejectedValue(new Error("storage error"))+ await loadDisplayPreferences()+ const unit = getUnitSystem()+ expect(unit === "metric" || unit === "imperial").toBe(true)+ })+})++describe("formatTime", () => {+ afterEach(async () => {+ await setPreferences("", "")+ })++ it("respects 24h format preference", async () => {+ await setPreferences("", "24h")+ const result = formatTime(1700000000)+ expect(result).not.toMatch(/am|pm/i)+ })++ it("respects 12h format preference", async () => {+ await setPreferences("", "12h")+ const result = formatTime(1700000000)+ expect(result).toMatch(/am|pm/i)})})diff --git a/apps/mobile/src/utils/geo.ts b/apps/mobile/src/utils/geo.tsindex e600ea94..8ecd9894 100644--- a/apps/mobile/src/utils/geo.ts+++ b/apps/mobile/src/utils/geo.ts@@ -3,6 +3,8 @@* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.*/+import NativeLocationService from "../services/NativeLocationService"+const EARTH_RADIUS_METERS = 6371000.0/** Haversine formula - mirrors GeofenceHelper.kt */@@ -29,9 +31,61 @@ export function computeTotalDistance(locations: { latitude: number; longitude: nreturn total}+// -- Display preferences (cached from SQLite) --++export type UnitSystem = "metric" | "imperial"+export type TimeFormat = "12h" | "24h"++let cachedUnitSystem: UnitSystem | null = null+let cachedTimeFormat: TimeFormat | null = null++/** Detect whether the device locale uses 12h time. */+function localeUses12h(): boolean {+ try {+ const sample = new Date(2000, 0, 1, 14).toLocaleTimeString(undefined, { hour: "numeric" })+ return /am|pm/i.test(sample)+ } catch {+ return false+ }+}++/** Resolve the effective unit system, using locale detection as fallback. */+function resolveUnitSystem(): UnitSystem {+ return cachedUnitSystem ?? (localeUsesMiles() ? "imperial" : "metric")+}++/** Resolve the effective time format, using locale detection as fallback. */+function resolveTimeFormat(): TimeFormat {+ return cachedTimeFormat ?? (localeUses12h() ? "12h" : "24h")+}++/** Load display preferences from native storage. Call on app start and after saving. */+export async function loadDisplayPreferences(): Promise<void> {+ try {+ const [unit, time] = await Promise.all([+ NativeLocationService.getSetting("unitSystem", ""),+ NativeLocationService.getSetting("timeFormat", "")+ ])+ cachedUnitSystem = unit === "metric" || unit === "imperial" ? unit : null+ cachedTimeFormat = time === "12h" || time === "24h" ? time : null+ } catch {+ // Keep defaults on error+ }+}++export function getUnitSystem(): UnitSystem {+ return resolveUnitSystem()+}++export function getTimeFormat(): TimeFormat {+ return resolveTimeFormat()+}++// -- Unit detection --+const MILE_LOCALES = new Set(["en-US", "en-GB", "en-MM", "en-LR"])-function usesMiles(): boolean {+function localeUsesMiles(): boolean {try {const locale = Intl.NumberFormat().resolvedOptions().localereturn MILE_LOCALES.has(locale)@@ -40,7 +94,13 @@ function usesMiles(): boolean {}}-/** Format m/s into a human-readable speed string using the device locale's unit. */+function usesMiles(): boolean {+ return resolveUnitSystem() === "imperial"+}++// -- Formatting functions --++/** Format m/s into a human-readable speed string. */export function formatSpeed(metersPerSecond: number): string {if (usesMiles()) {const mph = metersPerSecond * 2.23694@@ -50,7 +110,7 @@ export function formatSpeed(metersPerSecond: number): string {return `${kmh.toFixed(1)} km/h`}-/** Return the speed unit info for the current locale (used by TrackMap). */+/** Return the speed unit info (used by TrackMap). */export function getSpeedUnit(): { factor: number; unit: string } {return usesMiles() ? { factor: 2.23694, unit: "mph" } : { factor: 3.6, unit: "km/h" }}@@ -70,7 +130,8 @@ export function formatTime(unixSeconds: number, showSeconds = false): string {return d.toLocaleTimeString(undefined, {hour: "2-digit",minute: "2-digit",- ...(showSeconds && { second: "2-digit" })+ ...(showSeconds && { second: "2-digit" }),+ ...(cachedTimeFormat && { hour12: cachedTimeFormat === "12h" })})}@@ -83,12 +144,29 @@ export function formatDate(unixSeconds: number): string {})}-/** Format meters into a human-readable string using the device locale's unit. */+/** Format meters as a long distance string (e.g. "12.3 km" / "7.6 mi"). */export function formatDistance(meters: number): string {- if (usesMiles()) {- const miles = meters / 1609.344- return `${miles.toFixed(1)} mi`- }- const km = meters / 1000- return `${km.toFixed(1)} km`+ if (usesMiles()) return `${(meters / 1609.344).toFixed(1)} mi`+ return `${(meters / 1000).toFixed(1)} km`+}++/** Format meters as a short distance string (e.g. "50m" / "164 ft"). */+export function formatShortDistance(meters: number): string {+ if (usesMiles()) return `${Math.round(meters * 3.28084)} ft`+ return `${Math.round(meters)}m`+}++/** Returns the short distance unit label for input fields ("m" or "ft"). */+export function shortDistanceUnit(): string {+ return usesMiles() ? "ft" : "m"+}++/** Convert a user-entered short distance to meters. */+export function inputToMeters(value: number): number {+ return usesMiles() ? value / 3.28084 : value+}++/** Convert meters to the user's short distance unit for pre-filling inputs. */+export function metersToInput(meters: number): number {+ return usesMiles() ? Math.round(meters * 3.28084) : meters}