Colota - Android GPS Location tracker
refactor(tracking): fields first, and the profile that owns them (#853)
Max Dietrichb0ff2c7d23a1
diff --git a/apps/docs/docs/configuration/sync-presets.md b/apps/docs/docs/configuration/sync-presets.mdindex e6d4a740..42051e21 100644--- a/apps/docs/docs/configuration/sync-presets.md+++ b/apps/docs/docs/configuration/sync-presets.md@@ -4,27 +4,29 @@ sidebar_position: 1# Sync Presets-Colota includes built-in presets that configure tracking interval, movement threshold, and sync interval together.+Colota includes built-in presets that configure interval, movement threshold, sync interval and retry interval together. Each row on the screen prints its fix rate, its sync cadence and what it costs.-| Preset | Interval | Distance | Sync Interval | Best For |-| --------------- | -------- | -------- | ------------- | --------------- |-| **Instant** | 5s | 0m | Instant (0s) | City navigation |-| **Balanced** | 30s | 2m | 5 minutes | Daily commute |-| **Power Saver** | 60s | 2m | 15 minutes | Long trips |-| **Custom** | 1s-∞ | 0m-∞ | 0s-∞ | Advanced users |+| Preset | Interval | Distance | Sync interval | Retry interval | Cost |+| --------------- | -------- | -------- | ------------- | -------------- | -------------------------------- |+| **Instant** | 5 s | 0 m | Each fix | 30 s | Most battery, finest track |+| **Balanced** | 30 s | 2 m | 5 min | 5 min | Moderate battery, fewer wake-ups |+| **Power saver** | 60 s | 2 m | 15 min | 15 min | Least battery, coarser track |+| **Custom** | 1 s-∞ | 0 m-∞ | 0 s-∞ | last preset's | Printed from the numbers you set |-Select a preset in **Settings → Tracking & Sync** or choose **Custom** to configure each parameter individually.+Select a preset in **Settings → Tracking & sync → Recording** or choose **Custom** to set the interval and movement threshold under it. A preset owns those four values and nothing else: choosing a row in **Sync interval** or typing an interval there moves the preset to Custom, while the sync condition, the network name, the batch size and the accuracy filter leave it alone. The retry interval is how long a failed sync waits before the next attempt; Custom keeps whichever preset held it last.++If a [tracking profile](/docs/guides/tracking-profiles) is active it supplies its own sync interval, and the **Sync interval** group opens with a line naming the profile and the cadence in force.## Sync ConditionControls when Colota uploads locations. Locations are always recorded and queued locally regardless of this setting.-| Option | Behavior |-| ----------------- | ------------------------------------------------------ |-| **Any Network** | Upload on any connection (default) |-| **Wi-Fi Only** | Upload only on unmetered networks (Wi-Fi, Ethernet) |-| **Specific SSID** | Upload only when connected to a specific Wi-Fi network |-| **VPN** | Upload only when a VPN connection is active |+| Option | Behavior |+| -------------------------- | ----------------------------------------------------------------------------- |+| **Any network** | Syncs over mobile data as well as Wi-Fi, counting against your plan (default) |+| **Wi-Fi or Ethernet** | Syncs only on unmetered networks; fixes wait on mobile data |+| **Specific Wi-Fi network** | Syncs only on the network you name; nothing syncs until one is named |+| **VPN** | Syncs only while a VPN is up |This is useful for:@@ -32,8 +34,8 @@ This is useful for:- **Private backends** - Only sync when on your home network or VPN- **Roaming** - Prevent expensive data charges while traveling abroad-Configure this in **Settings → Tracking & Sync → Advanced Settings → Network Settings → Sync Only On**.+Configure this in **Settings → Tracking & sync → Sync only on**. For a specific network, type the name as shown in Wi-Fi settings, or take the one the phone is on from the button under the field.## Offline Mode-In [offline mode](/docs/configuration/server-settings#offline-mode), network settings (sync interval, retry behavior, sync condition) are hidden since no syncing occurs. Preset descriptions adjust to show only tracking parameters. For displaying the maps network requests are still made to maps.mxd.codes. See [Offline Maps](/docs/guides/offline-maps) for predownloading maps.+In [offline mode](/docs/configuration/server-settings#offline-mode), the Sync interval and Sync only on groups are hidden since no syncing occurs, and the retry interval in the table above is not used. Preset rows show only their recording values. For displaying the maps network requests are still made to maps.mxd.codes. See [Offline maps](/docs/guides/offline-maps) for predownloading maps.diff --git a/apps/docs/docs/configuration/tracking-settings.md b/apps/docs/docs/configuration/tracking-settings.mdindex 45f6ec97..6f0fc4de 100644--- a/apps/docs/docs/configuration/tracking-settings.md+++ b/apps/docs/docs/configuration/tracking-settings.md@@ -4,28 +4,28 @@ sidebar_position: 2# Tracking Settings-Found under **Settings → Tracking & Sync → Tracking Configuration**.+Found under **Settings → Tracking & sync → Recording**. The accuracy filter has its own group, **Accuracy filter**, at the bottom of the same screen.## Available Settings-| Setting | Description | Default | Minimum |-| ------------------ | ------------------------------------ | --------- | ------- |-| Tracking Interval | Time between GPS fixes | 5 seconds | 1s |-| Movement Threshold | Minimum movement to trigger update | 0 | 0 |-| Accuracy Threshold | Filter out fixes above this accuracy | 50 | 1 |-| Filter Inaccurate | Enable/disable accuracy filtering | Disabled | On/Off |+| Setting | Description | Default | Minimum |+| --------------------------- | --------------------------------- | --------- | ------- |+| Interval | Time between GPS fixes | 5 seconds | 1 s |+| Movement threshold | Minimum movement to keep a fix | 0 | 0 |+| Filter inaccurate locations | Enable/disable accuracy filtering | Off | On/Off |+| Accuracy threshold | Drop fixes rated worse than this | 50 | 1 |-The two distance settings use whichever unit you picked in **Settings → Appearance**, so they read as meters or feet. There is no upper limit on any of the three numbers.+The interval and movement threshold sit under **Custom** in the Recording group; picking a preset sets both. The two distance settings use whichever unit you picked in **Settings → Appearance**, so they read as meters or feet. Every number field takes whole numbers only and states its minimum under its label; a value below it is set to the minimum when you leave the field. There is no upper limit on any of the three numbers.:::info[Tracking profiles override two of these]-If a [tracking profile](/docs/guides/tracking-profiles) is active, it supplies its own tracking interval and movement threshold for as long as its condition holds. The values on this screen are what the app falls back to when no profile applies, so a profile is the usual reason fixes arrive at a different rate than the one set here.+If a [tracking profile](/docs/guides/tracking-profiles) is active, it supplies its own interval, movement threshold and sync interval for as long as its condition holds. The Recording and Sync interval groups then open with a line naming the profile and the values in force, and the rows below stay the defaults the app falls back to when no profile applies. A profile is the usual reason fixes arrive at a different rate than the one set here.:::-## Tracking Interval+## Interval-How often the app requests a GPS fix. Shorter intervals give denser track points but drain more battery.+How often the app requests a GPS fix. Shorter intervals keep the GPS awake more of the time and record more points.- **1-5 seconds**: High detail, suitable for driving or cycling- **15-30 seconds**: Good balance for walking or commuting@@ -33,14 +33,14 @@ How often the app requests a GPS fix. Shorter intervals give denser track points## Movement Threshold-Only records a new location if you've moved at least this far since the last recorded point. Useful for filtering out stationary noise.+Only records a new location if you've moved at least this far since the last recorded point. Both the interval and this distance must pass before a fix is kept, so a higher threshold saves storage and sync data rather than battery. It is not applied inside a pause zone or by a stationary profile.- **0**: Record every GPS fix (default)- **10-50 m**: Skip stationary updates, good for daily use## Accuracy Filter-When enabled, GPS fixes with accuracy worse than the threshold are discarded. This prevents recording poor-quality positions from indoor or urban environments.+When on, fixes the chip rates worse than the threshold are dropped. A stricter threshold leaves gaps indoors and in dense streets, where every fix is rated poorly. The switch's own caption carries the threshold in both states, so turning the filter off hides the field without losing the number.The accuracy value comes from the GPS chip's own estimate of its confidence, not from ground truth. Chips sometimes report a tight accuracy on a position that is badly wrong, and no threshold can reject those, because the fix does not admit to being imprecise. If a stationary device is filling your history with drift, the [Movement Threshold](#movement-threshold) is the setting that keeps those points out of the log.@@ -55,5 +55,5 @@ Colota drops these automatically by comparing the chip's reported speed against## See also- [Sync Presets](sync-presets.md) - how often the queue is flushed to your server, and on which connections-- [Tracking Profiles](/docs/guides/tracking-profiles) - switch interval and movement threshold automatically on charging, speed or a stationary phone+- [Tracking profiles](/docs/guides/tracking-profiles) - switch interval and movement threshold automatically on charging, speed or a stationary phone- [Geofencing](/docs/guides/geofencing) - pause GPS entirely inside a zonediff --git a/apps/docs/docs/guides/tracking-profiles.md b/apps/docs/docs/guides/tracking-profiles.mdindex 4b7c3d2a..7b2ee7a1 100644--- a/apps/docs/docs/guides/tracking-profiles.md+++ b/apps/docs/docs/guides/tracking-profiles.md@@ -2,13 +2,13 @@sidebar_position: 2----# Tracking Profiles+# Tracking profilesimport ScreenshotGallery from '@site/src/components/ScreenshotGallery'-Tracking profiles automatically adjust GPS interval, distance filter, and sync settings when conditions like charging, car mode, or speed thresholds are met.+A tracking profile is a rule: while a condition holds, such as charging, Android Auto or a speed, Colota records and syncs with that profile's interval, movement threshold and sync interval instead of the Tracking & sync values.-<ScreenshotGallery screenshots={[ { src: "/img/screenshots/TrackingProfiles.png", label: "Tracking Profiles" }, ]} />+<ScreenshotGallery screenshots={[ { src: "/img/screenshots/TrackingProfiles.png", label: "Tracking profiles" }, ]} />## Use Cases@@ -19,22 +19,28 @@ Tracking profiles automatically adjust GPS interval, distance filter, and sync s## Setup-1. Go to **Settings** → **Tracking Profiles**-2. Tap **Create Profile**-3. Enter a name and select a condition trigger-4. Configure the GPS interval, distance filter, and sync interval-5. Set a priority (higher priority profiles take precedence when multiple conditions match)-6. Tap **Create Profile** to save+1. Go to **Settings** → **Tracking profiles**+2. Tap **Create profile** in the app bar+3. Pick the condition; each row says what watching it costs, and a speed condition asks for the speed+4. Optionally name it (blank saves as the condition's name) and set a priority+5. Set the tracking interval, movement threshold and sync interval; each field says which Tracking & sync value it replaces+6. Tap **Create profile**++The editor's first line reads the rule back as you build it, for example "When charging, track every 5 s, any movement and sync each fix." Tap a profile in the list to edit it; Delete is at the bottom of the editor.++## The list++The list opens with a line that says which profile is in force and its values, "No profile active · Tracking & sync applies: …" while tracking runs without one, or "Profiles apply while tracking runs" while tracking is off. Below it every profile is one row in evaluation order, reading as a sentence: condition, then what it records, then how it syncs, for example "When charging · Every 5 s, any movement · syncs each fix". The row in force opens with "Active". The switch beside a row enables or disables it without opening it; a disabled profile is never in force.## Condition Types-| Condition | Trigger |-| --------------- | --------------------------------------------------------- |-| **Charging** | Phone is plugged in to a power source |-| **Car Mode** | Android Auto is connected |-| **Speed Above** | Average speed exceeds the configured threshold (km/h) |-| **Speed Below** | Average speed drops below the configured threshold (km/h) |-| **Stationary** | Device not moving for approximately 60 seconds |+| Condition | Trigger | Cost |+| --- | --- | --- |+| **Charging** | Phone is plugged in to a power source | Nothing to watch |+| **Android Auto** | Android Auto is connected | Nothing to watch |+| **Speed above** | Average speed exceeds the speed you set (km/h or mph) | Fixes keep flowing to measure it, even below the movement threshold |+| **Speed below** | Average speed drops below the speed you set (km/h or mph) | Fixes keep flowing to measure it, even below the movement threshold |+| **Stationary** | Still for the activation delay (60 s by default) | Fixes keep flowing to measure it; movement threshold not used |Speed conditions use a rolling average of the last 5 GPS readings to avoid triggering on momentary speed spikes. The stationary condition uses a fixed speed threshold (0.3 m/s) that has to hold across 60 seconds of fixes, so unlike speed-below it does not flap on GPS noise near zero. The window is measured over the fixes themselves, so a stretch with no fixes at all is not counted as stillness and the profile waits for the stream instead of switching on.@@ -60,20 +66,20 @@ Your distance filter does not have that effect: whenever a speed or stationary pEach profile overrides the default tracking configuration with:-- **GPS Interval** - How often to request a location fix (seconds)-- **Distance Filter** - Minimum movement required between updates (meters)-- **Sync Interval** - How often to sync with the server (Instant, 1 min, 5 min, 15 min, or Custom)-- **Priority** - Determines which profile wins when multiple conditions match simultaneously (higher = wins)+- **Tracking interval** - How often to request a location fix (seconds)+- **Movement threshold** - Minimum movement required between updates (meters or feet)+- **Sync interval** - How often to sync with the server (Instant, 1 min, 5 min, 15 min, or Custom)+- **Priority** - Determines which profile wins when multiple conditions match simultaneously (higher wins; equal numbers go to the older profile)- **Activation Delay** - How long the condition must keep matching before the profile is applied (seconds, default 0 = immediate). Prevents activating on brief spikes, e.g. a momentary speed reading. For the Stationary condition it instead sets how long the device must be still before the profile activates (default 60s).- **Deactivation Delay** - How long to wait after the condition stops matching before reverting to default settings (seconds). Prevents rapid toggling when conditions fluctuate.-When creating a new profile, GPS interval, distance filter, and sync interval are pre-filled with your current values from main Settings. Each field also shows a hint with the default value for reference.+When creating a new profile, the tracking interval, movement threshold and sync interval are pre-filled with your current Tracking & sync values, and each field says which value it replaces. The values a profile hands back to are the ones the service loaded when tracking started; a Tracking & sync change applies at the next restart.**Choosing delay values:** together the two delays make a profile "sticky" - hard to switch on by accident, hard to switch off by accident. Clean on/off signals like Charging and Android Auto want activation 0 (switch the instant you plug in or connect) plus a small deactivation delay so a brief disconnect or cable wiggle does not drop you. Noisy signals like speed want both: an activation delay to ignore short spikes (a Driving profile won't trigger from one GPS glitch while you walk) and a longer deactivation delay to ride through red lights, traffic and tunnels without flapping. Rule of thumb: if a profile keeps flickering on and off, raise the delays; if it reacts too slowly, lower them. Tracking never stops during either wait - you stay on your defaults through an activation delay, and on the profile through a deactivation delay.## Priority-When multiple conditions match at the same time, the profile with the highest priority wins.+When multiple conditions match at the same time, the profile with the highest priority wins; equal priorities go to the older profile. The list shows profiles in that order, so it is the order they are checked in.:::tip[Combining Profiles]@@ -86,8 +92,8 @@ If you use both a Speed Below and a Stationary profile, give Stationary the high| Profile | Condition | Interval | Distance | Priority | Activation | Deactivation | Use case || --- | --- | --- | --- | --- | --- | --- | --- || Stationary | Stationary | 1800s | 0m | 40 | 60s | n/a | Heartbeat while not moving |-| Driving | Car Mode | 10s | 1m | 30 | 0s | 30s | Detailed route while driving |-| Walking | Speed Below 8 km/h | 60s | 2m | 20 | 20s | 45s | Battery-friendly on foot |+| Driving | Android Auto | 10s | 1m | 30 | 0s | 30s | Detailed route while driving |+| Walking | Speed below 8 km/h | 60s | 2m | 20 | 20s | 45s | Battery-friendly on foot || Charging | Charging | 15s | 0m | 10 | 0s | 30s | High accuracy while plugged in |Note that Stationary has the highest priority so it takes over from Walking when you stop. Charging has the lowest priority so a more specific profile (e.g. Driving) wins when both match.@@ -101,9 +107,16 @@ Note that Stationary has the highest priority so it takes over from Walking when- If the condition matches again before the delay expires, the timer is cancelled- After the delay expires, settings revert to the defaults configured in the Settings screen- Profile changes made in the editor take effect immediately on the running service+- **Tracking & sync** shows the active profile above the Recording and Sync interval groups with the values in force. The rows below are the defaults the profile is overriding## Active Profile Indicators-When a profile is active, the Dashboard shows it: an info card on the map names the active profile. When inside a pause zone, the pause card shows which profile will resume on exit (e.g., "Profile 'Charging' resumes on exit").+When a profile is active, Colota shows it in three places:++- **Dashboard** - The state line reads "Tracking · ProfileName"+- **Tracking profiles** - The list's first line names it with the values in force, and its row opens with "Active"+- **Tracking & sync** - A line above the Recording and Sync interval groups names it with the values in force++All of them clear when the profile deactivates (after the deactivation delay) or when tracking stops.-The indicator disappears automatically when the profile deactivates (after the deactivation delay) or when tracking stops.+A blank name saves as the condition's name, so two untouched charging profiles are both called "Charging"; a setup link import replaces a profile by name, so give profiles you share distinct names.diff --git a/apps/mobile/src/components/features/settings/PresetOption.tsx b/apps/mobile/src/components/features/settings/PresetOption.tsxdeleted file mode 100644index a8b2f3c3..00000000--- a/apps/mobile/src/components/features/settings/PresetOption.tsx+++ /dev/null@@ -1,129 +0,0 @@-/**- * Copyright (C) 2026 Max Dietrich- * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.- */-import React from "react"-import { View, Text, StyleSheet, Pressable } from "react-native"-import { Zap, Check } from "lucide-react-native"-import { SelectablePreset, TRACKING_PRESETS } from "../../../types/global"-import { fonts } from "../../../styles/typography"-import { useTheme } from "../../../hooks/useTheme"-import { RadioDot } from "../../ui/RadioDot"--interface BadgeProps {- icon: React.ReactElement- label: string- color: string-}--function Badge({ icon, label, color }: BadgeProps) {- return (- <View style={[styles.badge, { backgroundColor: color + "20", borderColor: color + "40" }]}>- <View style={styles.badgeContent}>- {icon}- <Text style={[styles.badgeText, { color }]}>{label}</Text>- </View>- </View>- )-}--interface PresetOptionProps {- preset: SelectablePreset- isSelected: boolean- isOfflineMode: boolean- onSelect: (preset: SelectablePreset) => void-}--export function PresetOption({ preset, isSelected, isOfflineMode, onSelect }: PresetOptionProps) {- const { colors } = useTheme()- const config = TRACKING_PRESETS[preset]- const showRecommendedBadge = preset === "balanced"- const showWarningBadge = config.batteryImpact === "High"-- return (- <Pressable- style={({ pressed }) => [pressed && { opacity: colors.pressedOpacity }]}- onPress={() => onSelect(preset)}- accessibilityRole="radio"- accessibilityState={{ checked: isSelected }}- >- <View style={styles.content}>- <View style={styles.leftContent}>- <View style={styles.textContent}>- <View style={styles.titleRow}>- <Text- style={[- styles.label,- isSelected ? { color: colors.primaryDark, ...fonts.bold } : { color: colors.text }- ]}- >- {config.label}- </Text>- {showRecommendedBadge && (- <Badge icon={<Check size={10} color={colors.success} />} label="Recommended" color={colors.success} />- )}- {showWarningBadge && (- <Badge- icon={<Zap size={10} color={colors.warning} />}- label="High Battery Usage"- color={colors.warning}- />- )}- </View>- <Text style={[styles.description, { color: colors.textSecondary }]}>- {isOfflineMode ? config.description.split(" • ")[0] : config.description}- </Text>- </View>- </View>-- <RadioDot selected={isSelected} />- </View>- </Pressable>- )-}--const styles = StyleSheet.create({- content: {- flexDirection: "row",- alignItems: "center",- paddingVertical: 12- },- leftContent: {- flex: 1- },- textContent: {- flex: 1- },- titleRow: {- flexDirection: "row",- alignItems: "center",- flexWrap: "wrap",- gap: 8,- marginBottom: 4- },- label: {- fontSize: 16,- ...fonts.semiBold,- letterSpacing: -0.2- },- badge: {- paddingHorizontal: 8,- paddingVertical: 3,- borderRadius: 6- },- badgeContent: {- flexDirection: "row",- alignItems: "center",- gap: 4- },- badgeText: {- fontSize: 10,- ...fonts.bold,- letterSpacing: 0.3- },- description: {- fontSize: 13,- ...fonts.regular,- lineHeight: 18- }-})diff --git a/apps/mobile/src/components/features/settings/SyncIntervalPicker.tsx b/apps/mobile/src/components/features/settings/SyncIntervalPicker.tsxnew file mode 100644index 00000000..86bb5415--- /dev/null+++ b/apps/mobile/src/components/features/settings/SyncIntervalPicker.tsx@@ -0,0 +1,170 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import React, { useEffect, useRef, useState } from "react"+import { View, Text, StyleSheet } from "react-native"+import { useTheme } from "../../../hooks/useTheme"+import { useTimeout } from "../../../hooks/useTimeout"+import { fontSizes, fonts, lineHeights } from "../../../styles/typography"+import {+ SAVE_SUCCESS_DISPLAY_MS,+ SYNC_INTERVAL_LABELS,+ SYNC_INTERVAL_PRESETS,+ SYNC_INTERVAL_SUBS,+ size,+ space+} from "../../../constants"+import { NumericInput } from "../../ui/NumericInput"+import { RadioRow } from "../../ui/RadioRow"+import { formatDuration } from "../../../utils/dashboardState"+import { parseWholeNumber, wholeNumberError } from "../../../utils/settingsValidation"++type SyncIntervalPickerProps = {+ /** A heading above the group; the settings screen titles the card instead and passes neither. */+ label?: string+ hint?: string+ value: number+ /** The floor a blurred value is clamped to. Settings takes 1, a profile takes 0. */+ min?: number+ /** Pull the first row up under a SectionTitle or the heading; off when a row precedes the group. */+ pullUp?: boolean+ /** A preset row was chosen. */+ onSelect: (seconds: number) => void+ /** A valid number was typed into the custom field. */+ onChange: (seconds: number) => void+ /** An invalid number was corrected on blur. */+ onClamp: (seconds: number) => void+ testIDPrefix?: string+}++/**+ * The presets, Custom, and the field Custom reveals. Two screens draw this, and when it was+ * copy-pasted both carried the same defect: Custom seeded a hardcoded 1800 and saved it, throwing+ * away the interval you had.+ *+ * Custom mode cannot be derived from the value, because every number a user might start from is+ * also a preset. It is state here, and opening Custom saves nothing at all - it only seeds the+ * field from the current value and waits for a real one.+ */+export function SyncIntervalPicker({+ label,+ hint,+ value,+ min = 1,+ pullUp = true,+ onSelect,+ onChange,+ onClamp,+ testIDPrefix = "sync-interval"+}: SyncIntervalPickerProps) {+ const { colors } = useTheme()+ const [customOpen, setCustomOpen] = useState(false)+ const [input, setInput] = useState(value.toString())+ const [clampMessage, setClampMessage] = useState<string | undefined>()+ const clampTimer = useTimeout()+ const isCustom = customOpen || !SYNC_INTERVAL_PRESETS.includes(value)++ const emitted = useRef(value)+ useEffect(() => {+ if (value !== emitted.current) {+ emitted.current = value+ setInput(value.toString())+ }+ }, [value])++ const report = (seconds: number, notify: (seconds: number) => void) => {+ emitted.current = seconds+ notify(seconds)+ }++ const fieldHint = `${min > 0 ? `At least ${min} s. ` : ""}Longer means fewer requests and a later server.`++ return (+ <View>+ {label ? <Text style={[styles.label, { color: colors.text }]}>{label}</Text> : null}+ {hint ? <Text style={[styles.hint, { color: colors.textSecondary }]}>{hint}</Text> : null}++ <View accessibilityRole="radiogroup" style={pullUp && styles.group}>+ {SYNC_INTERVAL_PRESETS.map((seconds) => (+ <RadioRow+ key={seconds}+ testID={`${testIDPrefix}-${seconds}`}+ label={SYNC_INTERVAL_LABELS[seconds]}+ sub={SYNC_INTERVAL_SUBS[seconds]}+ selected={!isCustom && value === seconds}+ onPress={() => {+ setCustomOpen(false)+ report(seconds, onSelect)+ }}+ />+ ))}+ <RadioRow+ testID={`${testIDPrefix}-custom`}+ label="Custom"+ sub={+ isCustom+ ? value === 0+ ? "Syncs each fix"+ : `Syncs every ${formatDuration(value)}`+ : "Set your own interval"+ }+ selected={isCustom}+ onPress={() => {+ setInput(value.toString())+ setCustomOpen(true)+ }}+ />++ {isCustom && (+ <View style={styles.customField}>+ <NumericInput+ label="Sync interval"+ value={input}+ onChange={(next) => {+ setInput(next)+ setClampMessage(undefined)+ const parsed = parseWholeNumber(next)+ if (parsed !== null && parsed >= min) report(parsed, onChange)+ }}+ onBlur={() => {+ const parsed = parseWholeNumber(input)+ if (parsed !== null && parsed >= min) return+ setInput(min.toString())+ setClampMessage(`Set to ${min} s`)+ clampTimer.set(() => setClampMessage(undefined), SAVE_SUCCESS_DISPLAY_MS)+ report(min, onClamp)+ }}+ unit="s"+ placeholder="300"+ hint={fieldHint}+ error={wholeNumberError(input, min, "s")}+ message={clampMessage}+ />+ </View>+ )}+ </View>+ </View>+ )+}++const styles = StyleSheet.create({+ label: {+ fontSize: fontSizes.label,+ ...fonts.semiBold,+ marginBottom: space.xs+ },+ hint: {+ fontSize: fontSizes.description,+ ...fonts.regular,+ lineHeight: lineHeights.description+ },+ group: {+ marginTop: -space.sm+ },+ customField: {+ paddingLeft: size.iconColumn,+ marginTop: -space.xs+ }+})diff --git a/apps/mobile/src/components/features/settings/SyncStrategySettings.tsx b/apps/mobile/src/components/features/settings/SyncStrategySettings.tsxindex be0ce26b..8f79155b 100644--- a/apps/mobile/src/components/features/settings/SyncStrategySettings.tsx+++ b/apps/mobile/src/components/features/settings/SyncStrategySettings.tsx@@ -4,14 +4,36 @@*/import React, { useState, useCallback, useEffect } from "react"-import { Text, StyleSheet, Switch, View, Pressable, TextInput, AppState } from "react-native"-import { Lightbulb, ChevronDown, ChevronUp } from "lucide-react-native"-import { Settings, TRACKING_PRESETS, SelectablePreset, ThemeColors, SyncCondition } from "../../../types/global"-import { fonts, fontSizes } from "../../../styles/typography"-import { SYNC_INTERVAL_PRESETS, SYNC_INTERVAL_LABELS, OVERLAND_BATCH_MIN, OVERLAND_BATCH_MAX } from "../../../constants"-import { SectionTitle, Card, Divider, NumericInput, SettingRow } from "../../index"-import { PresetOption } from "./PresetOption"+import { Text, StyleSheet, View, AppState } from "react-native"+import { UserRoundPen } from "lucide-react-native"+import {+ Settings,+ TRACKING_PRESETS,+ SelectablePreset,+ SyncCondition,+ SavedTrackingProfile+} from "../../../types/global"+import { fonts, fontSizes, lineHeights } from "../../../styles/typography"+import { OVERLAND_BATCH_MAX, OVERLAND_BATCH_MIN, SAVE_SUCCESS_DISPLAY_MS, size, space } from "../../../constants"+import {+ Button,+ Card,+ Divider,+ NumericInput,+ RadioRow,+ SectionTitle,+ SettingRow,+ StateLine,+ TextField,+ Toggle+} from "../../index"+import { SyncIntervalPicker } from "./SyncIntervalPicker"+import { useTheme } from "../../../hooks/useTheme"+import { useTimeout } from "../../../hooks/useTimeout"import { shortDistanceUnit, inputToMeters, metersToInput } from "../../../utils/geo"+import { syncSummary, trackingSummary } from "../../../utils/dashboardState"+import { recordingClause } from "../../../utils/profileRow"+import { parseWholeNumber, wholeNumberError } from "../../../utils/settingsValidation"import { isOverlandFormat } from "../../../utils/apiPayload"import NativeLocationService from "../../../services/NativeLocationService"@@ -20,24 +42,44 @@ interface SyncStrategySettingsProps {onSettingsChange: (newSettings: Settings) => voidonDebouncedSave: (newSettings: Settings) => voidonImmediateSave: (newSettings: Settings) => void- colors: ThemeColors+ /** The profile in force, whose values the Recording and Sync interval groups then show as overridden. */+ activeProfile?: SavedTrackingProfile | null}+type NumericKey = "interval" | "distance" | "accuracyThreshold"++const NUMERIC_MIN: Record<NumericKey, number> = { interval: 1, distance: 0, accuracyThreshold: 1 }++const SYNC_CONDITION_OPTIONS: { value: SyncCondition; label: string; sub: string }[] = [+ {+ value: "any",+ label: "Any network",+ sub: "Mobile data and Wi-Fi · syncs never wait, counts against your data plan"+ },+ { value: "wifi_any", label: "Wi-Fi or Ethernet", sub: "Unmetered networks only · fixes wait on mobile data" },+ { value: "wifi_ssid", label: "Specific Wi-Fi network", sub: "One network by name · fixes wait elsewhere" },+ { value: "vpn", label: "VPN", sub: "Only while a VPN is up · fixes wait otherwise" }+]++const lowerFirst = (text: string) => text.charAt(0).toLowerCase() + text.slice(1)+export function SyncStrategySettings({settings,onSettingsChange,onDebouncedSave,onImmediateSave,- colors+ activeProfile = null}: SyncStrategySettingsProps) {+ const { colors } = useTheme()+ const unit = shortDistanceUnit()const [intervalInput, setIntervalInput] = useState(settings.interval.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 [overlandBatchSizeInput, setOverlandBatchSizeInput] = useState(settings.overlandBatchSize.toString())- const [showAdvanced, setShowAdvanced] = useState(false)+ const [clampMessage, setClampMessage] = useState<{ key: string; text: string } | null>(null)+ const clampTimer = useTimeout()const showOverlandBatchSize = isOverlandFormat(settings.apiTemplate, settings.dawarichMode)const [currentSsid, setCurrentSsid] = useState("")@@ -56,59 +98,58 @@ export function SyncStrategySettings({return () => sub.remove()}, [settings.syncCondition])- const isCustomSyncInterval = !SYNC_INTERVAL_PRESETS.includes(settings.syncInterval)-- // Sync inputs with settings changes (e.g. preset selection)+ // A preset press rewrites the fields; a keystroke that already means the stored value keeps its text.useEffect(() => {- setIntervalInput(settings.interval.toString())- setDistanceInput(metersToInput(settings.distance ?? 0).toString())- setAccuracyThresholdInput(metersToInput(settings.accuracyThreshold).toString())- setSyncIntervalInput(settings.syncInterval.toString())- setOverlandBatchSizeInput(settings.overlandBatchSize.toString())- }, [- settings.interval,- settings.distance,- settings.accuracyThreshold,- settings.syncInterval,- settings.overlandBatchSize- ])-- const handleNumericChange = useCallback(- (key: "interval" | "distance" | "accuracyThreshold", value: string, min: number = 0) => {- if (key === "interval") setIntervalInput(value)- if (key === "distance") setDistanceInput(value)- if (key === "accuracyThreshold") setAccuracyThresholdInput(value)-- const num = Number(value)- if (!isNaN(num) && num >= min) {- const stored = key === "distance" || key === "accuracyThreshold" ? inputToMeters(num) : num- const next = { ...settings, [key]: stored, syncPreset: "custom" as const }- onDebouncedSave(next)- }- },- [settings, onDebouncedSave]- )+ const keep = (shown: number) => (text: string) => (parseWholeNumber(text) === shown ? text : shown.toString())+ setIntervalInput(keep(settings.interval))+ setDistanceInput(keep(metersToInput(settings.distance ?? 0)))+ setAccuracyThresholdInput(keep(metersToInput(settings.accuracyThreshold)))+ setOverlandBatchSizeInput(keep(settings.overlandBatchSize))+ }, [settings.interval, settings.distance, settings.accuracyThreshold, settings.overlandBatchSize])++ const noteClamp = (key: string, text: string) => {+ setClampMessage({ key, text })+ clampTimer.set(() => setClampMessage(null), SAVE_SUCCESS_DISPLAY_MS)+ }+ const clampNote = (key: string) => (clampMessage?.key === key ? clampMessage.text : undefined)- const handleNumericBlur = useCallback(- (key: "interval" | "distance" | "accuracyThreshold", min: number = 0) => {- const currentStr =- key === "interval" ? intervalInput : key === "distance" ? distanceInput : accuracyThresholdInput- 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 === "accuracyThreshold") setAccuracyThresholdInput(min.toString())-- const stored = key === "distance" || key === "accuracyThreshold" ? inputToMeters(val) : val- const next = { ...settings, [key]: stored }- onSettingsChange(next)- onImmediateSave(next)- }- },- [intervalInput, distanceInput, accuracyThresholdInput, settings, onSettingsChange, onImmediateSave]- )+ const setInput = (key: NumericKey, value: string) => {+ if (key === "interval") setIntervalInput(value)+ if (key === "distance") setDistanceInput(value)+ if (key === "accuracyThreshold") setAccuracyThresholdInput(value)+ }+ const inputOf = (key: NumericKey) =>+ key === "interval" ? intervalInput : key === "distance" ? distanceInput : accuracyThresholdInput+ const toStored = (key: NumericKey, value: number) => (key === "interval" ? value : inputToMeters(value))++ const handleNumericChange = (key: NumericKey, value: string) => {+ setInput(key, value)+ setClampMessage(null)+ const num = parseWholeNumber(value)+ if (num === null || num < NUMERIC_MIN[key]) return+ const next = { ...settings, [key]: toStored(key, num) }+ onSettingsChange(next)+ onDebouncedSave(next)+ }++ const handleNumericBlur = (key: NumericKey) => {+ const min = NUMERIC_MIN[key]+ const num = parseWholeNumber(inputOf(key))+ if (num !== null && num >= min) return+ setInput(key, min.toString())+ noteClamp(key, `Set to ${min} ${key === "interval" ? "s" : unit}`)+ const next = { ...settings, [key]: toStored(key, min) }+ onSettingsChange(next)+ onImmediateSave(next)+ }++ const isCustomPreset = settings.syncPreset === "custom"++ const handleCustomSelect = useCallback(() => {+ const next: Settings = { ...settings, syncPreset: "custom" }+ onSettingsChange(next)+ onImmediateSave(next)+ }, [settings, onSettingsChange, onImmediateSave])const handlePresetSelect = useCallback((preset: SelectablePreset) => {@@ -127,351 +168,257 @@ export function SyncStrategySettings({[settings, onSettingsChange, onImmediateSave])- const handleGridSelect = useCallback(- (key: string, value: number) => {- const next = {- ...settings,- [key]: value,- syncPreset: "custom" as const- }+ // A preset owns the sync interval, so changing it is Custom; nothing else on the screen flips the preset.+ const handleSyncIntervalChange = useCallback(+ (seconds: number, save: (next: Settings) => void) => {+ const next: Settings = { ...settings, syncInterval: seconds, syncPreset: "custom" }onSettingsChange(next)- onDebouncedSave(next)+ save(next)},- [settings, onSettingsChange, onDebouncedSave]+ [settings, onSettingsChange])- return (- <View style={styles.section}>- <SectionTitle>Tracking Configuration</SectionTitle>- <Card>- <View accessibilityRole="radiogroup">- {(Object.keys(TRACKING_PRESETS) as SelectablePreset[]).map((preset, index) => (- <View key={preset}>- {index > 0 && <View style={styles.presetSpacer} />}- <PresetOption- preset={preset}- isSelected={settings.syncPreset === preset}- isOfflineMode={settings.isOfflineMode}- onSelect={handlePresetSelect}- />- </View>- ))}- </View>+ const handleBatchChange = (value: string) => {+ setOverlandBatchSizeInput(value)+ setClampMessage(null)+ const num = parseWholeNumber(value)+ if (num === null || num < OVERLAND_BATCH_MIN || num > OVERLAND_BATCH_MAX) return+ const next = { ...settings, overlandBatchSize: num }+ onSettingsChange(next)+ onDebouncedSave(next)+ }- <Divider />-- <Pressable- style={({ pressed }) => [styles.advancedToggle, pressed && { opacity: colors.pressedOpacity }]}- onPress={() => setShowAdvanced(!showAdvanced)}- >- <Text style={[styles.advancedText, { color: colors.text }]}>Advanced Settings</Text>- {showAdvanced ? (- <ChevronUp size={20} color={colors.textLight} />- ) : (- <ChevronDown size={20} color={colors.textLight} />- )}- </Pressable>-- {showAdvanced && (- <View style={styles.advancedPanel}>- {settings.syncPreset === "custom" && (- <View style={[styles.customBanner, { backgroundColor: colors.info + "15" }]}>- <View style={styles.bannerRow}>- <Lightbulb size={14} color={colors.info} />- <Text style={[styles.customBannerText, { color: colors.info }]}>Using custom configuration</Text>- </View>- </View>- )}+ const handleBatchBlur = () => {+ const num = parseWholeNumber(overlandBatchSizeInput)+ if (num !== null && num >= OVERLAND_BATCH_MIN && num <= OVERLAND_BATCH_MAX) return+ const clamped = num === null || num < OVERLAND_BATCH_MIN ? OVERLAND_BATCH_MIN : OVERLAND_BATCH_MAX+ setOverlandBatchSizeInput(clamped.toString())+ noteClamp("batch", `Set to ${clamped} points`)+ const next = { ...settings, overlandBatchSize: clamped }+ onSettingsChange(next)+ onImmediateSave(next)+ }++ const batchError = (() => {+ if (overlandBatchSizeInput === "") return undefined+ const num = parseWholeNumber(overlandBatchSizeInput)+ if (num === null) return "A whole number"+ if (num < OVERLAND_BATCH_MIN || num > OVERLAND_BATCH_MAX) return `${OVERLAND_BATCH_MIN} to ${OVERLAND_BATCH_MAX}`+ return undefined+ })()++ const presetSub = (preset: SelectablePreset) => {+ const config = TRACKING_PRESETS[preset]+ return `${trackingSummary(config.interval, config.distance, config.syncInterval, settings.isOfflineMode)} · ${config.cost}`+ }- {/* Tracking Parameters Group */}- <View style={styles.paramGroup}>- <Text style={[styles.paramGroupTitle, { color: colors.text }]}>Tracking Parameters</Text>+ const thresholdShown = `${metersToInput(settings.accuracyThreshold)} ${unit}`+ const filterHint = settings.filterInaccurateLocations+ ? `Drops fixes the chip rates worse than ${thresholdShown}. Stricter leaves gaps indoors.`+ : `Every fix is kept. When on, fixes worse than ${thresholdShown} are dropped.`+ const ssidTyped = settings.syncSsid+ const offerCurrentSsid = currentSsid !== "" && currentSsid.toLowerCase() !== ssidTyped.toLowerCase()++ return (+ <View>+ <Text style={[styles.intro, { color: colors.textSecondary }]}>+ How often a fix is recorded and when it syncs. Changes apply at once and restart tracking.+ </Text>++ <SectionTitle>Recording</SectionTitle>+ <Card rows>+ {activeProfile && (+ <>+ <StateLine+ icon={UserRoundPen}+ iconColor={colors.textSecondary}+ label={`${activeProfile.name} is active`}+ caption={`In force: ${lowerFirst(recordingClause(activeProfile))}`}+ testID="profile-override-recording"+ />+ <Divider tight />+ </>+ )}+ <View accessibilityRole="radiogroup" style={!activeProfile && styles.group}>+ {(Object.keys(TRACKING_PRESETS) as SelectablePreset[]).map((preset) => (+ <RadioRow+ key={preset}+ testID={`preset-${preset}`}+ label={TRACKING_PRESETS[preset].label}+ sub={presetSub(preset)}+ selected={settings.syncPreset === preset}+ onPress={() => handlePresetSelect(preset)}+ />+ ))}+ <RadioRow+ testID="preset-custom"+ label="Custom"+ sub={+ isCustomPreset+ ? trackingSummary(settings.interval, settings.distance, settings.syncInterval, settings.isOfflineMode)+ : "Your own interval and movement threshold"+ }+ selected={isCustomPreset}+ onPress={handleCustomSelect}+ />++ {isCustomPreset && (+ <View style={styles.reveal}><NumericInput- label="Tracking Interval"+ label="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}+ onChange={(val) => handleNumericChange("interval", val)}+ onBlur={() => handleNumericBlur("interval")}+ unit="s"+ placeholder="30"+ hint="At least 1 s. Shorter keeps the GPS awake more of the time and records more points."+ error={wholeNumberError(intervalInput, NUMERIC_MIN.interval, "s")}+ message={clampNote("interval")}/><NumericInput- label="Movement Threshold"+ label="Movement threshold"value={distanceInput}- onChange={(val) => handleNumericChange("distance", val, 0)}- onBlur={() => handleNumericBlur("distance", 0)}- unit={shortDistanceUnit()}- placeholder="10"- hint="Only record if moved more than this distance"- colors={colors}+ onChange={(val) => handleNumericChange("distance", val)}+ onBlur={() => handleNumericBlur("distance")}+ unit={unit}+ placeholder="2"+ hint="0 keeps every fix. Both the interval and this distance must pass before a fix is kept; higher saves storage and sync data, not battery. Not applied in a pause zone or by a stationary profile."+ error={wholeNumberError(distanceInput, NUMERIC_MIN.distance, unit)}+ message={clampNote("distance")}/></View>+ )}+ </View>+ </Card>- {!settings.isOfflineMode && (+ {!settings.isOfflineMode && (+ <>+ <SectionTitle style={styles.groupTop}>Sync interval</SectionTitle>+ <Card rows>+ {activeProfile && (<>- <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}>- {SYNC_INTERVAL_PRESETS.map((sec) => {- const isSelected = settings.syncInterval === sec && !isCustomSyncInterval- return (- <Pressable- key={sec}- style={({ pressed }) => [- styles.gridOption,- {- borderColor: colors.border,- backgroundColor: colors.background- },- isSelected && {- borderColor: colors.primary,- backgroundColor: colors.primary + "20"- },- pressed && { opacity: colors.pressedOpacity }- ]}- onPress={() => handleGridSelect("syncInterval", sec)}- >- <Text style={[styles.gridLabel, { color: isSelected ? colors.primary : colors.text }]}>- {SYNC_INTERVAL_LABELS[sec]}- </Text>- </Pressable>- )- })}- <Pressable- style={({ pressed }) => [- styles.gridOption,- {- borderColor: colors.border,- backgroundColor: colors.background- },- isCustomSyncInterval && {- borderColor: colors.primary,- backgroundColor: colors.primary + "20"- },- pressed && { opacity: colors.pressedOpacity }- ]}- onPress={() => {- if (!isCustomSyncInterval) {- const customValue = 1800- setSyncIntervalInput(customValue.toString())- handleGridSelect("syncInterval", customValue)- }- }}- >- <Text- style={[styles.gridLabel, { color: isCustomSyncInterval ? colors.primary : colors.text }]}- >- Custom- </Text>- </Pressable>- </View>- </View>-- {isCustomSyncInterval && (- <View style={styles.customSyncInput}>- <NumericInput- label="Custom Sync Interval"- value={syncIntervalInput}- onChange={(val) => {- setSyncIntervalInput(val)- const num = Number(val)- if (!isNaN(num) && num >= 1) {- const next = { ...settings, syncInterval: num, syncPreset: "custom" as const }- onDebouncedSave(next)- }- }}- onBlur={() => {- let val = Number(syncIntervalInput)- if (isNaN(val) || val < 1) {- val = 1- setSyncIntervalInput("1")- const next = { ...settings, syncInterval: val, syncPreset: "custom" as const }- onSettingsChange(next)- onImmediateSave(next)- }- }}- unit="seconds"- placeholder="1800"- hint="Custom interval in seconds"- colors={colors}- />- </View>- )}-- {showOverlandBatchSize && (- <View style={styles.customSyncInput}>- <NumericInput- label="Batch Size"- value={overlandBatchSizeInput}- onChange={(val) => {- setOverlandBatchSizeInput(val)- const num = Number(val)- if (!isNaN(num) && num >= OVERLAND_BATCH_MIN && num <= OVERLAND_BATCH_MAX) {- const next = { ...settings, overlandBatchSize: num }- onDebouncedSave(next)- }- }}- onBlur={() => {- let val = Number(overlandBatchSizeInput)- if (isNaN(val) || val < OVERLAND_BATCH_MIN) val = OVERLAND_BATCH_MIN- if (val > OVERLAND_BATCH_MAX) val = OVERLAND_BATCH_MAX- if (val !== settings.overlandBatchSize || overlandBatchSizeInput !== val.toString()) {- setOverlandBatchSizeInput(val.toString())- const next = { ...settings, overlandBatchSize: val }- onSettingsChange(next)- onImmediateSave(next)- }+ <StateLine+ icon={UserRoundPen}+ iconColor={colors.textSecondary}+ label={`${activeProfile.name} is active`}+ caption={`In force: ${syncSummary(activeProfile.syncInterval)}`}+ testID="profile-override-sync"+ />+ <Divider tight />+ </>+ )}+ <SyncIntervalPicker+ pullUp={!activeProfile}+ value={settings.syncInterval}+ onSelect={(seconds) => handleSyncIntervalChange(seconds, onImmediateSave)}+ onChange={(seconds) => handleSyncIntervalChange(seconds, onDebouncedSave)}+ onClamp={(seconds) => handleSyncIntervalChange(seconds, onImmediateSave)}+ />++ {showOverlandBatchSize && (+ <>+ <Divider tight />+ <View style={styles.batch}>+ <NumericInput+ label="Batch size"+ value={overlandBatchSizeInput}+ onChange={handleBatchChange}+ onBlur={handleBatchBlur}+ unit="points"+ placeholder="50"+ hint={`${OVERLAND_BATCH_MIN} to ${OVERLAND_BATCH_MAX} points per request. Larger means fewer requests and bigger payloads.`}+ error={batchError}+ message={clampNote("batch")}+ />+ </View>+ </>+ )}+ </Card>++ <SectionTitle style={styles.groupTop}>Sync only on</SectionTitle>+ <Card rows>+ <View accessibilityRole="radiogroup" style={styles.group}>+ {SYNC_CONDITION_OPTIONS.map(({ value, label, sub }) => (+ <React.Fragment key={value}>+ <RadioRow+ testID={`sync-condition-${value}`}+ label={label}+ sub={sub}+ selected={settings.syncCondition === value}+ onPress={() => {+ const next = { ...settings, syncCondition: value }+ onSettingsChange(next)+ onImmediateSave(next)+ }}+ />+ {/* Belongs to its own row, not to the end of the group: VPN sits below it. */}+ {value === "wifi_ssid" && settings.syncCondition === "wifi_ssid" && (+ <View style={[styles.reveal, offerCurrentSsid ? styles.revealButtonTail : styles.revealTail]}>+ <TextField+ label="Network name"+ testID="sync-ssid-input"+ mono+ value={ssidTyped}+ onChangeText={(text) => {+ const next = { ...settings, syncSsid: text }+ onSettingsChange(next)+ onDebouncedSave(next)}}- unit="points"- placeholder="50"- hint={`Points/upload (${OVERLAND_BATCH_MIN}-${OVERLAND_BATCH_MAX}). Larger = fewer requests, bigger payloads.`}- colors={colors}+ placeholder="As shown in Wi-Fi settings"+ autoCapitalize="none"+ autoCorrect={false}+ error={ssidTyped.trim() === "" ? "Nothing syncs until a network is named" : undefined}/>- </View>- )}-- {/* Sync Condition */}- <View style={styles.settingRowSpaced}>- <Text style={[styles.blockLabel, { color: colors.text }]}>Sync Only On</Text>- <Text style={[styles.blockHint, { color: colors.textSecondary }]}>- {settings.syncCondition === "any" && "Upload on any network connection"}- {settings.syncCondition === "wifi_any" && "Upload only when connected to Wi-Fi"}- {settings.syncCondition === "wifi_ssid" && "Upload only on a specific Wi-Fi network"}- {settings.syncCondition === "vpn" && "Upload only when VPN is active"}- </Text>- <View style={styles.syncConditionChips}>- {(- [- { value: "any", label: "Any" },- { value: "wifi_any", label: "Wi-Fi" },- { value: "wifi_ssid", label: "SSID" },- { value: "vpn", label: "VPN" }- ] as { value: SyncCondition; label: string }[]- ).map((option) => (- <Pressable- key={option.value}+ {offerCurrentSsid && (+ <Button+ variant="secondary"+ title={`Use ${currentSsid}`}+ testID="sync-ssid-use"onPress={() => {- const next = {- ...settings,- syncCondition: option.value,- syncPreset: "custom" as const- }+ const next = { ...settings, syncSsid: currentSsid }onSettingsChange(next)onImmediateSave(next)}}- style={[- styles.syncConditionChip,- {- backgroundColor:- settings.syncCondition === option.value ? colors.primary + "20" : colors.background,- borderColor: settings.syncCondition === option.value ? colors.primary : colors.border- }- ]}- >- <Text- style={[- styles.syncConditionChipText,- { color: settings.syncCondition === option.value ? colors.primary : colors.textSecondary }- ]}- >- {option.label}- </Text>- </Pressable>- ))}- </View>- {settings.syncCondition === "wifi_ssid" && (- <View style={styles.ssidRow}>- <TextInput- style={[- styles.ssidInput,- { borderColor: colors.border, color: colors.text, backgroundColor: colors.background }- ]}- value={settings.syncSsid}- onChangeText={(text) => {- const next = { ...settings, syncSsid: text }- onSettingsChange(next)- onDebouncedSave(next)- }}- placeholder="Enter Wi-Fi SSID"- placeholderTextColor={colors.placeholder}- autoCapitalize="none"- autoCorrect={false}/>- {currentSsid !== "" && currentSsid.toLowerCase() !== settings.syncSsid.toLowerCase() && (- <Pressable- style={({ pressed }) => [- styles.ssidFillButton,- { borderColor: colors.primary, backgroundColor: colors.primary + "15" },- pressed && { opacity: colors.pressedOpacity }- ]}- onPress={() => {- const next = { ...settings, syncSsid: currentSsid }- onSettingsChange(next)- onImmediateSave(next)- }}- >- <Text style={[styles.ssidFillText, { color: colors.primary }]}>Use current</Text>- </Pressable>- )}- </View>- )}- </View>- </View>-- <Divider />- </>- )}-- {/* Quality Parameters Group */}- <View style={styles.paramGroup}>- <Text style={[styles.paramGroupTitle, { color: colors.text }]}>Quality Filters</Text>-- <SettingRow label="Filter Inaccurate Locations" hint="Reject fixes the GPS chip reports as imprecise">- <Switch- value={settings.filterInaccurateLocations}- onValueChange={(value) =>- onImmediateSave({- ...settings,- filterInaccurateLocations: value- })- }- trackColor={{- false: colors.border,- true: colors.primary + "80"- }}- thumbColor={settings.filterInaccurateLocations ? colors.primary : colors.border}- />- </SettingRow>-- {settings.filterInaccurateLocations && (- <View style={[styles.nestedSetting, { borderLeftColor: colors.border }]}>- <NumericInput- label="Accuracy Threshold"- value={accuracyThresholdInput}- onChange={(val) => handleNumericChange("accuracyThreshold", val, 1)}- onBlur={() => handleNumericBlur("accuracyThreshold", 1)}- unit={shortDistanceUnit()}- placeholder="50"- hint="Based on the chip's own estimate, which can be optimistic"- colors={colors}- />- </View>- )}+ )}+ </View>+ )}+ </React.Fragment>+ ))}</View>+ </Card>+ </>+ )}++ <SectionTitle style={styles.groupTop}>Accuracy filter</SectionTitle>+ <Card rows>+ <SettingRow label="Filter inaccurate locations" hint={filterHint}>+ <Toggle+ accessibilityLabel="Filter inaccurate locations"+ value={settings.filterInaccurateLocations}+ onValueChange={(value) => {+ const next = { ...settings, filterInaccurateLocations: value }+ onSettingsChange(next)+ onImmediateSave(next)+ }}+ />+ </SettingRow>++ {settings.filterInaccurateLocations && (+ <View style={styles.filterField}>+ <NumericInput+ label="Accuracy threshold"+ value={accuracyThresholdInput}+ onChange={(val) => handleNumericChange("accuracyThreshold", val)}+ onBlur={() => handleNumericBlur("accuracyThreshold")}+ unit={unit}+ placeholder="50"+ hint={`At least 1 ${unit}. The chip's own estimate, often optimistic; lower drops more fixes.`}+ error={wholeNumberError(accuracyThresholdInput, NUMERIC_MIN.accuracyThreshold, unit)}+ message={clampNote("accuracyThreshold")}+ /></View>)}</Card>@@ -480,129 +427,34 @@ export function SyncStrategySettings({}const styles = StyleSheet.create({- section: {- marginBottom: 24- },- presetSpacer: {- height: 8- },- advancedToggle: {- flexDirection: "row",- justifyContent: "space-between",- alignItems: "center",- paddingVertical: 12- },- advancedText: {- fontSize: 16,- ...fonts.semiBold- },- advancedPanel: {- marginTop: 16- },- customBanner: {- padding: 14,- borderRadius: 10,- marginBottom: 20- },- bannerRow: {- flexDirection: "row",- alignItems: "center",- gap: 8- },- customBannerText: {- fontSize: 13,- ...fonts.medium- },- paramGroup: {- marginBottom: 4- },- paramGroupTitle: {- fontSize: 13,- ...fonts.bold,- textTransform: "uppercase",- letterSpacing: 1,- marginBottom: 16,- opacity: 0.6- },- settingBlock: {- marginBottom: 20- },- blockLabel: {- fontSize: fontSizes.label,- ...fonts.semiBold,- marginBottom: 4- },- blockHint: {- fontSize: 13,+ intro: {+ fontSize: fontSizes.body,...fonts.regular,- marginBottom: 12,- lineHeight: 18- },- optionsGrid: {- flexDirection: "row",- gap: 8,- flexWrap: "wrap"- },- gridOption: {- width: "31%", // ~3 per row with gap in a flexWrap container- borderWidth: 2,- borderRadius: 10,- paddingVertical: 14,- alignItems: "center"- },- gridLabel: {- fontSize: 14,- ...fonts.semiBold- },- settingRowSpaced: {- marginTop: 16- },- nestedSetting: {- marginTop: 12,- paddingLeft: 16,- borderLeftWidth: 3- },- customSyncInput: {- marginTop: 12+ lineHeight: lineHeights.body,+ marginBottom: space.lg},- syncConditionChips: {- flexDirection: "row",- gap: 6+ group: {+ marginTop: -space.sm},- syncConditionChip: {- paddingHorizontal: 12,- paddingVertical: 6,- borderRadius: 12,- borderWidth: 1+ groupTop: {+ marginTop: space.xl},- syncConditionChipText: {- ...fonts.medium,- fontSize: 12+ // The row above already pays space.lg below it; the field's own bottom margin is the card's tail.+ reveal: {+ paddingLeft: size.iconColumn,+ marginTop: -space.xs},- ssidRow: {- flexDirection: "row",- alignItems: "center",- marginTop: 8,- gap: 8+ revealTail: {+ paddingBottom: space.lg},- ssidInput: {- flex: 1,- borderWidth: 1.5,- borderRadius: 8,- paddingHorizontal: 10,- paddingVertical: 6,- fontSize: 13,- fontFamily: "monospace"+ // Button bakes marginVertical space.sm, which completes the 16 to the next row.+ revealButtonTail: {+ paddingBottom: space.sm},- ssidFillButton: {- alignSelf: "flex-start",- paddingHorizontal: 10,- paddingVertical: 6,- borderRadius: 8,- borderWidth: 1+ batch: {+ paddingTop: space.lg},- ssidFillText: {- ...fonts.medium,- fontSize: 12+ filterField: {+ marginTop: -space.xs}})diff --git a/apps/mobile/src/components/features/settings/__tests__/PresetOption.test.tsx b/apps/mobile/src/components/features/settings/__tests__/PresetOption.test.tsxdeleted file mode 100644index e65c89cf..00000000--- a/apps/mobile/src/components/features/settings/__tests__/PresetOption.test.tsx+++ /dev/null@@ -1,104 +0,0 @@-import React from "react"-import { render, fireEvent } from "@testing-library/react-native"-import { TRACKING_PRESETS } from "../../../../types/global"--jest.mock("../../../../hooks/useTheme", () => ({- useTheme: () => ({- colors: {- primary: "#0d9488",- primaryDark: "#115E59",- text: "#000",- textSecondary: "#6b7280",- textLight: "#9ca3af",- success: "#22c55e",- warning: "#f59e0b",- border: "#e5e7eb"- }- })-}))--jest.mock("../../../ui/RadioDot", () => {- const R = require("react")- const { View } = require("react-native")- return {- RadioDot: ({ selected }: any) => R.createElement(View, { testID: selected ? "radio-selected" : "radio-unselected" })- }-})--jest.mock("lucide-react-native", () => {- const R = require("react")- const { View } = require("react-native")- return {- Zap: () => R.createElement(View, null),- Check: () => R.createElement(View, null)- }-})--import { PresetOption } from "../PresetOption"--describe("PresetOption", () => {- const mockOnSelect = jest.fn()-- beforeEach(() => {- jest.clearAllMocks()- })-- it("renders preset label and description", () => {- const { getByText } = render(- <PresetOption preset="balanced" isSelected={false} isOfflineMode={false} onSelect={mockOnSelect} />- )-- expect(getByText(TRACKING_PRESETS.balanced.label)).toBeTruthy()- expect(getByText(TRACKING_PRESETS.balanced.description)).toBeTruthy()- })-- it("shows offline description when isOfflineMode is true", () => {- const { getByText } = render(- <PresetOption preset="balanced" isSelected={false} isOfflineMode={true} onSelect={mockOnSelect} />- )-- expect(getByText(TRACKING_PRESETS.balanced.description.split(" • ")[0])).toBeTruthy()- })-- it("calls onSelect with preset when pressed", () => {- const { getByRole } = render(- <PresetOption preset="instant" isSelected={false} isOfflineMode={false} onSelect={mockOnSelect} />- )-- fireEvent.press(getByRole("radio"))-- expect(mockOnSelect).toHaveBeenCalledWith("instant")- })-- it("shows selected radio dot when isSelected", () => {- const { getByTestId } = render(- <PresetOption preset="balanced" isSelected isOfflineMode={false} onSelect={mockOnSelect} />- )-- expect(getByTestId("radio-selected")).toBeTruthy()- })-- it("shows unselected radio dot when not selected", () => {- const { getByTestId } = render(- <PresetOption preset="balanced" isSelected={false} isOfflineMode={false} onSelect={mockOnSelect} />- )-- expect(getByTestId("radio-unselected")).toBeTruthy()- })-- it("shows Recommended badge for balanced preset", () => {- const { getByText } = render(- <PresetOption preset="balanced" isSelected={false} isOfflineMode={false} onSelect={mockOnSelect} />- )-- expect(getByText("Recommended")).toBeTruthy()- })-- it("shows High Battery Usage badge for instant preset", () => {- const { getByText } = render(- <PresetOption preset="instant" isSelected={false} isOfflineMode={false} onSelect={mockOnSelect} />- )-- expect(getByText("High Battery Usage")).toBeTruthy()- })-})diff --git a/apps/mobile/src/components/features/settings/__tests__/SyncIntervalPicker.test.tsx b/apps/mobile/src/components/features/settings/__tests__/SyncIntervalPicker.test.tsxnew file mode 100644index 00000000..28db81a8--- /dev/null+++ b/apps/mobile/src/components/features/settings/__tests__/SyncIntervalPicker.test.tsx@@ -0,0 +1,141 @@+import React from "react"+import { render, fireEvent, act } from "@testing-library/react-native"+import { SAVE_SUCCESS_DISPLAY_MS } from "../../../../constants"+jest.mock("../../../../hooks/useTheme", () => ({+ useTheme: () => ({ colors: require("@colota/shared").lightColors })+}))++import { SyncIntervalPicker } from "../SyncIntervalPicker"++describe("SyncIntervalPicker", () => {+ const onSelect = jest.fn()+ const onChange = jest.fn()+ const onClamp = jest.fn()++ beforeEach(() => {+ jest.clearAllMocks()+ })++ function renderPicker(value = 300, min?: number) {+ return render(+ <SyncIntervalPicker+ label="Sync interval"+ hint="How often to upload data to server"+ value={value}+ min={min}+ onSelect={onSelect}+ onChange={onChange}+ onClamp={onClamp}+ />+ )+ }++ it("offers every preset plus Custom", () => {+ const { getByTestId } = renderPicker()++ expect(getByTestId("sync-interval-0")).toBeTruthy()+ expect(getByTestId("sync-interval-60")).toBeTruthy()+ expect(getByTestId("sync-interval-300")).toBeTruthy()+ expect(getByTestId("sync-interval-900")).toBeTruthy()+ expect(getByTestId("sync-interval-custom")).toBeTruthy()+ })++ it("reports a preset press without touching the custom field", () => {+ const { getByTestId, queryByDisplayValue } = renderPicker()++ fireEvent.press(getByTestId("sync-interval-60"))++ expect(onSelect).toHaveBeenCalledWith(60)+ expect(queryByDisplayValue("300")).toBeNull()+ })++ it("opens Custom on the interval you already had and reports nothing", () => {+ const { getByTestId, getByDisplayValue } = renderPicker(300)++ fireEvent.press(getByTestId("sync-interval-custom"))++ // Both callers used to seed a hardcoded 1800 here and save it, discarding the interval.+ expect(onSelect).not.toHaveBeenCalled()+ expect(onChange).not.toHaveBeenCalled()+ expect(onClamp).not.toHaveBeenCalled()+ expect(getByDisplayValue("300")).toBeTruthy()+ })++ it("leaves Custom for a preset even though the value it opened on was itself a preset", () => {+ const { getByTestId, queryByDisplayValue } = renderPicker(300)++ fireEvent.press(getByTestId("sync-interval-custom"))+ expect(queryByDisplayValue("300")).toBeTruthy()++ fireEvent.press(getByTestId("sync-interval-60"))++ expect(queryByDisplayValue("300")).toBeNull()+ expect(onSelect).toHaveBeenCalledWith(60)+ })++ it("stays in Custom when the value is off every preset", () => {+ const { getByDisplayValue } = renderPicker(120)++ expect(getByDisplayValue("120")).toBeTruthy()+ })++ it("reports a typed value only once it is valid", () => {+ const { getByDisplayValue } = renderPicker(120)++ fireEvent.changeText(getByDisplayValue("120"), "")+ expect(onChange).not.toHaveBeenCalled()++ fireEvent.changeText(getByDisplayValue(""), "45")+ expect(onChange).toHaveBeenCalledWith(45)+ })++ it("clamps to the floor its caller sets, which differs between settings and a profile", () => {+ const { getByDisplayValue } = renderPicker(120, 0)++ fireEvent.changeText(getByDisplayValue("120"), "-5")+ fireEvent(getByDisplayValue("-5"), "blur")++ expect(onClamp).toHaveBeenCalledWith(0)+ })++ it("prices every row, with Custom printing the interval it holds in the same units as the others", () => {+ const { getByText } = renderPicker(90)++ expect(getByText("Each fix is its own request · radio never idles")).toBeTruthy()+ expect(getByText("One request every 15 min · the server hears you up to 15 min late")).toBeTruthy()+ expect(getByText("Syncs every 90 s")).toBeTruthy()+ })++ it("draws no heading when the caller titles the group itself", () => {+ const { queryByText } = render(+ <SyncIntervalPicker value={300} onSelect={onSelect} onChange={onChange} onClamp={onClamp} />+ )++ expect(queryByText("Sync interval")).toBeNull()+ })++ it("rejects a decimal with an error instead of storing a rounded value", () => {+ const { getByDisplayValue, getByText } = renderPicker(120)++ fireEvent.changeText(getByDisplayValue("120"), "1.5")++ expect(onChange).not.toHaveBeenCalled()+ expect(getByText("A whole number")).toBeTruthy()+ })++ it("says what a blur clamped to, for as long as a save notice shows", () => {+ jest.useFakeTimers()+ const { getByDisplayValue, getByText, queryByText } = renderPicker(120)++ fireEvent.changeText(getByDisplayValue("120"), "")+ fireEvent(getByDisplayValue(""), "blur")++ expect(onClamp).toHaveBeenCalledWith(1)+ expect(getByText("Set to 1 s")).toBeTruthy()+ act(() => {+ jest.advanceTimersByTime(SAVE_SUCCESS_DISPLAY_MS)+ })+ expect(queryByText("Set to 1 s")).toBeNull()+ jest.useRealTimers()+ })+})diff --git a/apps/mobile/src/components/features/settings/__tests__/SyncStrategySettings.test.tsx b/apps/mobile/src/components/features/settings/__tests__/SyncStrategySettings.test.tsxindex ccc89133..218c4c16 100644--- a/apps/mobile/src/components/features/settings/__tests__/SyncStrategySettings.test.tsx+++ b/apps/mobile/src/components/features/settings/__tests__/SyncStrategySettings.test.tsx@@ -1,16 +1,44 @@import React from "react"-import { render, fireEvent } from "@testing-library/react-native"-import { DEFAULT_SETTINGS, TRACKING_PRESETS, Settings } from "../../../../types/global"+import { render, fireEvent, act } from "@testing-library/react-native"+import { DEFAULT_SETTINGS, TRACKING_PRESETS, Settings, SavedTrackingProfile } from "../../../../types/global"+import { SAVE_SUCCESS_DISPLAY_MS } from "../../../../constants"// Mock barrel export (avoids transitive native module imports)jest.mock("../../../index", () => {const R = require("react")- const { View, Text, TextInput } = require("react-native")+ const { View, Text, TextInput, Pressable } = require("react-native")return {+ ListItem: require("../../../../testing/componentStubs").ListItemStub,+ TextField: require("../../../../testing/componentStubs").TextFieldStub,+ Button: function (props: any) {+ return R.createElement(+ Pressable,+ { testID: props.testID, onPress: props.onPress, disabled: props.disabled, accessibilityRole: "button" },+ R.createElement(Text, null, props.title)+ )+ },+ Toggle: function (props: any) {+ return R.createElement(require("react-native").Switch, {+ testID: props.testID,+ value: props.value,+ onValueChange: props.onValueChange,+ disabled: props.disabled,+ accessibilityLabel: props.accessibilityLabel+ })+ },+ RadioRow: ({ testID, label, sub, selected, onPress }: any) =>+ R.createElement(+ Pressable,+ { testID, onPress, accessibilityRole: "radio", accessibilityState: { checked: selected } },+ R.createElement(Text, null, label, selected ? " (selected)" : ""),+ sub ? R.createElement(Text, null, sub) : null+ ),SectionTitle: ({ children }: any) => R.createElement(Text, null, children),- Card: ({ children }: any) => R.createElement(View, null, children),- Divider: () => R.createElement(View, null),- NumericInput: ({ label, value, onChange, onBlur, unit, hint, placeholder: ph }: any) =>+ Card: ({ children, style }: any) => R.createElement(View, { testID: "card", style }, children),+ Divider: () => R.createElement(View, { testID: "divider" }),+ StateLine: ({ label, caption, testID }: any) =>+ R.createElement(View, { testID }, R.createElement(Text, null, label), R.createElement(Text, null, caption)),+ NumericInput: ({ label, value, onChange, onBlur, unit, hint, placeholder: ph, error, message }: any) =>R.createElement(View,null,@@ -23,7 +51,9 @@ jest.mock("../../../index", () => {placeholder: ph,keyboardType: "numeric"}),- R.createElement(Text, null, unit)+ R.createElement(Text, null, unit),+ error ? R.createElement(Text, null, error) : null,+ message ? R.createElement(Text, null, message) : null),SettingRow: ({ label, hint, children }: any) =>R.createElement(@@ -36,41 +66,66 @@ jest.mock("../../../index", () => {}})+jest.mock("../SyncIntervalPicker", () => {+ const R = require("react")+ const { View, Text, Pressable } = require("react-native")+ const { SYNC_INTERVAL_PRESETS } = require("../../../../constants")+ return {+ SyncIntervalPicker: ({ label, hint, value, pullUp, onSelect, onChange }: any) =>+ R.createElement(+ View,+ { testID: "sync-interval-picker", accessibilityValue: { text: pullUp ? "pulled" : "flush" } },+ label ? R.createElement(Text, null, label) : null,+ hint ? R.createElement(Text, null, hint) : null,+ SYNC_INTERVAL_PRESETS.map((seconds: number) =>+ R.createElement(+ Pressable,+ {+ key: seconds,+ testID: `sync-interval-${seconds}`,+ onPress: () => onSelect(seconds),+ accessibilityState: { checked: value === seconds }+ },+ R.createElement(Text, null, String(seconds))+ )+ ),+ R.createElement(Pressable, { testID: "sync-interval-typed", onPress: () => onChange(90) })+ )+ }+})++jest.mock("../../../../hooks/useTheme", () => ({+ useTheme: () => ({ colors: require("@colota/shared").lightColors })+}))+jest.mock("../../../../utils/geo", () => ({shortDistanceUnit: () => "m",inputToMeters: (value: number) => value,metersToInput: (meters: number) => meters}))-jest.mock("../PresetOption", () => ({- PresetOption: ({ preset, isSelected, onSelect }: any) => {- const R = require("react")- const { Pressable, Text } = require("react-native")- return R.createElement(- Pressable,- { testID: `preset-${preset}`, onPress: () => onSelect(preset) },- R.createElement(Text, null, preset, isSelected ? " (selected)" : "")- )+const mockGetCurrentSsid = jest.fn()+jest.mock("../../../../services/NativeLocationService", () => ({+ __esModule: true,+ default: {+ getCurrentSsid: (...args: unknown[]) => mockGetCurrentSsid(...args)}}))-const mockColors = {- primary: "#0d9488",- primaryDark: "#115E59",- border: "#e5e7eb",- text: "#000",- textSecondary: "#6b7280",- textLight: "#9ca3af",- background: "#fff",- info: "#3b82f6",- card: "#fff",- backgroundElevated: "#f9fafb",- placeholder: "#9ca3af",- textOnPrimary: "#fff"-} as any-import { SyncStrategySettings } from "../SyncStrategySettings"+const charging: SavedTrackingProfile = {+ id: 7,+ name: "Charging",+ interval: 5,+ distance: 20,+ syncInterval: 900,+ priority: 1,+ condition: { type: "charging" } as any,+ activationDelay: 0,+ deactivationDelay: 0+} as SavedTrackingProfile+describe("SyncStrategySettings", () => {let mockOnSettingsChange: jest.Mocklet mockOnDebouncedSave: jest.Mock@@ -78,13 +133,19 @@ describe("SyncStrategySettings", () => {let baseSettings: SettingsbeforeEach(() => {+ jest.useFakeTimers()mockOnSettingsChange = jest.fn()mockOnDebouncedSave = jest.fn()mockOnImmediateSave = jest.fn()+ mockGetCurrentSsid.mockResolvedValue("")baseSettings = { ...DEFAULT_SETTINGS }})- function renderComponent(settingsOverride?: Partial<Settings>) {+ afterEach(() => {+ jest.useRealTimers()+ })++ function renderComponent(settingsOverride?: Partial<Settings>, activeProfile: SavedTrackingProfile | null = null) {const settings = { ...baseSettings, ...settingsOverride }return render(<SyncStrategySettings@@ -92,43 +153,70 @@ describe("SyncStrategySettings", () => {onSettingsChange={mockOnSettingsChange}onDebouncedSave={mockOnDebouncedSave}onImmediateSave={mockOnImmediateSave}- colors={mockColors}+ activeProfile={activeProfile}/>)}+ describe("groups", () => {+ it("names each group by what it sets, with no heading inside a card", () => {+ const { getByText, queryByText } = renderComponent()++ expect(getByText("Recording")).toBeTruthy()+ expect(getByText("Sync interval")).toBeTruthy()+ expect(getByText("Sync only on")).toBeTruthy()+ expect(getByText("Accuracy filter")).toBeTruthy()+ expect(queryByText("Network settings")).toBeNull()+ })++ it("states the restart consequence once, as static text", () => {+ const { getByText } = renderComponent()++ expect(+ getByText("How often a fix is recorded and when it syncs. Changes apply at once and restart tracking.")+ ).toBeTruthy()+ })++ it("hides both sync groups offline and drops the sync clause from every preset", () => {+ const { queryByText, getByText } = renderComponent({ isOfflineMode: true })++ expect(queryByText("Sync interval")).toBeNull()+ expect(queryByText("Sync only on")).toBeNull()+ expect(getByText("Every 30 s after 2 m · moderate battery, fewer wake-ups")).toBeTruthy()+ })+ })+describe("presets", () => {it("renders all three presets inline", () => {const { getByTestId } = renderComponent()- // Presets are rendered inline (no picker to open)expect(getByTestId("preset-instant")).toBeTruthy()expect(getByTestId("preset-balanced")).toBeTruthy()expect(getByTestId("preset-powersaver")).toBeTruthy()})+ it("prices every preset on its row as fix rate, sync cadence and cost, so the trade reads before the tap", () => {+ const { getByText } = renderComponent()++ expect(getByText("Every 5 s, any movement · syncs each fix · most battery, finest track")).toBeTruthy()+ expect(getByText("Every 30 s after 2 m · syncs every 5 min · moderate battery, fewer wake-ups")).toBeTruthy()+ expect(getByText("Every 1 min after 2 m · syncs every 15 min · least battery, coarser track")).toBeTruthy()+ expect(getByText("Power saver")).toBeTruthy()+ })+it("selecting a preset applies its config via onImmediateSave", () => {const { getByTestId } = renderComponent()- // Select balanced directly (inline)fireEvent.press(getByTestId("preset-balanced"))- expect(mockOnSettingsChange).toHaveBeenCalledWith(- expect.objectContaining({- syncPreset: "balanced",- interval: TRACKING_PRESETS.balanced.interval,- distance: TRACKING_PRESETS.balanced.distance,- syncInterval: TRACKING_PRESETS.balanced.syncInterval- })- )- expect(mockOnImmediateSave).toHaveBeenCalledWith(- expect.objectContaining({- syncPreset: "balanced",- interval: TRACKING_PRESETS.balanced.interval,- distance: TRACKING_PRESETS.balanced.distance,- syncInterval: TRACKING_PRESETS.balanced.syncInterval- })- )+ const expected = expect.objectContaining({+ syncPreset: "balanced",+ interval: TRACKING_PRESETS.balanced.interval,+ distance: TRACKING_PRESETS.balanced.distance,+ syncInterval: TRACKING_PRESETS.balanced.syncInterval+ })+ expect(mockOnSettingsChange).toHaveBeenCalledWith(expected)+ expect(mockOnImmediateSave).toHaveBeenCalledWith(expected)})it("selecting a preset in offline mode skips sync fields", () => {@@ -138,241 +226,322 @@ describe("SyncStrategySettings", () => {const savedSettings = mockOnImmediateSave.mock.calls[0][0]expect(savedSettings.syncPreset).toBe("balanced")- expect(savedSettings.interval).toBe(TRACKING_PRESETS.balanced.interval)- expect(savedSettings.distance).toBe(TRACKING_PRESETS.balanced.distance)- // syncInterval and retryInterval should NOT be overwritten in offline modeexpect(savedSettings.syncInterval).toBe(DEFAULT_SETTINGS.syncInterval)expect(savedSettings.retryInterval).toBe(DEFAULT_SETTINGS.retryInterval)})})- describe("advanced toggle", () => {- it("shows advanced settings when toggle is pressed", () => {- const { getByText, queryByText } = renderComponent()+ describe("custom", () => {+ it("is a row in the same list, so the state is where the choice is", () => {+ const { getByTestId } = renderComponent({ syncPreset: "custom" })- expect(queryByText("Tracking Parameters")).toBeNull()+ expect(getByTestId("preset-custom").props.accessibilityState).toMatchObject({ checked: true })+ })- fireEvent.press(getByText("Advanced Settings"))+ it("opens the parameters it owns, and a named preset does not", () => {+ const custom = renderComponent({ syncPreset: "custom" })+ expect(custom.getByText("Interval")).toBeTruthy()+ expect(custom.getByText("Movement threshold")).toBeTruthy()- expect(getByText("Tracking Parameters")).toBeTruthy()- expect(getByText("Network Settings")).toBeTruthy()+ const named = renderComponent({ syncPreset: "balanced" })+ expect(named.queryByText("Movement threshold")).toBeNull()})- it("hides advanced settings when toggle is pressed again", () => {- const { getByText, queryByText } = renderComponent()-- fireEvent.press(getByText("Advanced Settings"))- expect(getByText("Tracking Parameters")).toBeTruthy()+ it("prints its stored numbers and no cost adjective, since a guess for typed numbers would be dishonest", () => {+ const { getByText } = renderComponent({ syncPreset: "custom", interval: 20, distance: 5, syncInterval: 90 })- fireEvent.press(getByText("Advanced Settings"))- expect(queryByText("Tracking Parameters")).toBeNull()+ expect(getByText("Every 20 s after 5 m · syncs every 90 s")).toBeTruthy()})})- describe("custom banner", () => {- it("shows custom configuration banner when preset is custom", () => {- const { getByText } = renderComponent({ syncPreset: "custom" })+ describe("typed fields", () => {+ it("lands a second edit within the debounce on top of the first, instead of dropping it", () => {+ const { getByDisplayValue } = renderComponent({ syncPreset: "custom", interval: 5, distance: 0 })++ fireEvent.changeText(getByDisplayValue("5"), "20")+ expect(mockOnSettingsChange).toHaveBeenCalledWith(expect.objectContaining({ interval: 20 }))+ expect(mockOnDebouncedSave).toHaveBeenLastCalledWith(expect.objectContaining({ interval: 20 }))+ })++ it("stores nothing for a cleared field, a decimal or a sign, and says why under the field", () => {+ const { getByDisplayValue, getByText, queryByText } = renderComponent({+ syncPreset: "custom",+ interval: 5,+ distance: 10+ })++ fireEvent.changeText(getByDisplayValue("10"), "")+ expect(mockOnDebouncedSave).not.toHaveBeenCalled()+ expect(queryByText("A whole number")).toBeNull()- fireEvent.press(getByText("Advanced Settings"))+ fireEvent.changeText(getByDisplayValue(""), "1.5")+ expect(mockOnDebouncedSave).not.toHaveBeenCalled()+ expect(getByText("A whole number")).toBeTruthy()- expect(getByText("Using custom configuration")).toBeTruthy()+ fireEvent.changeText(getByDisplayValue("5"), "0")+ expect(mockOnDebouncedSave).not.toHaveBeenCalled()+ expect(getByText("At least 1 s")).toBeTruthy()})- it("does not show custom banner when a named preset is selected", () => {- const { getByText, queryByText } = renderComponent({ syncPreset: "instant" })+ it("clamps an empty interval to 1 s on blur, saves at once and says so for a moment", () => {+ const { getByDisplayValue, getByText, queryByText } = renderComponent({ syncPreset: "custom", interval: 5 })- fireEvent.press(getByText("Advanced Settings"))+ fireEvent.changeText(getByDisplayValue("5"), "")+ fireEvent(getByDisplayValue(""), "blur")++ expect(mockOnSettingsChange).toHaveBeenCalledWith(expect.objectContaining({ interval: 1 }))+ expect(mockOnImmediateSave).toHaveBeenCalledWith(expect.objectContaining({ interval: 1 }))+ expect(getByDisplayValue("1")).toBeTruthy()+ expect(getByText("Set to 1 s")).toBeTruthy()- expect(queryByText("Using custom configuration")).toBeNull()+ act(() => {+ jest.advanceTimersByTime(SAVE_SUCCESS_DISPLAY_MS)+ })+ expect(queryByText("Set to 1 s")).toBeNull()})- })- describe("sync interval chips", () => {- it("renders all sync interval options inline", () => {- const { getByText, getAllByText } = renderComponent()+ it("leaves a valid value alone on blur", () => {+ const { getByDisplayValue } = renderComponent({ syncPreset: "custom", interval: 5 })- fireEvent.press(getByText("Advanced Settings"))+ fireEvent.changeText(getByDisplayValue("5"), "10")+ fireEvent(getByDisplayValue("10"), "blur")- expect(getAllByText("Instant").length).toBeGreaterThan(0)- expect(getByText("1 min")).toBeTruthy()- expect(getByText("5 min")).toBeTruthy()- expect(getByText("15 min")).toBeTruthy()- expect(getByText("Custom")).toBeTruthy()+ expect(mockOnImmediateSave).not.toHaveBeenCalled()})- it("selecting a sync interval sets preset to custom", () => {- const { getByText } = renderComponent()+ it("clamps a cleared movement threshold to 0 on blur and keeps the unit on the note", () => {+ const { getByDisplayValue, getByText } = renderComponent({ syncPreset: "custom", interval: 5, distance: 10 })- fireEvent.press(getByText("Advanced Settings"))- fireEvent.press(getByText("5 min"))+ fireEvent.changeText(getByDisplayValue("10"), "abc")+ fireEvent(getByDisplayValue("abc"), "blur")- expect(mockOnSettingsChange).toHaveBeenCalledWith(- expect.objectContaining({- syncInterval: 300,- syncPreset: "custom"- })- )- expect(mockOnDebouncedSave).toHaveBeenCalledWith(- expect.objectContaining({- syncInterval: 300,- syncPreset: "custom"- })+ expect(mockOnImmediateSave).toHaveBeenCalledWith(expect.objectContaining({ distance: 0 }))+ expect(getByText("Set to 0 m")).toBeTruthy()+ })++ it("keeps the text you typed when the stored value already means it", () => {+ const { getByDisplayValue, rerender } = renderComponent({ syncPreset: "custom", interval: 5 })++ fireEvent.changeText(getByDisplayValue("5"), "020")+ rerender(+ <SyncStrategySettings+ settings={{ ...baseSettings, syncPreset: "custom", interval: 20 }}+ onSettingsChange={mockOnSettingsChange}+ onDebouncedSave={mockOnDebouncedSave}+ onImmediateSave={mockOnImmediateSave}+ />)++ expect(getByDisplayValue("020")).toBeTruthy()})})- describe("filter inaccurate locations", () => {- it("shows accuracy threshold input when filter is enabled", () => {- const { getByText } = renderComponent({ filterInaccurateLocations: true })+ describe("what flips the preset to Custom", () => {+ it("a sync interval row does, because a preset owns that value", () => {+ const { getByTestId } = renderComponent({ syncPreset: "balanced" })- fireEvent.press(getByText("Advanced Settings"))+ fireEvent.press(getByTestId("sync-interval-300"))- expect(getByText("Accuracy Threshold")).toBeTruthy()+ expect(mockOnSettingsChange).toHaveBeenCalledWith(+ expect.objectContaining({ syncInterval: 300, syncPreset: "custom" })+ )+ expect(mockOnImmediateSave).toHaveBeenCalledWith(+ expect.objectContaining({ syncInterval: 300, syncPreset: "custom" })+ )})- it("hides accuracy threshold input when filter is disabled", () => {- const { getByText, queryByText } = renderComponent({ filterInaccurateLocations: false })+ it("a typed sync interval does, through the debounced save", () => {+ const { getByTestId } = renderComponent({ syncPreset: "balanced" })- fireEvent.press(getByText("Advanced Settings"))+ fireEvent.press(getByTestId("sync-interval-typed"))- expect(queryByText("Accuracy Threshold")).toBeNull()+ expect(mockOnSettingsChange).toHaveBeenCalledWith(+ expect.objectContaining({ syncInterval: 90, syncPreset: "custom" })+ )+ expect(mockOnDebouncedSave).toHaveBeenCalledWith(+ expect.objectContaining({ syncInterval: 90, syncPreset: "custom" })+ )})- })- describe("numeric input blur behavior", () => {- it("clamps interval to min 1 on blur when value is 0", () => {- const { getByText, getByDisplayValue } = renderComponent({- interval: 5,- syncPreset: "custom"+ it("a sync condition, the accuracy threshold and the toggle do not", () => {+ const { getByTestId, getByDisplayValue, getByLabelText } = renderComponent({+ syncPreset: "balanced",+ filterInaccurateLocations: true,+ accuracyThreshold: 100})- fireEvent.press(getByText("Advanced Settings"))+ fireEvent.press(getByTestId("sync-condition-vpn"))+ expect(mockOnImmediateSave).toHaveBeenLastCalledWith(+ expect.objectContaining({ syncCondition: "vpn", syncPreset: "balanced" })+ )- const intervalInput = getByDisplayValue("5")- fireEvent.changeText(intervalInput, "0")- fireEvent(intervalInput, "blur")+ fireEvent.changeText(getByDisplayValue("100"), "80")+ expect(mockOnDebouncedSave).toHaveBeenLastCalledWith(+ expect.objectContaining({ accuracyThreshold: 80, syncPreset: "balanced" })+ )- // Should clamp to 1 and call onSettingsChange + onImmediateSave- expect(mockOnSettingsChange).toHaveBeenCalledWith(expect.objectContaining({ interval: 1 }))- expect(mockOnImmediateSave).toHaveBeenCalledWith(expect.objectContaining({ interval: 1 }))+ fireEvent(getByLabelText("Filter inaccurate locations"), "valueChange", false)+ expect(mockOnImmediateSave).toHaveBeenLastCalledWith(+ expect.objectContaining({ filterInaccurateLocations: false, syncPreset: "balanced" })+ )})+ })- it("clamps interval to min 1 on blur when value is negative", () => {- const { getByText, getByDisplayValue } = renderComponent({- interval: 5,- syncPreset: "custom"- })+ describe("profile override", () => {+ it("shows the values in force inside the two groups a profile overrides, and only those", () => {+ const { getByTestId, getByText, queryByTestId } = renderComponent({}, charging)++ expect(getByTestId("profile-override-recording")).toBeTruthy()+ expect(getByText("In force: every 5 s after 20 m")).toBeTruthy()+ expect(getByTestId("profile-override-sync")).toBeTruthy()+ expect(getByText("In force: syncs every 15 min")).toBeTruthy()+ expect(queryByTestId("profile-override-notice")).toBeNull()+ })- fireEvent.press(getByText("Advanced Settings"))+ it("keeps the rows below selectable, since they are the defaults the profile hands back", () => {+ const { getByTestId } = renderComponent({}, charging)- const intervalInput = getByDisplayValue("5")- fireEvent.changeText(intervalInput, "-3")- fireEvent(intervalInput, "blur")+ fireEvent.press(getByTestId("preset-balanced"))- expect(mockOnSettingsChange).toHaveBeenCalledWith(expect.objectContaining({ interval: 1 }))- expect(mockOnImmediateSave).toHaveBeenCalledWith(expect.objectContaining({ interval: 1 }))+ expect(mockOnImmediateSave).toHaveBeenCalledWith(expect.objectContaining({ syncPreset: "balanced" }))})- it("clamps interval to min 1 on blur when value is NaN", () => {- const { getByText, getByDisplayValue } = renderComponent({- interval: 5,- syncPreset: "custom"- })+ it("drops the pull under the title when a state line precedes the sync rows", () => {+ const withProfile = renderComponent({}, charging)+ expect(withProfile.getByTestId("sync-interval-picker").props.accessibilityValue.text).toBe("flush")- fireEvent.press(getByText("Advanced Settings"))+ const without = renderComponent()+ expect(without.getByTestId("sync-interval-picker").props.accessibilityValue.text).toBe("pulled")+ })- const intervalInput = getByDisplayValue("5")- fireEvent.changeText(intervalInput, "abc")- fireEvent(intervalInput, "blur")+ it("stays quiet when no profile is active, so the line means something when it appears", () => {+ const { queryByTestId } = renderComponent()- expect(mockOnSettingsChange).toHaveBeenCalledWith(expect.objectContaining({ interval: 1 }))- expect(mockOnImmediateSave).toHaveBeenCalledWith(expect.objectContaining({ interval: 1 }))+ expect(queryByTestId("profile-override-recording")).toBeNull()+ expect(queryByTestId("profile-override-sync")).toBeNull()})+ })- it("does not clamp interval on blur when value is valid", () => {- const { getByText, getByDisplayValue } = renderComponent({- interval: 5,- syncPreset: "custom"- })+ describe("sync condition", () => {+ it("states what every option costs without one being chosen", () => {+ const { getByText } = renderComponent({ syncCondition: "any" })- fireEvent.press(getByText("Advanced Settings"))+ expect(getByText("Mobile data and Wi-Fi · syncs never wait, counts against your data plan")).toBeTruthy()+ expect(getByText("Wi-Fi or Ethernet")).toBeTruthy()+ expect(getByText("Unmetered networks only · fixes wait on mobile data")).toBeTruthy()+ expect(getByText("One network by name · fixes wait elsewhere")).toBeTruthy()+ expect(getByText("Only while a VPN is up · fixes wait otherwise")).toBeTruthy()+ })- const intervalInput = getByDisplayValue("5")- fireEvent.changeText(intervalInput, "10")- fireEvent(intervalInput, "blur")+ it("puts the network name under its own row, not at the end of the group below VPN", () => {+ const { toJSON } = renderComponent({ syncCondition: "wifi_ssid", syncSsid: "Home" })- // Valid value - onSettingsChange should only have been called from changeText (debounced save),- // not from blur (no clamping needed)- expect(mockOnImmediateSave).not.toHaveBeenCalled()+ const ids: string[] = []+ const walk = (node: any) => {+ if (!node || typeof node !== "object") return+ if (Array.isArray(node)) return node.forEach(walk)+ if (node.props?.testID) ids.push(node.props.testID)+ ;(node.children ?? []).forEach(walk)+ }+ walk(toJSON())++ expect(ids.indexOf("sync-ssid-input")).toBeGreaterThan(ids.indexOf("sync-condition-wifi_ssid"))+ expect(ids.indexOf("sync-ssid-input")).toBeLessThan(ids.indexOf("sync-condition-vpn"))})- it("clamps distance to min 0 on blur when value is negative", () => {- const { getByText, getByDisplayValue } = renderComponent({- interval: 5,- distance: 10,- syncPreset: "custom"- })+ it("reveals the network name only for the one option that needs it", () => {+ const { queryByTestId } = renderComponent({ syncCondition: "wifi_any" })+ expect(queryByTestId("sync-ssid-input")).toBeNull()- fireEvent.press(getByText("Advanced Settings"))+ const named = renderComponent({ syncCondition: "wifi_ssid", syncSsid: "Home" })+ expect(named.queryByTestId("sync-ssid-input")).toBeTruthy()+ })- const distanceInput = getByDisplayValue("10")- fireEvent.changeText(distanceInput, "-5")- fireEvent(distanceInput, "blur")+ it("marks a blank network name as an error, because nothing syncs until one is named", () => {+ const blank = renderComponent({ syncCondition: "wifi_ssid", syncSsid: "" })+ expect(blank.getByText("Nothing syncs until a network is named")).toBeTruthy()- expect(mockOnSettingsChange).toHaveBeenCalledWith(expect.objectContaining({ distance: 0 }))- expect(mockOnImmediateSave).toHaveBeenCalledWith(expect.objectContaining({ distance: 0 }))+ const named = renderComponent({ syncCondition: "wifi_ssid", syncSsid: "Home" })+ expect(named.queryByText("Nothing syncs until a network is named")).toBeNull()})- it("clamps distance to min 0 on blur when value is NaN", () => {- const { getByText, getByDisplayValue } = renderComponent({- interval: 5,- distance: 10,- syncPreset: "custom"- })+ it("offers the network the phone is on, named, only while it differs from the one typed", async () => {+ mockGetCurrentSsid.mockResolvedValue("Colota-5G")+ const { findByText, getByTestId } = renderComponent({ syncCondition: "wifi_ssid", syncSsid: "" })++ expect(await findByText("Use Colota-5G")).toBeTruthy()+ fireEvent.press(getByTestId("sync-ssid-use"))+ expect(mockOnImmediateSave).toHaveBeenCalledWith(expect.objectContaining({ syncSsid: "Colota-5G" }))- fireEvent.press(getByText("Advanced Settings"))+ mockGetCurrentSsid.mockResolvedValue("home")+ const same = renderComponent({ syncCondition: "wifi_ssid", syncSsid: "Home" })+ await act(async () => {+ await Promise.resolve()+ })+ expect(same.queryByTestId("sync-ssid-use")).toBeNull()+ })+ })- const distanceInput = getByDisplayValue("10")- fireEvent.changeText(distanceInput, "abc")- fireEvent(distanceInput, "blur")+ describe("accuracy filter", () => {+ it("carries the threshold in the hint in both states, so hiding the field loses nothing", () => {+ const on = renderComponent({ filterInaccurateLocations: true, accuracyThreshold: 50 })+ expect(on.getByText("Drops fixes the chip rates worse than 50 m. Stricter leaves gaps indoors.")).toBeTruthy()+ expect(on.getByText("Accuracy threshold")).toBeTruthy()- expect(mockOnSettingsChange).toHaveBeenCalledWith(expect.objectContaining({ distance: 0 }))- expect(mockOnImmediateSave).toHaveBeenCalledWith(expect.objectContaining({ distance: 0 }))+ const off = renderComponent({ filterInaccurateLocations: false, accuracyThreshold: 50 })+ expect(off.getByText("Every fix is kept. When on, fixes worse than 50 m are dropped.")).toBeTruthy()+ expect(off.queryByText("Accuracy threshold")).toBeNull()})- it("clamps accuracy threshold to min 1 on blur when value is below", () => {- const { getByText, getByDisplayValue } = renderComponent({- interval: 5,- filterInaccurateLocations: true,- accuracyThreshold: 100,- syncPreset: "custom"- })+ it("moves the switch at once: local state first, then the immediate save", () => {+ const calls: string[] = []+ mockOnSettingsChange.mockImplementation(() => calls.push("local"))+ mockOnImmediateSave.mockImplementation(() => calls.push("save"))+ const { getByLabelText } = renderComponent({ filterInaccurateLocations: false })++ fireEvent(getByLabelText("Filter inaccurate locations"), "valueChange", true)++ expect(calls).toEqual(["local", "save"])+ expect(mockOnImmediateSave).toHaveBeenCalledWith(expect.objectContaining({ filterInaccurateLocations: true }))+ })- fireEvent.press(getByText("Advanced Settings"))+ it("clamps the threshold to 1 on blur when it is below", () => {+ const { getByDisplayValue } = renderComponent({ filterInaccurateLocations: true, accuracyThreshold: 100 })- const thresholdInput = getByDisplayValue("100")- fireEvent.changeText(thresholdInput, "0")- fireEvent(thresholdInput, "blur")+ fireEvent.changeText(getByDisplayValue("100"), "0")+ fireEvent(getByDisplayValue("0"), "blur")expect(mockOnSettingsChange).toHaveBeenCalledWith(expect.objectContaining({ accuracyThreshold: 1 }))expect(mockOnImmediateSave).toHaveBeenCalledWith(expect.objectContaining({ accuracyThreshold: 1 }))})+ })- it("does not clamp accuracy threshold on blur when value is valid", () => {- const { getByText, getByDisplayValue } = renderComponent({- interval: 5,- filterInaccurateLocations: true,- accuracyThreshold: 100,- syncPreset: "custom"- })+ describe("batch size", () => {+ const overland = { apiTemplate: "overland" as const }- fireEvent.press(getByText("Advanced Settings"))+ it("shows the range as an error while the number is outside it and stores nothing", () => {+ const { getByDisplayValue, getByText } = renderComponent({ ...overland, overlandBatchSize: 50 })- const thresholdInput = getByDisplayValue("100")- fireEvent.changeText(thresholdInput, "200")- fireEvent(thresholdInput, "blur")+ fireEvent.changeText(getByDisplayValue("50"), "900")- expect(mockOnImmediateSave).not.toHaveBeenCalled()+ expect(getByText("1 to 500")).toBeTruthy()+ expect(mockOnDebouncedSave).not.toHaveBeenCalled()+ })++ it("clamps to the nearer bound on blur without touching the preset", () => {+ const { getByDisplayValue, getByText } = renderComponent({+ ...overland,+ overlandBatchSize: 50,+ syncPreset: "balanced"+ })++ fireEvent.changeText(getByDisplayValue("50"), "900")+ fireEvent(getByDisplayValue("900"), "blur")++ expect(mockOnImmediateSave).toHaveBeenCalledWith(+ expect.objectContaining({ overlandBatchSize: 500, syncPreset: "balanced" })+ )+ expect(getByText("Set to 500 points")).toBeTruthy()})})})diff --git a/apps/mobile/src/constants/index.ts b/apps/mobile/src/constants/index.tsindex 1408b43b..24a1bf20 100644--- a/apps/mobile/src/constants/index.ts+++ b/apps/mobile/src/constants/index.ts@@ -71,7 +71,7 @@ export const elevation = {overlay: 6} as const-export const DEFAULT_MAP_ZOOM = 17+export const DEFAULT_MAP_ZOOM = 15export const WORLD_MAP_ZOOM = 2export const MAX_MAP_ZOOM = 18export const GEOFENCE_ZOOM_PADDING = [80, 80, 80, 80] as const@@ -89,34 +89,43 @@ export const PROFILE_CONDITIONS: {icon: typeof Zapdescription: string}[] = [- { type: "charging", label: "Charging", listLabel: "When charging", icon: Zap, description: "Phone is plugged in" },+ {+ type: "charging",+ label: "Charging",+ listLabel: "When charging",+ icon: Zap,+ description: "Phone is plugged in · costs nothing to watch"+ },{type: "android_auto",- label: "Car Mode",- listLabel: "Android Auto / Car mode",+ label: "Android Auto",+ listLabel: "On Android Auto",icon: Car,- description: "Android Auto connected"+ description: "Android Auto is connected · costs nothing to watch"},{type: "speed_above",- label: "Speed Above",+ label: "Speed above",listLabel: "Speed above",icon: ArrowUp,- description: "Moving faster than threshold"+ description:+ "Average of the last 5 fixes is faster than the speed below · fixes keep flowing to measure it, even below the movement threshold"},{type: "speed_below",- label: "Speed Below",+ label: "Speed below",listLabel: "Speed below",icon: ArrowDown,- description: "Moving slower than threshold"+ description:+ "Average of the last 5 fixes is slower than the speed below · fixes keep flowing to measure it, even below the movement threshold"},{type: "stationary",label: "Stationary",listLabel: "When stationary",icon: Pause,- description: "Not moving for ~60 seconds"+ description:+ "Still for the activation delay · records a point every interval, movement threshold not used · fixes keep flowing to measure it"}]diff --git a/apps/mobile/src/screens/ProfileEditorScreen.tsx b/apps/mobile/src/screens/ProfileEditorScreen.tsxindex bf434186..bc9bb539 100644--- a/apps/mobile/src/screens/ProfileEditorScreen.tsx+++ b/apps/mobile/src/screens/ProfileEditorScreen.tsx@@ -3,89 +3,114 @@* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.*/-import React, { useState, useEffect, useCallback } from "react"-import { View, Text, StyleSheet, ScrollView, TextInput, Pressable } from "react-native"+import React, { useState, useEffect, useLayoutEffect, useCallback } from "react"+import { View, Text, StyleSheet, ScrollView } from "react-native"import { useTheme } from "../hooks/useTheme"import { useTracking } from "../contexts/TrackingProvider"+import { useTimeout } from "../hooks/useTimeout"import { ProfileService } from "../services/ProfileService"-import { showAlert } from "../services/modalService"+import { showAlert, showConfirm } from "../services/modalService"import { TrackingProfile, ProfileConditionType } from "../types/global"-import { fonts } from "../styles/typography"-import { Container, SectionTitle, Card, Divider, SettingRow, NumericInput, FieldMessage } from "../components"-import { Check } from "lucide-react-native"+import { fontSizes, fonts, lineHeights } from "../styles/typography"+import { SyncIntervalPicker } from "../components/features/settings/SyncIntervalPicker"+import {+ Button,+ Card,+ Container,+ Divider,+ FieldMessage,+ NumericInput,+ RadioRow,+ SectionTitle,+ SettingRow,+ TextField+} from "../components"+import { Check, Trash2 } from "lucide-react-native"import { logger } from "../utils/logger"-import { shortDistanceUnit, inputToMeters, metersToInput } from "../utils/geo"+import { shortDistanceUnit, inputToMeters, metersToInput, getSpeedUnit, speedToInput, inputToSpeed } from "../utils/geo"+import { formatDuration } from "../utils/dashboardState"+import { conditionOf, profileSentence } from "../utils/profileRow"+import { parseWholeNumber, wholeNumberError } from "../utils/settingsValidation"import {- MS_TO_KMH,PROFILE_CONDITIONS,- SYNC_INTERVAL_PRESETS,+ SAVE_SUCCESS_DISPLAY_MS,SYNC_INTERVAL_LABELS,STATIONARY_MAX_INTERVAL_SECONDS,- defaultProfileDelays+ defaultProfileDelays,+ size,+ space} from "../constants"import type { RootScreenProps } from "../types/navigation"-function formatSyncDefault(seconds: number): string {- if (SYNC_INTERVAL_LABELS[seconds]) return SYNC_INTERVAL_LABELS[seconds]- if (seconds < 60) return `${seconds}s`- return `${Math.round(seconds / 60)} min`-}+type Draft = Omit<TrackingProfile, "id" | "createdAt">+type NumericKey = "interval" | "distance" | "activationDelay" | "deactivationDelay" | "speed"++const DEFAULT_SPEED_INPUT = 30+const DEFAULT_PRIORITY = 10++const isSpeedType = (type: ProfileConditionType) => type === "speed_above" || type === "speed_below"export function ProfileEditorScreen({ navigation, route }: RootScreenProps<"Profile Editor">) {const { colors } = useTheme()const { settings } = useTracking()const profileId = route?.params?.profileId as number | undefinedconst isEditing = !!profileId+ const distanceUnit = shortDistanceUnit()+ const speedUnit = getSpeedUnit().unit- const [profile, setProfile] = useState<Omit<TrackingProfile, "id" | "createdAt">>({+ const [profile, setProfile] = useState<Draft>({name: "",interval: settings.interval,distance: settings.distance,syncInterval: settings.syncInterval,- priority: 10,+ priority: DEFAULT_PRIORITY,condition: { type: "charging" },...defaultProfileDelays("charging"),enabled: true})- const [speedKmh, setSpeedKmh] = useState("30")const [saving, setSaving] = useState(false)+ const [text, setText] = useState({+ interval: String(settings.interval),+ distance: String(metersToInput(settings.distance)),+ speed: String(DEFAULT_SPEED_INPUT),+ priority: String(DEFAULT_PRIORITY),+ activationDelay: String(defaultProfileDelays("charging").activationDelay),+ deactivationDelay: String(defaultProfileDelays("charging").deactivationDelay)+ })+ const [note, setNote] = useState<{ key: NumericKey; text: string } | null>(null)+ const noteTimer = useTimeout()- // String representations for numeric inputs- const [intervalStr, setIntervalStr] = useState(String(settings.interval))- const [distanceStr, setDistanceStr] = useState(String(metersToInput(settings.distance)))- const [priorityStr, setPriorityStr] = useState("10")- const [activationDelayStr, setActivationDelayStr] = useState("0")- const [delayStr, setDelayStr] = useState("60")- const [syncIntervalStr, setSyncIntervalStr] = useState(String(settings.syncInterval))+ useLayoutEffect(() => {+ navigation.setOptions({ headerTitle: isEditing ? "Edit profile" : "New profile" })+ }, [navigation, isEditing])useEffect(() => {if (!profileId) return-ProfileService.getProfiles().then((profiles) => {const existing = profiles.find((p) => p.id === profileId)- if (existing) {- setProfile({- name: existing.name,- interval: existing.interval,- distance: existing.distance,- syncInterval: existing.syncInterval,- priority: existing.priority,- condition: existing.condition,- activationDelay: existing.activationDelay,- deactivationDelay: existing.deactivationDelay,- enabled: existing.enabled- })- setIntervalStr(String(existing.interval))- setDistanceStr(String(metersToInput(existing.distance)))- setPriorityStr(String(existing.priority))- setActivationDelayStr(String(existing.activationDelay))- setDelayStr(String(existing.deactivationDelay))- setSyncIntervalStr(String(existing.syncInterval))- if (existing.condition.speedThreshold) {- setSpeedKmh((existing.condition.speedThreshold * MS_TO_KMH).toFixed(0))- }- }+ if (!existing) return+ setProfile({+ name: existing.name,+ interval: existing.interval,+ distance: existing.distance,+ syncInterval: existing.syncInterval,+ priority: existing.priority,+ condition: existing.condition,+ activationDelay: existing.activationDelay,+ deactivationDelay: existing.deactivationDelay,+ enabled: existing.enabled+ })+ setText({+ interval: String(existing.interval),+ distance: String(metersToInput(existing.distance)),+ speed: String(+ existing.condition.speedThreshold ? speedToInput(existing.condition.speedThreshold) : DEFAULT_SPEED_INPUT+ ),+ priority: String(existing.priority),+ activationDelay: String(existing.activationDelay),+ deactivationDelay: String(existing.deactivationDelay)+ })}).catch((err) => {logger.error("[ProfileEditor] Failed to load profile:", err)@@ -94,75 +119,116 @@ export function ProfileEditorScreen({ navigation, route }: RootScreenProps<"Prof})}, [profileId, navigation])- const handleNumericChange = useCallback(- (setter: (v: string) => void, field: keyof typeof profile, value: string, min = 0) => {- setter(value)- const num = Number(value)- if (!isNaN(num) && num >= min) {- const stored = field === "distance" ? inputToMeters(num) : num- setProfile((prev) => ({ ...prev, [field]: stored }))- }- },- []- )-- const setConditionType = useCallback(- (type: ProfileConditionType) => {- const isSpeed = type === "speed_above" || type === "speed_below"- const isStationary = type === "stationary"- const { activationDelay: defaultActivation, deactivationDelay: defaultDeactivation } = defaultProfileDelays(type)- setProfile((prev) => ({- ...prev,- // A distance filter is ignored for a stationary profile; store 0 so UI, DB and runtime agree.- distance: isStationary ? 0 : prev.distance,- deactivationDelay: prev.condition.type !== type ? defaultDeactivation : prev.deactivationDelay,- activationDelay: prev.condition.type !== type ? defaultActivation : prev.activationDelay,- condition: {- type,- ...(isSpeed ? { speedThreshold: Number(speedKmh) / MS_TO_KMH } : {})- }- }))- if (isStationary) setDistanceStr("0")- if (profile.condition.type !== type) {- setDelayStr(String(defaultDeactivation))- setActivationDelayStr(String(defaultActivation))- }- },- [speedKmh, profile.condition.type]- )-- const handleSpeedChange = useCallback((val: string) => {- setSpeedKmh(val)- const num = Number(val)- if (!isNaN(num) && num > 0) {- setProfile((prev) => ({- ...prev,- condition: { ...prev.condition, speedThreshold: num / MS_TO_KMH }- }))- }+ const type = profile.condition.type+ const isSpeed = isSpeedType(type)+ const isStationary = type === "stationary"+ const conditionLabel = conditionOf(profile).label++ const store = useCallback((key: NumericKey, value: number) => {+ setProfile((prev) => {+ if (key === "speed") return { ...prev, condition: { ...prev.condition, speedThreshold: inputToSpeed(value) } }+ if (key === "distance") return { ...prev, distance: inputToMeters(value) }+ return { ...prev, [key]: value }+ })}, [])- const handleSave = useCallback(async () => {- if (!profile.name.trim()) {- showAlert("Missing Name", "Please enter a profile name.", "warning")- return- }- if (profile.interval < 1) {- showAlert("Invalid Interval", "Tracking interval must be at least 1 second.", "warning")- return- }- const isSpeed = profile.condition.type === "speed_above" || profile.condition.type === "speed_below"- if (isSpeed && (!profile.condition.speedThreshold || profile.condition.speedThreshold <= 0)) {- showAlert("Missing Speed", "Speed conditions require a positive speed threshold.", "warning")- return+ const minOf = (key: NumericKey) => (key === "interval" || key === "speed" ? 1 : 0)+ const unitOf = (key: NumericKey) => (key === "distance" ? distanceUnit : key === "speed" ? speedUnit : "s")++ const handleNumeric = (key: NumericKey, value: string) => {+ setText((prev) => ({ ...prev, [key]: value }))+ setNote(null)+ const num = parseWholeNumber(value)+ if (num !== null && num >= minOf(key)) store(key, num)+ }++ // An empty or below-minimum box clamps to the minimum on blur and says so, the Tracking & sync rule.+ const handleBlur = (key: NumericKey) => {+ const min = minOf(key)+ const num = parseWholeNumber(text[key])+ if (num !== null && num >= min) return+ setText((prev) => ({ ...prev, [key]: String(min) }))+ setNote({ key, text: `Set to ${min} ${unitOf(key)}` })+ noteTimer.set(() => setNote(null), SAVE_SUCCESS_DISPLAY_MS)+ store(key, min)+ }++ const errorOf = (key: NumericKey) => wholeNumberError(text[key], minOf(key), unitOf(key))+ const noteOf = (key: NumericKey) => (note?.key === key ? note.text : undefined)++ const priorityError = text.priority !== "" && parseWholeNumber(text.priority) === null ? "A whole number" : undefined+ const handlePriority = (value: string) => {+ setText((prev) => ({ ...prev, priority: value }))+ const num = parseWholeNumber(value)+ if (num !== null) setProfile((prev) => ({ ...prev, priority: num }))+ }+ const handlePriorityBlur = () => {+ if (parseWholeNumber(text.priority) === null) setText((prev) => ({ ...prev, priority: String(profile.priority) }))+ }++ const setConditionType = (next: ProfileConditionType) => {+ if (next === type) return+ const previousDefaults = defaultProfileDelays(type)+ const nextDefaults = defaultProfileDelays(next)+ const keepDelays =+ profile.activationDelay !== previousDefaults.activationDelay ||+ profile.deactivationDelay !== previousDefaults.deactivationDelay+ const delays = keepDelays+ ? { activationDelay: profile.activationDelay, deactivationDelay: profile.deactivationDelay }+ : nextDefaults+ const speedThreshold = isSpeedType(next)+ ? (profile.condition.speedThreshold ?? inputToSpeed(parseWholeNumber(text.speed) ?? DEFAULT_SPEED_INPUT))+ : undefined+ setProfile((prev) => ({+ ...prev,+ ...delays,+ // A distance filter is ignored for a stationary profile; store 0 so UI, DB and runtime agree.+ distance: next === "stationary" ? 0 : prev.distance,+ condition: { type: next, ...(speedThreshold !== undefined ? { speedThreshold } : {}) }+ }))+ setText((prev) => ({+ ...prev,+ distance: next === "stationary" ? "0" : prev.distance,+ activationDelay: String(delays.activationDelay),+ deactivationDelay: String(delays.deactivationDelay),+ speed: speedThreshold !== undefined ? String(speedToInput(speedThreshold)) : prev.speed+ }))+ }++ const handleDelete = useCallback(async () => {+ if (!profileId) return+ const confirmed = await showConfirm({+ title: "Delete profile",+ message: `Delete "${profile.name || conditionLabel}"?`,+ confirmText: "Delete",+ destructive: true+ })+ if (!confirmed) return+ try {+ await ProfileService.deleteProfile(profileId)+ navigation.goBack()+ } catch (err) {+ logger.error("[ProfileEditor] Delete failed:", err)+ showAlert("Error", "Failed to delete profile.", "error")}+ }, [profileId, profile.name, conditionLabel, navigation])++ const hasFieldError =+ !!priorityError ||+ !!errorOf("interval") ||+ (!isStationary && !!errorOf("distance")) ||+ (isSpeed && !!errorOf("speed")) ||+ !!errorOf("activationDelay") ||+ (!isStationary && !!errorOf("deactivationDelay"))+ const handleSave = useCallback(async () => {+ const next: Draft = { ...profile, name: profile.name.trim() || conditionLabel }setSaving(true)try {if (isEditing && profileId) {- await ProfileService.updateProfile({ id: profileId, ...profile })+ await ProfileService.updateProfile({ id: profileId, ...next })} else {- await ProfileService.createProfile(profile)+ await ProfileService.createProfile(next)}navigation.goBack()} catch (err) {@@ -171,15 +237,9 @@ export function ProfileEditorScreen({ navigation, route }: RootScreenProps<"Prof} finally {setSaving(false)}- }, [profile, isEditing, profileId, navigation])-- const isSpeed = profile.condition.type === "speed_above" || profile.condition.type === "speed_below"- const isCustomSyncInterval = !SYNC_INTERVAL_PRESETS.includes(profile.syncInterval)+ }, [profile, conditionLabel, isEditing, profileId, navigation])- const inputStyle = [- styles.numInput,- { backgroundColor: colors.backgroundElevated, color: colors.text, borderColor: colors.border }- ]+ const syncDefault = SYNC_INTERVAL_LABELS[settings.syncInterval] ?? formatDuration(settings.syncInterval)return (<Container>@@ -188,366 +248,206 @@ export function ProfileEditorScreen({ navigation, route }: RootScreenProps<"ProfkeyboardShouldPersistTaps="handled"showsVerticalScrollIndicator={false}>- <View style={styles.header}>- <Text style={[styles.title, { color: colors.text }]}>{isEditing ? "Edit Profile" : "New Profile"}</Text>- </View>+ <Text style={[styles.intro, { color: colors.textSecondary }]} testID="profile-sentence">+ {profileSentence(profile, settings.isOfflineMode)}+ </Text>++ <SectionTitle>Condition</SectionTitle>+ <Card rows>+ <View accessibilityRole="radiogroup" style={styles.group}>+ {PROFILE_CONDITIONS.map((opt) => (+ <React.Fragment key={opt.type}>+ <RadioRow+ testID={`condition-${opt.type}`}+ icon={opt.icon}+ label={opt.label}+ sub={opt.description}+ selected={type === opt.type}+ onPress={() => setConditionType(opt.type)}+ />+ {isSpeedType(opt.type) && type === opt.type && (+ <View style={styles.reveal}>+ <NumericInput+ label="Speed"+ testID="speed-input"+ value={text.speed}+ onChange={(v) => handleNumeric("speed", v)}+ onBlur={() => handleBlur("speed")}+ unit={speedUnit}+ placeholder={String(DEFAULT_SPEED_INPUT)}+ hint={`At least 1 ${speedUnit}. Applies while your average speed is ${opt.type === "speed_above" ? "above" : "below"} it.`}+ error={errorOf("speed")}+ message={noteOf("speed")}+ />+ </View>+ )}+ </React.Fragment>+ ))}+ </View>+ </Card>- {/* Name & Priority */}- <SectionTitle>Profile</SectionTitle>- <Card>- <View style={styles.inputGroup}>- <Text style={[styles.label, { color: colors.textSecondary }]}>Name</Text>- <TextInput- style={[- styles.input,- { backgroundColor: colors.background, color: colors.text, borderColor: colors.border }- ]}- placeholder="e.g. Driving, Cycling..."- placeholderTextColor={colors.placeholder}+ <SectionTitle style={styles.groupTop}>Profile</SectionTitle>+ <Card rows style={styles.cardTop}>+ <View style={styles.field}>+ <TextField+ testID="name-input"+ label="Name"+ placeholder={conditionLabel}value={profile.name}onChangeText={(val) => setProfile((prev) => ({ ...prev, name: val }))}/>+ <FieldMessage>Shown on the Dashboard while active. Blank uses the condition's name.</FieldMessage></View>-- <Divider />-- <SettingRow label="Priority" hint="Higher number wins when multiple profiles match">- <TextInput- style={inputStyle}+ <Divider tight />+ <SettingRow+ label="Priority"+ hint="Higher wins when two profiles match at once. Equal numbers go to the older profile."+ >+ <TextField+ accessibilityLabel="Priority"+ testID="priority-input"+ figure+ style={styles.numInput}keyboardType="numeric"- value={priorityStr}- onChangeText={(val) => handleNumericChange(setPriorityStr, "priority", val, 0)}- placeholder="10"- placeholderTextColor={colors.placeholder}+ value={text.priority}+ onChangeText={handlePriority}+ onBlur={handlePriorityBlur}+ placeholder={String(DEFAULT_PRIORITY)}+ error={priorityError}/></SettingRow></Card>- {/* Condition */}- <SectionTitle style={styles.sectionGap}>Activation Condition</SectionTitle>- <Card>- <View style={styles.conditionGrid}>- {PROFILE_CONDITIONS.map((opt) => {- const Icon = opt.icon- const selected = profile.condition.type === opt.type- return (- <Pressable- key={opt.type}- style={({ pressed }) => [- styles.conditionOption,- {- backgroundColor: selected ? colors.primary + "15" : colors.background,- borderColor: selected ? colors.primary : colors.border- },- pressed && { opacity: colors.pressedOpacity }- ]}- onPress={() => setConditionType(opt.type)}- >- <Icon size={20} color={selected ? colors.primary : colors.textSecondary} />- <Text style={[styles.conditionLabel, { color: selected ? colors.primary : colors.text }]}>- {opt.label}- </Text>- <Text style={[styles.conditionDesc, { color: colors.textLight }]}>{opt.description}</Text>- </Pressable>- )- })}- </View>-- {isSpeed && (- <>- <Divider />- <View style={styles.inputGroup}>- <Text style={[styles.label, { color: colors.textSecondary }]}>Speed Threshold (km/h)</Text>- <TextInput- style={[- styles.input,- { backgroundColor: colors.background, color: colors.text, borderColor: colors.border }- ]}- placeholder="30"- placeholderTextColor={colors.placeholder}- value={speedKmh}- onChangeText={handleSpeedChange}- keyboardType="numeric"- />- </View>- </>- )}- </Card>-- {/* Tracking Settings */}- <SectionTitle style={styles.sectionGap}>Tracking Settings</SectionTitle>- <Card>- <SettingRow label="Tracking Interval" hint={`Default: ${settings.interval}s`}>- <View style={styles.inputWithUnit}>- <TextInput- style={inputStyle}- keyboardType="numeric"- value={intervalStr}- onChangeText={(val) => handleNumericChange(setIntervalStr, "interval", val, 1)}- placeholder="5"- placeholderTextColor={colors.placeholder}- />- <Text style={[styles.unit, { color: colors.textSecondary }]}>sec</Text>- </View>- </SettingRow>-- {profile.condition.type === "stationary" && profile.interval > STATIONARY_MAX_INTERVAL_SECONDS && (- <FieldMessage variant="warning">- The device may miss the first {Math.floor(profile.interval / 60)} minutes of a trip when you start moving- with the specified interval!+ <SectionTitle style={styles.groupTop}>Tracking while active</SectionTitle>+ <Card rows style={styles.cardTop}>+ <NumericInput+ label="Tracking interval"+ testID="interval-input"+ value={text.interval}+ onChange={(v) => handleNumeric("interval", v)}+ onBlur={() => handleBlur("interval")}+ unit="s"+ placeholder={String(settings.interval)}+ hint={`At least 1 s. Replaces the ${formatDuration(settings.interval)} from Tracking & sync while this profile is active. Shorter keeps the GPS awake more of the time and records more points.`}+ error={errorOf("interval")}+ message={noteOf("interval")}+ />+ {isStationary && profile.interval > STATIONARY_MAX_INTERVAL_SECONDS && (+ <FieldMessage variant="warning" style={styles.warning}>+ Longer than {STATIONARY_MAX_INTERVAL_SECONDS} s may leave the first {formatDuration(profile.interval)} of+ a trip unrecorded</FieldMessage>)}-- <Divider />-- {profile.condition.type === "stationary" ? (- <FieldMessage>- Movement threshold does not apply to a stationary profile - a point is recorded at every interval.- </FieldMessage>- ) : (+ {isStationary ? (<SettingRow- label="Movement Threshold"- hint={`Default: ${metersToInput(settings.distance)} ${shortDistanceUnit()}`}+ disabled+ label="Movement threshold"+ hint="Not used while still · a point is recorded every interval">- <View style={styles.inputWithUnit}>- <TextInput- style={inputStyle}- keyboardType="numeric"- value={distanceStr}- onChangeText={(val) => handleNumericChange(setDistanceStr, "distance", val, 0)}- placeholder="0"- placeholderTextColor={colors.placeholder}- />- <Text style={[styles.unit, { color: colors.textSecondary }]}>{shortDistanceUnit()}</Text>- </View>+ <Text style={[styles.figure, { color: colors.textDisabled }]}>0 {distanceUnit}</Text></SettingRow>+ ) : (+ <NumericInput+ label="Movement threshold"+ testID="distance-input"+ value={text.distance}+ onChange={(v) => handleNumeric("distance", v)}+ onBlur={() => handleBlur("distance")}+ unit={distanceUnit}+ placeholder={String(metersToInput(settings.distance))}+ hint={`At least 0 ${distanceUnit}. Replaces the ${metersToInput(settings.distance)} ${distanceUnit} from Tracking & sync. 0 records any movement, larger skips small drift.`}+ error={errorOf("distance")}+ message={noteOf("distance")}+ />)}-{!settings.isOfflineMode && (<>- <Divider />-- <View style={styles.syncLabelRow}>- <Text style={[styles.settingLabel, { color: colors.text }]}>Sync Interval</Text>- <Text style={[styles.settingHint, { color: colors.textSecondary }]}>- Default: {formatSyncDefault(settings.syncInterval)}- </Text>- </View>- <View style={styles.syncGrid}>- {SYNC_INTERVAL_PRESETS.map((sec) => {- const isSelected =- profile.syncInterval === sec && SYNC_INTERVAL_PRESETS.includes(profile.syncInterval)- return (- <Pressable- key={sec}- style={({ pressed }) => [- styles.syncOption,- {- backgroundColor: isSelected ? colors.primary + "15" : colors.background,- borderColor: isSelected ? colors.primary : colors.border- },- pressed && { opacity: colors.pressedOpacity }- ]}- onPress={() => setProfile((prev) => ({ ...prev, syncInterval: sec }))}- >- <Text style={[styles.syncOptionLabel, { color: isSelected ? colors.primary : colors.text }]}>- {SYNC_INTERVAL_LABELS[sec]}- </Text>- </Pressable>- )- })}- <Pressable- style={({ pressed }) => [- styles.syncOption,- {- backgroundColor: isCustomSyncInterval ? colors.primary + "15" : colors.background,- borderColor: isCustomSyncInterval ? colors.primary : colors.border- },- pressed && { opacity: colors.pressedOpacity }- ]}- onPress={() => {- if (!isCustomSyncInterval) {- const customValue = 1800- setSyncIntervalStr(customValue.toString())- setProfile((prev) => ({ ...prev, syncInterval: customValue }))- }- }}- >- <Text- style={[styles.syncOptionLabel, { color: isCustomSyncInterval ? colors.primary : colors.text }]}- >- Custom- </Text>- </Pressable>+ <Divider tight />+ <View style={styles.pickerTop}>+ <SyncIntervalPicker+ label="Sync interval"+ hint={`Replaces the ${syncDefault} from Tracking & sync while this profile is active · shorter means more wake-ups`}+ value={profile.syncInterval}+ min={0}+ pullUp={false}+ onSelect={(seconds) => setProfile((prev) => ({ ...prev, syncInterval: seconds }))}+ onChange={(seconds) => setProfile((prev) => ({ ...prev, syncInterval: seconds }))}+ onClamp={(seconds) => setProfile((prev) => ({ ...prev, syncInterval: seconds }))}+ /></View>-- {isCustomSyncInterval && (- <View style={styles.customSyncInput}>- <NumericInput- label="Custom Sync Interval"- value={syncIntervalStr}- onChange={(val) => {- setSyncIntervalStr(val)- const num = Number(val)- if (!isNaN(num) && num >= 0) {- setProfile((prev) => ({ ...prev, syncInterval: num }))- }- }}- onBlur={() => {- const num = Number(syncIntervalStr)- if (isNaN(num) || num < 0) {- setSyncIntervalStr("0")- setProfile((prev) => ({ ...prev, syncInterval: 0 }))- }- }}- unit="seconds"- placeholder="1800"- hint="Custom interval in seconds"- colors={colors}- />- </View>- )}</>)}</Card>- <SectionTitle style={styles.sectionGap}>Switching</SectionTitle>- <Card>- {profile.condition.type === "stationary" ? (- <SettingRow- label="Activation Delay"- hint="How long the device must be still before this profile activates. Resumes instantly via the hardware motion sensor when you move again."- >- <View style={styles.inputWithUnit}>- <TextInput- style={inputStyle}- keyboardType="numeric"- value={activationDelayStr}- onChangeText={(val) => handleNumericChange(setActivationDelayStr, "activationDelay", val, 0)}- placeholder="60"- placeholderTextColor={colors.placeholder}- />- <Text style={[styles.unit, { color: colors.textSecondary }]}>sec</Text>- </View>- </SettingRow>- ) : (- <>- <SettingRow- label="Activation Delay"- hint="How long the condition must hold before this profile takes over. Avoids switching on brief, temporary changes. 0 = instant."- >- <View style={styles.inputWithUnit}>- <TextInput- style={inputStyle}- keyboardType="numeric"- value={activationDelayStr}- onChangeText={(val) => handleNumericChange(setActivationDelayStr, "activationDelay", val, 0)}- placeholder="0"- placeholderTextColor={colors.placeholder}- />- <Text style={[styles.unit, { color: colors.textSecondary }]}>sec</Text>- </View>- </SettingRow>-- <Divider />-- <SettingRow- label="Deactivation Delay"- hint="How long after the condition stops before reverting to your defaults. Prevents rapid back-and-forth switching."- >- <View style={styles.inputWithUnit}>- <TextInput- style={inputStyle}- keyboardType="numeric"- value={delayStr}- onChangeText={(val) => handleNumericChange(setDelayStr, "deactivationDelay", val, 0)}- placeholder="60"- placeholderTextColor={colors.placeholder}- />- <Text style={[styles.unit, { color: colors.textSecondary }]}>sec</Text>- </View>- </SettingRow>- </>+ <SectionTitle style={styles.groupTop}>Switching</SectionTitle>+ <Card rows style={styles.cardTop}>+ <NumericInput+ label="Activation delay"+ testID="activation-delay-input"+ value={text.activationDelay}+ onChange={(v) => handleNumeric("activationDelay", v)}+ onBlur={() => handleBlur("activationDelay")}+ unit="s"+ placeholder={String(defaultProfileDelays(type).activationDelay)}+ hint={+ isStationary+ ? "At least 0 s. How long every fix must read as still first; 0 switches at the first still fix. Moving again ends the profile at once through the motion sensor."+ : "At least 0 s. How long the condition must hold first. 0 switches at once, longer ignores a brief plug or unplug."+ }+ error={errorOf("activationDelay")}+ message={noteOf("activationDelay")}+ />+ {!isStationary && (+ <NumericInput+ label="Deactivation delay"+ testID="deactivation-delay-input"+ value={text.deactivationDelay}+ onChange={(v) => handleNumeric("deactivationDelay", v)}+ onBlur={() => handleBlur("deactivationDelay")}+ unit="s"+ placeholder={String(defaultProfileDelays(type).deactivationDelay)}+ hint="At least 0 s. How long after the condition ends before Tracking & sync applies again. Longer rides out a brief gap so the profile does not flap."+ error={errorOf("deactivationDelay")}+ message={noteOf("deactivationDelay")}+ />)}</Card>- {/* Save Button */}- <Pressable- style={({ pressed }) => [- styles.saveBtn,- { backgroundColor: colors.primary },- saving && styles.saveBtnDisabled,- pressed && { opacity: colors.pressedOpacity }- ]}+ <Button+ testID="save-profile-btn"+ title={isEditing ? "Save changes" : "Create profile"}+ icon={Check}+ loading={saving}+ disabled={hasFieldError}onPress={handleSave}- disabled={saving}- >- <Check size={20} color={colors.textOnPrimary} />- <Text style={[styles.saveBtnText, { color: colors.textOnPrimary }]}>- {saving ? "Saving..." : isEditing ? "Save Changes" : "Create Profile"}- </Text>- </Pressable>+ style={styles.save}+ />+ {isEditing && (+ <Button+ testID="delete-profile-btn"+ title="Delete profile"+ icon={Trash2}+ variant="danger"+ onPress={handleDelete}+ />+ )}</ScrollView></Container>)}const styles = StyleSheet.create({- scrollContent: { paddingHorizontal: 16, paddingTop: 16, paddingBottom: 40 },- header: { marginBottom: 20 },- title: { fontSize: 28, ...fonts.bold, letterSpacing: -0.5 },- inputGroup: { marginBottom: 4 },- label: {- fontSize: 12,- ...fonts.semiBold,- marginBottom: 6,- textTransform: "uppercase",- letterSpacing: 0.5- },- input: { padding: 14, borderWidth: 1.5, borderRadius: 10, fontSize: 15, ...fonts.regular },- numInput: {- borderWidth: 1,- padding: 10,- borderRadius: 10,- fontSize: 15,- textAlign: "center",- width: 64,- ...fonts.regular- },- inputWithUnit: { flexDirection: "row", alignItems: "center", gap: 6 },- unit: { fontSize: 14, ...fonts.medium, minWidth: 28 },- conditionGrid: {- flexDirection: "row",- flexWrap: "wrap",- gap: 10- },- conditionOption: {- width: "47%",- padding: 12,- borderRadius: 10,- borderWidth: 1.5,- alignItems: "center",- gap: 4- },- conditionLabel: { fontSize: 13, ...fonts.semiBold },- conditionDesc: { fontSize: 11, ...fonts.regular, textAlign: "center" },- syncLabelRow: { marginBottom: 8 },- settingLabel: { fontSize: 16, ...fonts.semiBold, marginBottom: 2 },- settingHint: { fontSize: 13, ...fonts.regular, lineHeight: 18 },- syncGrid: { flexDirection: "row", flexWrap: "wrap", gap: 8 },- syncOption: { width: "31%", padding: 12, borderRadius: 10, borderWidth: 1.5, alignItems: "center" }, // ~3 per row with gap- syncOptionLabel: { fontSize: 13, ...fonts.semiBold },- customSyncInput: { marginTop: 12 },- saveBtn: {- flexDirection: "row",- alignItems: "center",- justifyContent: "center",- gap: 8,- padding: 16,- borderRadius: 12,- marginTop: 16- },- saveBtnText: { fontSize: 16, ...fonts.semiBold },- saveBtnDisabled: { opacity: 0.6 },- sectionGap: { marginTop: 24 }+ scrollContent: { paddingHorizontal: space.lg, paddingTop: space.lg, paddingBottom: space.xxl },+ intro: { fontSize: fontSizes.body, ...fonts.regular, lineHeight: lineHeights.body, marginBottom: space.lg },+ group: { marginTop: -space.sm },+ groupTop: { marginTop: space.xl },+ cardTop: { paddingTop: space.lg },+ // The row above already pays space.lg below it; the field's own bottom margin is the card's tail.+ reveal: { paddingLeft: size.iconColumn, marginTop: -space.xs },+ field: { paddingBottom: space.lg },+ numInput: { width: size.numericField },+ figure: { fontSize: fontSizes.input, ...fonts.medium, fontVariant: ["tabular-nums"] },+ warning: { marginTop: -space.sm, marginBottom: space.lg },+ pickerTop: { paddingTop: space.lg },+ save: { marginTop: space.xl }})diff --git a/apps/mobile/src/screens/TrackingProfilesScreen.tsx b/apps/mobile/src/screens/TrackingProfilesScreen.tsxindex fff19589..b28630ba 100644--- a/apps/mobile/src/screens/TrackingProfilesScreen.tsx+++ b/apps/mobile/src/screens/TrackingProfilesScreen.tsx@@ -3,48 +3,31 @@* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.*/-import React, { useState, useEffect, useCallback } from "react"-import { View, Text, StyleSheet, FlatList, Switch, Pressable, Share } from "react-native"+import React, { useState, useEffect, useCallback, useLayoutEffect } from "react"+import { View, Text, StyleSheet, ScrollView, Share } from "react-native"+import { Plus, Share2, UserRoundPen } from "lucide-react-native"import { useTheme } from "../hooks/useTheme"import { useTracking } from "../contexts/TrackingProvider"+import { useActiveProfile } from "../hooks/useActiveProfile"import { ProfileService } from "../services/ProfileService"-import { showAlert, showConfirm } from "../services/modalService"+import { showAlert } from "../services/modalService"import { SavedTrackingProfile, ScreenProps } from "../types/global"-import { fonts } from "../styles/typography"-import { Container, SectionTitle, Card } from "../components"-import { Plus, X, Zap, Share2 } from "lucide-react-native"+import { fontSizes, fonts, lineHeights } from "../styles/typography"+import { Card, Container, Divider, EmptyState, HeaderAction, ListItem, StateLine, Toggle } from "../components"import { logger } from "../utils/logger"import { buildProfilesLink } from "../utils/setupLink"-import { PROFILE_CONDITIONS, MS_TO_KMH, HIT_SLOP_MD } from "../constants"--function formatCondition(profile: SavedTrackingProfile): string {- const condition = PROFILE_CONDITIONS.find((c) => c.type === profile.condition.type)- const label = condition?.listLabel || profile.condition.type- if (profile.condition.type === "speed_above" || profile.condition.type === "speed_below") {- const kmh = ((profile.condition.speedThreshold ?? 0) * MS_TO_KMH).toFixed(0)- return `${label} ${kmh} km/h`- }- return label-}--function formatSettings(profile: SavedTrackingProfile, isOfflineMode?: boolean): string {- const parts = [`${profile.interval}s interval`]- if (profile.distance > 0) parts.push(`${profile.distance}m threshold`)- if (!isOfflineMode) {- parts.push(profile.syncInterval === 0 ? "instant sync" : `${profile.syncInterval}s sync`)- }- return parts.join(" \u2022 ")-}+import { conditionOf, describeProfileState, profileRowSub } from "../utils/profileRow"+import { space } from "../constants"export function TrackingProfilesScreen({ navigation }: ScreenProps) {const { colors } = useTheme()- const { settings, activeProfileName } = useTracking()+ const { settings, activeProfileId, tracking } = useTracking()+ const activeProfile = useActiveProfile(activeProfileId)const [profiles, setProfiles] = useState<SavedTrackingProfile[]>([])const loadProfiles = useCallback(async () => {try {- const data = await ProfileService.getProfiles()- setProfiles(data)+ setProfiles(await ProfileService.getProfiles())} catch (err) {logger.error("[TrackingProfilesScreen] Failed to load profiles:", err)}@@ -54,18 +37,12 @@ export function TrackingProfilesScreen({ navigation }: ScreenProps) {loadProfiles()}, [loadProfiles])- // Reload when returning from editor- useEffect(() => {- const unsubscribe = navigation.addListener("focus", () => {- loadProfiles()- })- return unsubscribe- }, [navigation, loadProfiles])+ useEffect(() => navigation.addListener("focus", loadProfiles), [navigation, loadProfiles])const toggleEnabled = useCallback(- async (id: number, value: boolean) => {+ async (id: number, enabled: boolean) => {try {- await ProfileService.updateProfile({ id, enabled: value })+ await ProfileService.updateProfile({ id, enabled })await loadProfiles()} catch {showAlert("Error", "Failed to update profile.", "error")@@ -84,198 +61,110 @@ export function TrackingProfilesScreen({ navigation }: ScreenProps) {}}, [profiles])- const handleDelete = useCallback(- async (item: SavedTrackingProfile) => {- const confirmed = await showConfirm({- title: "Delete Profile",- message: `Delete "${item.name}"?`,- confirmText: "Delete",- destructive: true- })-- if (!confirmed) return-- try {- await ProfileService.deleteProfile(item.id)- await loadProfiles()- } catch {- showAlert("Error", "Failed to delete profile.", "error")- }- },- [loadProfiles]+ const openEditor = useCallback(+ (profileId?: number) => navigation.navigate("Profile Editor", profileId === undefined ? {} : { profileId }),+ [navigation])- const renderItem = useCallback(- ({ item }: { item: SavedTrackingProfile }) => {- const condition = PROFILE_CONDITIONS.find((c) => c.type === item.condition.type)- const ConditionIcon = condition?.icon || Zap- const isActive = activeProfileName === item.name-- return (- <Card style={[styles.card, isActive && styles.activeCard, isActive && { borderColor: colors.primary }]}>- <Pressable- style={({ pressed }) => [styles.row, pressed && { opacity: colors.pressedOpacity }]}- onPress={() => navigation.navigate("Profile Editor", { profileId: item.id })}- >- <View style={[styles.iconWrap, { backgroundColor: colors.primary + "15" }]}>- <ConditionIcon size={18} color={colors.primary} />- </View>-- <View style={styles.info}>- <View style={styles.nameRow}>- <Text style={[styles.name, { color: colors.text }]}>{item.name}</Text>- {isActive && (- <View style={[styles.activeBadge, { backgroundColor: colors.success + "20" }]}>- <Text style={[styles.activeBadgeText, { color: colors.success }]}>Active</Text>- </View>- )}- <View style={[styles.priorityBadge, { backgroundColor: colors.border }]}>- <Text style={[styles.priorityText, { color: colors.textSecondary }]}>P{item.priority}</Text>- </View>- </View>- <Text style={[styles.condition, { color: colors.textSecondary }]}>{formatCondition(item)}</Text>- <Text style={[styles.settings, { color: colors.textLight }]}>- {formatSettings(item, settings.isOfflineMode)}- </Text>- </View>-- <View style={styles.actions}>- <Switch- testID={`toggle-profile-${item.id}`}- value={item.enabled}- onValueChange={(val) => toggleEnabled(item.id, val)}- trackColor={{ false: colors.border, true: colors.primary + "80" }}- thumbColor={item.enabled ? colors.primary : colors.border}- />-- <Pressable- testID={`delete-profile-${item.id}`}- onPress={() => handleDelete(item)}- style={({ pressed }) => [- styles.deleteBtn,- { backgroundColor: colors.error + "15" },- pressed && { opacity: colors.pressedOpacity }- ]}- >- <X size={16} color={colors.error} />- </Pressable>- </View>- </Pressable>- </Card>- )- },- [colors, activeProfileName, settings.isOfflineMode, toggleEnabled, handleDelete, navigation]+ const hasProfiles = profiles.length > 0+ const renderHeaderActions = useCallback(+ () => (+ <View style={styles.headerRow}>+ {hasProfiles && (+ <HeaderAction+ icon={Share2}+ label="Share all profiles"+ onPress={handleShareProfiles}+ testID="share-profiles-btn"+ />+ )}+ <HeaderAction icon={Plus} label="Create profile" onPress={() => openEditor()} testID="add-profile-btn" />+ </View>+ ),+ [hasProfiles, handleShareProfiles, openEditor])+ useLayoutEffect(() => {+ navigation.setOptions({ headerRight: renderHeaderActions })+ }, [navigation, renderHeaderActions])++ const state = describeProfileState(activeProfile, settings, tracking)return (<Container>- <FlatList- data={profiles}- keyExtractor={(item) => item.id.toString()}- contentContainerStyle={styles.list}- showsVerticalScrollIndicator={false}- ListHeaderComponent={+ <ScrollView contentContainerStyle={styles.scrollContent} keyboardShouldPersistTaps="handled">+ {hasProfiles ? (<>- <View style={styles.header}>- <Text style={[styles.title, { color: colors.text }]}>Tracking Profiles</Text>- <Text style={[styles.subtitle, { color: colors.textSecondary }]}>- Auto-switch GPS settings based on charging, Android Auto, or speed- </Text>- </View>-- <Pressable- style={({ pressed }) => [- styles.createBtn,- { backgroundColor: colors.primary },- pressed && { opacity: colors.pressedOpacity }- ]}- onPress={() => navigation.navigate("Profile Editor", {})}- >- <Plus size={20} color={colors.textOnPrimary} />- <Text style={[styles.createBtnText, { color: colors.textOnPrimary }]}>Create Profile</Text>- </Pressable>-- {profiles.length > 0 && (- <View style={styles.activeHeader}>- <SectionTitle>Profiles ({profiles.length})</SectionTitle>- <Pressable- testID="share-profiles-btn"- onPress={handleShareProfiles}- hitSlop={HIT_SLOP_MD}- style={({ pressed }) => [styles.shareBtn, pressed && { opacity: colors.pressedOpacity }]}- >- <Share2 size={20} color={colors.textSecondary} />- </Pressable>- </View>- )}- </>- }- ListEmptyComponent={- <View style={styles.empty}>- <Text style={[styles.emptyText, { color: colors.textSecondary }]}>No profiles yet</Text>- <Text style={[styles.emptyHint, { color: colors.textLight }]}>- Create a profile to automatically switch tracking settings when charging, connected to Android Auto, or- based on speed+ <Text style={[styles.intro, { color: colors.textSecondary }]}>+ Checked top to bottom while tracking runs. The first profile whose condition holds replaces the Tracking &+ sync values.</Text>- </View>- }- renderItem={renderItem}- />+ <Card rows>+ <StateLine+ icon={state.icon}+ iconColor={state.tone === "success" ? colors.success : colors.textSecondary}+ label={state.label}+ caption={state.caption}+ testID="profile-state"+ />+ <Divider tight />+ {profiles.map((profile, i) => {+ const inForce = tracking && profile.id === activeProfileId+ return (+ <React.Fragment key={profile.id}>+ {i > 0 && <Divider tight inset />}+ <ListItem+ testID={`profile-${profile.id}`}+ icon={conditionOf(profile).icon}+ iconColor={inForce ? colors.success : undefined}+ label={profile.name}+ sub={profileRowSub(profile, inForce, settings.isOfflineMode)}+ subLines={2}+ onPress={() => openEditor(profile.id)}+ trailing={+ <Toggle+ accessibilityLabel={`Use ${profile.name}`}+ testID={`profile-toggle-${profile.id}`}+ value={profile.enabled}+ onValueChange={(enabled) => toggleEnabled(profile.id, enabled)}+ />+ }+ />+ </React.Fragment>+ )+ })}+ </Card>+ </>+ ) : (+ <EmptyState+ icon={UserRoundPen}+ title="No profiles yet"+ hint="A profile changes how you track while a condition holds, such as charging or driving"+ action={{ label: "Create profile", onPress: () => openEditor() }}+ style={styles.empty}+ />+ )}+ </ScrollView></Container>)}const styles = StyleSheet.create({- list: { padding: 16, paddingBottom: 40 },- header: { marginBottom: 20 },- title: { fontSize: 28, ...fonts.bold, letterSpacing: -0.5, marginBottom: 6 },- subtitle: { fontSize: 14, ...fonts.regular, lineHeight: 20 },- createBtn: {- flexDirection: "row",- alignItems: "center",- justifyContent: "center",- gap: 8,- padding: 16,- borderRadius: 12,- marginBottom: 24+ headerRow: {+ flexDirection: "row"},- createBtnText: { fontSize: 15, ...fonts.semiBold },- card: { marginBottom: 12 },- activeCard: { borderWidth: 2 },- row: { flexDirection: "row", alignItems: "center" },- iconWrap: {- width: 36,- height: 36,- borderRadius: 10,- alignItems: "center",- justifyContent: "center",- marginRight: 12+ scrollContent: {+ flexGrow: 1,+ paddingHorizontal: space.lg,+ paddingTop: space.lg,+ paddingBottom: space.xxl},- info: { flex: 1, marginRight: 12 },- nameRow: { flexDirection: "row", alignItems: "center", gap: 8, marginBottom: 2 },- name: { fontSize: 15, ...fonts.semiBold },- activeBadge: { paddingHorizontal: 6, paddingVertical: 2, borderRadius: 4 },- activeBadgeText: { fontSize: 10, ...fonts.semiBold, textTransform: "uppercase" },- priorityBadge: { paddingHorizontal: 6, paddingVertical: 2, borderRadius: 4 },- priorityText: { fontSize: 10, ...fonts.semiBold },- condition: { fontSize: 13, ...fonts.medium, marginBottom: 2 },- settings: { fontSize: 11, ...fonts.regular },- actions: { alignItems: "center", gap: 8 },- deleteBtn: {- width: 32,- height: 32,- borderRadius: 16,- alignItems: "center",- justifyContent: "center"+ intro: {+ fontSize: fontSizes.body,+ ...fonts.regular,+ lineHeight: lineHeights.body,+ marginBottom: space.lg},- activeHeader: { flexDirection: "row", alignItems: "center", justifyContent: "space-between" },- shareBtn: { padding: 4, marginBottom: 12 },- empty: { alignItems: "center", paddingVertical: 40 },- emptyText: { fontSize: 15, ...fonts.semiBold, marginBottom: 6 },- emptyHint: {- fontSize: 13,- textAlign: "center",- maxWidth: 280,- lineHeight: 18+ empty: {+ paddingHorizontal: 0}})diff --git a/apps/mobile/src/screens/TrackingSyncScreen.tsx b/apps/mobile/src/screens/TrackingSyncScreen.tsxindex e0f1f825..80b5e2e6 100644--- a/apps/mobile/src/screens/TrackingSyncScreen.tsx+++ b/apps/mobile/src/screens/TrackingSyncScreen.tsx@@ -6,17 +6,24 @@import React, { useCallback } from "react"import { StyleSheet, ScrollView } from "react-native"import { ScreenProps, Settings } from "../types/global"-import { useTheme } from "../hooks/useTheme"import { useAutoSave } from "../hooks/useAutoSave"+import { useActiveProfile } from "../hooks/useActiveProfile"import { useTracking } from "../contexts/TrackingProvider"import { FloatingSaveIndicator } from "../components/ui/FloatingSaveIndicator"import { Container } from "../components"import { SyncStrategySettings } from "../components/features/settings/SyncStrategySettings"+import { space } from "../constants"export function TrackingSyncScreen({}: ScreenProps) {- const { settings, setSettings, updateSettingsLocal, restartTracking } = useTracking()- const { colors } = useTheme()- const { saving, saveSuccess, debouncedSaveAndRestart, immediateSaveAndRestart } = useAutoSave()+ const { settings, setSettings, updateSettingsLocal, restartTracking, activeProfileId } = useTracking()+ const activeProfile = useActiveProfile(activeProfileId)+ const {+ saving,+ message: saveMessage,+ isError: saveIsError,+ debouncedSaveAndRestart,+ immediateSaveAndRestart+ } = useAutoSave()const handleDebouncedSave = useCallback((newSettings: Settings) => {@@ -50,19 +57,19 @@ export function TrackingSyncScreen({}: ScreenProps) {onSettingsChange={updateSettingsLocal}onDebouncedSave={handleDebouncedSave}onImmediateSave={handleImmediateSave}- colors={colors}+ activeProfile={activeProfile}/></ScrollView>- <FloatingSaveIndicator saving={saving} success={saveSuccess} colors={colors} />+ <FloatingSaveIndicator saving={saving} message={saveMessage} isError={saveIsError} /></Container>)}const styles = StyleSheet.create({scrollContent: {- paddingHorizontal: 16,- paddingTop: 16,- paddingBottom: 40+ paddingHorizontal: space.lg,+ paddingTop: space.lg,+ paddingBottom: space.xxl}})diff --git a/apps/mobile/src/screens/__tests__/ProfileEditorScreen.test.tsx b/apps/mobile/src/screens/__tests__/ProfileEditorScreen.test.tsxindex 65831e23..c964f74f 100644--- a/apps/mobile/src/screens/__tests__/ProfileEditorScreen.test.tsx+++ b/apps/mobile/src/screens/__tests__/ProfileEditorScreen.test.tsx@@ -1,8 +1,7 @@import React from "react"-import { render, fireEvent, waitFor } from "@testing-library/react-native"+import { render, fireEvent, waitFor, act } from "@testing-library/react-native"import { TrackingProfile } from "../../types/global"--// --- Mocks ---+import { SAVE_SUCCESS_DISPLAY_MS } from "../../constants"const mockProfiles: TrackingProfile[] = [{@@ -22,72 +21,108 @@ const mockProfiles: TrackingProfile[] = [const mockGetProfiles = jest.fn().mockResolvedValue(mockProfiles)const mockCreateProfile = jest.fn().mockResolvedValue(1)const mockUpdateProfile = jest.fn().mockResolvedValue(true)+const mockDeleteProfile = jest.fn().mockResolvedValue(true)jest.mock("../../services/ProfileService", () => ({ProfileService: {getProfiles: () => mockGetProfiles(),createProfile: (p: any) => mockCreateProfile(p),- updateProfile: (p: any) => mockUpdateProfile(p)+ updateProfile: (p: any) => mockUpdateProfile(p),+ deleteProfile: (id: number) => mockDeleteProfile(id)}}))const mockShowAlert = jest.fn()-+const mockShowConfirm = jest.fn()jest.mock("../../services/modalService", () => ({- showAlert: (...args: any[]) => mockShowAlert(...args)+ showAlert: (...args: any[]) => mockShowAlert(...args),+ showConfirm: (...args: any[]) => mockShowConfirm(...args)}))jest.mock("../../utils/geo", () => ({...jest.requireActual("../../utils/geo"),shortDistanceUnit: () => "m",metersToInput: (v: number) => v,- inputToMeters: (v: number) => v+ inputToMeters: (v: number) => v,+ getSpeedUnit: () => ({ factor: 3.6, unit: "km/h" }),+ speedToInput: (mps: number) => Math.round(mps * 3.6),+ inputToSpeed: (v: number) => v / 3.6}))+let mockSettings = { isOfflineMode: false, interval: 5, distance: 0, syncInterval: 0 }jest.mock("../../contexts/TrackingProvider", () => ({- useTracking: () => ({- settings: {- isOfflineMode: false,- interval: 5,- distance: 0,- syncInterval: 0- }- })+ useTracking: () => ({ settings: mockSettings })}))+jest.mock("../../components/features/settings/SyncIntervalPicker", () => {+ const R = require("react")+ const { View, Text, Pressable } = require("react-native")+ const { SYNC_INTERVAL_PRESETS, SYNC_INTERVAL_LABELS } = require("../../constants")+ return {+ SyncIntervalPicker: ({ label, hint, value, onSelect }: any) =>+ R.createElement(+ View,+ null,+ R.createElement(Text, null, label),+ R.createElement(Text, null, hint),+ SYNC_INTERVAL_PRESETS.map((seconds: number) =>+ R.createElement(+ Pressable,+ {+ key: seconds,+ testID: `sync-interval-${seconds}`,+ onPress: () => onSelect(seconds),+ accessibilityState: { checked: value === seconds }+ },+ R.createElement(Text, null, SYNC_INTERVAL_LABELS[seconds])+ )+ )+ )+ }+})+jest.mock("../../hooks/useTheme", () => ({- useTheme: () => ({- colors: {- primary: "#0d9488",- border: "#e5e7eb",- text: "#000",- textSecondary: "#6b7280",- textLight: "#9ca3af",- background: "#fff",- info: "#3b82f6",- success: "#22c55e",- error: "#ef4444",- card: "#fff",- backgroundElevated: "#f9fafb",- placeholder: "#9ca3af",- textOnPrimary: "#fff"- }- })+ useTheme: () => ({ colors: require("@colota/shared").lightColors })}))jest.mock("../../components", () => {const R = require("react")- const { View, Text } = require("react-native")+ const { View, Text, Pressable, TextInput } = require("react-native")return {+ TextField: require("../../testing/componentStubs").TextFieldStub,+ RadioRow: ({ testID, label, sub, selected, onPress }: any) =>+ R.createElement(+ Pressable,+ { testID, onPress, accessibilityRole: "radio", accessibilityState: { checked: selected } },+ R.createElement(Text, null, label),+ sub ? R.createElement(Text, null, sub) : null+ ),+ Button: ({ title, onPress, disabled, testID }: any) =>+ R.createElement(+ Pressable,+ { testID, onPress, disabled, accessibilityRole: "button", accessibilityState: { disabled } },+ R.createElement(Text, null, title)+ ),Container: ({ children }: any) => R.createElement(View, null, children),SectionTitle: ({ children }: any) => R.createElement(Text, null, children),Card: ({ children }: any) => R.createElement(View, null, children),- Divider: () => R.createElement(View, null),- SettingRow: ({ label, hint, children }: any) =>+ NumericInput: ({ label, value, onChange, onBlur, unit, hint, error, message, testID }: any) =>R.createElement(View,null,R.createElement(Text, null, label),+ hint ? R.createElement(Text, null, hint) : null,+ R.createElement(TextInput, { testID, value, onChangeText: onChange, onBlur }),+ unit ? R.createElement(Text, null, unit) : null,+ error ? R.createElement(Text, null, error) : null,+ message ? R.createElement(Text, null, message) : null+ ),+ Divider: () => R.createElement(View, null),+ SettingRow: ({ label, hint, children, disabled }: any) =>+ R.createElement(+ View,+ { accessibilityState: { disabled: !!disabled } },+ R.createElement(Text, null, label),hint && R.createElement(Text, null, hint),children),@@ -95,343 +130,227 @@ jest.mock("../../components", () => {}})-const mockGoBack = jest.fn()+jest.mock("../../utils/logger", () => ({ logger: { error: jest.fn() } }))-const mockNavigation = {- goBack: mockGoBack-}+const mockGoBack = jest.fn()+const mockSetOptions = jest.fn()+const mockNavigation = { goBack: mockGoBack, setOptions: mockSetOptions }import { ProfileEditorScreen } from "../ProfileEditorScreen"describe("ProfileEditorScreen", () => {beforeEach(() => {jest.clearAllMocks()+ mockSettings = { isOfflineMode: false, interval: 5, distance: 0, syncInterval: 0 }mockGetProfiles.mockResolvedValue(mockProfiles)})- function renderNewProfile() {- return render(<ProfileEditorScreen navigation={mockNavigation as any} route={{ params: {} } as any} />)- }+ const renderNew = () =>+ render(<ProfileEditorScreen navigation={mockNavigation as any} route={{ params: {} } as any} />)+ const renderEdit = (profileId = 1) =>+ render(<ProfileEditorScreen navigation={mockNavigation as any} route={{ params: { profileId } } as any} />)- function renderEditProfile(profileId = 1) {- return render(<ProfileEditorScreen navigation={mockNavigation as any} route={{ params: { profileId } } as any} />)- }+ describe("the sentence", () => {+ it("reads the draft back as the rule and follows every edit", () => {+ const { getByTestId } = renderNew()- // --- New Profile Mode ---+ expect(getByTestId("profile-sentence").props.children).toBe(+ "When charging, track every 5 s, any movement and sync each fix."+ )- it("renders new profile title", () => {- const { getByText } = renderNewProfile()- expect(getByText("New Profile")).toBeTruthy()- })+ fireEvent.press(getByTestId("condition-speed_above"))+ fireEvent.changeText(getByTestId("speed-input"), "50")+ fireEvent.changeText(getByTestId("interval-input"), "2")+ fireEvent.changeText(getByTestId("distance-input"), "10")+ fireEvent.press(getByTestId("sync-interval-60"))- it("shows Create Profile button for new profile", () => {- const { getByText } = renderNewProfile()- expect(getByText("Create Profile")).toBeTruthy()- })-- it("shows all condition options", () => {- const { getByText } = renderNewProfile()-- expect(getByText("Charging")).toBeTruthy()- expect(getByText("Car Mode")).toBeTruthy()- expect(getByText("Speed Above")).toBeTruthy()- expect(getByText("Speed Below")).toBeTruthy()- })-- it("shows all sync interval options inline", () => {- const { getByText, getAllByText } = renderNewProfile()-- expect(getAllByText("Instant").length).toBeGreaterThan(0)- expect(getByText("1 min")).toBeTruthy()- expect(getByText("5 min")).toBeTruthy()- expect(getByText("15 min")).toBeTruthy()- })-- it("pre-fills fields with main settings values", () => {- const { getByDisplayValue, getAllByDisplayValue } = renderNewProfile()-- expect(getByDisplayValue("5")).toBeTruthy() // interval from settings- // distance from settings is 0; activation delay also defaults to 0- expect(getAllByDisplayValue("0").length).toBeGreaterThan(0)- })-- it("shows default hints from main settings", () => {- const { getByText } = renderNewProfile()-- expect(getByText("Default: 5s")).toBeTruthy()- expect(getByText("Default: 0 m")).toBeTruthy()- expect(getByText("Default: Instant")).toBeTruthy()- })-- // --- Validation ----- it("shows alert when saving with empty name", async () => {- const { getByText } = renderNewProfile()-- fireEvent.press(getByText("Create Profile"))-- await waitFor(() => {- expect(mockShowAlert).toHaveBeenCalledWith("Missing Name", "Please enter a profile name.", "warning")+ expect(getByTestId("profile-sentence").props.children).toBe(+ "When faster than 50 km/h, track every 2 s after 10 m and sync every 1 min."+ )})- })-- it("saves with speed condition when threshold is valid", async () => {- const { getByText, getByDisplayValue } = renderNewProfile()- const nameInput = getByDisplayValue("")- fireEvent.changeText(nameInput, "Speed Test")+ it("drops the sync clause in offline mode and hides the sync picker", () => {+ mockSettings = { ...mockSettings, isOfflineMode: true }+ const { getByTestId, queryByText } = renderNew()- // Select speed_above condition - defaults to 30 km/h threshold- fireEvent.press(getByText("Speed Above"))-- fireEvent.press(getByText("Create Profile"))-- await waitFor(() => {- expect(mockCreateProfile).toHaveBeenCalled()- expect(mockGoBack).toHaveBeenCalled()+ expect(getByTestId("profile-sentence").props.children).toBe("When charging, track every 5 s, any movement.")+ expect(queryByText("Sync interval")).toBeNull()})})- // --- Successful save ---+ describe("condition", () => {+ it("comes first, in sentence case, with what watching it costs on each row", () => {+ const { getByText, getAllByText, getByTestId } = renderNew()- it("creates profile and navigates back on valid save", async () => {- const { getByText, getByDisplayValue } = renderNewProfile()+ expect(getByText("Android Auto")).toBeTruthy()+ expect(getByText("Speed above")).toBeTruthy()+ expect(getByText("Phone is plugged in · costs nothing to watch")).toBeTruthy()+ expect(getAllByText(/fixes keep flowing to measure it, even below the movement threshold/)).toHaveLength(2)+ expect(getByTestId("condition-charging").props.accessibilityState.checked).toBe(true)+ })- const nameInput = getByDisplayValue("")- fireEvent.changeText(nameInput, "My Profile")+ it("reveals the speed field under a speed condition only, in the user's unit", () => {+ const { getByTestId, queryByTestId, getByText } = renderNew()+ expect(queryByTestId("speed-input")).toBeNull()- fireEvent.press(getByText("Create Profile"))+ fireEvent.press(getByTestId("condition-speed_below"))- await waitFor(() => {- expect(mockCreateProfile).toHaveBeenCalled()- expect(mockGoBack).toHaveBeenCalled()+ expect(getByTestId("speed-input").props.value).toBe("30")+ expect(getByText("At least 1 km/h. Applies while your average speed is below it.")).toBeTruthy()+ expect(getByText("km/h")).toBeTruthy()})- })- it("does not call createProfile when validation fails", async () => {- const { getByText } = renderNewProfile()+ it("keeps delays the user changed across a condition switch and resets untouched ones", () => {+ const { getByTestId } = renderNew()- // Try to save with empty name- fireEvent.press(getByText("Create Profile"))+ fireEvent.press(getByTestId("condition-stationary"))+ expect(getByTestId("activation-delay-input").props.value).toBe("60")- await waitFor(() => {- expect(mockShowAlert).toHaveBeenCalled()+ fireEvent.changeText(getByTestId("activation-delay-input"), "90")+ fireEvent.press(getByTestId("condition-charging"))+ expect(getByTestId("activation-delay-input").props.value).toBe("90")})-- expect(mockCreateProfile).not.toHaveBeenCalled()})- // --- Edit Mode ---+ describe("stationary", () => {+ it("blocks the movement threshold with the reason instead of hiding it, and drops the deactivation delay", () => {+ const { getByTestId, getByText, queryByTestId } = renderNew()- it("renders edit profile title when editing", async () => {- const { getByText } = renderEditProfile()+ fireEvent.press(getByTestId("condition-stationary"))- await waitFor(() => {- expect(getByText("Edit Profile")).toBeTruthy()+ expect(getByText("Not used while still · a point is recorded every interval")).toBeTruthy()+ expect(getByText("0 m")).toBeTruthy()+ expect(queryByTestId("distance-input")).toBeNull()+ expect(queryByTestId("deactivation-delay-input")).toBeNull()+ expect(getByText(/How long every fix must read as still first/)).toBeTruthy()})- })- it("shows Save Changes button when editing", async () => {- const { getByText } = renderEditProfile()+ it("warns above 60 s without blocking Save", () => {+ const { getByTestId, getByText, queryByText } = renderNew()+ fireEvent.press(getByTestId("condition-stationary"))+ expect(queryByText(/may leave the first/)).toBeNull()- await waitFor(() => {- expect(getByText("Save Changes")).toBeTruthy()- })- })+ fireEvent.changeText(getByTestId("interval-input"), "300")- it("loads existing profile data", async () => {- const { getByDisplayValue } = renderEditProfile()-- await waitFor(() => {- expect(getByDisplayValue("Existing Profile")).toBeTruthy()- expect(getByDisplayValue("15")).toBeTruthy() // priority- expect(getByDisplayValue("10")).toBeTruthy() // interval+ expect(getByText("Longer than 60 s may leave the first 5 min of a trip unrecorded")).toBeTruthy()+ expect(getByTestId("save-profile-btn").props.accessibilityState.disabled).toBe(false)})})- it("loads speed threshold in km/h", async () => {- const { getByDisplayValue } = renderEditProfile()+ describe("override fields", () => {+ it("name the Tracking & sync value they replace instead of a bare default", () => {+ mockSettings = { isOfflineMode: false, interval: 30, distance: 2, syncInterval: 300 }+ const { getByText } = renderNew()- // 13.89 m/s * 3.6 = 50 km/h- await waitFor(() => {- expect(getByDisplayValue("50")).toBeTruthy()+ expect(getByText(/^At least 1 s\. Replaces the 30 s from Tracking & sync/)).toBeTruthy()+ expect(getByText(/^At least 0 m\. Replaces the 2 m from Tracking & sync/)).toBeTruthy()+ expect(getByText(/^Replaces the 5 min from Tracking & sync/)).toBeTruthy()})- })- it("calls updateProfile when saving in edit mode", async () => {- const { getByText } = renderEditProfile()+ it("rejects a decimal on the field and disables Save until it is fixed", () => {+ const { getByTestId, getByText, queryByText } = renderNew()- await waitFor(() => {- expect(getByText("Save Changes")).toBeTruthy()- })+ fireEvent.changeText(getByTestId("interval-input"), "1.5")- fireEvent.press(getByText("Save Changes"))+ expect(getByText("A whole number")).toBeTruthy()+ expect(getByTestId("save-profile-btn").props.accessibilityState.disabled).toBe(true)- await waitFor(() => {- expect(mockUpdateProfile).toHaveBeenCalled()- expect(mockGoBack).toHaveBeenCalled()+ fireEvent.changeText(getByTestId("interval-input"), "15")+ expect(queryByText("A whole number")).toBeNull()+ expect(getByTestId("save-profile-btn").props.accessibilityState.disabled).toBe(false)})- })- it("shows error and navigates back on load failure", async () => {- mockGetProfiles.mockRejectedValueOnce(new Error("DB Error"))+ it("clamps an emptied interval to 1 s on blur and says so for a moment", () => {+ jest.useFakeTimers()+ const { getByTestId, getByText, queryByText } = renderNew()- renderEditProfile()+ fireEvent.changeText(getByTestId("interval-input"), "")+ fireEvent(getByTestId("interval-input"), "blur")- await waitFor(() => {- expect(mockShowAlert).toHaveBeenCalledWith("Error", "Failed to load profile data.", "error")- expect(mockGoBack).toHaveBeenCalled()+ expect(getByTestId("interval-input").props.value).toBe("1")+ expect(getByText("Set to 1 s")).toBeTruthy()+ act(() => {+ jest.advanceTimersByTime(SAVE_SUCCESS_DISPLAY_MS)+ })+ expect(queryByText("Set to 1 s")).toBeNull()+ jest.useRealTimers()})- })-- it("shows error when save fails", async () => {- mockCreateProfile.mockRejectedValueOnce(new Error("Save failed"))- const { getByText, getByDisplayValue } = renderNewProfile()+ it("restores the stored priority when its box is left empty, and flags a non-number", () => {+ const { getByTestId, getByText, queryByText } = renderNew()- const nameInput = getByDisplayValue("")- fireEvent.changeText(nameInput, "Fail Profile")+ fireEvent.changeText(getByTestId("priority-input"), "x")+ expect(getByText("A whole number")).toBeTruthy()+ expect(getByTestId("save-profile-btn").props.accessibilityState.disabled).toBe(true)- fireEvent.press(getByText("Create Profile"))-- await waitFor(() => {- expect(mockShowAlert).toHaveBeenCalledWith("Error", "Failed to save profile.", "error")+ fireEvent.changeText(getByTestId("priority-input"), "")+ fireEvent(getByTestId("priority-input"), "blur")+ expect(getByTestId("priority-input").props.value).toBe("10")+ expect(queryByText("A whole number")).toBeNull()})})- // --- Speed condition visibility ----- it("shows speed threshold input only for speed conditions", () => {- const { getByText, queryByText } = renderNewProfile()-- // Default is charging - no speed input- expect(queryByText("Speed Threshold (km/h)")).toBeNull()-- // Select Speed Above- fireEvent.press(getByText("Speed Above"))- expect(getByText("Speed Threshold (km/h)")).toBeTruthy()-- // Switch back to charging- fireEvent.press(getByText("Charging"))- expect(queryByText("Speed Threshold (km/h)")).toBeNull()- })-- // --- Activation delay ----- it("shows activation delay for all conditions, and deactivation delay only for non-stationary", () => {- const { getByText, queryByText } = renderNewProfile()-- // Charging: both delays- expect(getByText("Activation Delay")).toBeTruthy()- expect(getByText("Deactivation Delay")).toBeTruthy()-- // Stationary: activation delay only (deactivation is instant via the motion sensor)- fireEvent.press(getByText("Stationary"))- expect(getByText("Activation Delay")).toBeTruthy()- expect(queryByText("Deactivation Delay")).toBeNull()- })-- it("hides the movement threshold for a stationary profile and shows a note instead", () => {- const { getByText, queryByText } = renderNewProfile()+ describe("save and delete", () => {+ it("creates a profile with the condition's name when the name is blank, four taps from Create", async () => {+ const { getByTestId } = renderNew()- // Default (charging): the field is shown- expect(getByText("Movement Threshold")).toBeTruthy()+ fireEvent.press(getByTestId("save-profile-btn"))- // Stationary: field hidden (the distance filter is forced to 0), note shown instead- fireEvent.press(getByText("Stationary"))- expect(queryByText("Movement Threshold")).toBeNull()- expect(getByText(/Movement threshold does not apply/)).toBeTruthy()- })-- it("defaults stationary activation delay to 60", () => {- const { getByText, getByDisplayValue } = renderNewProfile()-- fireEvent.press(getByText("Stationary"))- expect(getByDisplayValue("60")).toBeTruthy()- })-- it("loads existing activation delay in edit mode", async () => {- const { getByDisplayValue } = renderEditProfile()-- await waitFor(() => {- expect(getByDisplayValue("12")).toBeTruthy()+ await waitFor(() => expect(mockCreateProfile).toHaveBeenCalledWith(expect.objectContaining({ name: "Charging" })))+ expect(mockShowAlert).not.toHaveBeenCalled()+ expect(mockGoBack).toHaveBeenCalled()})- })-- // --- Numeric input ---- it("updates interval via numeric input", () => {- const { getByDisplayValue } = renderNewProfile()+ it("stores a speed in m/s from the display unit", async () => {+ const { getByTestId } = renderNew()- const intervalInput = getByDisplayValue("5")- fireEvent.changeText(intervalInput, "15")+ fireEvent.press(getByTestId("condition-speed_above"))+ fireEvent.changeText(getByTestId("speed-input"), "50")+ fireEvent.press(getByTestId("save-profile-btn"))- expect(getByDisplayValue("15")).toBeTruthy()- })-- it("updates priority via numeric input", () => {- const { getByDisplayValue } = renderNewProfile()-- const priorityInput = getByDisplayValue("10")- fireEvent.changeText(priorityInput, "25")-- expect(getByDisplayValue("25")).toBeTruthy()- })-- // --- Stationary interval warning ---+ await waitFor(() =>+ expect(mockCreateProfile).toHaveBeenCalledWith(+ expect.objectContaining({ condition: { type: "speed_above", speedThreshold: expect.closeTo(13.89, 1) } })+ )+ )+ })- describe("stationary interval warning", () => {- it("does not show the warning while interval is at or below 60s", () => {- const { getByText, queryByText, getByDisplayValue } = renderNewProfile()+ it("loads an existing profile into every field and saves through updateProfile", async () => {+ const { findByTestId, getByTestId } = renderEdit()- fireEvent.press(getByText("Stationary"))- const intervalInput = getByDisplayValue("5")- fireEvent.changeText(intervalInput, "60")+ expect((await findByTestId("name-input")).props.value).toBe("Existing Profile")+ expect(getByTestId("speed-input").props.value).toBe("50")+ expect(getByTestId("interval-input").props.value).toBe("10")+ expect(getByTestId("activation-delay-input").props.value).toBe("12")+ expect(mockSetOptions).toHaveBeenCalledWith({ headerTitle: "Edit profile" })- expect(queryByText(/may miss the first \d+ minutes of a trip/)).toBeNull()+ fireEvent.press(getByTestId("save-profile-btn"))+ await waitFor(() =>+ expect(mockUpdateProfile).toHaveBeenCalledWith(expect.objectContaining({ id: 1, priority: 15 }))+ )})- it("shows a warning when the interval exceeds 60s", () => {- const { getByText, getByDisplayValue } = renderNewProfile()+ it("shows an error and goes back when the profile cannot load", async () => {+ mockGetProfiles.mockRejectedValueOnce(new Error("db"))+ renderEdit()- fireEvent.press(getByText("Stationary"))- const intervalInput = getByDisplayValue("5")- fireEvent.changeText(intervalInput, "600")-- expect(getByText(/may miss the first \d+ minutes of a trip/)).toBeTruthy()+ await waitFor(() => expect(mockShowAlert).toHaveBeenCalledWith("Error", "Failed to load profile data.", "error"))+ expect(mockGoBack).toHaveBeenCalled()})- it("does not show the warning for non-stationary conditions even with large intervals", () => {- const { queryByText, getByDisplayValue } = renderNewProfile()-- const intervalInput = getByDisplayValue("5")- fireEvent.changeText(intervalInput, "3600")+ it("offers Delete only while editing and confirms before deleting", async () => {+ const draft = renderNew()+ expect(draft.queryByTestId("delete-profile-btn")).toBeNull()- expect(queryByText(/may miss the first \d+ minutes of a trip/)).toBeNull()- })+ mockShowConfirm.mockResolvedValueOnce(false).mockResolvedValueOnce(true)+ const { findByTestId } = renderEdit()+ fireEvent.press(await findByTestId("delete-profile-btn"))+ await waitFor(() => expect(mockShowConfirm).toHaveBeenCalled())+ expect(mockDeleteProfile).not.toHaveBeenCalled()- it("loads an existing Stationary profile with interval > 60 unchanged", async () => {- mockGetProfiles.mockResolvedValueOnce([- {- id: 1,- name: "Old Stationary",- interval: 3600,- distance: 0,- syncInterval: 0,- priority: 10,- condition: { type: "stationary" },- activationDelay: 0,- deactivationDelay: 0,- enabled: true- }- ])-- const { getByDisplayValue, getByText } = renderEditProfile()-- await waitFor(() => {- expect(getByDisplayValue("3600")).toBeTruthy()- })- expect(getByText(/may miss the first \d+ minutes of a trip/)).toBeTruthy()+ fireEvent.press(await findByTestId("delete-profile-btn"))+ await waitFor(() => expect(mockDeleteProfile).toHaveBeenCalledWith(1))+ expect(mockGoBack).toHaveBeenCalled()})})})diff --git a/apps/mobile/src/screens/__tests__/TrackingProfilesScreen.test.tsx b/apps/mobile/src/screens/__tests__/TrackingProfilesScreen.test.tsxindex cd4c1313..d1e3fdcb 100644--- a/apps/mobile/src/screens/__tests__/TrackingProfilesScreen.test.tsx+++ b/apps/mobile/src/screens/__tests__/TrackingProfilesScreen.test.tsx@@ -1,350 +1,273 @@import React from "react"import { render, fireEvent, waitFor } from "@testing-library/react-native"import { Share } from "react-native"+import { lightColors } from "@colota/shared"import { TrackingProfile } from "../../types/global"-// --- Mocks ----const mockProfiles: TrackingProfile[] = [- {- id: 1,- name: "Charging",- interval: 10,- distance: 0,- syncInterval: 0,- priority: 10,- condition: { type: "charging" },- activationDelay: 0,- deactivationDelay: 60,- enabled: true- },{id: 2,name: "Driving",- interval: 3,- distance: 5,+ interval: 2,+ distance: 10,syncInterval: 60,priority: 20,condition: { type: "speed_above", speedThreshold: 13.89 },activationDelay: 15,deactivationDelay: 30,+ enabled: true+ },+ {+ id: 1,+ name: "Commute",+ interval: 5,+ distance: 0,+ syncInterval: 0,+ priority: 10,+ condition: { type: "charging" },+ activationDelay: 0,+ deactivationDelay: 60,enabled: false}]const mockGetProfiles = jest.fn().mockResolvedValue(mockProfiles)const mockUpdateProfile = jest.fn().mockResolvedValue(true)-const mockDeleteProfile = jest.fn().mockResolvedValue(true)jest.mock("../../services/ProfileService", () => ({ProfileService: {getProfiles: () => mockGetProfiles(),- updateProfile: (update: any) => mockUpdateProfile(update),- deleteProfile: (id: number) => mockDeleteProfile(id)+ updateProfile: (update: any) => mockUpdateProfile(update)}}))const mockShowAlert = jest.fn()-const mockShowConfirm = jest.fn().mockResolvedValue(true)-jest.mock("../../services/modalService", () => ({- showAlert: (...args: any[]) => mockShowAlert(...args),- showConfirm: (...args: any[]) => mockShowConfirm(...args)+ showAlert: (...args: any[]) => mockShowAlert(...args)}))-let mockActiveProfileName: string | null = null-+let mockActiveProfileId: number | null = null+let mockTracking = truejest.mock("../../contexts/TrackingProvider", () => ({useTracking: () => ({- activeProfileName: mockActiveProfileName,- settings: { isOfflineMode: false }+ activeProfileId: mockActiveProfileId,+ tracking: mockTracking,+ settings: { isOfflineMode: false, interval: 30, distance: 2, syncInterval: 300 }})}))+jest.mock("../../hooks/useActiveProfile", () => ({+ useActiveProfile: (id: number | null) => (id === null ? null : (mockProfiles.find((p) => p.id === id) ?? null))+}))+jest.mock("../../hooks/useTheme", () => ({- useTheme: () => ({- colors: {- primary: "#0d9488",- border: "#e5e7eb",- text: "#000",- textSecondary: "#6b7280",- textLight: "#9ca3af",- background: "#fff",- success: "#22c55e",- error: "#ef4444",- card: "#fff",- backgroundElevated: "#f9fafb",- textOnPrimary: "#fff"- }- })+ useTheme: () => ({ colors: jest.requireActual("@colota/shared").lightColors })+}))++jest.mock("../../utils/geo", () => ({+ ...jest.requireActual("../../utils/geo"),+ shortDistanceUnit: () => "m",+ metersToInput: (v: number) => v,+ getSpeedUnit: () => ({ factor: 3.6, unit: "km/h" }),+ speedToInput: (mps: number) => Math.round(mps * 3.6)}))jest.mock("../../components", () => {const R = require("react")- const { View, Text } = require("react-native")+ const { View, Text, Pressable } = require("react-native")return {+ EmptyState: ({ title, hint, action }: any) =>+ R.createElement(+ View,+ null,+ R.createElement(Text, null, title),+ R.createElement(Text, null, hint),+ action &&+ R.createElement(+ Pressable,+ { testID: "empty-action", onPress: action.onPress },+ R.createElement(Text, null, action.label)+ )+ ),+ HeaderAction: ({ label, onPress, testID }: any) =>+ R.createElement(Pressable, { testID, onPress, accessibilityRole: "button", accessibilityLabel: label }),+ Toggle: function (props: any) {+ return R.createElement(require("react-native").Switch, {+ testID: props.testID,+ value: props.value,+ onValueChange: props.onValueChange,+ accessibilityLabel: props.accessibilityLabel+ })+ },+ ListItem: ({ label, sub, onPress, testID, icon, iconColor, trailing }: any) =>+ R.createElement(+ View,+ null,+ R.createElement(+ Pressable,+ { testID, onPress, accessibilityRole: "button", accessibilityLabel: `${label}, ${sub}` },+ R.createElement(Text, null, label),+ R.createElement(Text, null, sub),+ R.createElement(Text, { testID: `${testID}-glyph`, style: { color: iconColor } }, icon?.displayName ?? "icon")+ ),+ trailing+ ),+ StateLine: ({ label, caption, iconColor, testID }: any) =>+ R.createElement(+ View,+ { testID, accessibilityValue: { text: iconColor } },+ R.createElement(Text, null, label),+ R.createElement(Text, null, caption)+ ),Container: ({ children }: any) => R.createElement(View, null, children),- SectionTitle: ({ children }: any) => R.createElement(Text, null, children),- Card: ({ children, style }: any) => R.createElement(View, { style }, children)+ Card: ({ children }: any) => R.createElement(View, { testID: "profiles-card" }, children),+ Divider: () => R.createElement(View, null)}})-const mockNavigate = jest.fn()-const mockAddListener = jest.fn().mockReturnValue(jest.fn())--const mockNavigation = {- navigate: mockNavigate,- addListener: mockAddListener-}+jest.mock("../../utils/logger", () => ({ logger: { error: jest.fn() } }))import { TrackingProfilesScreen } from "../TrackingProfilesScreen"+const mockNavigate = jest.fn()+const mockAddListener = jest.fn().mockReturnValue(jest.fn())+const mockSetOptions = jest.fn()+const mockNavigation = { navigate: mockNavigate, addListener: mockAddListener, setOptions: mockSetOptions }+const headerRight = () => render(mockSetOptions.mock.calls.at(-1)[0].headerRight())+describe("TrackingProfilesScreen", () => {beforeEach(() => {jest.clearAllMocks()- mockActiveProfileName = null+ mockActiveProfileId = null+ mockTracking = truemockGetProfiles.mockResolvedValue(mockProfiles)- mockShowConfirm.mockResolvedValue(true)})function renderScreen() {return render(<TrackingProfilesScreen navigation={mockNavigation as any} />)}- it("renders profile list", async () => {- const { getByText } = renderScreen()-- await waitFor(() => {- expect(getByText("Charging")).toBeTruthy()- expect(getByText("Driving")).toBeTruthy()- })- })-- it("shows profile condition text", async () => {- const { getByText } = renderScreen()-- await waitFor(() => {- expect(getByText("When charging")).toBeTruthy()- expect(getByText(/Speed above 50 km\/h/)).toBeTruthy()- })- })-- it("shows profile settings summary", async () => {- const { getByText } = renderScreen()-- await waitFor(() => {- expect(getByText(/10s interval/)).toBeTruthy()- expect(getByText(/3s interval/)).toBeTruthy()- })- })-- it("shows priority badges", async () => {- const { getByText } = renderScreen()-- await waitFor(() => {- expect(getByText("P10")).toBeTruthy()- expect(getByText("P20")).toBeTruthy()- })- })-- it("shows empty state when no profiles", async () => {- mockGetProfiles.mockResolvedValue([])-- const { getByText } = renderScreen()+ describe("the state line", () => {+ it("names the profile in force with its values and tints its glyph", async () => {+ mockActiveProfileId = 2+ const { findByText, getByText, getByTestId } = renderScreen()- await waitFor(() => {- expect(getByText("No profiles yet")).toBeTruthy()+ expect(await findByText("Driving is active")).toBeTruthy()+ expect(getByText("In force: every 2 s after 10 m · syncs every 1 min")).toBeTruthy()+ expect(getByTestId("profile-state").props.accessibilityValue.text).toBe(lightColors.success)})- })- it("navigates to editor when pressing Create Profile", async () => {- const { getByText } = renderScreen()+ it("gives the default a meaning while tracking runs with no profile", async () => {+ const { findByText, getByText } = renderScreen()- await waitFor(() => {- expect(getByText("Create Profile")).toBeTruthy()+ expect(await findByText("No profile active")).toBeTruthy()+ expect(getByText("Tracking & sync applies: every 30 s after 2 m · syncs every 5 min")).toBeTruthy()})- fireEvent.press(getByText("Create Profile"))-- expect(mockNavigate).toHaveBeenCalledWith("Profile Editor", {})- })+ it("says profiles wait for tracking instead of inventing a state", async () => {+ mockTracking = false+ mockActiveProfileId = 2+ const { findByText, queryByText } = renderScreen()- it("navigates to editor with profileId when pressing a profile", async () => {- const { getByText } = renderScreen()-- await waitFor(() => {- expect(getByText("Charging")).toBeTruthy()+ expect(await findByText("Profiles apply while tracking runs")).toBeTruthy()+ expect(queryByText(/^Active · /)).toBeNull()})-- fireEvent.press(getByText("Charging"))-- expect(mockNavigate).toHaveBeenCalledWith("Profile Editor", { profileId: 1 })})- it("shows confirmation dialog before deleting", async () => {- const { getByText, getByTestId } = renderScreen()+ describe("the rows", () => {+ it("reads each profile as a sentence in priority order, with its switch", async () => {+ const { findByText, getByText, getByTestId } = renderScreen()- await waitFor(() => {- expect(getByText("Charging")).toBeTruthy()+ expect(await findByText("Speed above 50 km/h · Every 2 s after 10 m · syncs every 1 min")).toBeTruthy()+ expect(getByText("When charging · Every 5 s, any movement · syncs each fix")).toBeTruthy()+ expect(getByTestId("profile-toggle-2").props.value).toBe(true)+ expect(getByTestId("profile-toggle-1").props.value).toBe(false)+ expect(getByTestId("profile-toggle-1").props.accessibilityLabel).toBe("Use Commute")})- fireEvent.press(getByTestId("delete-profile-1"))+ it("opens the row in force with Active and tints its glyph, and no other", async () => {+ mockActiveProfileId = 2+ const { findByText, getByTestId, queryByText } = renderScreen()- await waitFor(() => {- expect(mockShowConfirm).toHaveBeenCalledWith(expect.objectContaining({ title: "Delete Profile" }))+ expect(await findByText("Active · speed above 50 km/h · Every 2 s after 10 m · syncs every 1 min")).toBeTruthy()+ expect(getByTestId("profile-2-glyph").props.style.color).toBe(lightColors.success)+ expect(getByTestId("profile-1-glyph").props.style.color).toBeUndefined()+ expect(queryByText(/Active · when charging/)).toBeNull()})- await waitFor(() => {- expect(mockDeleteProfile).toHaveBeenCalledWith(1)- })- })+ it("opens the editor from the row body", async () => {+ const { findByTestId } = renderScreen()- it("shows section title with profile count", async () => {- const { getByText } = renderScreen()+ fireEvent.press(await findByTestId("profile-1"))- await waitFor(() => {- expect(getByText("Profiles (2)")).toBeTruthy()+ expect(mockNavigate).toHaveBeenCalledWith("Profile Editor", { profileId: 1 })})- })- it("shows error when toggle fails", async () => {- mockUpdateProfile.mockRejectedValueOnce(new Error("Network error"))+ it("flips a profile's switch and reloads, and says when that fails", async () => {+ const { findByTestId } = renderScreen()- const { getByText, getByTestId } = renderScreen()+ fireEvent(await findByTestId("profile-toggle-1"), "valueChange", true)- await waitFor(() => {- expect(getByText("Driving")).toBeTruthy()- })+ await waitFor(() => expect(mockUpdateProfile).toHaveBeenCalledWith({ id: 1, enabled: true }))+ expect(mockGetProfiles).toHaveBeenCalledTimes(2)- fireEvent(getByTestId("toggle-profile-2"), "onValueChange", true)-- await waitFor(() => {- expect(mockShowAlert).toHaveBeenCalledWith("Error", expect.any(String), "error")+ mockUpdateProfile.mockRejectedValueOnce(new Error("db"))+ fireEvent(await findByTestId("profile-toggle-2"), "valueChange", false)+ await waitFor(() => expect(mockShowAlert).toHaveBeenCalledWith("Error", "Failed to update profile.", "error"))})- })-- it("reloads profiles on focus", () => {- renderScreen()- // Verify navigation focus listener is registered- expect(mockAddListener).toHaveBeenCalledWith("focus", expect.any(Function))- })-- it("shows Active badge when profile matches activeProfileName from context", async () => {- mockActiveProfileName = "Charging"-- const { getByText } = renderScreen()-- await waitFor(() => {- expect(getByText("Active")).toBeTruthy()+ it("reloads on focus, so an edit shows on the way back", () => {+ renderScreen()+ expect(mockAddListener).toHaveBeenCalledWith("focus", expect.any(Function))})})- it("does not show Active badge when no profile is active", async () => {- mockActiveProfileName = null+ describe("the app bar", () => {+ it("holds Share before Create, and Share only with profiles", async () => {+ const { findByTestId } = renderScreen()+ await findByTestId("profile-1")- const { queryByText } = renderScreen()-- await waitFor(() => {- expect(queryByText("Active")).toBeNull()- })- })-- describe("share profiles", () => {- let shareSpy: jest.SpyInstance-- beforeEach(() => {- shareSpy = jest.spyOn(Share, "share").mockResolvedValue({ action: "sharedAction", activityType: undefined })- })-- afterEach(() => {- shareSpy.mockRestore()- })+ const bar = headerRight()+ expect(bar.getByLabelText("Share all profiles")).toBeTruthy()+ expect(bar.getByLabelText("Create profile")).toBeTruthy()- it("does not render the share button when there are no profiles", async () => {mockGetProfiles.mockResolvedValue([])- const { queryByTestId, getByText } = renderScreen()-- await waitFor(() => {- expect(getByText("No profiles yet")).toBeTruthy()- })-- expect(queryByTestId("share-profiles-btn")).toBeNull()+ const empty = renderScreen()+ await empty.findByText("No profiles yet")+ expect(headerRight().queryByLabelText("Share all profiles")).toBeNull()})- it("renders the share button when at least one profile exists", async () => {- const { getByTestId } = renderScreen()+ it("shares a setup link with every profile and no database fields", async () => {+ const shareSpy = jest.spyOn(Share, "share").mockResolvedValue({ action: "sharedAction", activityType: undefined })+ const { findByTestId } = renderScreen()+ await findByTestId("profile-1")- await waitFor(() => {- expect(getByTestId("share-profiles-btn")).toBeTruthy()- })- })-- it("opens the share sheet with a colota://setup link on press", async () => {- const { getByTestId } = renderScreen()+ fireEvent.press(headerRight().getByLabelText("Share all profiles"))- await waitFor(() => {- expect(getByTestId("share-profiles-btn")).toBeTruthy()- })-- fireEvent.press(getByTestId("share-profiles-btn"))-- await waitFor(() => {- expect(shareSpy).toHaveBeenCalledTimes(1)- })-- const arg = shareSpy.mock.calls[0][0]- expect(arg.message).toMatch(/^colota:\/\/setup\?config=/)+ await waitFor(() => expect(shareSpy).toHaveBeenCalledWith({ message: expect.stringContaining("colota://setup") }))+ const link: string = shareSpy.mock.calls[0][0].message as string+ expect(decodeURIComponent(link.split("config=")[1])).not.toMatch(/"id"/)+ shareSpy.mockRestore()})- it("encodes profiles without id or createdAt fields", async () => {- const { getByTestId } = renderScreen()-- await waitFor(() => {- expect(getByTestId("share-profiles-btn")).toBeTruthy()- })-- fireEvent.press(getByTestId("share-profiles-btn"))+ it("opens the editor on an empty draft from Create", async () => {+ const { findByTestId } = renderScreen()+ await findByTestId("profile-1")- await waitFor(() => {- expect(shareSpy).toHaveBeenCalledTimes(1)- })+ fireEvent.press(headerRight().getByLabelText("Create profile"))- const link = shareSpy.mock.calls[0][0].message as string- const encoded = link.split("config=")[1]- const decoded = JSON.parse(atob(encoded))-- expect(decoded.profiles).toHaveLength(2)- expect(decoded.profiles[0]).not.toHaveProperty("id")- expect(decoded.profiles[0]).not.toHaveProperty("createdAt")- expect(decoded.profiles[0]).toEqual({- name: "Charging",- interval: 10,- distance: 0,- syncInterval: 0,- priority: 10,- condition: { type: "charging" },- activationDelay: 0,- deactivationDelay: 60,- enabled: true- })- expect(decoded.profiles[1].condition).toEqual({ type: "speed_above", speedThreshold: 13.89 })+ expect(mockNavigate).toHaveBeenCalledWith("Profile Editor", {})})+ })- it("shows an error alert when sharing fails", async () => {- shareSpy.mockRejectedValueOnce(new Error("share failed"))-- const { getByTestId } = renderScreen()-- await waitFor(() => {- expect(getByTestId("share-profiles-btn")).toBeTruthy()- })-- fireEvent.press(getByTestId("share-profiles-btn"))+ it("shows the empty state with one action and no card or caption", async () => {+ mockGetProfiles.mockResolvedValue([])+ const { findByText, queryByTestId, queryByText, getByTestId } = renderScreen()- await waitFor(() => {- expect(mockShowAlert).toHaveBeenCalledWith("Error", "Failed to share profiles.", "error")- })- })+ expect(await findByText("No profiles yet")).toBeTruthy()+ expect(queryByTestId("profiles-card")).toBeNull()+ expect(queryByText(/Checked top to bottom/)).toBeNull()+ fireEvent.press(getByTestId("empty-action"))+ expect(mockNavigate).toHaveBeenCalledWith("Profile Editor", {})})})diff --git a/apps/mobile/src/screens/__tests__/TrackingSyncScreen.test.tsx b/apps/mobile/src/screens/__tests__/TrackingSyncScreen.test.tsxnew file mode 100644index 00000000..39c6b231--- /dev/null+++ b/apps/mobile/src/screens/__tests__/TrackingSyncScreen.test.tsx@@ -0,0 +1,123 @@+import React from "react"+import { render, fireEvent, waitFor } from "@testing-library/react-native"+const mockSetSettings = jest.fn()+const mockUpdateSettingsLocal = jest.fn()+const mockRestartTracking = jest.fn()+let mockActiveProfileId: number | null = null++jest.mock("../../contexts/TrackingProvider", () => ({+ useTracking: () => ({+ settings: require("../../types/global").DEFAULT_SETTINGS,+ setSettings: mockSetSettings,+ updateSettingsLocal: mockUpdateSettingsLocal,+ restartTracking: mockRestartTracking,+ activeProfileId: mockActiveProfileId+ })+}))++const mockDebouncedSaveAndRestart = jest.fn()+const mockImmediateSaveAndRestart = jest.fn()+jest.mock("../../hooks/useAutoSave", () => ({+ useAutoSave: () => ({+ saving: false,+ message: null,+ isError: false,+ debouncedSaveAndRestart: mockDebouncedSaveAndRestart,+ immediateSaveAndRestart: mockImmediateSaveAndRestart+ })+}))++const mockGetProfiles = jest.fn()+jest.mock("../../services/NativeLocationService", () => ({+ __esModule: true,+ default: {+ getProfiles: (...args: unknown[]) => mockGetProfiles(...args)+ }+}))++jest.mock("../../utils/logger", () => ({ logger: { error: jest.fn() } }))++jest.mock("../../components", () => {+ const R = require("react")+ const { View } = require("react-native")+ return { Container: ({ children }: any) => R.createElement(View, null, children) }+})++jest.mock("../../components/ui/FloatingSaveIndicator", () => ({ FloatingSaveIndicator: () => null }))++jest.mock("../../components/features/settings/SyncStrategySettings", () => {+ const R = require("react")+ const { View, Text, Pressable } = require("react-native")+ const { DEFAULT_SETTINGS: base } = require("../../types/global")+ return {+ SyncStrategySettings: ({ onSettingsChange, onDebouncedSave, onImmediateSave, activeProfile }: any) =>+ R.createElement(+ View,+ null,+ R.createElement(Text, null, activeProfile ? `${activeProfile.name} is active` : "no profile"),+ R.createElement(Pressable, {+ testID: "type",+ onPress: () => {+ const next = { ...base, interval: 20 }+ onSettingsChange(next)+ onDebouncedSave(next)+ }+ }),+ R.createElement(Pressable, {+ testID: "preset",+ onPress: () => onImmediateSave({ ...base, syncPreset: "balanced" })+ })+ )+ }+})++import { TrackingSyncScreen } from "../TrackingSyncScreen"++const mockProps = { navigation: {} as any, route: { params: undefined } as any }++beforeEach(() => {+ jest.clearAllMocks()+ mockActiveProfileId = null+ mockGetProfiles.mockResolvedValue([{ id: 4, name: "Charging", interval: 5, distance: 20, syncInterval: 900 }])+})++describe("TrackingSyncScreen", () => {+ it("wires a typed edit to local state first, then the debounced save that restarts tracking", () => {+ const { getByTestId } = render(<TrackingSyncScreen {...mockProps} />)++ fireEvent.press(getByTestId("type"))++ expect(mockUpdateSettingsLocal).toHaveBeenCalledWith(expect.objectContaining({ interval: 20 }))+ expect(mockDebouncedSaveAndRestart).toHaveBeenCalledTimes(1)+ const [save, restart] = mockDebouncedSaveAndRestart.mock.calls[0]+ save()+ restart()+ expect(mockSetSettings).toHaveBeenCalledWith(expect.objectContaining({ interval: 20 }))+ expect(mockRestartTracking).toHaveBeenCalledWith(expect.objectContaining({ interval: 20 }))+ })++ it("wires a discrete choice to the immediate save", () => {+ const { getByTestId } = render(<TrackingSyncScreen {...mockProps} />)++ fireEvent.press(getByTestId("preset"))++ expect(mockImmediateSaveAndRestart).toHaveBeenCalledTimes(1)+ const [save] = mockImmediateSaveAndRestart.mock.calls[0]+ save()+ expect(mockSetSettings).toHaveBeenCalledWith(expect.objectContaining({ syncPreset: "balanced" }))+ })++ it("resolves the active profile so the groups it overrides can show the values in force", async () => {+ mockActiveProfileId = 4+ const { findByText } = render(<TrackingSyncScreen {...mockProps} />)++ expect(await findByText("Charging is active")).toBeTruthy()+ })++ it("hands over no profile while none is active", async () => {+ const { getByText } = render(<TrackingSyncScreen {...mockProps} />)++ await waitFor(() => expect(getByText("no profile")).toBeTruthy())+ expect(mockGetProfiles).not.toHaveBeenCalled()+ })+})diff --git a/apps/mobile/src/utils/__tests__/profileRow.test.ts b/apps/mobile/src/utils/__tests__/profileRow.test.tsnew file mode 100644index 00000000..890ba719--- /dev/null+++ b/apps/mobile/src/utils/__tests__/profileRow.test.ts@@ -0,0 +1,146 @@+import {+ conditionText,+ describeProfileState,+ profileRowSub,+ profileSentence,+ profileStateLabel,+ recordingClause+} from "../profileRow"+import { loadDisplayPreferences } from "../geo"+import type { SavedTrackingProfile } from "../../types/global"++const mockGetSetting = jest.fn()+jest.mock("../../services/NativeLocationService", () => ({+ __esModule: true,+ default: { getSetting: (...args: string[]) => mockGetSetting(...args) }+}))++const units = async (system: "metric" | "imperial") => {+ mockGetSetting.mockImplementation((key: string) => Promise.resolve(key === "unitSystem" ? system : ""))+ await loadDisplayPreferences()+}++beforeAll(() => units("metric"))++const profile = (overrides: Partial<SavedTrackingProfile>): SavedTrackingProfile => ({+ id: 1,+ name: "Commute",+ interval: 5,+ distance: 0,+ syncInterval: 0,+ priority: 10,+ condition: { type: "charging" },+ activationDelay: 0,+ deactivationDelay: 60,+ enabled: true,+ ...overrides+})+const commute = profile({})+const driving = profile({+ id: 2,+ name: "Driving",+ interval: 2,+ distance: 10,+ syncInterval: 60,+ condition: { type: "speed_above", speedThreshold: 13.89 }+})+const resting = profile({+ id: 3,+ name: "Resting",+ interval: 60,+ distance: 0,+ syncInterval: 300,+ condition: { type: "stationary" }+})+const car = profile({+ id: 4,+ name: "Car",+ interval: 10,+ distance: 5,+ syncInterval: 300,+ condition: { type: "android_auto" }+})+const settings = { interval: 30, distance: 2, syncInterval: 300, isOfflineMode: false }++describe("profileRowSub", () => {+ it("reads as one sentence: condition, recording, sync", () => {+ expect(profileRowSub(commute, false, false)).toBe("When charging · Every 5 s, any movement · syncs each fix")+ expect(profileRowSub(driving, false, false)).toBe("Speed above 50 km/h · Every 2 s after 10 m · syncs every 1 min")+ expect(profileRowSub(car, false, false)).toBe("On Android Auto · Every 10 s after 5 m · syncs every 5 min")+ })++ it("opens with Active and lower-cases the condition for the row in force", () => {+ expect(profileRowSub(commute, true, false)).toBe(+ "Active · when charging · Every 5 s, any movement · syncs each fix"+ )+ expect(profileRowSub(driving, true, false)).toBe(+ "Active · speed above 50 km/h · Every 2 s after 10 m · syncs every 1 min"+ )+ })++ it("says while still for a stationary profile, since its distance is forced to 0", () => {+ expect(profileRowSub(resting, false, false)).toBe("When stationary · Every 1 min while still · syncs every 5 min")+ expect(recordingClause(resting)).toBe("Every 1 min while still")+ })++ it("drops the sync clause in offline mode", () => {+ expect(profileRowSub(commute, false, true)).toBe("When charging · Every 5 s, any movement")+ })++ it("prints the speed in the user's unit", async () => {+ await units("imperial")+ expect(conditionText(driving)).toBe("Speed above 31 mph")+ expect(profileRowSub(driving, false, false)).toBe("Speed above 31 mph · Every 2 s after 33 ft · syncs every 1 min")+ await units("metric")+ })+})++describe("profileSentence", () => {+ it("is the rule the editor reads back", () => {+ expect(profileSentence(commute, false)).toBe("When charging, track every 5 s, any movement and sync each fix.")+ expect(profileSentence(driving, false)).toBe(+ "When faster than 50 km/h, track every 2 s after 10 m and sync every 1 min."+ )+ expect(profileSentence(resting, false)).toBe("When stationary, track every 1 min while still and sync every 5 min.")+ expect(profileSentence({ ...driving, condition: { type: "speed_below", speedThreshold: 2.78 } }, false)).toBe(+ "When slower than 10 km/h, track every 2 s after 10 m and sync every 1 min."+ )+ })++ it("stops after the recording clause in offline mode", () => {+ expect(profileSentence(commute, true)).toBe("When charging, track every 5 s, any movement.")+ })+})++describe("describeProfileState", () => {+ it("names the profile in force with its values", () => {+ const s = describeProfileState(driving, settings, true)+ expect(s.tone).toBe("success")+ expect(s.label).toBe("Driving is active")+ expect(s.caption).toBe("In force: every 2 s after 10 m · syncs every 1 min")+ })++ it("gives the default a meaning when tracking runs with no profile", () => {+ const s = describeProfileState(null, settings, true)+ expect(s.tone).toBe("secondary")+ expect(s.label).toBe("No profile active")+ expect(s.caption).toBe("Tracking & sync applies: every 30 s after 2 m · syncs every 5 min")+ })++ it("says profiles wait for tracking rather than inventing a state", () => {+ expect(describeProfileState(driving, settings, false).caption).toBe("Profiles apply while tracking runs")+ })++ it("prints while still for a stationary profile in force", () => {+ expect(describeProfileState(resting, settings, true).caption).toBe(+ "In force: every 1 min while still · syncs every 5 min"+ )+ })++ it("takes its label from profileStateLabel, so the Settings row cannot drift from this line", () => {+ expect(describeProfileState(driving, settings, true).label).toBe(profileStateLabel(driving.name, true))+ expect(describeProfileState(null, settings, true).label).toBe(profileStateLabel(null, true))+ expect(describeProfileState(driving, settings, false).label).toBe(profileStateLabel(driving.name, false))+ expect(profileStateLabel("Driving", false)).toBe("No profile active")+ })+})diff --git a/apps/mobile/src/utils/profileRow.ts b/apps/mobile/src/utils/profileRow.tsnew file mode 100644index 00000000..8ff7065e--- /dev/null+++ b/apps/mobile/src/utils/profileRow.ts@@ -0,0 +1,99 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import { UserRoundPen, type LucideIcon } from "lucide-react-native"+import { PROFILE_CONDITIONS } from "../constants"+import type { SavedTrackingProfile, Settings, TrackingProfile } from "../types/global"+import { formatInterval, recordingSummary, syncSummary, trackingSummary } from "./dashboardState"+import { getSpeedUnit, speedToInput } from "./geo"++type ProfileLike = Pick<TrackingProfile, "condition" | "interval" | "distance" | "syncInterval">++const lowerFirst = (text: string) => text.charAt(0).toLowerCase() + text.slice(1)++export function conditionOf(profile: Pick<TrackingProfile, "condition">) {+ return PROFILE_CONDITIONS.find((c) => c.type === profile.condition.type) ?? PROFILE_CONDITIONS[0]+}++/** "When charging", "Speed above 50 km/h": the clause a row and the editor's sentence open with. */+export function conditionText(profile: Pick<TrackingProfile, "condition">): string {+ const { type, speedThreshold } = profile.condition+ if (type === "speed_above" || type === "speed_below") {+ return `${conditionOf(profile).listLabel} ${speedToInput(speedThreshold ?? 0)} ${getSpeedUnit().unit}`+ }+ return conditionOf(profile).listLabel+}++/** The recording half; a stationary profile forces the distance to 0, so "any movement" would mislead. */+export function recordingClause(profile: ProfileLike): string {+ if (profile.condition.type === "stationary") return `${formatInterval(profile.interval)} while still`+ return recordingSummary(profile.interval, profile.distance)+}++/** The one line under a profile's name: [Active · ]condition · recording · sync. */+export function profileRowSub(profile: ProfileLike, inForce: boolean, isOfflineMode: boolean): string {+ const condition = conditionText(profile)+ const parts = [inForce ? `Active · ${lowerFirst(condition)}` : condition, recordingClause(profile)]+ if (!isOfflineMode) parts.push(syncSummary(profile.syncInterval))+ return parts.join(" · ")+}++/** The rule as one sentence, the editor's caption: "When charging, track every 5 s, any movement and sync each fix." */+export function profileSentence(profile: ProfileLike, isOfflineMode: boolean): string {+ const { type, speedThreshold } = profile.condition+ const unit = getSpeedUnit().unit+ const when =+ type === "speed_above"+ ? `When faster than ${speedToInput(speedThreshold ?? 0)} ${unit}`+ : type === "speed_below"+ ? `When slower than ${speedToInput(speedThreshold ?? 0)} ${unit}`+ : conditionText(profile)+ const track = `track ${lowerFirst(recordingClause(profile))}`+ if (isOfflineMode) return `${when}, ${track}.`+ return `${when}, ${track} and ${syncSummary(profile.syncInterval).replace(/^syncs/, "sync")}.`+}++/** "Charging is active" or "No profile active": the Profiles state line and the Settings row print one string. */+export function profileStateLabel(activeName: string | null | undefined, tracking: boolean): string {+ return tracking && activeName ? `${activeName} is active` : "No profile active"+}++export interface ProfileState {+ icon: LucideIcon+ tone: "success" | "secondary"+ label: string+ caption: string+}++/** The list's first row: which profile is in force, or what applies instead. */+export function describeProfileState(+ activeProfile: SavedTrackingProfile | null,+ settings: Pick<Settings, "interval" | "distance" | "syncInterval" | "isOfflineMode">,+ tracking: boolean+): ProfileState {+ if (!tracking) {+ return {+ icon: UserRoundPen,+ tone: "secondary",+ label: profileStateLabel(null, false),+ caption: "Profiles apply while tracking runs"+ }+ }+ if (activeProfile) {+ const sync = settings.isOfflineMode ? "" : ` · ${syncSummary(activeProfile.syncInterval)}`+ return {+ icon: conditionOf(activeProfile).icon,+ tone: "success",+ label: profileStateLabel(activeProfile.name, true),+ caption: `In force: ${lowerFirst(recordingClause(activeProfile))}${sync}`+ }+ }+ return {+ icon: UserRoundPen,+ tone: "secondary",+ label: profileStateLabel(null, true),+ caption: `Tracking & sync applies: ${lowerFirst(trackingSummary(settings.interval, settings.distance, settings.syncInterval, settings.isOfflineMode))}`+ }+}