Skip to content

Colota - Android GPS Location tracker

Refactor settings screens: extract hooks, components, and centralize constants

Max Dietrich6aafc090fd08
diff --git a/src/components/features/settings/ConnectionSettings.tsx b/src/components/features/settings/ConnectionSettings.tsx
new file mode 100644
index 00000000..a392b8ef
--- /dev/null
+++ b/src/components/features/settings/ConnectionSettings.tsx
@@ -0,0 +1,326 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+import React, { useState, useCallback } from "react"
+import { Text, StyleSheet, TextInput, Switch, View, TouchableOpacity } from "react-native"
+import { Settings, ThemeColors } from "../../../types/global"
+import NativeLocationService from "../../../services/NativeLocationService"
+import { isPrivateHost, isEndpointAllowed } from "../../../utils/settingsValidation"
+import { Button, Card, SectionTitle, Divider } from "../../index"
+
+interface ConnectionSettingsProps {
+ settings: Settings
+ endpointInput: string
+ onEndpointInputChange: (value: string) => void
+ onSettingsChange: (newSettings: Settings) => void
+ colors: ThemeColors
+ navigation: any
+}
+
+export function ConnectionSettings({
+ settings,
+ endpointInput,
+ onEndpointInputChange,
+ onSettingsChange,
+ colors,
+ navigation
+}: ConnectionSettingsProps) {
+ const [testing, setTesting] = useState(false)
+ const [testResponse, setTestResponse] = useState<string | null>(null)
+ const [testError, setTestError] = useState(false)
+
+ const handleOfflineModeChange = useCallback(
+ (enabled: boolean) => {
+ onSettingsChange({ ...settings, isOfflineMode: enabled })
+ },
+ [settings, onSettingsChange]
+ )
+
+ const handleTestEndpoint = useCallback(async () => {
+ if (!endpointInput) return
+ setTesting(true)
+ setTestResponse(null)
+ setTestError(false)
+
+ try {
+ const recentLocation = await NativeLocationService.getMostRecentLocation()
+ if (!recentLocation) {
+ setTestResponse("No location available yet. Start tracking first.")
+ setTestError(true)
+ return
+ }
+
+ const fieldMap = settings.fieldMap
+ const payload: Record<string, number | boolean> = {
+ [fieldMap.lat]: recentLocation.latitude,
+ [fieldMap.lon]: recentLocation.longitude,
+ [fieldMap.acc]: Math.round(recentLocation.accuracy)
+ }
+
+ if (fieldMap.alt) payload[fieldMap.alt] = 0
+ if (fieldMap.vel) payload[fieldMap.vel] = 0
+ if (fieldMap.batt) payload[fieldMap.batt] = 0
+ if (fieldMap.bs) payload[fieldMap.bs] = 0
+ if (fieldMap.tst) {
+ payload[fieldMap.tst] = Math.floor(Date.now() / 1000)
+ }
+
+ let authHeaders: Record<string, string> = {}
+ try {
+ authHeaders = await NativeLocationService.getAuthHeaders()
+ } catch {
+ // proceed without auth headers
+ }
+
+ const response = await fetch(endpointInput, {
+ method: "POST",
+ headers: { "Content-Type": "application/json", ...authHeaders },
+ body: JSON.stringify(payload)
+ })
+
+ if (response.ok) {
+ setTestResponse("✓ Connection successful")
+ onSettingsChange({ ...settings, endpoint: endpointInput })
+ } else {
+ setTestResponse(`Failed: ${response.status}`)
+ setTestError(true)
+ }
+ } catch (err: any) {
+ setTestResponse(err.message || "Connection failed")
+ setTestError(true)
+ } finally {
+ setTesting(false)
+ setTimeout(() => setTestResponse(null), 3000)
+ }
+ }, [endpointInput, settings, onSettingsChange])
+
+ return (
+ <View style={styles.section}>
+ <SectionTitle>Connection</SectionTitle>
+ <Card>
+ <View style={styles.settingRow}>
+ <View style={styles.settingContent}>
+ <Text style={[styles.settingLabel, { color: colors.text }]}>Offline Mode</Text>
+ <Text style={[styles.settingHint, { color: colors.textSecondary }]}>Save locally, no network sync</Text>
+ </View>
+ <Switch
+ value={settings.isOfflineMode}
+ onValueChange={handleOfflineModeChange}
+ trackColor={{
+ false: colors.border,
+ true: colors.primary + "80"
+ }}
+ thumbColor={settings.isOfflineMode ? colors.primary : "#f4f3f4"}
+ />
+ </View>
+
+ {!settings.isOfflineMode && (
+ <>
+ <Divider />
+
+ <View style={styles.inputGroup}>
+ <View style={styles.inputHeader}>
+ <Text style={[styles.inputLabel, { color: colors.text }]}>Server Endpoint</Text>
+ {endpointInput && (
+ <View
+ style={[
+ styles.protocolBadge,
+ {
+ backgroundColor: endpointInput.startsWith("https://")
+ ? colors.success + "20"
+ : colors.warning + "20"
+ }
+ ]}
+ >
+ <Text
+ style={[
+ styles.protocolText,
+ {
+ color: endpointInput.startsWith("https://") ? colors.success : colors.warning
+ }
+ ]}
+ >
+ {endpointInput.startsWith("https://") ? "HTTPS" : "HTTP"}
+ </Text>
+ </View>
+ )}
+ </View>
+
+ <TextInput
+ style={[
+ styles.input,
+ {
+ borderColor: colors.border,
+ color: colors.text,
+ backgroundColor: colors.background
+ }
+ ]}
+ value={endpointInput}
+ onChangeText={onEndpointInputChange}
+ placeholder="https://your-server.com/api/locations"
+ placeholderTextColor={colors.placeholder}
+ autoCapitalize="none"
+ autoCorrect={false}
+ keyboardType="url"
+ />
+
+ {endpointInput.startsWith("http://") && !isPrivateHost(endpointInput) && (
+ <Text style={[styles.httpWarning, { color: colors.warning }]}>
+ HTTP only allowed for private IPs / localhost
+ </Text>
+ )}
+ </View>
+
+ <Button
+ style={[
+ styles.testButton,
+ { backgroundColor: colors.primary },
+ (!endpointInput || !isEndpointAllowed(endpointInput)) && styles.disabledButton
+ ]}
+ onPress={() => {
+ if (!endpointInput || !isEndpointAllowed(endpointInput)) return
+ handleTestEndpoint()
+ }}
+ title={testing ? "Testing..." : "Test Connection"}
+ color="#f8f7f7"
+ />
+
+ {testResponse && (
+ <View
+ style={[
+ styles.responseBox,
+ {
+ borderColor: testError ? colors.error : colors.success,
+ backgroundColor: (testError ? colors.error : colors.success) + "15"
+ }
+ ]}
+ >
+ <Text style={[styles.responseText, { color: testError ? colors.error : colors.success }]}>
+ {testResponse}
+ </Text>
+ </View>
+ )}
+
+ <Divider />
+
+ <TouchableOpacity
+ style={styles.linkRow}
+ onPress={() => navigation.navigate("Auth Settings")}
+ activeOpacity={0.6}
+ >
+ <View style={styles.linkContent}>
+ <Text style={[styles.linkLabel, { color: colors.text }]}>Authentication & Headers</Text>
+ <Text style={[styles.linkSub, { color: colors.textSecondary }]}>
+ Basic auth, bearer tokens, custom headers
+ </Text>
+ </View>
+ <Text style={[styles.linkArrow, { color: colors.textLight }]}>›</Text>
+ </TouchableOpacity>
+ </>
+ )}
+ </Card>
+ </View>
+ )
+}
+
+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,
+ fontWeight: "600",
+ marginBottom: 2
+ },
+ settingHint: {
+ fontSize: 13,
+ lineHeight: 18
+ },
+ inputGroup: {
+ marginBottom: 12
+ },
+ inputHeader: {
+ flexDirection: "row",
+ justifyContent: "space-between",
+ alignItems: "center",
+ marginBottom: 10
+ },
+ inputLabel: {
+ fontSize: 15,
+ fontWeight: "600"
+ },
+ protocolBadge: {
+ paddingHorizontal: 10,
+ paddingVertical: 4,
+ borderRadius: 12
+ },
+ protocolText: {
+ fontSize: 11,
+ fontWeight: "700"
+ },
+ input: {
+ borderWidth: 1.5,
+ padding: 16,
+ borderRadius: 12,
+ fontSize: 15
+ },
+ testButton: {
+ padding: 16,
+ borderRadius: 12,
+ alignItems: "center",
+ marginTop: 12
+ },
+ disabledButton: {
+ opacity: 0.5
+ },
+ responseBox: {
+ marginTop: 12,
+ padding: 14,
+ borderWidth: 1.5,
+ borderRadius: 12,
+ alignItems: "center"
+ },
+ responseText: {
+ fontSize: 14,
+ fontWeight: "600"
+ },
+ linkRow: {
+ flexDirection: "row",
+ justifyContent: "space-between",
+ alignItems: "center",
+ paddingVertical: 12
+ },
+ linkContent: {
+ flex: 1
+ },
+ linkLabel: {
+ fontSize: 16,
+ fontWeight: "600",
+ marginBottom: 2
+ },
+ linkSub: {
+ fontSize: 13
+ },
+ linkArrow: {
+ fontSize: 28,
+ fontWeight: "300",
+ marginLeft: 12
+ },
+ httpWarning: {
+ marginTop: 6,
+ fontSize: 12,
+ fontWeight: "500"
+ }
+})
diff --git a/src/components/features/settings/ServerConnection.tsx b/src/components/features/settings/ServerConnection.tsx
index d506b841..0ee32052 100644
--- a/src/components/features/settings/ServerConnection.tsx
+++ b/src/components/features/settings/ServerConnection.tsx
@@ -10,9 +10,7 @@ import { useTheme } from "../../../hooks/useTheme"
import { useTracking } from "../../../contexts/TrackingProvider"
import { ServerStatus, ServerConnectionProps } from "../../../types/global"
import NativeLocationService from "../../../services/NativeLocationService"
-
-const SERVER_TIMEOUT = 5000
-const SERVER_CHECK_INTERVAL = 5 * 60 * 1000
+import { SERVER_TIMEOUT, SERVER_CHECK_INTERVAL } from "../../../constants"
export function ServerConnection({ endpoint, navigation }: ServerConnectionProps) {
const { colors } = useTheme()
diff --git a/src/components/features/settings/StatsCard.tsx b/src/components/features/settings/StatsCard.tsx
index a7bb5f13..8af345d2 100644
--- a/src/components/features/settings/StatsCard.tsx
+++ b/src/components/features/settings/StatsCard.tsx
@@ -6,6 +6,7 @@ import React from "react"
import { View, Text, StyleSheet, TouchableOpacity } from "react-native"
import { ThemeColors } from "../../../types/global"
import { getQueueColor } from "../../../utils/queueStatus"
+import { HIGH_QUEUE_THRESHOLD, CRITICAL_QUEUE_THRESHOLD } from "../../../constants"
interface StatsCardProps {
queueCount: number
@@ -18,9 +19,6 @@ interface StatsCardProps {
type WarningLevel = "normal" | "warning" | "critical"
-const HIGH_QUEUE_THRESHOLD = 50
-const CRITICAL_QUEUE_THRESHOLD = 100
-
/**
* StatsCard Component - Improved Design
*
diff --git a/src/components/features/settings/SyncStrategySettings.tsx b/src/components/features/settings/SyncStrategySettings.tsx
new file mode 100644
index 00000000..eb8ed31d
--- /dev/null
+++ b/src/components/features/settings/SyncStrategySettings.tsx
@@ -0,0 +1,493 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+import React, { useState, useCallback, useEffect } from "react"
+import { Text, StyleSheet, Switch, View, TouchableOpacity } from "react-native"
+import { Settings, TRACKING_PRESETS, SyncPreset, SelectablePreset, ThemeColors } from "../../../types/global"
+import { SectionTitle, Card, Divider, NumericInput } from "../../index"
+import { PresetOption } from "./PresetOption"
+
+interface SyncStrategySettingsProps {
+ settings: Settings
+ onSettingsChange: (newSettings: Settings) => void
+ onDebouncedSave: (newSettings: Settings) => void
+ onImmediateSave: (newSettings: Settings) => void
+ colors: ThemeColors
+}
+
+export function SyncStrategySettings({
+ settings,
+ onSettingsChange,
+ onDebouncedSave,
+ onImmediateSave,
+ colors
+}: SyncStrategySettingsProps) {
+ const [intervalInput, setIntervalInput] = useState(settings.interval.toString())
+ const [distanceInput, setDistanceInput] = useState(settings.distance?.toString() || "0")
+ const [accuracyTresholdInput, setAccuracyTresholdInput] = useState(settings.accuracyThreshold.toString())
+ const [showAdvanced, setShowAdvanced] = useState(false)
+
+ // Sync inputs with settings changes
+ useEffect(() => {
+ setIntervalInput(settings.interval.toString())
+ setDistanceInput(settings.distance?.toString() || "0")
+ }, [settings.interval, settings.distance])
+
+ const handleNumericChange = useCallback(
+ (key: "interval" | "distance" | "accuracyTreshold", value: string, min: number = 0) => {
+ if (key === "interval") setIntervalInput(value)
+ if (key === "distance") setDistanceInput(value)
+ if (key === "accuracyTreshold") setAccuracyTresholdInput(value)
+
+ const num = Number(value)
+ if (!isNaN(num) && num >= min) {
+ const next = { ...settings, [key]: num, syncPreset: "custom" as const }
+ onSettingsChange(next)
+ onDebouncedSave(next)
+ }
+ },
+ [settings, onSettingsChange, onDebouncedSave]
+ )
+
+ const handleNumericBlur = useCallback(
+ (key: "interval" | "distance" | "accuracyTreshold", min: number = 0) => {
+ const currentStr = key === "interval" ? intervalInput : key === "distance" ? distanceInput : accuracyTresholdInput
+ let val = Number(currentStr)
+
+ if (isNaN(val) || val < min) {
+ val = min
+ if (key === "interval") setIntervalInput(min.toString())
+ if (key === "distance") setDistanceInput(min.toString())
+ if (key === "accuracyTreshold") setAccuracyTresholdInput(min.toString())
+
+ const next = { ...settings, [key]: val }
+ onSettingsChange(next)
+ onImmediateSave(next)
+ }
+ },
+ [intervalInput, distanceInput, accuracyTresholdInput, settings, onSettingsChange, onImmediateSave]
+ )
+
+ const handlePresetSelect = useCallback(
+ (preset: SyncPreset) => {
+ if (preset === "custom") {
+ const next = { ...settings, syncPreset: "custom" as const }
+ onSettingsChange(next)
+ onImmediateSave(next)
+ return
+ }
+
+ const config = TRACKING_PRESETS[preset]
+ const next: Settings = {
+ ...settings,
+ syncPreset: preset,
+ interval: config.interval,
+ distance: config.distance,
+ syncInterval: config.syncInterval,
+ retryInterval: config.retryInterval
+ }
+
+ onImmediateSave(next)
+ },
+ [settings, onSettingsChange, onImmediateSave]
+ )
+
+ const handleGridSelect = useCallback(
+ (key: string, value: number) => {
+ const next = {
+ ...settings,
+ [key]: value,
+ syncPreset: "custom" as const
+ }
+ onSettingsChange(next)
+ onDebouncedSave(next)
+ },
+ [settings, onSettingsChange, onDebouncedSave]
+ )
+
+ return (
+ <View style={styles.section}>
+ <SectionTitle>Sync Strategy</SectionTitle>
+ <Card>
+ <View style={styles.presetsContainer}>
+ {(Object.keys(TRACKING_PRESETS) as SelectablePreset[]).map((preset, index) => (
+ <View key={preset}>
+ <PresetOption
+ preset={preset}
+ isSelected={settings.syncPreset === preset}
+ onSelect={handlePresetSelect}
+ colors={colors}
+ />
+ {index < Object.keys(TRACKING_PRESETS).length - 1 && <View style={styles.presetSpacer} />}
+ </View>
+ ))}
+ </View>
+
+ <TouchableOpacity
+ style={[
+ styles.advancedToggle,
+ showAdvanced ? styles.advancedToggleActive : styles.advancedToggleInactive,
+ { borderColor: showAdvanced ? colors.primary : colors.border }
+ ]}
+ onPress={() => setShowAdvanced(!showAdvanced)}
+ activeOpacity={0.7}
+ >
+ <Text style={[styles.advancedText, { color: colors.primary }]}>
+ {showAdvanced ? "− Hide" : "+ Show"} Advanced Settings
+ </Text>
+ </TouchableOpacity>
+
+ {showAdvanced && (
+ <View style={styles.advancedPanel}>
+ <Divider />
+
+ {settings.syncPreset === "custom" && (
+ <View
+ style={[
+ styles.customBanner,
+ {
+ backgroundColor: colors.info + "15",
+ borderLeftColor: colors.info
+ }
+ ]}
+ >
+ <Text style={[styles.customBannerText, { color: colors.info }]}>💡 Using custom configuration</Text>
+ </View>
+ )}
+
+ {/* Tracking Parameters Group */}
+ <View style={styles.paramGroup}>
+ <Text style={[styles.paramGroupTitle, { color: colors.text }]}>Tracking Parameters</Text>
+
+ <NumericInput
+ label="Tracking Interval"
+ value={intervalInput}
+ onChange={(val) => handleNumericChange("interval", val, 1)}
+ onBlur={() => handleNumericBlur("interval", 1)}
+ unit="seconds"
+ placeholder="1"
+ hint="How often to capture GPS position"
+ colors={colors}
+ />
+
+ <NumericInput
+ label="Movement Threshold"
+ value={distanceInput}
+ onChange={(val) => handleNumericChange("distance", val, 0)}
+ onBlur={() => handleNumericBlur("distance", 0)}
+ unit="meters"
+ placeholder="10"
+ hint="Only record if moved more than this distance"
+ colors={colors}
+ />
+ </View>
+
+ <Divider />
+
+ {/* Network Parameters Group */}
+ <View style={styles.paramGroup}>
+ <Text style={[styles.paramGroupTitle, { color: colors.text }]}>Network Settings</Text>
+
+ {/* Sync Interval */}
+ <View style={styles.settingBlock}>
+ <Text style={[styles.blockLabel, { color: colors.text }]}>Sync Interval</Text>
+ <Text style={[styles.blockHint, { color: colors.textSecondary }]}>
+ How often to upload data to server
+ </Text>
+
+ <View style={styles.optionsGrid}>
+ {([0, 60, 300, 900] as const).map((sec) => {
+ const labels: Record<number, string> = {
+ 0: "Instant",
+ 60: "1 min",
+ 300: "5 min",
+ 900: "15 min"
+ }
+ const isSelected = settings.syncInterval === sec
+
+ return (
+ <TouchableOpacity
+ key={sec}
+ style={[
+ styles.gridOption,
+ {
+ borderColor: colors.border,
+ backgroundColor: colors.background
+ },
+ isSelected && {
+ borderColor: colors.primary,
+ backgroundColor: colors.primary + "20"
+ }
+ ]}
+ onPress={() => handleGridSelect("syncInterval", sec)}
+ activeOpacity={0.7}
+ >
+ <Text style={[styles.gridLabel, { color: isSelected ? colors.primary : colors.text }]}>
+ {labels[sec]}
+ </Text>
+ </TouchableOpacity>
+ )
+ })}
+ </View>
+ </View>
+
+ {/* Retry Interval */}
+ <View style={styles.settingBlock}>
+ <Text style={[styles.blockLabel, { color: colors.text }]}>Retry Interval</Text>
+ <Text style={[styles.blockHint, { color: colors.textSecondary }]}>
+ Wait time before retrying failed uploads
+ </Text>
+
+ <View style={styles.optionsGrid}>
+ {([30, 300, 900] as const).map((sec) => {
+ const labels: Record<number, string> = {
+ 30: "30s",
+ 300: "5m",
+ 900: "15m"
+ }
+ const isSelected = settings.retryInterval === sec
+
+ return (
+ <TouchableOpacity
+ key={sec}
+ style={[
+ styles.gridOption,
+ {
+ borderColor: colors.border,
+ backgroundColor: colors.background
+ },
+ isSelected && {
+ borderColor: colors.primary,
+ backgroundColor: colors.primary + "20"
+ }
+ ]}
+ onPress={() => handleGridSelect("retryInterval", sec)}
+ activeOpacity={0.7}
+ >
+ <Text style={[styles.gridLabel, { color: isSelected ? colors.primary : colors.text }]}>
+ {labels[sec]}
+ </Text>
+ </TouchableOpacity>
+ )
+ })}
+ </View>
+ </View>
+
+ {/* Max Retries */}
+ <View style={styles.settingBlock}>
+ <Text style={[styles.blockLabel, { color: colors.text }]}>Max Retry Attempts</Text>
+ <View style={styles.retryGrid}>
+ {[3, 5, 10, 0].map((val) => (
+ <TouchableOpacity
+ key={val}
+ style={[
+ styles.retryChip,
+ {
+ borderColor: colors.border,
+ backgroundColor: colors.background
+ },
+ settings.maxRetries === val && {
+ borderColor: colors.primary,
+ backgroundColor: colors.primary + "20"
+ }
+ ]}
+ onPress={() => handleGridSelect("maxRetries", val)}
+ activeOpacity={0.7}
+ >
+ <Text
+ style={[
+ styles.retryChipText,
+ { color: settings.maxRetries === val ? colors.primary : colors.text }
+ ]}
+ >
+ {val === 0 ? "∞" : val}
+ </Text>
+ </TouchableOpacity>
+ ))}
+ </View>
+ <Text style={[styles.blockHint, styles.retryHint, { color: colors.textSecondary }]}>
+ {settings.maxRetries === 0
+ ? "⚠️ Unlimited retries may cause queue buildup"
+ : `Give up after ${settings.maxRetries} failed attempts`}
+ </Text>
+ </View>
+ </View>
+
+ <Divider />
+
+ {/* Quality Parameters Group */}
+ <View style={styles.paramGroup}>
+ <Text style={[styles.paramGroupTitle, { color: colors.text }]}>Quality Filters</Text>
+
+ <View style={styles.settingRow}>
+ <View style={styles.settingContent}>
+ <Text style={[styles.settingLabel, { color: colors.text }]}>Filter Inaccurate Locations</Text>
+ <Text style={[styles.settingHint, { color: colors.textSecondary }]}>
+ Reject low-accuracy GPS readings
+ </Text>
+ </View>
+ <Switch
+ value={settings.filterInaccurateLocations}
+ onValueChange={(value) =>
+ onImmediateSave({
+ ...settings,
+ filterInaccurateLocations: value
+ })
+ }
+ trackColor={{
+ false: colors.border,
+ true: colors.primary + "80"
+ }}
+ thumbColor={settings.filterInaccurateLocations ? colors.primary : "#f4f3f4"}
+ />
+ </View>
+
+ {settings.filterInaccurateLocations && (
+ <View style={styles.nestedSetting}>
+ <NumericInput
+ label="Accuracy Threshold"
+ value={accuracyTresholdInput}
+ onChange={(val) => handleNumericChange("accuracyTreshold", val, 50)}
+ onBlur={() => handleNumericBlur("accuracyTreshold", 50)}
+ unit="meters"
+ placeholder="50"
+ hint="Reject readings with accuracy worse than this"
+ colors={colors}
+ />
+ </View>
+ )}
+ </View>
+ </View>
+ )}
+ </Card>
+ </View>
+ )
+}
+
+const styles = StyleSheet.create({
+ section: {
+ marginBottom: 24
+ },
+ presetsContainer: {
+ marginBottom: 16
+ },
+ presetSpacer: {
+ height: 8
+ },
+ advancedToggle: {
+ paddingVertical: 14,
+ paddingHorizontal: 16,
+ alignItems: "center",
+ borderRadius: 12,
+ borderWidth: 1.5,
+ marginTop: 8
+ },
+ advancedToggleActive: {
+ backgroundColor: "transparent"
+ },
+ advancedToggleInactive: {
+ backgroundColor: "transparent"
+ },
+ advancedText: {
+ fontSize: 15,
+ fontWeight: "600"
+ },
+ advancedPanel: {
+ marginTop: 16
+ },
+ customBanner: {
+ padding: 14,
+ borderRadius: 10,
+ marginBottom: 20,
+ borderLeftWidth: 4
+ },
+ customBannerText: {
+ fontSize: 13,
+ fontWeight: "500"
+ },
+ paramGroup: {
+ marginBottom: 4
+ },
+ paramGroupTitle: {
+ fontSize: 13,
+ fontWeight: "700",
+ textTransform: "uppercase",
+ letterSpacing: 1,
+ marginBottom: 16,
+ opacity: 0.6
+ },
+ settingBlock: {
+ marginBottom: 20
+ },
+ blockLabel: {
+ fontSize: 15,
+ fontWeight: "600",
+ marginBottom: 4
+ },
+ blockHint: {
+ fontSize: 13,
+ marginBottom: 12,
+ lineHeight: 18
+ },
+ optionsGrid: {
+ flexDirection: "row",
+ gap: 8,
+ flexWrap: "wrap"
+ },
+ gridOption: {
+ minWidth: "22%",
+ borderWidth: 2,
+ borderRadius: 10,
+ paddingVertical: 14,
+ alignItems: "center"
+ },
+ gridLabel: {
+ fontSize: 14,
+ fontWeight: "600"
+ },
+ retryGrid: {
+ flexDirection: "row",
+ gap: 10
+ },
+ retryChip: {
+ flex: 1,
+ borderWidth: 2,
+ borderRadius: 10,
+ paddingVertical: 12,
+ alignItems: "center"
+ },
+ retryChipText: {
+ fontSize: 16,
+ fontWeight: "700"
+ },
+ retryHint: {
+ marginTop: 8
+ },
+ settingRow: {
+ flexDirection: "row",
+ justifyContent: "space-between",
+ alignItems: "center",
+ paddingVertical: 4
+ },
+ settingContent: {
+ flex: 1,
+ marginRight: 16
+ },
+ settingLabel: {
+ fontSize: 16,
+ fontWeight: "600",
+ marginBottom: 2
+ },
+ settingHint: {
+ fontSize: 13,
+ lineHeight: 18
+ },
+ nestedSetting: {
+ marginTop: 12,
+ paddingLeft: 16,
+ borderLeftWidth: 3,
+ borderLeftColor: "rgba(0,0,0,0.1)"
+ }
+})
diff --git a/src/components/index.ts b/src/components/index.ts
index a2fae7ac..a2e4149f 100644
--- a/src/components/index.ts
+++ b/src/components/index.ts
@@ -46,3 +46,5 @@ export { DatabaseStatistics } from "./features/databases/DatabaseStatistics"
export { ServerConnection } from "./features/settings/ServerConnection"
export { StatsCard } from "./features/settings/StatsCard"
export { PresetOption } from "./features/settings/PresetOption"
+export { ConnectionSettings } from "./features/settings/ConnectionSettings"
+export { SyncStrategySettings } from "./features/settings/SyncStrategySettings"
diff --git a/src/constants/index.ts b/src/constants/index.ts
new file mode 100644
index 00000000..30fd70bf
--- /dev/null
+++ b/src/constants/index.ts
@@ -0,0 +1,20 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+// Timing
+export const AUTOSAVE_DEBOUNCE_MS = 1500
+export const STATS_REFRESH_IDLE = 30_000
+export const STATS_REFRESH_FAST = 3_000
+export const SERVER_TIMEOUT = 5_000
+export const SERVER_CHECK_INTERVAL = 5 * 60 * 1000
+export const SAVE_SUCCESS_DISPLAY_MS = 2000
+
+// Thresholds
+export const HIGH_QUEUE_THRESHOLD = 50
+export const CRITICAL_QUEUE_THRESHOLD = 100
+
+// URLs
+export const REPO_URL = "https://github.com/dietrichmax/colota"
+export const PRIVACY_POLICY_URL = "https://mxd.codes/colota/privacy-policy"
diff --git a/src/hooks/useAutoSave.ts b/src/hooks/useAutoSave.ts
new file mode 100644
index 00000000..e485d832
--- /dev/null
+++ b/src/hooks/useAutoSave.ts
@@ -0,0 +1,125 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+import { useState, useCallback } from "react"
+import { useTimeout } from "./useTimeout"
+import { AUTOSAVE_DEBOUNCE_MS, SAVE_SUCCESS_DISPLAY_MS } from "../constants"
+
+/**
+ * Hook that encapsulates the debounced auto-save pattern used across settings screens.
+ *
+ * Manages:
+ * - Debounced and immediate save triggers
+ * - Saving/success state for FloatingSaveIndicator
+ * - Timeout cleanup on unmount (via useTimeout)
+ */
+export function useAutoSave() {
+ const [saving, setSaving] = useState(false)
+ const [saveSuccess, setSaveSuccess] = useState(false)
+ const saveTimeout = useTimeout()
+ const restartTimeout = useTimeout()
+ const successTimeout = useTimeout()
+
+ const executeSave = useCallback(
+ async (saveFn: () => Promise<void>) => {
+ setSaving(true)
+ try {
+ await saveFn()
+ setSaveSuccess(true)
+ successTimeout.set(() => setSaveSuccess(false), SAVE_SUCCESS_DISPLAY_MS)
+ } catch (err) {
+ console.error("[useAutoSave] Save failed:", err)
+ } finally {
+ setSaving(false)
+ }
+ },
+ [successTimeout]
+ )
+
+ const debouncedSave = useCallback(
+ (saveFn: () => Promise<void>) => {
+ saveTimeout.set(() => executeSave(saveFn), AUTOSAVE_DEBOUNCE_MS)
+ },
+ [saveTimeout, executeSave]
+ )
+
+ const immediateSave = useCallback(
+ (saveFn: () => Promise<void>) => {
+ saveTimeout.clear()
+ executeSave(saveFn)
+ },
+ [saveTimeout, executeSave]
+ )
+
+ /**
+ * Schedules a debounced restart after settings are persisted.
+ * Use when you need to save settings first, then restart tracking after the debounce.
+ */
+ const debouncedSaveAndRestart = useCallback(
+ (saveFn: () => Promise<void>, restartFn: () => Promise<void>) => {
+ saveTimeout.set(async () => {
+ setSaving(true)
+ try {
+ await saveFn()
+ restartTimeout.set(async () => {
+ try {
+ await restartFn()
+ setSaveSuccess(true)
+ successTimeout.set(() => setSaveSuccess(false), SAVE_SUCCESS_DISPLAY_MS)
+ } catch (err) {
+ console.error("[useAutoSave] Restart failed:", err)
+ } finally {
+ setSaving(false)
+ }
+ }, AUTOSAVE_DEBOUNCE_MS)
+ } catch (err) {
+ setSaving(false)
+ console.error("[useAutoSave] Save failed:", err)
+ }
+ }, AUTOSAVE_DEBOUNCE_MS)
+ },
+ [saveTimeout, restartTimeout, successTimeout]
+ )
+
+ /**
+ * Immediately saves and schedules a debounced restart.
+ * Use for discrete changes (toggle, preset selection) that should persist immediately
+ * but batch the restart.
+ */
+ const immediateSaveAndRestart = useCallback(
+ (saveFn: () => Promise<void>, restartFn: () => Promise<void>) => {
+ saveTimeout.clear()
+ setSaving(true)
+ saveFn()
+ .then(() => {
+ restartTimeout.set(async () => {
+ try {
+ await restartFn()
+ setSaveSuccess(true)
+ successTimeout.set(() => setSaveSuccess(false), SAVE_SUCCESS_DISPLAY_MS)
+ } catch (err) {
+ console.error("[useAutoSave] Restart failed:", err)
+ } finally {
+ setSaving(false)
+ }
+ }, AUTOSAVE_DEBOUNCE_MS)
+ })
+ .catch((err) => {
+ setSaving(false)
+ console.error("[useAutoSave] Save failed:", err)
+ })
+ },
+ [saveTimeout, restartTimeout, successTimeout]
+ )
+
+ return {
+ saving,
+ saveSuccess,
+ debouncedSave,
+ immediateSave,
+ debouncedSaveAndRestart,
+ immediateSaveAndRestart
+ }
+}
diff --git a/src/hooks/useTimeout.ts b/src/hooks/useTimeout.ts
new file mode 100644
index 00000000..0a3ae1e2
--- /dev/null
+++ b/src/hooks/useTimeout.ts
@@ -0,0 +1,34 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+import { useRef, useEffect, useCallback } from "react"
+
+/**
+ * Hook that manages a single timeout with automatic cleanup on unmount.
+ * Replaces scattered timeout ref + cleanup patterns across screens.
+ */
+export function useTimeout() {
+ const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
+
+ useEffect(() => {
+ return () => {
+ if (timeoutRef.current) clearTimeout(timeoutRef.current)
+ }
+ }, [])
+
+ const set = useCallback((callback: () => void, delay: number) => {
+ if (timeoutRef.current) clearTimeout(timeoutRef.current)
+ timeoutRef.current = setTimeout(callback, delay)
+ }, [])
+
+ const clear = useCallback(() => {
+ if (timeoutRef.current) {
+ clearTimeout(timeoutRef.current)
+ timeoutRef.current = null
+ }
+ }, [])
+
+ return { set, clear }
+}
diff --git a/src/screens/AboutScreen.tsx b/src/screens/AboutScreen.tsx
index e9d609f8..041a8e1c 100644
--- a/src/screens/AboutScreen.tsx
+++ b/src/screens/AboutScreen.tsx
@@ -10,9 +10,7 @@ import { useTheme } from "../hooks/useTheme"
import { SectionTitle, Card, Container, Divider, Footer } from "../components"
import NativeLocationService from "../services/NativeLocationService"
import icon from "../assets/icons/icon.png"
-
-const REPO_URL = "https://github.com/dietrichmax/colota"
-const PRIVACY_POLICY_URL = "https://mxd.codes/colota/privacy-policy"
+import { REPO_URL, PRIVACY_POLICY_URL } from "../constants"
// Helper function to map SDK to Android version
function getAndroidVersion(sdkVersion: number): string {
diff --git a/src/screens/ApiSettingsScreen.tsx b/src/screens/ApiSettingsScreen.tsx
index db75ae63..c0843992 100644
--- a/src/screens/ApiSettingsScreen.tsx
+++ b/src/screens/ApiSettingsScreen.tsx
@@ -3,10 +3,11 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
-import React, { useState, useCallback, useEffect, useRef } from "react"
+import React, { useState, useCallback } from "react"
import { Text, StyleSheet, TextInput, View, ScrollView, TouchableOpacity } from "react-native"
import { FieldMap, DEFAULT_FIELD_MAP, ScreenProps, CustomField, ApiTemplateName, API_TEMPLATES } from "../types/global"
import { useTheme } from "../hooks/useTheme"
+import { useAutoSave } from "../hooks/useAutoSave"
import { useTracking } from "../contexts/TrackingProvider"
import { SectionTitle, FloatingSaveIndicator, Container, Divider } from "../components"
@@ -55,11 +56,7 @@ export function ApiSettingsScreen({}: ScreenProps) {
const [localFieldMap, setLocalFieldMap] = useState<FieldMap>(settings.fieldMap || DEFAULT_FIELD_MAP)
const [localCustomFields, setLocalCustomFields] = useState<CustomField[]>(settings.customFields || [])
const [localTemplate, setLocalTemplate] = useState<ApiTemplateName>(settings.apiTemplate || "custom")
- const saveTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
- const restartTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
-
- const [saving, setSaving] = useState(false)
- const [saveSuccess, setSaveSuccess] = useState(false)
+ const { saving, saveSuccess, debouncedSaveAndRestart, immediateSaveAndRestart } = useAutoSave()
const referenceFieldMap = getReferenceFieldMap(localTemplate)
@@ -71,70 +68,63 @@ export function ApiSettingsScreen({}: ScreenProps) {
}
/**
- * Saves all API config and restarts tracking if active
+ * Build sanitized settings from current field map, custom fields, and template.
+ * Returns null if validation fails (empty field mappings).
*/
- const saveAllSettings = useCallback(
- async (newFieldMap: FieldMap, newCustomFields: CustomField[], newTemplate: ApiTemplateName) => {
- // Sanitize: trim all field values
+ const buildSanitizedSettings = useCallback(
+ (newFieldMap: FieldMap, newCustomFields: CustomField[], newTemplate: ApiTemplateName) => {
const sanitizedMap = Object.fromEntries(
Object.entries(newFieldMap).map(([key, value]) => [key, value.trim()])
) as FieldMap
- // Prevent saving if any field mapping is empty
if (Object.values(sanitizedMap).some((v) => v === "")) {
- return
+ return null
}
- // Sanitize custom fields: trim and remove entries with empty keys
const sanitizedCustomFields = newCustomFields
.map((f) => ({ key: f.key.trim(), value: f.value.trim() }))
.filter((f) => f.key.length > 0)
- try {
- setSaving(true)
- setSaveSuccess(false)
-
- const newSettings = {
- ...settings,
- fieldMap: sanitizedMap,
- customFields: sanitizedCustomFields,
- apiTemplate: newTemplate
- }
-
- await setSettings(newSettings)
-
- // Debounce the restart — only fires once after settings stabilize
- if (restartTimeoutRef.current) clearTimeout(restartTimeoutRef.current)
- restartTimeoutRef.current = setTimeout(async () => {
- try {
- await restartTracking(newSettings)
- setSaveSuccess(true)
- setTimeout(() => setSaveSuccess(false), 2000)
- } catch (err) {
- console.error("[ApiSettingsScreen] Restart failed:", err)
- } finally {
- setSaving(false)
- }
- }, 1500)
- } catch (err) {
- setSaving(false)
- console.error("[ApiSettingsScreen] Failed to save settings:", err)
+ return {
+ ...settings,
+ fieldMap: sanitizedMap,
+ customFields: sanitizedCustomFields,
+ apiTemplate: newTemplate
}
},
- [settings, setSettings, restartTracking]
+ [settings]
)
/**
- * Debounced save (1.5s delay)
+ * Debounced save + restart for continuous changes (typing)
*/
const debouncedSave = useCallback(
(newFieldMap: FieldMap, newCustomFields: CustomField[], newTemplate: ApiTemplateName) => {
- if (saveTimeoutRef.current) {
- clearTimeout(saveTimeoutRef.current)
- }
- saveTimeoutRef.current = setTimeout(() => saveAllSettings(newFieldMap, newCustomFields, newTemplate), 1500)
+ const newSettings = buildSanitizedSettings(newFieldMap, newCustomFields, newTemplate)
+ if (!newSettings) return
+
+ debouncedSaveAndRestart(
+ () => setSettings(newSettings),
+ () => restartTracking(newSettings)
+ )
},
- [saveAllSettings]
+ [buildSanitizedSettings, setSettings, restartTracking, debouncedSaveAndRestart]
+ )
+
+ /**
+ * Immediate save + restart for discrete changes (template switch, reset, remove)
+ */
+ const saveImmediately = useCallback(
+ (newFieldMap: FieldMap, newCustomFields: CustomField[], newTemplate: ApiTemplateName) => {
+ const newSettings = buildSanitizedSettings(newFieldMap, newCustomFields, newTemplate)
+ if (!newSettings) return
+
+ immediateSaveAndRestart(
+ () => setSettings(newSettings),
+ () => restartTracking(newSettings)
+ )
+ },
+ [buildSanitizedSettings, setSettings, restartTracking, immediateSaveAndRestart]
)
/**
@@ -145,20 +135,15 @@ export function ApiSettingsScreen({}: ScreenProps) {
setLocalTemplate(template)
if (template === "custom") {
- // Keep current field map and custom fields, just save the template change
- if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current)
- saveAllSettings(localFieldMap, localCustomFields, template)
+ saveImmediately(localFieldMap, localCustomFields, template)
} else {
const tmpl = API_TEMPLATES[template]
setLocalFieldMap(tmpl.fieldMap)
setLocalCustomFields(tmpl.customFields)
-
- // Save immediately on template change
- if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current)
- saveAllSettings(tmpl.fieldMap, tmpl.customFields, template)
+ saveImmediately(tmpl.fieldMap, tmpl.customFields, template)
}
},
- [localFieldMap, localCustomFields, saveAllSettings]
+ [localFieldMap, localCustomFields, saveImmediately]
)
/**
@@ -185,24 +170,20 @@ export function ApiSettingsScreen({}: ScreenProps) {
(key: keyof FieldMap) => {
const newFieldMap = { ...localFieldMap, [key]: referenceFieldMap[key] }
setLocalFieldMap(newFieldMap)
-
- if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current)
- saveAllSettings(newFieldMap, localCustomFields, localTemplate)
+ saveImmediately(newFieldMap, localCustomFields, localTemplate)
},
- [localFieldMap, localCustomFields, localTemplate, referenceFieldMap, saveAllSettings]
+ [localFieldMap, localCustomFields, localTemplate, referenceFieldMap, saveImmediately]
)
/**
* Resets all fields to current template defaults
*/
const handleResetAll = useCallback(() => {
- if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current)
-
const refFields = getReferenceCustomFields(localTemplate)
setLocalFieldMap(referenceFieldMap)
setLocalCustomFields(refFields)
- saveAllSettings(referenceFieldMap, refFields, localTemplate)
- }, [referenceFieldMap, localTemplate, saveAllSettings])
+ saveImmediately(referenceFieldMap, refFields, localTemplate)
+ }, [referenceFieldMap, localTemplate, saveImmediately])
// --- Custom Fields handlers ---
@@ -233,20 +214,11 @@ export function ApiSettingsScreen({}: ScreenProps) {
const newTemplate = localTemplate !== "custom" ? "custom" : localTemplate
if (newTemplate !== localTemplate) setLocalTemplate(newTemplate)
- if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current)
- saveAllSettings(localFieldMap, newFields, newTemplate)
+ saveImmediately(localFieldMap, newFields, newTemplate)
},
- [localCustomFields, localFieldMap, localTemplate, saveAllSettings]
+ [localCustomFields, localFieldMap, localTemplate, saveImmediately]
)
- // Cleanup timeouts on unmount
- useEffect(() => {
- return () => {
- if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current)
- if (restartTimeoutRef.current) clearTimeout(restartTimeoutRef.current)
- }
- }, [])
-
// Check if any field mapping is modified from the reference
const hasModifications = (Object.keys(DEFAULT_FIELD_MAP) as Array<keyof FieldMap>).some((key) => isModified(key))
diff --git a/src/screens/AuthSettingsScreen.tsx b/src/screens/AuthSettingsScreen.tsx
index 836d5680..9fa90fb2 100644
--- a/src/screens/AuthSettingsScreen.tsx
+++ b/src/screens/AuthSettingsScreen.tsx
@@ -3,16 +3,15 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
-import React, { useState, useCallback, useEffect, useRef } from "react"
+import React, { useState, useCallback, useEffect } from "react"
import { Text, StyleSheet, TextInput, View, ScrollView, TouchableOpacity } from "react-native"
import { AuthConfig, AuthType, DEFAULT_AUTH_CONFIG, ScreenProps } from "../types/global"
import { useTheme } from "../hooks/useTheme"
+import { useAutoSave } from "../hooks/useAutoSave"
import { useTracking } from "../contexts/TrackingProvider"
import { SectionTitle, FloatingSaveIndicator, Container, Card, Divider } from "../components"
import NativeLocationService from "../services/NativeLocationService"
-const AUTOSAVE_DEBOUNCE_MS = 1500
-
const AUTH_TYPES: { value: AuthType; label: string }[] = [
{ value: "none", label: "None" },
{ value: "basic", label: "Basic Auth" },
@@ -28,10 +27,7 @@ export function AuthSettingsScreen({}: ScreenProps) {
const [config, setConfig] = useState<AuthConfig>(DEFAULT_AUTH_CONFIG)
const [loading, setLoading] = useState(true)
- const [saving, setSaving] = useState(false)
- const [saveSuccess, setSaveSuccess] = useState(false)
- const saveTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
- const restartTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
+ const { saving, saveSuccess, debouncedSaveAndRestart, immediateSaveAndRestart } = useAutoSave()
// Load config on mount
useEffect(() => {
@@ -47,47 +43,16 @@ export function AuthSettingsScreen({}: ScreenProps) {
})()
}, [])
- // Cleanup
- useEffect(() => {
- return () => {
- if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current)
- if (restartTimeoutRef.current) clearTimeout(restartTimeoutRef.current)
- }
- }, [])
-
- const saveConfig = useCallback(
- async (newConfig: AuthConfig) => {
- setSaving(true)
- try {
- await NativeLocationService.saveAuthConfig(newConfig)
-
- // Debounce the restart — only fires once after settings stabilize
- if (restartTimeoutRef.current) clearTimeout(restartTimeoutRef.current)
- restartTimeoutRef.current = setTimeout(async () => {
- try {
- await restartTracking(settings)
- setSaveSuccess(true)
- setTimeout(() => setSaveSuccess(false), 2000)
- } catch (err) {
- console.error("[AuthSettingsScreen] Restart failed:", err)
- } finally {
- setSaving(false)
- }
- }, AUTOSAVE_DEBOUNCE_MS)
- } catch (err) {
- setSaving(false)
- console.error("[AuthSettingsScreen] Save failed:", err)
- }
- },
- [restartTracking, settings]
- )
-
const debouncedSave = useCallback(
(newConfig: AuthConfig) => {
- if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current)
- saveTimeoutRef.current = setTimeout(() => saveConfig(newConfig), AUTOSAVE_DEBOUNCE_MS)
+ debouncedSaveAndRestart(
+ async () => {
+ await NativeLocationService.saveAuthConfig(newConfig)
+ },
+ () => restartTracking(settings)
+ )
},
- [saveConfig]
+ [debouncedSaveAndRestart, restartTracking, settings]
)
const updateConfig = useCallback(
@@ -103,11 +68,14 @@ export function AuthSettingsScreen({}: ScreenProps) {
(authType: AuthType) => {
const next = { ...config, authType }
setConfig(next)
- // Immediate save for auth type change
- if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current)
- saveConfig(next)
+ immediateSaveAndRestart(
+ async () => {
+ await NativeLocationService.saveAuthConfig(next)
+ },
+ () => restartTracking(settings)
+ )
},
- [config, saveConfig]
+ [config, immediateSaveAndRestart, restartTracking, settings]
)
// Custom headers as array for rendering
@@ -145,10 +113,14 @@ export function AuthSettingsScreen({}: ScreenProps) {
entries.splice(index, 1)
const next = { ...config, customHeaders: Object.fromEntries(entries) }
setConfig(next)
- if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current)
- saveConfig(next)
+ immediateSaveAndRestart(
+ async () => {
+ await NativeLocationService.saveAuthConfig(next)
+ },
+ () => restartTracking(settings)
+ )
},
- [config, saveConfig]
+ [config, immediateSaveAndRestart, restartTracking, settings]
)
if (loading) {
diff --git a/src/screens/DashboardScreen.tsx b/src/screens/DashboardScreen.tsx
index 3ed77d7c..f1c67973 100644
--- a/src/screens/DashboardScreen.tsx
+++ b/src/screens/DashboardScreen.tsx
@@ -19,9 +19,7 @@ import {
QuickAccess,
DatabaseStatistics
} from "../components"
-
-/** Stats refresh intervals */
-const STATS_REFRESH_IDLE = 30 * 1000
+import { STATS_REFRESH_IDLE } from "../constants"
export function DashboardScreen({ navigation }: ScreenProps) {
const { coords, settings, tracking, startTracking, stopTracking } = useTracking()
diff --git a/src/screens/DataManagementScreen.tsx b/src/screens/DataManagementScreen.tsx
index a408e96b..901c467e 100644
--- a/src/screens/DataManagementScreen.tsx
+++ b/src/screens/DataManagementScreen.tsx
@@ -3,7 +3,7 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
-import React, { useState, useCallback, useEffect, useRef } from "react"
+import React, { useState, useCallback } from "react"
import {
Text,
StyleSheet,
@@ -19,6 +19,8 @@ import { ScreenProps, DatabaseStats } from "../types/global"
import { useTheme } from "../hooks/useTheme"
import NativeLocationService from "../services/NativeLocationService"
import { Button, SectionTitle, Card, Container, Divider, FloatingSaveIndicator } from "../components"
+import { STATS_REFRESH_FAST } from "../constants"
+import { useTimeout } from "../hooks/useTimeout"
export function DataManagementScreen({}: ScreenProps) {
const { colors } = useTheme()
@@ -34,7 +36,7 @@ export function DataManagementScreen({}: ScreenProps) {
const [daysInput, setDaysInput] = useState("90")
const [isProcessing, setIsProcessing] = useState(false)
const [feedback, setFeedback] = useState<string | null>(null)
- const feedbackTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
+ const feedbackTimeout = useTimeout()
// Update stats
const updateStats = useCallback(async () => {
@@ -50,28 +52,19 @@ export function DataManagementScreen({}: ScreenProps) {
useFocusEffect(
useCallback(() => {
updateStats()
- const interval = setInterval(updateStats, 3000)
+ const interval = setInterval(updateStats, STATS_REFRESH_FAST)
return () => clearInterval(interval)
}, [updateStats])
)
- // Cleanup timeout on unmount
- useEffect(() => {
- return () => {
- if (feedbackTimeoutRef.current) {
- clearTimeout(feedbackTimeoutRef.current)
- }
- }
- }, [])
-
// Show feedback message
- const showFeedback = useCallback((message: string, duration = 2000) => {
- if (feedbackTimeoutRef.current) {
- clearTimeout(feedbackTimeoutRef.current)
- }
- setFeedback(message)
- feedbackTimeoutRef.current = setTimeout(() => setFeedback(null), duration)
- }, [])
+ const showFeedback = useCallback(
+ (message: string, duration = 2000) => {
+ setFeedback(message)
+ feedbackTimeout.set(() => setFeedback(null), duration)
+ },
+ [feedbackTimeout]
+ )
// Manual flush
const handleManualFlush = useCallback(async () => {
diff --git a/src/screens/ExportDataScreen.tsx b/src/screens/ExportDataScreen.tsx
index 9fe69bae..1608b251 100644
--- a/src/screens/ExportDataScreen.tsx
+++ b/src/screens/ExportDataScreen.tsx
@@ -9,17 +9,7 @@ import { Container, Card, SectionTitle, Divider } from "../components"
import { useTheme } from "../hooks/useTheme"
import { ThemeColors, LocationCoords } from "../types/global"
import NativeLocationService from "../services/NativeLocationService"
-import {
- LARGE_FILE_THRESHOLD,
- formatBytes,
- getByteSize,
- convertToCSV,
- convertToGeoJSON,
- convertToGPX,
- convertToKML
-} from "../utils/exportConverters"
-
-type ExportFormat = "csv" | "geojson" | "gpx" | "kml"
+import { LARGE_FILE_THRESHOLD, formatBytes, getByteSize, EXPORT_FORMATS, ExportFormat } from "../utils/exportConverters"
interface ExportStats {
totalLocations: number
@@ -63,14 +53,7 @@ export function ExportDataScreen() {
return
}
- const converters: Record<ExportFormat, (data: LocationCoords[]) => string> = {
- csv: convertToCSV,
- geojson: convertToGeoJSON,
- gpx: convertToGPX,
- kml: convertToKML
- }
-
- const content = converters[selectedFormat](cachedData.current)
+ const content = EXPORT_FORMATS[selectedFormat].convert(cachedData.current)
setFileSize(formatBytes(getByteSize(content)))
}, [selectedFormat])
@@ -88,32 +71,10 @@ export function ExportDataScreen() {
setExportProgress(`Converting ${normalizedData.length} locations...`)
- let content = ""
- let fileExtension = ""
- let mimeType = ""
-
- switch (format) {
- case "csv":
- content = convertToCSV(normalizedData)
- fileExtension = ".csv"
- mimeType = "text/csv"
- break
- case "geojson":
- content = convertToGeoJSON(normalizedData)
- fileExtension = ".geojson"
- mimeType = "application/json"
- break
- case "gpx":
- content = convertToGPX(normalizedData)
- fileExtension = ".gpx"
- mimeType = "application/gpx+xml"
- break
- case "kml":
- content = convertToKML(normalizedData)
- fileExtension = ".kml"
- mimeType = "application/vnd.google-earth.kml+xml"
- break
- }
+ const formatConfig = EXPORT_FORMATS[format]
+ const content = formatConfig.convert(normalizedData)
+ const fileExtension = formatConfig.extension
+ const mimeType = formatConfig.mimeType
const exportSize = getByteSize(content)
@@ -217,55 +178,23 @@ export function ExportDataScreen() {
<SectionTitle>Select Format</SectionTitle>
<Card>
- <FormatOption
- icon="📊"
- title="CSV"
- subtitle="Spreadsheet Format"
- description="Excel, Google Sheets, data analysis"
- extension=".csv"
- selected={selectedFormat === "csv"}
- onPress={() => setSelectedFormat("csv")}
- colors={colors}
- />
-
- <Divider />
-
- <FormatOption
- icon="🗺️"
- title="GeoJSON"
- subtitle="Geographic Data"
- description="Mapbox, Leaflet, QGIS, ArcGIS"
- extension=".geojson"
- selected={selectedFormat === "geojson"}
- onPress={() => setSelectedFormat("geojson")}
- colors={colors}
- />
-
- <Divider />
-
- <FormatOption
- icon="📍"
- title="GPX"
- subtitle="GPS Exchange"
- description="Garmin, Strava, Google Earth"
- extension=".gpx"
- selected={selectedFormat === "gpx"}
- onPress={() => setSelectedFormat("gpx")}
- colors={colors}
- />
-
- <Divider />
-
- <FormatOption
- icon="🌍"
- title="KML"
- subtitle="Keyhole Markup Language"
- description="Google Earth, Google Maps, ArcGIS"
- extension=".kml"
- selected={selectedFormat === "kml"}
- onPress={() => setSelectedFormat("kml")}
- colors={colors}
- />
+ {(Object.entries(EXPORT_FORMATS) as [ExportFormat, (typeof EXPORT_FORMATS)[ExportFormat]][]).map(
+ ([key, config], index, arr) => (
+ <React.Fragment key={key}>
+ <FormatOption
+ icon={config.icon}
+ title={config.label}
+ subtitle={config.subtitle}
+ description={config.description}
+ extension={config.extension}
+ selected={selectedFormat === key}
+ onPress={() => setSelectedFormat(key)}
+ colors={colors}
+ />
+ {index < arr.length - 1 && <Divider />}
+ </React.Fragment>
+ )
+ )}
</Card>
</View>
@@ -288,7 +217,7 @@ export function ExportDataScreen() {
<Text style={styles.exportIcon}>📤</Text>
<View style={styles.exportText}>
<Text style={[styles.exportTitle, styles.exportButtonText]}>
- Export {selectedFormat.toUpperCase()}
+ Export {EXPORT_FORMATS[selectedFormat].label}
</Text>
<Text style={[styles.exportSubtitle, styles.exportButtonText]}>
{stats.totalLocations.toLocaleString()} locations
diff --git a/src/screens/LocationInspectorScreen.tsx b/src/screens/LocationInspectorScreen.tsx
index dbffe7c4..628b29a7 100644
--- a/src/screens/LocationInspectorScreen.tsx
+++ b/src/screens/LocationInspectorScreen.tsx
@@ -9,6 +9,7 @@ import { Container, Card } from "../components"
import { useTheme } from "../hooks/useTheme"
import { ThemeColors } from "../types/global"
import NativeLocationService from "../services/NativeLocationService"
+import { STATS_REFRESH_FAST } from "../constants"
// Types
interface LocationData {
@@ -135,7 +136,7 @@ export function LocationInspectorScreen() {
useEffect(() => {
if (autoRefresh) {
setPage(0) // Always show newest data in live mode
- refreshInterval.current = setInterval(fetchData, 3000)
+ refreshInterval.current = setInterval(fetchData, STATS_REFRESH_FAST)
} else {
if (refreshInterval.current) {
clearInterval(refreshInterval.current)
diff --git a/src/screens/SettingsScreen.tsx b/src/screens/SettingsScreen.tsx
index 1611e15c..7e09495e 100644
--- a/src/screens/SettingsScreen.tsx
+++ b/src/screens/SettingsScreen.tsx
@@ -3,18 +3,19 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
-import React, { useState, useCallback, useEffect, useRef } from "react"
-import { Text, StyleSheet, TextInput, Switch, View, ScrollView, TouchableOpacity } from "react-native"
-import { ScreenProps, TRACKING_PRESETS, SyncPreset, SelectablePreset, Settings } from "../types/global"
+import React, { useState, useCallback, useEffect } from "react"
+import { Text, StyleSheet, Switch, View, ScrollView, TouchableOpacity } from "react-native"
+import { ScreenProps, Settings } from "../types/global"
import { useTheme } from "../hooks/useTheme"
+import { useAutoSave } from "../hooks/useAutoSave"
+import { STATS_REFRESH_FAST } from "../constants"
import NativeLocationService from "../services/NativeLocationService"
import { useTracking } from "../contexts/TrackingProvider"
import { FloatingSaveIndicator } from "../components/ui/FloatingSaveIndicator"
-import { Button, SectionTitle, Card, Container, Divider, Footer } from "../components"
-import { StatsCard, PresetOption, NumericInput } from "../components"
-import { isPrivateHost, isEndpointAllowed } from "../utils/settingsValidation"
-
-const AUTOSAVE_DEBOUNCE_MS = 1500
+import { SectionTitle, Card, Container, Divider, Footer } from "../components"
+import { StatsCard } from "../components"
+import { ConnectionSettings } from "../components/features/settings/ConnectionSettings"
+import { SyncStrategySettings } from "../components/features/settings/SyncStrategySettings"
/**
* Settings screen for configuring location tracking.
@@ -23,34 +24,19 @@ const AUTOSAVE_DEBOUNCE_MS = 1500
export function SettingsScreen({ navigation }: ScreenProps) {
const { settings, setSettings, restartTracking } = useTracking()
const { mode, toggleTheme, colors } = useTheme()
+ const { saving, saveSuccess, debouncedSaveAndRestart, immediateSaveAndRestart } = useAutoSave()
// Stats
const [queueCount, setQueueCount] = useState(0)
const [sentCount, setSentCount] = useState(0)
- // Inputs
- const [intervalInput, setIntervalInput] = useState(settings.interval.toString())
+ // Endpoint input (managed here since ConnectionSettings needs it and we sync with settings)
const [endpointInput, setEndpointInput] = useState(settings.endpoint || "")
- const [distanceInput, setDistanceInput] = useState(settings.distance?.toString() || "0")
- const [accuracyTresholdInput, setAccuracyTresholdInput] = useState(settings.accuracyThreshold.toString())
-
- // UI State
- const [testing, setTesting] = useState(false)
- const [testResponse, setTestResponse] = useState<string | null>(null)
- const [testError, setTestError] = useState(false)
- const [saving, setSaving] = useState(false)
- const [saveSuccess, setSaveSuccess] = useState(false)
- const [showAdvanced, setShowAdvanced] = useState(false)
-
- const saveTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
- const restartTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
- // Sync inputs with settings changes
+ // Sync endpoint input with settings changes
useEffect(() => {
- setIntervalInput(settings.interval.toString())
- setDistanceInput(settings.distance?.toString() || "0")
setEndpointInput(settings.endpoint || "")
- }, [settings.interval, settings.distance, settings.endpoint, settings.accuracyThreshold])
+ }, [settings.endpoint])
/** Update stats */
const updateStats = useCallback(async () => {
@@ -63,190 +49,35 @@ export function SettingsScreen({ navigation }: ScreenProps) {
}
}, [])
- /** Persist settings to SQLite and schedule a debounced restart */
- const saveAndRestart = useCallback(
- async (newSettings: Settings) => {
- setSaving(true)
- try {
- await setSettings(newSettings)
- } catch (err) {
- console.error("[SettingsScreen] Save failed", err)
- }
-
- // Debounce the restart — only fires once after settings stabilize
- if (restartTimeoutRef.current) clearTimeout(restartTimeoutRef.current)
- restartTimeoutRef.current = setTimeout(async () => {
- try {
- await restartTracking(newSettings)
- setSaveSuccess(true)
- setTimeout(() => setSaveSuccess(false), 2000)
- } catch (err) {
- console.error("[SettingsScreen] Restart failed", err)
- } finally {
- setSaving(false)
- }
- }, AUTOSAVE_DEBOUNCE_MS)
- },
- [setSettings, restartTracking]
- )
-
- const debouncedSave = useCallback(
- (newSettings: Settings) => {
- if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current)
- saveTimeoutRef.current = setTimeout(() => saveAndRestart(newSettings), AUTOSAVE_DEBOUNCE_MS)
- },
- [saveAndRestart]
- )
-
- const immediateSave = useCallback(
- (newSettings: Settings) => {
- if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current)
- saveAndRestart(newSettings)
- },
- [saveAndRestart]
- )
-
// Poll stats every 5 seconds
useEffect(() => {
updateStats()
- const interval = setInterval(updateStats, 5000)
+ const interval = setInterval(updateStats, STATS_REFRESH_FAST)
return () => clearInterval(interval)
}, [updateStats])
- // Cleanup
- useEffect(() => {
- return () => {
- if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current)
- if (restartTimeoutRef.current) clearTimeout(restartTimeoutRef.current)
- }
- }, [])
-
- /** Generic numeric input handler */
- const handleNumericChange = useCallback(
- (key: "interval" | "distance" | "accuracyTreshold", value: string, min: number = 0) => {
- if (key === "interval") setIntervalInput(value)
- if (key === "distance") setDistanceInput(value)
- if (key === "accuracyTreshold") setAccuracyTresholdInput(value)
-
- const num = Number(value)
- if (!isNaN(num) && num >= min) {
- const next = { ...settings, [key]: num, syncPreset: "custom" as const }
- setSettings(next)
- debouncedSave(next)
- }
- },
- [settings, setSettings, debouncedSave]
- )
-
- /** Ensure valid numbers on blur */
- const handleNumericBlur = useCallback(
- (key: "interval" | "distance" | "accuracyTreshold", min: number = 0) => {
- const currentStr = key === "interval" ? intervalInput : key === "distance" ? distanceInput : accuracyTresholdInput
- let val = Number(currentStr)
-
- if (isNaN(val) || val < min) {
- val = min
- if (key === "interval") setIntervalInput(min.toString())
- if (key === "distance") setDistanceInput(min.toString())
- if (key === "accuracyTreshold") setAccuracyTresholdInput(min.toString())
-
- const next = { ...settings, [key]: val }
- setSettings(next)
- immediateSave(next)
- }
- },
- [intervalInput, distanceInput, accuracyTresholdInput, settings, setSettings, immediateSave]
- )
-
- const handlePresetSelect = useCallback(
- async (preset: SyncPreset) => {
- if (preset === "custom") {
- const next = { ...settings, syncPreset: "custom" as const }
- setSettings(next)
- immediateSave(next)
- return
- }
-
- const config = TRACKING_PRESETS[preset]
- const next: Settings = {
- ...settings,
- syncPreset: preset,
- interval: config.interval,
- distance: config.distance,
- syncInterval: config.syncInterval,
- retryInterval: config.retryInterval
- }
-
- immediateSave(next)
+ /** Debounced save + restart for continuous changes (text input, sliders) */
+ const handleDebouncedSave = useCallback(
+ (newSettings: Settings) => {
+ setSettings(newSettings)
+ debouncedSaveAndRestart(
+ () => setSettings(newSettings),
+ () => restartTracking(newSettings)
+ )
},
- [settings, setSettings, immediateSave]
+ [setSettings, debouncedSaveAndRestart, restartTracking]
)
- const handleTestEndpoint = useCallback(async () => {
- if (!endpointInput) return
- setTesting(true)
- setTestResponse(null)
- setTestError(false)
-
- try {
- const recentLocation = await NativeLocationService.getMostRecentLocation()
- if (!recentLocation) {
- setTestResponse("No location available yet. Start tracking first.")
- setTestError(true)
- return
- }
-
- const fieldMap = settings.fieldMap
- const payload: Record<string, number | boolean> = {
- [fieldMap.lat]: recentLocation.latitude,
- [fieldMap.lon]: recentLocation.longitude,
- [fieldMap.acc]: Math.round(recentLocation.accuracy)
- }
-
- if (fieldMap.alt) payload[fieldMap.alt] = 0
- if (fieldMap.vel) payload[fieldMap.vel] = 0
- if (fieldMap.batt) payload[fieldMap.batt] = 0
- if (fieldMap.bs) payload[fieldMap.bs] = 0
- if (fieldMap.tst) {
- payload[fieldMap.tst] = Math.floor(Date.now() / 1000)
- }
-
- let authHeaders: Record<string, string> = {}
- try {
- authHeaders = await NativeLocationService.getAuthHeaders()
- } catch {
- // proceed without auth headers
- }
-
- const response = await fetch(endpointInput, {
- method: "POST",
- headers: { "Content-Type": "application/json", ...authHeaders },
- body: JSON.stringify(payload)
- })
-
- if (response.ok) {
- setTestResponse("✓ Connection successful")
- const next = { ...settings, endpoint: endpointInput }
- immediateSave(next)
- } else {
- setTestResponse(`Failed: ${response.status}`)
- setTestError(true)
- }
- } catch (err: any) {
- setTestResponse(err.message || "Connection failed")
- setTestError(true)
- } finally {
- setTesting(false)
- setTimeout(() => setTestResponse(null), 3000)
- }
- }, [endpointInput, settings, immediateSave])
-
- const handleOfflineModeChange = useCallback(
- (enabled: boolean) => {
- const next = { ...settings, isOfflineMode: enabled }
- immediateSave(next)
+ /** Immediate save + restart for discrete changes (toggles, presets) */
+ const handleImmediateSave = useCallback(
+ (newSettings: Settings) => {
+ setSettings(newSettings)
+ immediateSaveAndRestart(
+ () => setSettings(newSettings),
+ () => restartTracking(newSettings)
+ )
},
- [settings, immediateSave]
+ [setSettings, immediateSaveAndRestart, restartTracking]
)
return (
@@ -256,457 +87,41 @@ export function SettingsScreen({ navigation }: ScreenProps) {
keyboardShouldPersistTaps="handled"
showsVerticalScrollIndicator={false}
>
- {/* Header - More compact */}
+ {/* Header */}
<View style={styles.header}>
<Text style={[styles.title, { color: colors.text }]}>Settings</Text>
</View>
- {/* Stats Card - Enhanced with better spacing */}
+ {/* Stats Card */}
<StatsCard
queueCount={queueCount}
sentCount={sentCount}
- interval={intervalInput}
+ interval={settings.interval.toString()}
isOfflineMode={settings.isOfflineMode}
onManageClick={() => navigation.navigate("Data Management")}
colors={colors}
/>
- {/* Connection - Improved hierarchy */}
- <View style={styles.section}>
- <SectionTitle>Connection</SectionTitle>
- <Card>
- {/* Offline Mode - Better visual hierarchy */}
- <View style={styles.settingRow}>
- <View style={styles.settingContent}>
- <Text style={[styles.settingLabel, { color: colors.text }]}>Offline Mode</Text>
- <Text style={[styles.settingHint, { color: colors.textSecondary }]}>Save locally, no network sync</Text>
- </View>
- <Switch
- value={settings.isOfflineMode}
- onValueChange={handleOfflineModeChange}
- trackColor={{
- false: colors.border,
- true: colors.primary + "80"
- }}
- thumbColor={settings.isOfflineMode ? colors.primary : "#f4f3f4"}
- />
- </View>
-
- {!settings.isOfflineMode && (
- <>
- <Divider />
-
- {/* Endpoint - Improved spacing and visual design */}
- <View style={styles.inputGroup}>
- <View style={styles.inputHeader}>
- <Text style={[styles.inputLabel, { color: colors.text }]}>Server Endpoint</Text>
- {endpointInput && (
- <View
- style={[
- styles.protocolBadge,
- {
- backgroundColor: endpointInput.startsWith("https://")
- ? colors.success + "20"
- : colors.warning + "20"
- }
- ]}
- >
- <Text
- style={[
- styles.protocolText,
- {
- color: endpointInput.startsWith("https://") ? colors.success : colors.warning
- }
- ]}
- >
- {endpointInput.startsWith("https://") ? "HTTPS" : "HTTP"}
- </Text>
- </View>
- )}
- </View>
-
- <TextInput
- style={[
- styles.input,
- {
- borderColor: colors.border,
- color: colors.text,
- backgroundColor: colors.background
- }
- ]}
- value={endpointInput}
- onChangeText={setEndpointInput}
- placeholder="https://your-server.com/api/locations"
- placeholderTextColor={colors.placeholder}
- autoCapitalize="none"
- autoCorrect={false}
- keyboardType="url"
- />
-
- {/* Inline warning for non-private HTTP */}
- {endpointInput.startsWith("http://") && !isPrivateHost(endpointInput) && (
- <Text style={[styles.httpWarning, { color: colors.warning }]}>
- HTTP only allowed for private IPs / localhost
- </Text>
- )}
- </View>
-
- {/* Test button with improved styling */}
- <Button
- style={[
- styles.testButton,
- { backgroundColor: colors.primary },
- (!endpointInput || !isEndpointAllowed(endpointInput)) && styles.disabledButton
- ]}
- onPress={() => {
- if (!endpointInput || !isEndpointAllowed(endpointInput)) return // prevent action
- handleTestEndpoint()
- }}
- title={testing ? "Testing..." : "Test Connection"}
- color="#f8f7f7"
- />
-
- {/* Test response with animation would be nice */}
- {testResponse && (
- <View
- style={[
- styles.responseBox,
- {
- borderColor: testError ? colors.error : colors.success,
- backgroundColor: (testError ? colors.error : colors.success) + "15"
- }
- ]}
- >
- <Text style={[styles.responseText, { color: testError ? colors.error : colors.success }]}>
- {testResponse}
- </Text>
- </View>
- )}
-
- <Divider />
-
- <TouchableOpacity
- style={styles.linkRow}
- onPress={() => navigation.navigate("Auth Settings")}
- activeOpacity={0.6}
- >
- <View style={styles.linkContent}>
- <Text style={[styles.linkLabel, { color: colors.text }]}>Authentication & Headers</Text>
- <Text style={[styles.linkSub, { color: colors.textSecondary }]}>
- Basic auth, bearer tokens, custom headers
- </Text>
- </View>
- <Text style={[styles.linkArrow, { color: colors.textLight }]}>›</Text>
- </TouchableOpacity>
- </>
- )}
- </Card>
- </View>
-
- {/* Sync Strategy - Better visual grouping */}
- <View style={styles.section}>
- <SectionTitle>Sync Strategy</SectionTitle>
- <Card>
- {/* Presets with improved spacing */}
- <View style={styles.presetsContainer}>
- {(Object.keys(TRACKING_PRESETS) as SelectablePreset[]).map((preset, index) => (
- <View key={preset}>
- <PresetOption
- preset={preset}
- isSelected={settings.syncPreset === preset}
- onSelect={handlePresetSelect}
- colors={colors}
- />
- {index < Object.keys(TRACKING_PRESETS).length - 1 && <View style={styles.presetSpacer} />}
- </View>
- ))}
- </View>
-
- {/* Advanced Toggle - Better button design */}
- <TouchableOpacity
- style={[
- styles.advancedToggle,
- showAdvanced ? styles.advancedToggleActive : styles.advancedToggleInactive,
- {
- borderColor: showAdvanced ? colors.primary : colors.border
- }
- ]}
- onPress={() => setShowAdvanced(!showAdvanced)}
- activeOpacity={0.7}
- >
- <Text style={[styles.advancedText, { color: colors.primary }]}>
- {showAdvanced ? "− Hide" : "+ Show"} Advanced Settings
- </Text>
- </TouchableOpacity>
-
- {/* Advanced Panel - Collapsible with better organization */}
- {showAdvanced && (
- <View style={styles.advancedPanel}>
- <Divider />
-
- {settings.syncPreset === "custom" && (
- <View
- style={[
- styles.customBanner,
- {
- backgroundColor: colors.info + "15",
- borderLeftColor: colors.info
- }
- ]}
- >
- <Text style={[styles.customBannerText, { color: colors.info }]}>💡 Using custom configuration</Text>
- </View>
- )}
-
- {/* Tracking Parameters Group */}
- <View style={styles.paramGroup}>
- <Text style={[styles.paramGroupTitle, { color: colors.text }]}>Tracking Parameters</Text>
-
- <NumericInput
- label="Tracking Interval"
- value={intervalInput}
- onChange={(val) => handleNumericChange("interval", val, 1)}
- onBlur={() => handleNumericBlur("interval", 1)}
- unit="seconds"
- placeholder="1"
- hint="How often to capture GPS position"
- colors={colors}
- />
-
- <NumericInput
- label="Movement Threshold"
- value={distanceInput}
- onChange={(val) => handleNumericChange("distance", val, 0)}
- onBlur={() => handleNumericBlur("distance", 0)}
- unit="meters"
- placeholder="10"
- hint="Only record if moved more than this distance"
- colors={colors}
- />
- </View>
-
- <Divider />
-
- {/* Network Parameters Group */}
- <View style={styles.paramGroup}>
- <Text style={[styles.paramGroupTitle, { color: colors.text }]}>Network Settings</Text>
-
- {/* Sync Interval */}
- <View style={styles.settingBlock}>
- <Text style={[styles.blockLabel, { color: colors.text }]}>Sync Interval</Text>
- <Text style={[styles.blockHint, { color: colors.textSecondary }]}>
- How often to upload data to server
- </Text>
-
- <View style={styles.optionsGrid}>
- {([0, 60, 300, 900] as const).map((sec) => {
- const labels: Record<number, string> = {
- 0: "Instant",
- 60: "1 min",
- 300: "5 min",
- 900: "15 min"
- }
- const isSelected = settings.syncInterval === sec
-
- return (
- <TouchableOpacity
- key={sec}
- style={[
- styles.gridOption,
- {
- borderColor: colors.border,
- backgroundColor: colors.background
- },
- isSelected && {
- borderColor: colors.primary,
- backgroundColor: colors.primary + "20"
- }
- ]}
- onPress={() => {
- const next = {
- ...settings,
- syncInterval: sec,
- syncPreset: "custom" as const
- }
- setSettings(next)
- debouncedSave(next)
- }}
- activeOpacity={0.7}
- >
- <Text
- style={[
- styles.gridLabel,
- {
- color: isSelected ? colors.primary : colors.text
- }
- ]}
- >
- {labels[sec]}
- </Text>
- </TouchableOpacity>
- )
- })}
- </View>
- </View>
-
- {/* Retry Interval */}
- <View style={styles.settingBlock}>
- <Text style={[styles.blockLabel, { color: colors.text }]}>Retry Interval</Text>
- <Text style={[styles.blockHint, { color: colors.textSecondary }]}>
- Wait time before retrying failed uploads
- </Text>
-
- <View style={styles.optionsGrid}>
- {([30, 300, 900] as const).map((sec) => {
- const labels: Record<number, string> = {
- 30: "30s",
- 300: "5m",
- 900: "15m"
- }
- const isSelected = settings.retryInterval === sec
-
- return (
- <TouchableOpacity
- key={sec}
- style={[
- styles.gridOption,
- {
- borderColor: colors.border,
- backgroundColor: colors.background
- },
- isSelected && {
- borderColor: colors.primary,
- backgroundColor: colors.primary + "20"
- }
- ]}
- onPress={() => {
- const next = {
- ...settings,
- retryInterval: sec,
- syncPreset: "custom" as const
- }
- setSettings(next)
- debouncedSave(next)
- }}
- activeOpacity={0.7}
- >
- <Text
- style={[
- styles.gridLabel,
- {
- color: isSelected ? colors.primary : colors.text
- }
- ]}
- >
- {labels[sec]}
- </Text>
- </TouchableOpacity>
- )
- })}
- </View>
- </View>
-
- {/* Max Retries */}
- <View style={styles.settingBlock}>
- <Text style={[styles.blockLabel, { color: colors.text }]}>Max Retry Attempts</Text>
- <View style={styles.retryGrid}>
- {[3, 5, 10, 0].map((val) => (
- <TouchableOpacity
- key={val}
- style={[
- styles.retryChip,
- {
- borderColor: colors.border,
- backgroundColor: colors.background
- },
- settings.maxRetries === val && {
- borderColor: colors.primary,
- backgroundColor: colors.primary + "20"
- }
- ]}
- onPress={() => {
- const next = {
- ...settings,
- maxRetries: val,
- syncPreset: "custom" as const
- }
- setSettings(next)
- debouncedSave(next)
- }}
- activeOpacity={0.7}
- >
- <Text
- style={[
- styles.retryChipText,
- {
- color: settings.maxRetries === val ? colors.primary : colors.text
- }
- ]}
- >
- {val === 0 ? "∞" : val}
- </Text>
- </TouchableOpacity>
- ))}
- </View>
- <Text style={[styles.blockHint, styles.retryHint, { color: colors.textSecondary }]}>
- {settings.maxRetries === 0
- ? "⚠️ Unlimited retries may cause queue buildup"
- : `Give up after ${settings.maxRetries} failed attempts`}
- </Text>
- </View>
- </View>
-
- <Divider />
-
- {/* Quality Parameters Group */}
- <View style={styles.paramGroup}>
- <Text style={[styles.paramGroupTitle, { color: colors.text }]}>Quality Filters</Text>
-
- {/* Accuracy Filter */}
- <View style={styles.settingRow}>
- <View style={styles.settingContent}>
- <Text style={[styles.settingLabel, { color: colors.text }]}>Filter Inaccurate Locations</Text>
- <Text style={[styles.settingHint, { color: colors.textSecondary }]}>
- Reject low-accuracy GPS readings
- </Text>
- </View>
- <Switch
- value={settings.filterInaccurateLocations}
- onValueChange={(value) =>
- immediateSave({
- ...settings,
- filterInaccurateLocations: value
- })
- }
- trackColor={{
- false: colors.border,
- true: colors.primary + "80"
- }}
- thumbColor={settings.filterInaccurateLocations ? colors.primary : "#f4f3f4"}
- />
- </View>
+ {/* Connection */}
+ <ConnectionSettings
+ settings={settings}
+ endpointInput={endpointInput}
+ onEndpointInputChange={setEndpointInput}
+ onSettingsChange={handleImmediateSave}
+ colors={colors}
+ navigation={navigation}
+ />
- {settings.filterInaccurateLocations && (
- <View style={styles.nestedSetting}>
- <NumericInput
- label="Accuracy Threshold"
- value={accuracyTresholdInput}
- onChange={(val) => handleNumericChange("accuracyTreshold", val, 50)}
- onBlur={() => handleNumericBlur("accuracyTreshold", 50)}
- unit="meters"
- placeholder="50"
- hint="Reject readings with accuracy worse than this"
- colors={colors}
- />
- </View>
- )}
- </View>
- </View>
- )}
- </Card>
- </View>
+ {/* Sync Strategy */}
+ <SyncStrategySettings
+ settings={settings}
+ onSettingsChange={setSettings}
+ onDebouncedSave={handleDebouncedSave}
+ onImmediateSave={handleImmediateSave}
+ colors={colors}
+ />
- {/* Appearance - Simplified */}
+ {/* Appearance */}
<View style={styles.section}>
<SectionTitle>Appearance</SectionTitle>
<Card>
@@ -727,7 +142,7 @@ export function SettingsScreen({ navigation }: ScreenProps) {
</Card>
</View>
- {/* Advanced - Better visual separation */}
+ {/* Advanced */}
<View style={styles.section}>
<SectionTitle>Advanced</SectionTitle>
<Card>
@@ -800,159 +215,6 @@ const styles = StyleSheet.create({
fontWeight: "600",
marginBottom: 2
},
- settingHint: {
- fontSize: 13,
- lineHeight: 18
- },
- inputGroup: {
- marginBottom: 12
- },
- inputHeader: {
- flexDirection: "row",
- justifyContent: "space-between",
- alignItems: "center",
- marginBottom: 10
- },
- inputLabel: {
- fontSize: 15,
- fontWeight: "600"
- },
- protocolBadge: {
- paddingHorizontal: 10,
- paddingVertical: 4,
- borderRadius: 12
- },
- protocolText: {
- fontSize: 11,
- fontWeight: "700"
- },
- input: {
- borderWidth: 1.5,
- padding: 16,
- borderRadius: 12,
- fontSize: 15
- },
- testButton: {
- padding: 16,
- borderRadius: 12,
- alignItems: "center",
- marginTop: 12
- },
- disabledButton: {
- opacity: 0.5
- },
- responseBox: {
- marginTop: 12,
- padding: 14,
- borderWidth: 1.5,
- borderRadius: 12,
- alignItems: "center"
- },
- responseText: {
- fontSize: 14,
- fontWeight: "600"
- },
- presetsContainer: {
- marginBottom: 16
- },
- presetSpacer: {
- height: 8
- },
- advancedToggle: {
- paddingVertical: 14,
- paddingHorizontal: 16,
- alignItems: "center",
- borderRadius: 12,
- borderWidth: 1.5,
- marginTop: 8
- },
- advancedToggleActive: {
- backgroundColor: "transparent"
- },
- advancedToggleInactive: {
- backgroundColor: "transparent"
- },
- advancedText: {
- fontSize: 15,
- fontWeight: "600"
- },
- advancedPanel: {
- marginTop: 16
- },
- customBanner: {
- padding: 14,
- borderRadius: 10,
- marginBottom: 20,
- borderLeftWidth: 4
- },
- customBannerText: {
- fontSize: 13,
- fontWeight: "500"
- },
- paramGroup: {
- marginBottom: 4
- },
- paramGroupTitle: {
- fontSize: 13,
- fontWeight: "700",
- textTransform: "uppercase",
- letterSpacing: 1,
- marginBottom: 16,
- opacity: 0.6
- },
- settingBlock: {
- marginBottom: 20
- },
- blockLabel: {
- fontSize: 15,
- fontWeight: "600",
- marginBottom: 4
- },
- blockHint: {
- fontSize: 13,
- marginBottom: 12,
- lineHeight: 18
- },
- optionsGrid: {
- flexDirection: "row",
- gap: 8,
- flexWrap: "wrap"
- },
- gridOption: {
- minWidth: "22%",
- borderWidth: 2,
- borderRadius: 10,
- paddingVertical: 14,
- alignItems: "center"
- },
- gridLabel: {
- fontSize: 14,
- fontWeight: "600"
- },
- retryGrid: {
- flexDirection: "row",
- gap: 10
- },
- retryChip: {
- flex: 1,
- borderWidth: 2,
- borderRadius: 10,
- paddingVertical: 12,
- alignItems: "center"
- },
- retryChipText: {
- fontSize: 16,
- fontWeight: "700"
- },
- retryHint: {
- marginTop: 8
- },
- nestedSetting: {
- marginTop: 12,
- paddingLeft: 16,
- borderLeftWidth: 3,
- borderLeftColor: "rgba(0,0,0,0.1)"
- },
linkRow: {
flexDirection: "row",
justifyContent: "space-between",
@@ -974,10 +236,5 @@ const styles = StyleSheet.create({
fontSize: 28,
fontWeight: "300",
marginLeft: 12
- },
- httpWarning: {
- marginTop: 6,
- fontSize: 12,
- fontWeight: "500"
}
})
diff --git a/src/services/SettingsService.ts b/src/services/SettingsService.ts
index 56fe26be..21ff5b2b 100644
--- a/src/services/SettingsService.ts
+++ b/src/services/SettingsService.ts
@@ -12,72 +12,73 @@ import { Settings } from "../types/global"
*/
export const SettingsService = {
/**
- * Saves a single setting to native storage
- * Handles type conversion and key mapping
+ * Saves a single setting to native storage.
+ * Handles type conversion and key mapping.
+ * Throws on failure so callers can handle errors explicitly.
*/
- updateSetting: async (key: keyof Settings, value: any): Promise<boolean> => {
- try {
- let stringValue: string
+ updateSetting: async (key: keyof Settings, value: any): Promise<void> => {
+ let stringValue: string
- switch (key) {
- case "interval":
- // UI: seconds → Native: milliseconds
- stringValue = (Number(value) * 1000).toString()
- break
+ switch (key) {
+ case "interval":
+ // UI: seconds → Native: milliseconds
+ stringValue = (Number(value) * 1000).toString()
+ break
- case "fieldMap":
- case "customFields":
- // Object → JSON string
- stringValue = JSON.stringify(value)
- break
+ case "fieldMap":
+ case "customFields":
+ // Object → JSON string
+ stringValue = JSON.stringify(value)
+ break
- case "distance":
- // JS key: 'distance' → Native key: 'minUpdateDistance'
- await NativeLocationService.saveSetting("minUpdateDistance", value.toString())
- // Also save as 'distance' for JS hydration
- stringValue = value.toString()
- break
+ case "distance":
+ // JS key: 'distance' → Native key: 'minUpdateDistance'
+ await NativeLocationService.saveSetting("minUpdateDistance", value.toString())
+ // Also save as 'distance' for JS hydration
+ stringValue = value.toString()
+ break
- case "syncInterval":
- case "retryInterval":
- case "maxRetries":
- case "accuracyThreshold":
- // Already in correct format (numbers)
- stringValue = String(value)
- break
+ case "syncInterval":
+ case "retryInterval":
+ case "maxRetries":
+ case "accuracyThreshold":
+ // Already in correct format (numbers)
+ stringValue = String(value)
+ break
- case "filterInaccurateLocations":
- case "isOfflineMode":
- // Boolean → "true"/"false"
- stringValue = String(value)
- break
+ case "filterInaccurateLocations":
+ case "isOfflineMode":
+ // Boolean → "true"/"false"
+ stringValue = String(value)
+ break
- default:
- // Handles 'endpoint', 'syncPreset', etc.
- stringValue = String(value)
- }
-
- await NativeLocationService.saveSetting(key, stringValue)
- return true
- } catch (err) {
- console.error(`[SettingsService] Failed to save ${key}:`, err)
- return false
+ default:
+ // Handles 'endpoint', 'syncPreset', etc.
+ stringValue = String(value)
}
+
+ await NativeLocationService.saveSetting(key, stringValue)
},
/**
- * Updates multiple settings in parallel
+ * Updates multiple settings in parallel.
+ * Throws if any individual setting fails to persist.
*/
updateMultiple: async (settingsUpdate: Partial<Settings>): Promise<void> => {
- const keys = Object.keys(settingsUpdate)
- console.log(`[SettingsService] Batch updating ${keys.length} settings`)
+ const entries = Object.entries(settingsUpdate)
+ console.log(`[SettingsService] Batch updating ${entries.length} settings`)
- const promises = Object.entries(settingsUpdate).map(([key, val]) =>
- SettingsService.updateSetting(key as keyof Settings, val)
+ const results = await Promise.allSettled(
+ entries.map(([key, val]) => SettingsService.updateSetting(key as keyof Settings, val))
)
- await Promise.all(promises)
- console.log("[SettingsService] ✅ Batch update completed")
+ const failures = results.filter((r) => r.status === "rejected")
+ if (failures.length > 0) {
+ failures.forEach((f) => console.error("[SettingsService] Setting failed:", (f as PromiseRejectedResult).reason))
+ throw new Error(`Failed to save ${failures.length} of ${entries.length} settings`)
+ }
+
+ console.log("[SettingsService] Batch update completed")
}
}
diff --git a/src/services/__tests__/SettingsService.test.ts b/src/services/__tests__/SettingsService.test.ts
index f8899175..8a5c068a 100644
--- a/src/services/__tests__/SettingsService.test.ts
+++ b/src/services/__tests__/SettingsService.test.ts
@@ -64,15 +64,14 @@ describe("SettingsService", () => {
expect(mockSaveSetting).toHaveBeenCalledWith("endpoint", "https://example.com/api")
})
- it("returns true on success", async () => {
- const result = await SettingsService.updateSetting("endpoint", "https://test.com")
- expect(result).toBe(true)
+ it("does not throw on success", async () => {
+ await SettingsService.updateSetting("endpoint", "https://test.com")
+ expect(mockSaveSetting).toHaveBeenCalledWith("endpoint", "https://test.com")
})
- it("returns false on error", async () => {
+ it("propagates errors to caller", async () => {
mockSaveSetting.mockRejectedValueOnce(new Error("Native error"))
- const result = await SettingsService.updateSetting("endpoint", "test")
- expect(result).toBe(false)
+ await expect(SettingsService.updateSetting("endpoint", "test")).rejects.toThrow("Native error")
})
})
diff --git a/src/utils/exportConverters.ts b/src/utils/exportConverters.ts
index ca092003..1267223d 100644
--- a/src/utils/exportConverters.ts
+++ b/src/utils/exportConverters.ts
@@ -145,3 +145,54 @@ export const convertToKML = (data: LocationCoords[]): string => {
</kml>`
return kml
}
+
+export type ExportFormat = "csv" | "geojson" | "gpx" | "kml"
+
+export interface ExportFormatConfig {
+ label: string
+ subtitle: string
+ description: string
+ icon: string
+ extension: string
+ mimeType: string
+ convert: (data: LocationCoords[]) => string
+}
+
+export const EXPORT_FORMATS: Record<ExportFormat, ExportFormatConfig> = {
+ csv: {
+ label: "CSV",
+ subtitle: "Spreadsheet Format",
+ description: "Excel, Google Sheets, data analysis",
+ icon: "📊",
+ extension: ".csv",
+ mimeType: "text/csv",
+ convert: convertToCSV
+ },
+ geojson: {
+ label: "GeoJSON",
+ subtitle: "Geographic Data",
+ description: "Mapbox, Leaflet, QGIS, ArcGIS",
+ icon: "🗺️",
+ extension: ".geojson",
+ mimeType: "application/json",
+ convert: convertToGeoJSON
+ },
+ gpx: {
+ label: "GPX",
+ subtitle: "GPS Exchange",
+ description: "Garmin, Strava, Google Earth",
+ icon: "📍",
+ extension: ".gpx",
+ mimeType: "application/gpx+xml",
+ convert: convertToGPX
+ },
+ kml: {
+ label: "KML",
+ subtitle: "Keyhole Markup Language",
+ description: "Google Earth, Google Maps, ArcGIS",
+ icon: "🌍",
+ extension: ".kml",
+ mimeType: "application/vnd.google-earth.kml+xml",
+ convert: convertToKML
+ }
+}
diff --git a/src/utils/queueStatus.ts b/src/utils/queueStatus.ts
index 62a84e67..f7f2eba5 100644
--- a/src/utils/queueStatus.ts
+++ b/src/utils/queueStatus.ts
@@ -4,9 +4,7 @@
*/
import { ThemeColors } from "../types/global"
-
-const HIGH_QUEUE_THRESHOLD = 50
-const CRITICAL_QUEUE_THRESHOLD = 100
+import { HIGH_QUEUE_THRESHOLD, CRITICAL_QUEUE_THRESHOLD } from "../constants"
/**
* Returns the appropriate color for the queue count based on severity