Colota - Android GPS Location tracker
refactor(export): one screen for moving data in and out (#856)
Max Dietrichce0ad36812dd
diff --git a/apps/docs/docs/guides/data-export.md b/apps/docs/docs/guides/data-export.mdindex 05855eaa..81f5396f 100644--- a/apps/docs/docs/guides/data-export.md+++ b/apps/docs/docs/guides/data-export.md@@ -8,24 +8,30 @@ Export your location history in multiple formats.:::tip[Looking for a full archive?]-Data Export produces shareable, human-readable formats (CSV, GeoJSON, GPX, KML) of your location history. If you instead want a single password-encrypted archive of **everything** - locations, settings, geofences and credentials - for device migration or offsite storage, use [Backup & Restore](backup-restore.md).+Data Export produces shareable, human-readable formats (CSV, GeoJSON, GPX, KML) of your location history. If you instead want a single password-encrypted archive of **everything** - locations, settings, geofences and credentials - for device migration or offsite storage, use [Backup & restore](backup-restore.md).:::## Supported Formats-| Format | Extension | Use Case |-| ----------- | ---------- | --------------------------- |-| **CSV** | `.csv` | Spreadsheets, data analysis |-| **GeoJSON** | `.geojson` | Web mapping, GIS tools |-| **GPX** | `.gpx` | GPS devices, hiking apps |-| **KML** | `.kml` | Google Earth, mapping |+| Format | Extension | Use Case |+| --- | --- | --- |+| **CSV** | `.csv` | Spreadsheets, data analysis |+| **GeoJSON** | `.geojson` | Web mapping, GIS tools. One Point feature per recording, so each point carries its own time and attributes |+| **GPX** | `.gpx` | GPS devices, hiking apps |+| **KML** | `.kml` | Google Earth, mapping |++:::note[GeoJSON file size]++Each recording is written as its own feature so mapping tools can read one row and one timestamp per point. That repeats the attribute names on every point, which makes a GeoJSON export roughly twice the size of the other formats. A database of a few million points produces a file of several hundred megabytes. Compressing it recovers most of the difference.++:::## How to Export### Bulk Export-1. Go to **Settings → Export Locations**+1. Go to **Settings → Export & import**2. Select a format3. Tap **Export** and share the file via Android's share menu@@ -37,33 +43,33 @@ For exports on a schedule instead of on demand, see [Scheduled Export](#scheduleGo to the **History** tab → **Trips**. There are two ways to export:-- **All trips for the day** - tap **Export All** in the header, pick a format, share.-- **A custom selection** - long-press any trip card to enter selection mode. Tap additional cards to add or remove them. Use **Select all** to grab every trip. Tap the share icon in the selection header, pick a format, share. Works for a single trip too.+- **All trips for the day** - tap the share icon in the header, pick a format, share.+- **A custom selection** - long-press a trip to enter selection mode. Tap other trips to add or remove them; **Select all** is in the selection header's overflow menu. Tap the share icon in the selection header, pick a format, share. Works for a single trip too.-For a single trip you can also tap the card to open **Trip Detail**, then use the share icon in the header.+For a single trip you can also tap it to open **Trip Detail** and use the share icon in the header.Trip exports include a `trip` column/property so each location is tagged with its trip number. Custom selections produce a single file containing only the chosen trips.-To remove trips or single points instead of exporting them, see [Data Management](data-management.md#deleting-from-location-history).+To remove trips or single points instead of exporting them, see [Data management](data-management.md#deleting-from-location-history).import ScreenshotGallery from '@site/src/components/ScreenshotGallery'-<ScreenshotGallery screenshots={[ { src: "/img/screenshots/ExportData.png", label: "Export Data" }, { src: "/img/screenshots/AutoExport.png", label: "Auto-Export" }, ]} />+<ScreenshotGallery screenshots={[ { src: "/img/screenshots/ExportData.png", label: "Export Data" }, { src: "/img/screenshots/AutoExport.png", label: "Auto-export" }, ]} />-## Scheduled Export (Auto-Export)+## Scheduled Export (Auto-export)Automatically export your location data on a schedule without opening the app.### Setup-1. Go to **Settings → Auto-Export**+1. Go to **Settings → Auto-export**2. Select an export directory (files are saved there via Android's Storage Access Framework)3. Choose a format (CSV, GeoJSON, GPX, or KML)4. Set the frequency: **Daily**, **Weekly**, or **Monthly**5. Pick the **Time** (24-hour) in your device's local timezone. For **Weekly**, also pick a day of week. For **Monthly**, pick a day of month (1-31)6. Enable the toggle-You can also tap **Export Now** to trigger an immediate export using your current auto-export settings, without waiting for the next scheduled run.+You can also tap **Export Now** to trigger an immediate export using your current auto-export settings, without waiting for the next scheduled run. It works whether or not the toggle is on: the toggle governs the schedule, not the button. A line under the button says the export is running, and it keeps running if you leave the screen.### Export Range@@ -95,7 +101,7 @@ If several devices export into the same folder and none of the templates include- Uses Android AlarmManager (`setAndAllowWhileIdle`) to fire at your configured wall-clock time. Typical accuracy is within minutes; Doze mode may delay by up to ~15 minutes- After each export the next alarm is armed automatically. Alarms also re-arm after device reboot-- Exports fire at the configured time, not on enable. To run an export immediately for testing or backup, tap **Export Now**+- Exports fire at the configured time, not on enable. To run an export immediately for testing or backup, tap **Export Now**, which needs only an export directory- Promotes to a foreground service during export, preventing Android from killing long-running exports- Streams data in chunks (10,000 locations at a time) to keep memory usage low even with very large datasets- Writes to a temporary file first, then copies to the export directory - if something goes wrong mid-export, you never get a partial or corrupted file@@ -142,7 +148,7 @@ Other notes:- Templates longer than 100 characters are rejected, and `{device}` is shortened to 32 characters, so the result stays inside the filesystem's name limit.- If a file of the same name already exists, Android adds a counter (`… (1).gpx`). Colota still recognises those as its own.-Manual **Export Locations** and trip exports are unaffected. Those go through the Android share sheet, where you name the file yourself.+Manual exports and trip exports are unaffected. Those go through the Android share sheet, where you name the file yourself.## Storage Referencediff --git a/apps/docs/docs/guides/data-import.md b/apps/docs/docs/guides/data-import.mdindex e2571d24..af7a4834 100644--- a/apps/docs/docs/guides/data-import.md+++ b/apps/docs/docs/guides/data-import.md@@ -39,16 +39,12 @@ The exported file is saved to your phone's `Downloads` folder.## How to Import-1. Go to **Settings → Import Locations**+1. Go to **Settings → Export & import**2. Tap **Choose File** and pick the file you want to import3. Wait for the parse to finish (large Google Timeline files can take 10+ seconds)4. Review the preview: format, points found, duplicates that will be skipped, invalid rows, date range5. Choose **Import** (or **Import + Queue for Sync** - see below)-import ScreenshotGallery from '@site/src/components/ScreenshotGallery'--<ScreenshotGallery screenshots={[ { src: "/img/screenshots/ImportLocations.png", label: "Import Locations" }, ]} />-### How duplicates are handledTwo rows are considered duplicates when they share the same timestamp (1-second precision) **and** their latitude/longitude match to ~10 cm. This means:@@ -76,7 +72,7 @@ If you've configured an optional sync backend in **Settings → Connection**, th- Rows are written into Colota with `sent=1` - flagged as already replicated.- **The sync engine will not push them to your backend.**-- Use this when the backend already holds these points - for example, you're re-importing your own Colota export, or repopulating local history after a "Clear Sent History".+- Use this when the backend already holds these points - for example, you're re-importing your own Colota export, or repopulating local history after a "Delete synced locations".### Import + Queue for Sync@@ -96,7 +92,7 @@ Once queued, the rows are uploaded as soon as the next sync runs. Removing them- Imported rows show up immediately on the **Dashboard** and **Location History** screens.- Trip detection re-runs on demand the next time you open a screen that uses it (the trip computation is derived from the locations table on the fly).-- If you imported with **Import + Queue for Sync**, the queue counter in **Data Management** reflects the new pending rows; the next sync cycle replicates them to your configured backend.+- If you imported with **Import + Queue for Sync**, the queue counter in **Data management** reflects the new pending rows; the next sync cycle replicates them to your configured backend.## Edge Casesdiff --git a/apps/mobile/App.tsx b/apps/mobile/App.tsxindex 6e77d2fc..52e543dc 100644--- a/apps/mobile/App.tsx+++ b/apps/mobile/App.tsx@@ -30,8 +30,7 @@ import {DataManagementScreen,LocationHistoryScreen,LocationSummaryScreen,- ExportLocationsScreen,- ImportLocationsScreen,+ ExportImportScreen,AboutScreen,TrackingProfilesScreen,ProfileEditorScreen,@@ -114,14 +113,9 @@ const SCREEN_CONFIG: readonly ScreenConfig[] = [title: "Summary"},{- name: "Export Locations",- component: ExportLocationsScreen,- title: "Export locations"- },- {- name: "Import Locations",- component: ImportLocationsScreen,- title: "Import locations"+ name: "Export & Import",+ component: ExportImportScreen,+ title: "Export & import"},{name: "Auto-Export",diff --git a/apps/mobile/src/components/index.ts b/apps/mobile/src/components/index.tsindex 49c96ac0..5846bc46 100644--- a/apps/mobile/src/components/index.ts+++ b/apps/mobile/src/components/index.ts@@ -69,8 +69,6 @@ export { ConnectionSettings } from "./features/settings/ConnectionSettings"export { SyncStrategySettings } from "./features/settings/SyncStrategySettings"export { StatRow } from "./ui/StatRow"export { Footer } from "./ui/Footer"-export { FormatOption } from "./ui/FormatOption"-export { FormatSelector } from "./ui/FormatSelector"export { DashboardBanner } from "./features/dashboard/DashboardBanner"export { DashboardDock } from "./features/dashboard/DashboardDock"export { DayHeader } from "./features/inspector/DayHeader"diff --git a/apps/mobile/src/components/ui/FormatOption.tsx b/apps/mobile/src/components/ui/FormatOption.tsxdeleted file mode 100644index f6e4c542..00000000--- a/apps/mobile/src/components/ui/FormatOption.tsx+++ /dev/null@@ -1,122 +0,0 @@-/**- * Copyright (C) 2026 Max Dietrich- * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.- */--import React from "react"-import { Text, StyleSheet, View, Pressable } from "react-native"-import type { LucideIcon } from "lucide-react-native"-import { fonts } from "../../styles/typography"-import { useTheme } from "../../hooks/useTheme"-import { RadioDot } from "./RadioDot"--export const FormatOption = ({- icon: Icon,- title,- subtitle,- description,- extension,- selected,- onPress-}: {- icon: LucideIcon- title: string- subtitle: string- description: string- extension: string- selected: boolean- onPress: () => void-}) => {- const { colors } = useTheme()-- return (- <Pressable- style={({ pressed }) => [styles.formatOption, pressed && { opacity: colors.pressedOpacity }]}- onPress={onPress}- accessibilityRole="radio"- accessibilityState={{ checked: selected }}- >- <View style={styles.formatContent}>- <View style={styles.leftContent}>- <Icon size={22} color={colors.textLight} />- <View style={styles.textContent}>- <View style={styles.titleRow}>- <Text- style={[- styles.formatTitle,- selected ? { color: colors.primaryDark, ...fonts.bold } : { color: colors.text }- ]}- >- {title}- </Text>- <View- style={[- styles.extensionBadge,- {- backgroundColor: selected ? colors.primary + "20" : colors.primary + "15",- borderColor: selected ? colors.primary + "40" : colors.primary + "30"- }- ]}- >- <Text style={[styles.extensionText, { color: colors.primaryDark }]}>{extension}</Text>- </View>- </View>- <Text style={[styles.formatSubtitle, { color: colors.textSecondary }]}>{subtitle}</Text>- <Text style={[styles.formatDescription, { color: colors.textLight }]}>{description}</Text>- </View>- </View>-- <RadioDot selected={selected} />- </View>- </Pressable>- )-}--const styles = StyleSheet.create({- formatOption: {- paddingVertical: 8- },- formatContent: {- flexDirection: "row",- alignItems: "center"- },- leftContent: {- flex: 1,- flexDirection: "row",- alignItems: "center",- gap: 16- },- textContent: {- flex: 1- },- titleRow: {- flexDirection: "row",- alignItems: "center",- gap: 8,- marginBottom: 2- },- formatTitle: {- fontSize: 16,- ...fonts.semiBold,- letterSpacing: -0.2- },- extensionBadge: {- paddingHorizontal: 8,- paddingVertical: 3,- borderRadius: 6,- borderWidth: 1- },- extensionText: {- fontSize: 10,- ...fonts.bold,- letterSpacing: 0.3- },- formatSubtitle: {- fontSize: 13,- marginBottom: 2- },- formatDescription: {- fontSize: 12,- lineHeight: 16- }-})diff --git a/apps/mobile/src/components/ui/FormatSelector.tsx b/apps/mobile/src/components/ui/FormatSelector.tsxdeleted file mode 100644index 437cdf13..00000000--- a/apps/mobile/src/components/ui/FormatSelector.tsx+++ /dev/null@@ -1,37 +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 } from "react-native"-import { ExportFormat, EXPORT_FORMATS } from "../../utils/exportConverters"-import { Divider } from "./Divider"-import { FormatOption } from "./FormatOption"--export const FormatSelector = ({- selectedFormat,- onSelectFormat-}: {- selectedFormat: ExportFormat | null- onSelectFormat: (format: ExportFormat) => void-}) => (- <View accessibilityRole="radiogroup">- {(Object.entries(EXPORT_FORMATS) as [ExportFormat, (typeof EXPORT_FORMATS)[ExportFormat]][]).map(- ([key, config], index) => (- <React.Fragment key={key}>- {index > 0 && <Divider />}- <FormatOption- icon={config.icon}- title={config.label}- subtitle={config.subtitle}- description={config.description}- extension={config.extension}- selected={selectedFormat === key}- onPress={() => onSelectFormat(key)}- />- </React.Fragment>- )- )}- </View>-)diff --git a/apps/mobile/src/screens/AutoExportScreen.tsx b/apps/mobile/src/screens/AutoExportScreen.tsxindex dd6413ac..2848c2d7 100644--- a/apps/mobile/src/screens/AutoExportScreen.tsx+++ b/apps/mobile/src/screens/AutoExportScreen.tsx@@ -3,26 +3,29 @@* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.*/-import { useState, useCallback, useEffect } from "react"+import React, { useState, useCallback, useEffect } from "react"import { useFocusEffect } from "@react-navigation/native"-import { Text, StyleSheet, Switch, View, ScrollView, Pressable, DeviceEventEmitter, TextInput } from "react-native"-import { FolderOpen, CheckCircle, Share2, AlertTriangle } from "lucide-react-native"+import { ActivityIndicator, Text, StyleSheet, View, ScrollView, Pressable, DeviceEventEmitter } from "react-native"+import { FolderOpen, CircleCheckBig, Share2, TriangleAlert } from "lucide-react-native"import {- Container,+ Button,Card,- SectionTitle,- Divider,- FormatSelector,ChipGroup,- RadioDot,+ Container,+ Divider,FloatingSaveIndicator,+ ExportFormatDialog,+ ListItem,+ NumericInput,+ RadioRow,+ SectionTitle,SettingRow,- Button,TimePicker,- NumericInput+ Toggle,+ TextField} from "../components"import { useTheme } from "../hooks/useTheme"-import { useTimeout } from "../hooks/useTimeout"+import { ScreenProps } from "../types/global"import NativeLocationService from "../services/NativeLocationService"import {@@ -34,11 +37,12 @@ import {isValidFilenameTemplate,renderFilenamePreview} from "../utils/exportConverters"-import { fonts } from "../styles/typography"+import { fontSizes, fonts, lineHeights } from "../styles/typography"+import { FILE_FORMATS } from "../utils/fileFormats"import { logger } from "../utils/logger"import { formatExportDateTime, formatBytes } from "../utils/format"import { showAlert } from "../services/modalService"-import { SAVE_SUCCESS_DISPLAY_MS } from "../constants"+import { size, space, STATE_LAYER_ALPHA } from "../constants"type ExportInterval = "daily" | "weekly" | "monthly"type ExportMode = "all" | "incremental"@@ -75,6 +79,7 @@ const WEEKDAY_OPTIONS: readonly { value: string; label: string }[] = [export function AutoExportScreen(_props: ScreenProps) {const { colors } = useTheme()const [enabled, setEnabled] = useState(false)+ const [formatOpen, setFormatOpen] = useState(false)const [format, setFormat] = useState<ExportFormat>("geojson")const [interval, setInterval] = useState<ExportInterval>("daily")const [mode, setMode] = useState<ExportMode>("all")@@ -97,14 +102,16 @@ export function AutoExportScreen(_props: ScreenProps) {const [exportFiles, setExportFiles] = useState<ExportFile[]>([])const [loading, setLoading] = useState(true)const [exporting, setExporting] = useState(false)+ const [exportRunning, setExportRunning] = useState(false)const [saving, setSaving] = useState(false)- const [saveSuccess, setSaveSuccess] = useState(false)- const successTimeout = useTimeout()const loadStatus = useCallback(async () => {try {const status = await NativeLocationService.getAutoExportStatus()setEnabled(status.enabled)+ // Only ever turns it on: the worker's flag is still false between the enqueue and the run+ // starting, and a reload in that window would wipe the line the press just put up.+ if (status.running) setExportRunning(true)setFormat((status.format as ExportFormat) || "geojson")setInterval((status.interval as ExportInterval) || "daily")setMode((status.mode as ExportMode) || "all")@@ -161,15 +168,19 @@ export function AutoExportScreen(_props: ScreenProps) {const listener = DeviceEventEmitter.addListener("onAutoExportComplete",(event: { success: boolean; fileName: string | null; rowCount: number; error: string | null }) => {- if (event.success) {+ if (!event.success) {+ setLastError(event.error)+ showAlert("Export Failed", event.error || "Unknown error", "error")+ } else if (event.fileName) {setLastFileName(event.fileName)setLastRowCount(event.rowCount)setLastError(null)showAlert("Export Complete", `Exported ${event.rowCount} locations to ${event.fileName}`, "success")} else {- setLastError(event.error)- showAlert("Export Failed", event.error || "Unknown error", "error")+ setLastError(null)+ showAlert("Export Complete", "No new locations to export.", "success")}+ setExportRunning(false)loadStatus()loadExportFiles()}@@ -177,22 +188,17 @@ export function AutoExportScreen(_props: ScreenProps) {return () => listener.remove()}, [loadStatus, loadExportFiles])- const saveSetting = useCallback(- async (key: string, value: string) => {- setSaving(true)- try {- await NativeLocationService.saveSetting(key, value)- setSaving(false)- setSaveSuccess(true)- successTimeout.set(() => setSaveSuccess(false), SAVE_SUCCESS_DISPLAY_MS)- } catch (error) {- setSaving(false)- logger.error("[AutoExportScreen] Save failed:", error)- showAlert("Error", "Failed to save setting. Please try again.", "error")- }- },- [successTimeout]- )+ const saveSetting = useCallback(async (key: string, value: string) => {+ setSaving(true)+ try {+ await NativeLocationService.saveSetting(key, value)+ setSaving(false)+ } catch (error) {+ setSaving(false)+ logger.error("[AutoExportScreen] Save failed:", error)+ showAlert("Error", "Failed to save setting. Please try again.", "error")+ }+ }, [])const handleToggle = useCallback(async (value: boolean) => {@@ -350,7 +356,7 @@ export function AutoExportScreen(_props: ScreenProps) {setExporting(true)try {await NativeLocationService.runAutoExportNow()- showAlert("Export Started", "Export is running in the background. The status will update when complete.", "info")+ setExportRunning(true)} catch (error) {logger.error("[AutoExportScreen] Export now failed:", error)showAlert("Error", "Failed to start export.", "error")@@ -377,7 +383,9 @@ export function AutoExportScreen(_props: ScreenProps) {if (loading)return (<Container>- <View />+ <View style={styles.centered}>+ <ActivityIndicator size="large" color={colors.primary} />+ </View></Container>)@@ -393,32 +401,29 @@ export function AutoExportScreen(_props: ScreenProps) {</View>{/* Enable Toggle */}- <Card>+ <Card rows><SettingRowlabel="Enable Auto-Export"hint={enabled ? "Auto-Exports are scheduled" : "Auto-Exports are disabled"}>- <Switch- value={enabled}- onValueChange={handleToggle}- trackColor={{ false: colors.border, true: colors.primary + "80" }}- thumbColor={enabled ? colors.primary : colors.border}- />+ <Toggle accessibilityLabel="Enable auto-export" value={enabled} onValueChange={handleToggle} /></SettingRow></Card>{/* Export Directory */}<View style={styles.section}>- <SectionTitle>Export Directory</SectionTitle>+ <SectionTitle>Export directory</SectionTitle><Card><Pressable- style={({ pressed }) => [styles.directoryRow, pressed && { opacity: colors.pressedOpacity }]}+ accessibilityRole="button"+ android_ripple={{ color: colors.text + STATE_LAYER_ALPHA }}+ style={styles.directoryRow}onPress={handlePickDirectory}>- <FolderOpen size={22} color={colors.primary} />+ <FolderOpen size={size.icon.md} color={colors.primary} /><View style={styles.directoryContent}><Text style={[styles.settingLabel, { color: colors.text }]}>- {directoryUri ? "Directory Selected" : "Select Directory"}+ {directoryUri ? "Directory selected" : "Select directory"}</Text><Text style={[styles.settingDescription, { color: colors.textSecondary }]} numberOfLines={1}>{directoryUri@@ -426,7 +431,7 @@ export function AutoExportScreen(_props: ScreenProps) {: "Tap to choose where files are saved"}</Text></View>- {directoryUri && <CheckCircle size={18} color={colors.success} />}+ {directoryUri && <CircleCheckBig size={size.icon.md} color={colors.success} />}</Pressable></Card></View>@@ -434,29 +439,36 @@ export function AutoExportScreen(_props: ScreenProps) {{/* Format */}<View style={styles.section}><SectionTitle>Format</SectionTitle>- <Card>- <FormatSelector selectedFormat={format} onSelectFormat={handleFormatChange} />+ <Card rows>+ <ListItem+ testID="auto-export-format"+ icon={FILE_FORMATS[format].icon}+ label="Format"+ sub={EXPORT_FORMATS[format].label}+ onPress={() => setFormatOpen(true)}+ /></Card></View>{/* File Name */}<View style={styles.section}>- <SectionTitle>File Name</SectionTitle>+ <SectionTitle>File name</SectionTitle><Card>- <TextInput- style={[styles.templateInput, { color: colors.text, borderColor: colors.border }]}+ <TextField+ testID="filename-template-input"+ accessibilityLabel="File name template"+ monovalue={filenameTemplateInput}onChangeText={handleFilenameTemplateChange}onBlur={handleFilenameTemplateBlur}placeholder={DEFAULT_FILENAME_TEMPLATE}- placeholderTextColor={colors.textSecondary}autoCapitalize="none"autoCorrect={false}/>{FILENAME_TOKENS.map((token) => (<View key={token} style={styles.templateTokenRow}><Text style={[styles.templateToken, { color: colors.text }]}>{`{${token}}`}</Text>- <Text style={[styles.templateHint, { color: colors.textSecondary }]}>{tokenValues[token]}</Text>+ <Text style={[styles.templateTokenValue, { color: colors.textSecondary }]}>{tokenValues[token]}</Text></View>))}<Text style={[styles.templateHint, { color: colors.textSecondary }]}>@@ -501,46 +513,36 @@ export function AutoExportScreen(_props: ScreenProps) {unit="day"placeholder="1"min={1}- colors={colors}hint="1-31. Falls back to last day in shorter months."/></>)}<Divider />- <Text style={[styles.fieldLabel, { color: colors.textSecondary }]}>Time (24h)</Text>- <TimePicker value={timeOfDay} onChange={handleTimeChange} colors={colors} />+ <TimePicker label="Time (24h)" value={timeOfDay} onChange={handleTimeChange} /></Card></View>{/* Export Range */}<View style={styles.section}>- <SectionTitle>Export Range</SectionTitle>- <Card>+ <SectionTitle>Export range</SectionTitle>+ <Card rows>{MODE_OPTIONS.map((option, i) => (- <View key={option.key}>- {i > 0 && <Divider />}- <Pressable- style={({ pressed }) => [styles.modeRow, pressed && { opacity: colors.pressedOpacity }]}+ <React.Fragment key={option.key}>+ {i > 0 && <Divider tight />}+ <RadioRow+ label={option.label}+ sub={option.description}+ selected={mode === option.key}onPress={() => handleModeChange(option.key)}- >- <View style={styles.modeContent}>- <Text style={[styles.settingLabel, { color: mode === option.key ? colors.primary : colors.text }]}>- {option.label}- </Text>- <Text style={[styles.settingDescription, { color: colors.textSecondary }]}>- {option.description}- </Text>- </View>- <RadioDot selected={mode === option.key} />- </Pressable>- </View>+ />+ </React.Fragment>))}</Card></View>{/* File Retention */}<View style={styles.section}>- <SectionTitle>File Retention</SectionTitle>+ <SectionTitle>File retention</SectionTitle><Card><NumericInputlabel="Files to keep"@@ -550,7 +552,6 @@ export function AutoExportScreen(_props: ScreenProps) {unit="files"placeholder="10"min={0}- colors={colors}hint={filenameTemplate.includes("{device}")? "Set to 0 for unlimited. Counts only exports named for this device model, so other models sharing the folder are untouched."@@ -565,21 +566,21 @@ export function AutoExportScreen(_props: ScreenProps) {<SectionTitle>Status</SectionTitle><Card><View style={styles.statusRow}>- <Text style={[styles.statusLabel, { color: colors.textSecondary }]}>Last Export</Text>+ <Text style={[styles.statusLabel, { color: colors.textSecondary }]}>Last export</Text><Text style={[styles.statusValue, { color: colors.text }]}>{formatExportDateTime(lastExport)}</Text></View>{lastFileName && (<><Divider /><View style={styles.statusRow}>- <Text style={[styles.statusLabel, { color: colors.textSecondary }]}>Last File</Text>+ <Text style={[styles.statusLabel, { color: colors.textSecondary }]}>Last file</Text><Text style={[styles.statusValue, { color: colors.text }]} numberOfLines={1}>{lastFileName}</Text></View><Divider /><View style={styles.statusRow}>- <Text style={[styles.statusLabel, { color: colors.textSecondary }]}>Locations Exported</Text>+ <Text style={[styles.statusLabel, { color: colors.textSecondary }]}>Locations exported</Text><Text style={[styles.statusValue, { color: colors.text }]}>{lastRowCount}</Text></View></>@@ -588,7 +589,7 @@ export function AutoExportScreen(_props: ScreenProps) {<><Divider /><View style={styles.errorRow}>- <AlertTriangle size={14} color={colors.error} />+ <TriangleAlert size={size.icon.sm} color={colors.error} /><Text style={[styles.errorText, { color: colors.error }]} numberOfLines={2}>{lastError}</Text>@@ -599,7 +600,7 @@ export function AutoExportScreen(_props: ScreenProps) {<><Divider /><View style={styles.statusRow}>- <Text style={[styles.statusLabel, { color: colors.textSecondary }]}>Next Export</Text>+ <Text style={[styles.statusLabel, { color: colors.textSecondary }]}>Next export</Text><Text style={[styles.statusValue, { color: colors.text }]}>{formatExportDateTime(nextExport)}</Text></View></>@@ -608,7 +609,7 @@ export function AutoExportScreen(_props: ScreenProps) {<><Divider /><View style={styles.statusRow}>- <Text style={[styles.statusLabel, { color: colors.textSecondary }]}>Export Files</Text>+ <Text style={[styles.statusLabel, { color: colors.textSecondary }]}>Export files</Text><Text style={[styles.statusValue, { color: colors.text }]}>{fileCount}</Text></View></>@@ -620,18 +621,26 @@ export function AutoExportScreen(_props: ScreenProps) {{directoryUri && (<View style={styles.section}><Button- title={exporting ? "Exporting..." : "Export Now"}+ title={exporting ? "Exporting..." : "Export now"}onPress={handleExportNow}disabled={exporting}loading={exporting}/>+ {exportRunning && (+ <View style={styles.runningRow} testID="export-running">+ <ActivityIndicator size="small" color={colors.textSecondary} />+ <Text style={[styles.runningText, { color: colors.textSecondary }]}>+ Export running. It continues if you leave this screen.+ </Text>+ </View>+ )}</View>)}{/* Export History */}{exportFiles.length > 0 && (<View style={styles.section}>- <SectionTitle>Export History</SectionTitle>+ <SectionTitle>Export history</SectionTitle><Card>{exportFiles.map((file, i) => (<View key={file.name}>@@ -646,10 +655,13 @@ export function AutoExportScreen(_props: ScreenProps) {</Text></View><Pressable- style={({ pressed }) => [styles.shareButton, pressed && { opacity: 0.5 }]}+ accessibilityRole="button"+ accessibilityLabel={`Share ${file.name}`}+ android_ripple={{ color: colors.primary + STATE_LAYER_ALPHA, borderless: true }}+ style={styles.shareButton}onPress={() => handleShareFile(file)}>- <Share2 size={18} color={colors.primary} />+ <Share2 size={size.icon.md} color={colors.primary} /></Pressable></View></View>@@ -658,41 +670,65 @@ export function AutoExportScreen(_props: ScreenProps) {</View>)}</ScrollView>- <FloatingSaveIndicator saving={saving} success={saveSuccess} colors={colors} />+ <FloatingSaveIndicator saving={saving} />+ <ExportFormatDialog+ visible={formatOpen}+ title="Export format"+ message="Every scheduled run writes this format."+ onSelect={(next) => {+ setFormatOpen(false)+ handleFormatChange(next)+ }}+ onRequestClose={() => setFormatOpen(false)}+ /></Container>)}const styles = StyleSheet.create({+ centered: {+ flex: 1,+ justifyContent: "center",+ alignItems: "center"+ },+ runningRow: {+ flexDirection: "row",+ alignItems: "center",+ gap: space.sm+ },+ runningText: {+ flex: 1,+ fontSize: fontSizes.caption+ },scrollContent: {- paddingHorizontal: 16,- paddingBottom: 40+ paddingHorizontal: space.lg,+ paddingBottom: space.xxl},header: {- marginTop: 20,- marginBottom: 20+ marginTop: space.xl,+ marginBottom: space.xl},subtitle: {- fontSize: 14,- lineHeight: 20+ fontSize: fontSizes.body,+ lineHeight: lineHeights.body},section: {- marginTop: 24+ marginTop: space.xl},settingLabel: {- fontSize: 16,+ fontSize: fontSizes.label,...fonts.semiBold,- marginBottom: 2+ marginBottom: space.xxs},settingDescription: {- fontSize: 13,+ fontSize: fontSizes.description,...fonts.regular},directoryRow: {flexDirection: "row",alignItems: "center",- gap: 12,- paddingVertical: 4+ gap: space.md,+ paddingVertical: space.xs},directoryContent: {flex: 1@@ -701,96 +737,79 @@ const styles = StyleSheet.create({flexDirection: "row",justifyContent: "space-between",alignItems: "center",- paddingVertical: 4+ paddingVertical: space.xs},statusLabel: {- fontSize: 14,+ fontSize: fontSizes.body,...fonts.regular},statusValue: {- fontSize: 14,+ fontSize: fontSizes.body,...fonts.semiBold,flexShrink: 1,textAlign: "right",- marginLeft: 12+ marginStart: space.md},errorRow: {flexDirection: "row",alignItems: "center",- gap: 8,- paddingVertical: 6+ gap: space.sm,+ paddingVertical: space.sm},errorText: {- fontSize: 13,+ fontSize: fontSizes.description,...fonts.regular,flex: 1},- modeRow: {- flexDirection: "row",- justifyContent: "space-between",- alignItems: "center",- paddingVertical: 10- },- modeContent: {- flex: 1,- marginRight: 16- },fileRow: {flexDirection: "row",alignItems: "center",- paddingVertical: 8+ paddingVertical: space.sm},fileInfo: {flex: 1,- marginRight: 12+ marginEnd: space.md},fileName: {- fontSize: 13,+ fontSize: fontSizes.description,...fonts.semiBold,- marginBottom: 2+ marginBottom: space.xxs},fileMeta: {- fontSize: 12,+ fontSize: fontSizes.caption,...fonts.regular},shareButton: {- padding: 8+ padding: space.sm},fieldLabel: {- fontSize: 12,- ...fonts.semiBold,- textTransform: "uppercase",- letterSpacing: 0.5,- marginTop: 12,- marginBottom: 8- },- templateInput: {- fontSize: 15,- ...fonts.regular,- borderWidth: 1,- borderRadius: 8,- paddingHorizontal: 12,- paddingVertical: 10+ fontSize: fontSizes.description,+ ...fonts.medium,+ marginBottom: space.sm},templateHint: {- fontSize: 13,+ fontSize: fontSizes.description,...fonts.regular,- marginTop: 8+ marginTop: space.sm},templateTokenRow: {flexDirection: "row",alignItems: "baseline",- gap: 8+ gap: space.sm,+ marginTop: space.sm},templateToken: {- fontSize: 13,+ fontSize: fontSizes.description,...fonts.semiBold,- marginTop: 8,minWidth: 72},+ templateTokenValue: {+ fontSize: fontSizes.description,+ ...fonts.regular+ },templatePreview: {- fontSize: 13,+ fontSize: fontSizes.description,...fonts.semiBold,- marginTop: 8+ marginTop: space.sm}})diff --git a/apps/mobile/src/screens/ExportImportScreen.tsx b/apps/mobile/src/screens/ExportImportScreen.tsxnew file mode 100644index 00000000..56919fd1--- /dev/null+++ b/apps/mobile/src/screens/ExportImportScreen.tsx@@ -0,0 +1,374 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import React, { useCallback, useRef, useState } from "react"+import { DeviceEventEmitter, ScrollView, StyleSheet, Text, View } from "react-native"+import { useFocusEffect } from "@react-navigation/native"+import { Archive, CalendarRange, Clock, Download, HardDrive, MapPin, Upload } from "lucide-react-native"+import {+ Button,+ Card,+ Container,+ Divider,+ ExportFormatDialog,+ FieldMessage,+ ListItem,+ LoadingOverlay,+ SectionTitle,+ SettingRow,+ StateLine,+ StatRow,+ Toggle+} from "../components"+import { useTheme } from "../hooks/useTheme"+import NativeLocationService from "../services/NativeLocationService"+import ImportService, { type ImportPreview } from "../services/ImportService"+import { showAlert, showConfirm } from "../services/modalService"+import { logger } from "../utils/logger"+import { type ExportFormat } from "../utils/exportConverters"+import { FILE_FORMATS } from "../utils/fileFormats"+import {+ autoExportSub,+ backupFirstSub,+ commitConfirm,+ commitLabel,+ emptyPreviewCopy,+ exportLine,+ exportResultLine,+ importErrorMessage,+ importSourceLine,+ previewHeadline,+ queueHint,+ SHARE_FAILED_LINE,+ skippedLine+} from "../utils/locationTransfer"+import { fonts, fontSizes, lineHeights } from "../styles/typography"+import { space } from "../constants"+import type { ScreenProps } from "../types/global"++type AutoExportStatus = Awaited<ReturnType<typeof NativeLocationService.getAutoExportStatus>>+type Busy = "export" | "parse" | "commit" | null+type Message = { text: string; failed?: boolean }++const EMPTY = { total: 0, databaseSizeMB: 0 }++export function ExportImportScreen({ navigation }: ScreenProps) {+ const { colors } = useTheme()++ const [stats, setStats] = useState(EMPTY)+ const [loaded, setLoaded] = useState(false)+ const [autoExport, setAutoExport] = useState<AutoExportStatus | null>(null)+ const [busy, setBusy] = useState<Busy>(null)+ const [exportMessage, setExportMessage] = useState<Message | null>(null)+ const [importMessage, setImportMessage] = useState<Message | null>(null)+ const [formatOpen, setFormatOpen] = useState(false)+ const [preview, setPreview] = useState<ImportPreview | null>(null)+ const [queued, setQueued] = useState(false)++ // A ref, not the state, because two presses inside one render both read the same state value.+ const busyRef = useRef(false)+ // The staged file lives in a native stash on a 15 minute timer. Leaving the screen frees it now.+ const stagedRef = useRef(false)++ const read = useCallback(async () => {+ const [statsResult, autoResult] = await Promise.allSettled([+ NativeLocationService.getStats(),+ NativeLocationService.getAutoExportStatus()+ ])+ if (statsResult.status === "fulfilled") {+ setStats({ total: statsResult.value.total, databaseSizeMB: statsResult.value.databaseSizeMB })+ setLoaded(true)+ } else {+ logger.error("[ExportImportScreen] Failed to read stats:", statsResult.reason)+ }+ if (autoResult.status === "fulfilled") setAutoExport(autoResult.value)+ }, [])++ useFocusEffect(+ useCallback(() => {+ read()+ const sub = DeviceEventEmitter.addListener("onLocationUpdate", read)+ return () => {+ sub.remove()+ if (stagedRef.current) {+ stagedRef.current = false+ ImportService.cancelImport().catch(() => {})+ }+ }+ }, [read])+ )++ const discard = useCallback(() => {+ stagedRef.current = false+ setPreview(null)+ setQueued(false)+ ImportService.cancelImport().catch(() => {})+ }, [])++ const handleExport = useCallback(async (format: ExportFormat) => {+ setFormatOpen(false)+ if (busyRef.current) return+ busyRef.current = true+ setBusy("export")+ setExportMessage(null)+ try {+ const result = await NativeLocationService.exportToFile(format)+ if (!result) {+ setExportMessage({ text: exportLine(0) })+ return+ }+ // Dismissed before the share sheet, which would otherwise sit over this overlay.+ setBusy(null)+ try {+ await NativeLocationService.shareFile(result.filePath, result.mimeType, `Colota export`)+ setExportMessage({ text: exportResultLine(result.rowCount, format) })+ } catch (shareError) {+ logger.warn("[ExportImportScreen] Share failed:", shareError)+ setExportMessage({ text: SHARE_FAILED_LINE, failed: true })+ }+ } catch (err) {+ logger.error("[ExportImportScreen] Export failed:", err)+ showAlert("Export failed", "The file could not be written. Try again in a moment.", "error")+ } finally {+ busyRef.current = false+ setBusy(null)+ }+ }, [])++ const handleChooseFile = useCallback(async () => {+ if (busyRef.current) return+ let source: { uri: string } | null = null+ try {+ source = await ImportService.pickImportSource()+ } catch (err) {+ logger.error("[ExportImportScreen] pickImportSource failed:", err)+ showAlert("Could not open the picker", "The system file picker did not open.", "error")+ return+ }+ if (!source) return++ busyRef.current = true+ setBusy("parse")+ setImportMessage(null)+ try {+ const staged = await ImportService.importLocationsFromFile(source.uri)+ if (staged.newRows === 0) {+ await ImportService.cancelImport().catch(() => {})+ setImportMessage({ text: emptyPreviewCopy(staged), failed: true })+ return+ }+ stagedRef.current = true+ setQueued(false)+ setPreview(staged)+ } catch (err) {+ logger.error("[ExportImportScreen] Parse failed:", err)+ setImportMessage({ text: importErrorMessage((err as { code?: string }).code), failed: true })+ } finally {+ busyRef.current = false+ setBusy(null)+ }+ }, [])++ const handleCommit = useCallback(async () => {+ if (busyRef.current || !preview) return+ if (!(await showConfirm({ ...commitConfirm(preview, queued), destructive: false }))) return++ busyRef.current = true+ setBusy("commit")+ try {+ const inserted = await ImportService.commitImport(queued)+ stagedRef.current = false+ setPreview(null)+ setQueued(false)+ setImportMessage({ text: `Imported ${inserted.toLocaleString()} locations.` })+ await read()+ } catch (err) {+ logger.error("[ExportImportScreen] Commit failed:", err)+ setImportMessage({ text: importErrorMessage((err as { code?: string }).code), failed: true })+ } finally {+ busyRef.current = false+ setBusy(null)+ }+ }, [preview, queued, read])++ const skipped = preview ? skippedLine(preview) : undefined+ const headline = preview ? previewHeadline(preview) : null+ const PreviewIcon = preview ? FILE_FORMATS[preview.format].icon : MapPin++ return (+ <Container>+ <ScrollView contentContainerStyle={styles.scrollContent} keyboardShouldPersistTaps="handled">+ <Text style={[styles.intro, { color: colors.textSecondary }]}>+ What leaves this device as a file, and what comes back in from one.+ </Text>++ <View style={styles.section}>+ <SectionTitle>On this device</SectionTitle>+ <Card rows>+ <StatRow+ icon={MapPin}+ label="Locations"+ value={loaded ? stats.total.toLocaleString() : "…"}+ testID="stat-locations"+ />+ <Divider tight inset />+ <StatRow+ icon={HardDrive}+ label="Database size"+ value={loaded ? `${stats.databaseSizeMB.toFixed(2)} MB` : "…"}+ testID="stat-size"+ />+ </Card>+ </View>++ <View style={styles.section}>+ <SectionTitle>Send to a file</SectionTitle>+ <View>+ <Button+ variant="secondary"+ icon={Upload}+ title="Export all locations"+ testID="export-all-btn"+ loading={busy === "export"}+ disabled={busy !== null || stats.total === 0}+ onPress={() => setFormatOpen(true)}+ />+ {/* Nothing definitive until the first read lands, or the line claims an empty database+ for as long as the count takes. */}+ {exportMessage || loaded ? (+ <FieldMessage variant={exportMessage?.failed ? "error" : "info"}>+ {exportMessage?.text ?? exportLine(stats.total)}+ </FieldMessage>+ ) : null}+ </View>++ <Card rows style={styles.afterButton}>+ <ListItem+ testID="nav-location-history"+ icon={CalendarRange}+ label="Export a day or a trip"+ sub="History exports one day, or the trips you pick."+ subLines={2}+ onPress={() => navigation.navigate("Location History")}+ />+ <Divider tight inset />+ <ListItem+ testID="nav-auto-export"+ icon={Clock}+ label="Automatic export"+ sub={autoExportSub(autoExport)}+ subLines={2}+ onPress={() => navigation.navigate("Auto-Export")}+ />+ </Card>+ </View>++ <View style={styles.section}>+ <SectionTitle>Bring in from a file</SectionTitle>+ <Card rows>+ <ListItem+ testID="nav-backup-restore"+ icon={Archive}+ label="Back up first"+ sub={backupFirstSub()}+ subLines={2}+ onPress={() => navigation.navigate("Backup & Restore")}+ />+ </Card>++ {preview && headline ? (+ <>+ <Card rows style={styles.afterButton}>+ <StateLine+ icon={PreviewIcon}+ iconColor={colors.primary}+ label={headline.label}+ caption={headline.caption}+ testID="preview-state"+ />+ {preview.canQueueForSync && (+ <>+ <Divider tight />+ <SettingRow label="Also queue for upload" hint={queueHint(preview.newRows)}>+ <Toggle+ value={queued}+ onValueChange={setQueued}+ accessibilityLabel="Also queue for upload"+ testID="queue-toggle"+ />+ </SettingRow>+ </>+ )}+ </Card>+ {skipped ? <FieldMessage>{skipped}</FieldMessage> : null}+ <Button+ variant="primary"+ icon={Download}+ title={commitLabel(preview.newRows, queued)}+ testID="import-commit-btn"+ loading={busy === "commit"}+ disabled={busy !== null}+ onPress={handleCommit}+ />+ <Button variant="ghost" title="Discard" testID="import-discard-btn" onPress={discard} />+ </>+ ) : (+ <View>+ <Button+ variant="secondary"+ icon={Download}+ title="Choose a file"+ testID="import-file-btn"+ loading={busy === "parse"}+ disabled={busy !== null}+ onPress={handleChooseFile}+ />+ <FieldMessage variant={importMessage?.failed ? "warning" : "info"}>+ {importMessage?.text ?? importSourceLine()}+ </FieldMessage>+ </View>+ )}+ </View>+ </ScrollView>++ <ExportFormatDialog+ visible={formatOpen}+ title="Export format"+ message={`All ${stats.total.toLocaleString()} locations, oldest first.`}+ onSelect={handleExport}+ onRequestClose={() => setFormatOpen(false)}+ />+ <LoadingOverlay+ visible={busy === "export" || busy === "commit"}+ title={busy === "export" ? "Exporting" : "Importing"}+ message={+ busy === "commit" && preview+ ? `${preview.newRows.toLocaleString()} locations. Recording waits until this finishes.`+ : `${stats.total.toLocaleString()} locations.`+ }+ />+ </Container>+ )+}++const styles = StyleSheet.create({+ scrollContent: {+ paddingHorizontal: space.lg,+ paddingTop: space.lg,+ paddingBottom: space.xxl+ },+ intro: {+ fontSize: fontSizes.body,+ ...fonts.regular,+ lineHeight: lineHeights.body,+ marginBottom: space.lg+ },+ section: {+ marginBottom: space.xl+ },+ afterButton: {+ marginTop: space.md+ }+})diff --git a/apps/mobile/src/screens/ExportLocationsScreen.tsx b/apps/mobile/src/screens/ExportLocationsScreen.tsxdeleted file mode 100644index 070c978d..00000000--- a/apps/mobile/src/screens/ExportLocationsScreen.tsx+++ /dev/null@@ -1,191 +0,0 @@-/**- * Copyright (C) 2026 Max Dietrich- * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.- */--import { useState, useEffect, useCallback } from "react"-import { Text, StyleSheet, View, ScrollView } from "react-native"-import { fonts } from "../styles/typography"-import { MapPinOff, Upload } from "lucide-react-native"-import { Container, Card, SectionTitle, Button, FormatSelector, LoadingOverlay } from "../components"-import { useTheme } from "../hooks/useTheme"-import NativeLocationService from "../services/NativeLocationService"-import { EXPORT_FORMATS, ExportFormat } from "../utils/exportConverters"-import { logger } from "../utils/logger"-import { showAlert } from "../services/modalService"-import { ScreenProps } from "../types/global"--export function ExportLocationsScreen({}: ScreenProps) {- const { colors } = useTheme()- const [exporting, setExporting] = useState(false)- const [exportProgress, setExportProgress] = useState<string>("")- const [totalLocations, setTotalLocations] = useState(0)- const [selectedFormat, setSelectedFormat] = useState<ExportFormat | null>(null)-- const loadStats = useCallback(async () => {- try {- const stats = await NativeLocationService.getStats()- setTotalLocations(stats.total ?? 0)- } catch (error) {- logger.error("[ExportLocationsScreen] Failed to load stats:", error)- }- }, [])-- useEffect(() => {- loadStats()- }, [loadStats])-- const handleExport = async (format: ExportFormat) => {- if (totalLocations === 0) {- showAlert("No Data", "There are no locations in the database to export.", "info")- return- }-- setExporting(true)- setExportProgress("Exporting locations...")-- try {- const result = await NativeLocationService.exportToFile(format)-- if (!result) {- showAlert("No Data", "There are no locations in the database to export.", "info")- return- }-- setExportProgress(`Exported ${result.rowCount.toLocaleString()} locations`)-- setExporting(false)- setExportProgress("")-- try {- await NativeLocationService.shareFile(- result.filePath,- result.mimeType,- `Colota Export - ${result.rowCount} locations`- )- } catch (shareError: any) {- logger.warn("[ExportLocationsScreen] Share error:", shareError)- }- } catch (error) {- logger.error("[ExportLocationsScreen] Export failed:", error)- showAlert("Export Failed", "Unable to export your data. Please try again.", "error")- } finally {- setExporting(false)- setExportProgress("")- setSelectedFormat(null)- }- }-- return (- <Container>- <ScrollView contentContainerStyle={styles.scrollContent} showsVerticalScrollIndicator={false}>- {totalLocations === 0 ? (- <Card style={styles.emptyCard}>- <View style={styles.emptyState}>- <MapPinOff size={40} color={colors.textLight} />- <Text style={[styles.emptyTitle, { color: colors.text }]}>No Locations</Text>- <Text style={[styles.emptySubtitle, { color: colors.textLight }]}>- Start tracking to record locations that can be exported.- </Text>- </View>- </Card>- ) : (- <>- {/* Stats Card */}- <View style={[styles.statsContainer, { backgroundColor: colors.card, borderColor: colors.border }]}>- <View style={styles.statsGrid}>- <View style={styles.statItem}>- <Text style={[styles.statLabel, { color: colors.textSecondary }]}>Total Locations</Text>- <Text style={[styles.statValue, { color: colors.primaryDark }]}>- {totalLocations.toLocaleString()}- </Text>- </View>- </View>- </View>-- {/* Format Selection */}- <View style={styles.section}>- <SectionTitle>Select Format</SectionTitle>- <Card>- <FormatSelector selectedFormat={selectedFormat} onSelectFormat={setSelectedFormat} />- </Card>- </View>-- {/* Export Button */}- {selectedFormat && (- <View style={styles.exportButtonWrapper}>- <Button- onPress={() => handleExport(selectedFormat)}- disabled={exporting}- title={`Export ${EXPORT_FORMATS[selectedFormat].label}`}- icon={Upload}- />- </View>- )}- </>- )}- </ScrollView>-- <LoadingOverlay visible={exporting} title="Exporting Data" message={exportProgress} />- </Container>- )-}--const styles = StyleSheet.create({- scrollContent: {- paddingHorizontal: 16,- paddingTop: 20,- paddingBottom: 40- },- emptyCard: {- marginBottom: 24- },- emptyState: {- alignItems: "center",- paddingVertical: 32- },- emptyTitle: {- fontSize: 18,- ...fonts.semiBold,- marginTop: 12,- marginBottom: 4- },- emptySubtitle: {- fontSize: 13,- textAlign: "center",- lineHeight: 18- },- statsContainer: {- borderRadius: 16,- borderWidth: 2,- marginBottom: 24,- overflow: "hidden"- },- statsGrid: {- flexDirection: "row",- padding: 20- },- statItem: {- flex: 1,- alignItems: "center"- },- statLabel: {- fontSize: 12,- ...fonts.semiBold,- textTransform: "uppercase",- letterSpacing: 0.8,- marginBottom: 8- },- statValue: {- fontSize: 20,- ...fonts.bold,- letterSpacing: -0.5,- textAlign: "center"- },- section: {- marginBottom: 24- },- exportButtonWrapper: {- marginBottom: 16- }-})diff --git a/apps/mobile/src/screens/ImportLocationsScreen.tsx b/apps/mobile/src/screens/ImportLocationsScreen.tsxdeleted file mode 100644index d53eea98..00000000--- a/apps/mobile/src/screens/ImportLocationsScreen.tsx+++ /dev/null@@ -1,335 +0,0 @@-/**- * Copyright (C) 2026 Max Dietrich- * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.- */--import React, { useCallback, useEffect, useState } from "react"-import { ScrollView, StyleSheet, Text, View } from "react-native"-import { Download } from "lucide-react-native"-import { fonts } from "../styles/typography"-import { Button, Card, Container, Divider, LoadingOverlay, SectionTitle } from "../components"-import { useTheme } from "../hooks/useTheme"-import NativeLocationService from "../services/NativeLocationService"-import ImportService, { type ImportFormat, type ImportPreview } from "../services/ImportService"-import { showAlert, showChoice } from "../services/modalService"-import { logger } from "../utils/logger"-import { FILE_FORMATS, IMPORT_FORMAT_ORDER, importDescription } from "../utils/fileFormats"-import { ScreenProps } from "../types/global"-import type { ThemeColors } from "../types/global"--const IMPORT_FORMAT_LABELS = Object.fromEntries(- (Object.keys(FILE_FORMATS) as ImportFormat[]).map((k) => [k, FILE_FORMATS[k].label])-) as Record<ImportFormat, string>--// Warn before queueing this many points - the backend has to absorb one upload per row.-const SYNC_WARN_THRESHOLD = 10_000--const SUPPORTED_FORMATS = IMPORT_FORMAT_ORDER.map((key) => {- const f = FILE_FORMATS[key]- return { icon: f.icon, title: f.label, extension: f.extension, description: importDescription(f) }-})--function formatDate(unixSeconds: number | null): string {- if (unixSeconds == null) return "-"- return new Date(unixSeconds * 1000).toLocaleDateString()-}--function buildPreviewMessage(preview: ImportPreview): string {- const lines: string[] = []- lines.push(`Format: ${IMPORT_FORMAT_LABELS[preview.format]}`)- lines.push(`Points found: ${preview.totalParsed.toLocaleString()}`)- if (preview.duplicates > 0) {- lines.push(`Duplicates skipped: ${preview.duplicates.toLocaleString()}`)- }- if (preview.invalid > 0) {- lines.push(`Invalid: ${preview.invalid.toLocaleString()}`)- }- lines.push(`Date range: ${formatDate(preview.dateRangeStartSec)} - ${formatDate(preview.dateRangeEndSec)}`)- lines.push("")- lines.push(`Import ${preview.newRows.toLocaleString()} new location${preview.newRows !== 1 ? "s" : ""}?`)- if (preview.canQueueForSync) {- lines.push("")- lines.push('Choose "Import + Queue for Sync" to also upload these to your configured backend.')- if (preview.newRows >= SYNC_WARN_THRESHOLD) {- lines.push(- `Heads up: queueing ${preview.newRows.toLocaleString()} points means ${preview.newRows.toLocaleString()} upload requests against your backend.`- )- }- }- lines.push("")- lines.push("Tip: back up your data first (Settings -> Backup & Restore). Imports can't be selectively undone.")- return lines.join("\n")-}--function importErrorMessage(e: unknown): string {- const code = (e as { code?: string }).code- switch (code) {- case "E_IMPORT_UNSUPPORTED":- return "This file format isn't recognised. Supported: GeoJSON, Google Timeline, GPX, KML, and CSV (with latitude/longitude/time columns)."- case "E_IMPORT_CANCELLED":- return "Import cancelled."- case "E_BUSY":- return "Another backup, restore or import is already in progress."- case "E_IMPORT_NO_PENDING":- return "No staged import to commit. Choose a file again."- case "E_IMPORT_SYNC_UNAVAILABLE":- return "Sync isn't configured (offline mode or empty endpoint). Import without sync instead, or set up sync in Settings first."- default:- return e instanceof Error ? e.message : "Import failed."- }-}--const FormatRow = ({ entry, colors }: { entry: (typeof SUPPORTED_FORMATS)[number]; colors: ThemeColors }) => {- const Icon = entry.icon- return (- <View style={styles.formatRow}>- <Icon size={22} color={colors.textLight} />- <View style={styles.formatTextContent}>- <View style={styles.formatTitleRow}>- <Text style={[styles.formatTitle, { color: colors.text }]}>{entry.title}</Text>- <View- style={[- styles.extensionBadge,- { backgroundColor: colors.primary + "15", borderColor: colors.primary + "30" }- ]}- >- <Text style={[styles.extensionText, { color: colors.primaryDark }]}>{entry.extension}</Text>- </View>- </View>- <Text style={[styles.formatDescription, { color: colors.textLight }]}>{entry.description}</Text>- </View>- </View>- )-}--export function ImportLocationsScreen({}: ScreenProps) {- const { colors } = useTheme()- const [busy, setBusy] = useState(false)- const [progressLabel, setProgressLabel] = useState<string>("")- const [totalLocations, setTotalLocations] = useState(0)-- const loadStats = useCallback(async () => {- try {- const stats = await NativeLocationService.getStats()- setTotalLocations(stats.total ?? 0)- } catch (error) {- logger.error("[ImportLocationsScreen] Failed to load stats:", error)- }- }, [])-- useEffect(() => {- loadStats()- }, [loadStats])-- const handleChooseFile = useCallback(async () => {- let source: { uri: string; displayName: string | null } | null = null- try {- source = await ImportService.pickImportSource()- } catch (err) {- logger.error("[ImportLocationsScreen] pickImportSource failed:", err)- showAlert("Picker error", "Could not open the file picker.", "error")- return- }- if (!source) return-- setBusy(true)- setProgressLabel("Parsing file...")- let preview: ImportPreview- try {- preview = await ImportService.importLocationsFromFile(source.uri)- } catch (err) {- logger.error("[ImportLocationsScreen] importLocationsFromFile failed:", err)- setBusy(false)- setProgressLabel("")- showAlert("Import failed", importErrorMessage(err), "error")- return- }-- if (preview.newRows === 0) {- await ImportService.cancelImport().catch(() => {})- setBusy(false)- setProgressLabel("")- const title = preview.totalParsed === 0 ? "Nothing to import" : "Already imported"- const message =- preview.totalParsed === 0- ? "No locations were found in this file."- : `All ${preview.duplicates.toLocaleString()} points in this file are already in your history.`- showAlert(title, message, "info")- return- }-- setProgressLabel("")-- const buttons: Array<{ text: string; style?: "primary" | "secondary" | "destructive" }> = [- { text: "Cancel", style: "secondary" },- { text: "Import", style: "primary" }- ]- if (preview.canQueueForSync) {- // Destructive: queueing fires uploads to the backend, can't be undone server-side.- buttons.push({ text: "Import + Queue for Sync", style: "destructive" })- }-- const choice = await showChoice({- title: "Import locations?",- message: buildPreviewMessage(preview),- variant: "info",- buttons- })-- if (choice === 0) {- await ImportService.cancelImport().catch(() => {})- setBusy(false)- return- }- const asQueued = choice === 2-- setProgressLabel(- asQueued- ? `Importing ${preview.newRows.toLocaleString()} locations and queueing for sync...`- : `Importing ${preview.newRows.toLocaleString()} locations...`- )- try {- const inserted = await ImportService.commitImport(asQueued)- await loadStats()- showAlert(- "Import complete",- asQueued- ? `Imported ${inserted.toLocaleString()} location${inserted !== 1 ? "s" : ""} and queued for sync to your backend.`- : `Imported ${inserted.toLocaleString()} location${inserted !== 1 ? "s" : ""}.`,- "success"- )- } catch (err) {- logger.error("[ImportLocationsScreen] commitImport failed:", err)- showAlert("Import failed", importErrorMessage(err), "error")- } finally {- setBusy(false)- setProgressLabel("")- }- }, [loadStats])-- return (- <Container>- <ScrollView contentContainerStyle={styles.scrollContent} showsVerticalScrollIndicator={false}>- {/* Stats Card */}- <View style={[styles.statsContainer, { backgroundColor: colors.card, borderColor: colors.border }]}>- <View style={styles.statsGrid}>- <View style={styles.statItem}>- <Text style={[styles.statLabel, { color: colors.textSecondary }]}>Total Locations</Text>- <Text style={[styles.statValue, { color: colors.primaryDark }]}>{totalLocations.toLocaleString()}</Text>- </View>- </View>- </View>-- {/* Supported formats */}- <View style={styles.section}>- <SectionTitle>Supported Formats</SectionTitle>- <Card>- {SUPPORTED_FORMATS.map((entry, i) => (- <React.Fragment key={entry.title}>- {i > 0 && <Divider />}- <FormatRow entry={entry} colors={colors} />- </React.Fragment>- ))}- </Card>- </View>-- {/* Import action */}- <View style={styles.section}>- <SectionTitle>Import from File</SectionTitle>- <Card>- <Text style={[styles.intro, { color: colors.textSecondary }]}>- Merge location history from external files into your Colota database. Duplicates are skipped- automatically.- </Text>- <Text style={[styles.intro, { color: colors.textSecondary }]}>- Imported rows are flagged as already replicated by default, so they stay local. If you've configured an- optional sync backend, the confirm dialog also offers to queue them for upload.- </Text>- <Button onPress={handleChooseFile} disabled={busy} title="Choose File" icon={Download} />- </Card>- </View>- </ScrollView>-- <LoadingOverlay visible={busy} title="Importing" message={progressLabel} />- </Container>- )-}--const styles = StyleSheet.create({- scrollContent: {- paddingHorizontal: 16,- paddingTop: 20,- paddingBottom: 40- },- statsContainer: {- borderRadius: 16,- borderWidth: 2,- marginBottom: 24,- overflow: "hidden"- },- statsGrid: {- flexDirection: "row",- padding: 20- },- statItem: {- flex: 1,- alignItems: "center"- },- statLabel: {- fontSize: 12,- ...fonts.semiBold,- textTransform: "uppercase",- letterSpacing: 0.8,- marginBottom: 8- },- statValue: {- fontSize: 20,- ...fonts.bold,- letterSpacing: -0.5,- textAlign: "center"- },- section: {- marginBottom: 24- },- intro: {- marginBottom: 12,- fontSize: 14,- lineHeight: 20- },- formatRow: {- flexDirection: "row",- alignItems: "center",- paddingVertical: 10,- gap: 16- },- formatTextContent: {- flex: 1- },- formatTitleRow: {- flexDirection: "row",- alignItems: "center",- gap: 8,- marginBottom: 4,- flexWrap: "wrap"- },- formatTitle: {- fontSize: 15,- ...fonts.semiBold,- letterSpacing: -0.2- },- extensionBadge: {- paddingHorizontal: 8,- paddingVertical: 3,- borderRadius: 6,- borderWidth: 1- },- extensionText: {- fontSize: 10,- ...fonts.bold,- letterSpacing: 0.3- },- formatDescription: {- fontSize: 12,- lineHeight: 16- }-})diff --git a/apps/mobile/src/screens/SettingsScreen.tsx b/apps/mobile/src/screens/SettingsScreen.tsxindex 16201d4f..a0304649 100644--- a/apps/mobile/src/screens/SettingsScreen.tsx+++ b/apps/mobile/src/screens/SettingsScreen.tsx@@ -180,17 +180,17 @@ export function SettingsScreen({ navigation }: Props) {<ListItemtestID="nav-import-locations"icon={Download}- label="Import Locations"+ label="Export & Import"sub="Merge locations from a GeoJSON or Google Timeline file"- onPress={() => navigation.navigate("Import Locations")}+ onPress={() => navigation.navigate("Export & Import")}/><Divider /><ListItemtestID="nav-export-locations"icon={Upload}- label="Export Locations"+ label="Export & Import"sub="Export locations as CSV, GeoJSON, GPX or KML"- onPress={() => navigation.navigate("Export Locations")}+ onPress={() => navigation.navigate("Export & Import")}/><Divider /><ListItemdiff --git a/apps/mobile/src/screens/__tests__/AutoExportScreen.test.tsx b/apps/mobile/src/screens/__tests__/AutoExportScreen.test.tsxindex 1637ec6e..c3190c2c 100644--- a/apps/mobile/src/screens/__tests__/AutoExportScreen.test.tsx+++ b/apps/mobile/src/screens/__tests__/AutoExportScreen.test.tsx@@ -128,6 +128,24 @@ jest.mock("../../components", () => {const RN = require("react-native")const { EXPORT_FORMATS, EXPORT_FORMAT_KEYS } = require("../../utils/exportConverters")return {+ TextField: require("../../testing/componentStubs").TextFieldStub,+ RadioRow: function (props: any) {+ return R.createElement(+ RN.Pressable,+ { testID: props.testID, onPress: props.onPress, accessibilityState: { checked: props.selected } },+ R.createElement(RN.Text, null, props.label),+ props.sub ? R.createElement(RN.Text, null, props.sub) : null+ )+ },+ Toggle: function (props: any) {+ return require("react").createElement(require("react-native").Switch, {+ testID: props.testID,+ value: props.value,+ onValueChange: props.onValueChange,+ disabled: props.disabled,+ accessibilityLabel: props.accessibilityLabel+ })+ },Container: (props: any) => R.createElement(RN.View, null, props.children),Card: (props: any) => R.createElement(RN.View, null, props.children),SectionTitle: (props: any) => R.createElement(RN.Text, null, props.children),@@ -145,19 +163,27 @@ jest.mock("../../components", () => {))),- FormatSelector: (props: any) =>+ ListItem: ({ label, sub, testID, onPress }: any) =>R.createElement(- RN.View,- null,- EXPORT_FORMAT_KEYS.map((key: any) =>- R.createElement(- RN.Pressable,- { key, onPress: () => props.onSelectFormat(key), testID: `format-${key}` },- R.createElement(RN.Text, null, EXPORT_FORMATS[key].label),- R.createElement(RN.Text, null, EXPORT_FORMATS[key].extension)- )- )+ RN.Pressable,+ { testID, onPress },+ R.createElement(RN.Text, null, label),+ R.createElement(RN.Text, null, sub)),+ ExportFormatDialog: (props: any) =>+ props.visible+ ? R.createElement(+ RN.View,+ null,+ EXPORT_FORMAT_KEYS.map((key: any) =>+ R.createElement(+ RN.Pressable,+ { key, onPress: () => props.onSelect(key), testID: `format-${key}` },+ R.createElement(RN.Text, null, EXPORT_FORMATS[key].label)+ )+ )+ )+ : null,FloatingSaveIndicator: () => null,SettingRow: (props: any) =>R.createElement(@@ -206,9 +232,9 @@ jest.mock("lucide-react-native", () => {const stub = (name: any) => () => R.createElement(RN.Text, null, name)return {FolderOpen: stub("FolderOpen"),- CheckCircle: stub("CheckCircle"),+ CircleCheckBig: stub("CircleCheckBig"),Share2: stub("Share2"),- AlertTriangle: stub("AlertTriangle")+ TriangleAlert: stub("TriangleAlert")}})@@ -251,15 +277,17 @@ describe("AutoExportScreen", () => {})})- it("renders all format options", async () => {- const { getByText } = render(<AutoExportScreen {...mockProps} />)+ it("names the stored format on the row, and offers the rest in the shared dialog", async () => {+ const { getByText, getByTestId } = render(<AutoExportScreen {...mockProps} />)- await waitFor(() => {- expect(getByText("CSV")).toBeTruthy()- expect(getByText("GeoJSON")).toBeTruthy()- expect(getByText("GPX")).toBeTruthy()- expect(getByText("KML")).toBeTruthy()- })+ await waitFor(() => expect(getByTestId("auto-export-format")).toBeTruthy())+ expect(getByText("GeoJSON")).toBeTruthy()++ fireEvent.press(getByTestId("auto-export-format"))++ expect(getByTestId("format-csv")).toBeTruthy()+ expect(getByTestId("format-gpx")).toBeTruthy()+ expect(getByTestId("format-kml")).toBeTruthy()})it("renders all interval options including monthly", async () => {@@ -378,10 +406,10 @@ describe("AutoExportScreen", () => {const { getByText } = render(<AutoExportScreen {...mockProps} />)await waitFor(() => {- expect(getByText("Select Directory")).toBeTruthy()+ expect(getByText("Select directory")).toBeTruthy()})- fireEvent.press(getByText("Select Directory"))+ fireEvent.press(getByText("Select directory"))await waitFor(() => {expect(mockPickExportDirectory).toHaveBeenCalled()@@ -389,13 +417,12 @@ describe("AutoExportScreen", () => {})it("changing format saves the setting", async () => {- const { getByText } = render(<AutoExportScreen {...mockProps} />)+ const { getByTestId } = render(<AutoExportScreen {...mockProps} />)- await waitFor(() => {- expect(getByText("CSV")).toBeTruthy()- })+ await waitFor(() => expect(getByTestId("auto-export-format")).toBeTruthy())+ fireEvent.press(getByTestId("auto-export-format"))- fireEvent.press(getByText("CSV"))+ fireEvent.press(getByTestId("format-csv"))await waitFor(() => {expect(mockSaveSetting).toHaveBeenCalledWith("autoExportFormat", "csv")@@ -442,8 +469,8 @@ describe("AutoExportScreen", () => {const { getByText } = render(<AutoExportScreen {...mockProps} />)await waitFor(() => {- expect(getByText("Next Export")).toBeTruthy()- expect(getByText("Export Files")).toBeTruthy()+ expect(getByText("Next export")).toBeTruthy()+ expect(getByText("Export files")).toBeTruthy()expect(getByText("3")).toBeTruthy()})})@@ -463,8 +490,8 @@ describe("AutoExportScreen", () => {const { queryByText, getByText } = render(<AutoExportScreen {...mockProps} />)await waitFor(() => {- expect(queryByText("Next Export")).toBeNull()- expect(getByText("Export Files")).toBeTruthy()+ expect(queryByText("Next export")).toBeNull()+ expect(getByText("Export files")).toBeTruthy()})})@@ -622,7 +649,7 @@ describe("AutoExportScreen", () => {const { getByText } = render(<AutoExportScreen {...mockProps} />)await waitFor(() => {- expect(getByText("Export Now")).toBeTruthy()+ expect(getByText("Export now")).toBeTruthy()})})@@ -630,7 +657,7 @@ describe("AutoExportScreen", () => {const { queryByText } = render(<AutoExportScreen {...mockProps} />)await waitFor(() => {- expect(queryByText("Export Now")).toBeNull()+ expect(queryByText("Export now")).toBeNull()})})@@ -649,18 +676,95 @@ describe("AutoExportScreen", () => {const { getByText } = render(<AutoExportScreen {...mockProps} />)await waitFor(() => {- expect(getByText("Export Now")).toBeTruthy()+ expect(getByText("Export now")).toBeTruthy()})- fireEvent.press(getByText("Export Now"))+ fireEvent.press(getByText("Export now"))await waitFor(() => {expect(mockRunAutoExportNow).toHaveBeenCalled()- expect(mockShowAlert).toHaveBeenCalledWith(- "Export Started",- "Export is running in the background. The status will update when complete.",- "info"- )+ })+ })++ it("shows the export as running when the screen opens mid-run", async () => {+ // The line is component state, so returning to the screen while the worker is still going+ // would have shown nothing; the status map carries the worker's own flag for that.+ mockGetAutoExportStatus.mockResolvedValue({+ enabled: true,+ running: true,+ uri: "content://some-uri",+ mode: "all",+ lastExportTimestamp: 0,+ nextExportTimestamp: 0,+ fileCount: 0+ })++ const { getByTestId } = render(<AutoExportScreen {...mockProps} />)++ await waitFor(() => {+ expect(getByTestId("export-running")).toBeTruthy()+ })+ })++ it("says so when a manual export found nothing new", async () => {+ // The worker reports a zero-row run with no filename, which read as "Exported 0 locations to+ // null" before.+ mockGetAutoExportStatus.mockResolvedValue({+ enabled: true,+ uri: "content://some-uri",+ mode: "incremental",+ lastExportTimestamp: 0,+ nextExportTimestamp: 0,+ fileCount: 0+ })++ render(<AutoExportScreen {...mockProps} />)+ await waitFor(() => expect(mockGetAutoExportStatus).toHaveBeenCalled())++ act(() => {+ DeviceEventEmitter.emit("onAutoExportComplete", { success: true, fileName: null, rowCount: 0, error: null })+ })++ await waitFor(() => {+ expect(mockShowAlert).toHaveBeenCalledWith("Export Complete", "No new locations to export.", "success")+ })+ })++ it("keeps saying the export is running until the worker reports back", async () => {+ // runAutoExportNow only enqueues, so the button's own spinner lasts about a frame while a+ // real export runs for minutes. Nothing on the screen said the work was still going.+ mockGetAutoExportStatus.mockResolvedValue({+ enabled: true,+ uri: "content://some-uri",+ mode: "all",+ lastExportTimestamp: 0,+ nextExportTimestamp: 0,+ fileCount: 0+ })++ const { getByText, getByTestId, queryByTestId } = render(<AutoExportScreen {...mockProps} />)++ await waitFor(() => {+ expect(getByText("Export now")).toBeTruthy()+ })+ expect(queryByTestId("export-running")).toBeNull()++ fireEvent.press(getByText("Export now"))+ await waitFor(() => {+ expect(getByTestId("export-running")).toBeTruthy()+ })++ act(() => {+ DeviceEventEmitter.emit("onAutoExportComplete", {+ success: true,+ fileName: "colota-2026-09-06.geojson",+ rowCount: 12,+ error: null+ })+ })++ await waitFor(() => {+ expect(queryByTestId("export-running")).toBeNull()})})@@ -702,9 +806,9 @@ describe("AutoExportScreen", () => {const { getByText } = render(<AutoExportScreen {...mockProps} />)await waitFor(() => {- expect(getByText("Last File")).toBeTruthy()+ expect(getByText("Last file")).toBeTruthy()expect(getByText("colota_export_2026-03-10_1200.geojson")).toBeTruthy()- expect(getByText("Locations Exported")).toBeTruthy()+ expect(getByText("Locations exported")).toBeTruthy()expect(getByText("42")).toBeTruthy()})})@@ -741,7 +845,7 @@ describe("AutoExportScreen", () => {const { getByText } = render(<AutoExportScreen {...mockProps} />)await waitFor(() => {- expect(getByText("Export History")).toBeTruthy()+ expect(getByText("Export history")).toBeTruthy()expect(getByText("colota_export_2026-03-10.geojson")).toBeTruthy()expect(getByText("colota_export_2026-03-09.geojson")).toBeTruthy()})@@ -753,7 +857,7 @@ describe("AutoExportScreen", () => {const { queryByText } = render(<AutoExportScreen {...mockProps} />)await waitFor(() => {- expect(queryByText("Export History")).toBeNull()+ expect(queryByText("Export history")).toBeNull()})})diff --git a/apps/mobile/src/screens/__tests__/ExportImportScreen.test.tsx b/apps/mobile/src/screens/__tests__/ExportImportScreen.test.tsxnew file mode 100644index 00000000..8a983cc3--- /dev/null+++ b/apps/mobile/src/screens/__tests__/ExportImportScreen.test.tsx@@ -0,0 +1,370 @@+import React from "react"+import { render, fireEvent, waitFor, act } from "@testing-library/react-native"+import { DeviceEventEmitter } from "react-native"++let mockRefocus: (() => void) | null = null+jest.mock("@react-navigation/native", () => ({+ useFocusEffect: (cb: () => (() => void) | void) => {+ const R = require("react")+ R.useEffect(() => {+ let cleanup = cb()+ mockRefocus = () => {+ if (typeof cleanup === "function") cleanup()+ cleanup = cb()+ }+ return () => {+ if (typeof cleanup === "function") cleanup()+ mockRefocus = null+ }+ }, [cb])+ }+}))++jest.mock("../../hooks/useTheme", () => ({+ useTheme: () => ({ colors: require("@colota/shared").lightColors })+}))++const mockGetStats = jest.fn()+const mockGetAutoExportStatus = jest.fn()+const mockExportToFile = jest.fn()+const mockShareFile = jest.fn()++// Every method on the real service is a static opening with `this.ensureModule()`, so a callback+// handed over unbound throws before it reaches native. The double loses its receiver the same way.+jest.mock("../../services/NativeLocationService", () => {+ const service: Record<string, unknown> = {}+ const onReceiver = (impl: (...a: unknown[]) => unknown) =>+ function (this: unknown, ...a: unknown[]) {+ if (this !== service) throw new TypeError("undefined is not a function")+ return impl(...a)+ }+ Object.assign(service, {+ getStats: onReceiver((...a) => mockGetStats(...a)),+ getAutoExportStatus: onReceiver((...a) => mockGetAutoExportStatus(...a)),+ exportToFile: onReceiver((...a) => mockExportToFile(...a)),+ shareFile: onReceiver((...a) => mockShareFile(...a))+ })+ return { __esModule: true, default: service }+})++const mockPickImportSource = jest.fn()+const mockImportLocationsFromFile = jest.fn()+const mockCommitImport = jest.fn()+const mockCancelImport = jest.fn()+jest.mock("../../services/ImportService", () => ({+ __esModule: true,+ default: {+ pickImportSource: (...a: unknown[]) => mockPickImportSource(...a),+ importLocationsFromFile: (...a: unknown[]) => mockImportLocationsFromFile(...a),+ commitImport: (...a: unknown[]) => mockCommitImport(...a),+ cancelImport: (...a: unknown[]) => mockCancelImport(...a)+ }+}))++const mockShowConfirm = jest.fn()+const mockShowAlert = jest.fn()+jest.mock("../../services/modalService", () => ({+ showConfirm: (...a: unknown[]) => mockShowConfirm(...a),+ showAlert: (...a: unknown[]) => mockShowAlert(...a)+}))++jest.mock("../../utils/logger", () => ({ logger: { error: jest.fn(), warn: jest.fn(), debug: jest.fn() } }))++jest.mock("../../components", () => {+ const R = require("react")+ const { View, Text, Pressable } = require("react-native")+ return {+ 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),+ StatRow: ({ label, value, testID }: any) =>+ R.createElement(View, { testID }, R.createElement(Text, null, label), R.createElement(Text, null, value)),+ StateLine: ({ label, caption, testID }: any) =>+ R.createElement(View, { testID }, R.createElement(Text, null, label), R.createElement(Text, null, caption)),+ FieldMessage: ({ children, variant }: any) =>+ R.createElement(Text, { accessibilityValue: { text: variant ?? "info" } }, children),+ SettingRow: ({ label, hint, children }: any) =>+ R.createElement(View, null, R.createElement(Text, null, label), R.createElement(Text, null, hint), children),+ Toggle: ({ value, onValueChange, testID }: any) =>+ R.createElement(Pressable, { testID, onPress: () => onValueChange(!value) }),+ ListItem: ({ label, sub, testID, onPress }: any) =>+ R.createElement(+ Pressable,+ { testID, onPress },+ R.createElement(Text, null, label),+ R.createElement(Text, null, sub)+ ),+ Button: ({ title, onPress, disabled, testID, loading }: any) =>+ R.createElement(+ Pressable,+ { testID, onPress, disabled, accessibilityState: { disabled: !!disabled, busy: !!loading } },+ R.createElement(Text, null, title)+ ),+ LoadingOverlay: ({ visible, title }: any) => (visible ? R.createElement(Text, null, title) : null),+ ExportFormatDialog: ({ visible, onSelect }: any) =>+ visible+ ? R.createElement(+ Pressable,+ { testID: "pick-geojson", onPress: () => onSelect("geojson") },+ R.createElement(Text, null, "Export format")+ )+ : null+ }+})++import { ExportImportScreen } from "../ExportImportScreen"++const stats = (over: Record<string, number> = {}) => ({ total: 12483, databaseSizeMB: 3.42, ...over })++const auto = (over: Record<string, unknown> = {}) => ({+ enabled: true,+ running: false,+ format: "geojson",+ interval: "daily",+ uri: "content://tree",+ lastError: null,+ retentionCount: 10,+ ...over+})++const preview = (over: Record<string, unknown> = {}) => ({+ format: "geojson",+ totalParsed: 15908,+ invalid: 12,+ duplicates: 12415,+ newRows: 3481,+ dateRangeStartSec: 1552348800,+ dateRangeEndSec: 1788854400,+ canQueueForSync: true,+ ...over+})++const mockNavigation = { navigate: jest.fn(), setOptions: jest.fn(), goBack: jest.fn() }++const renderScreen = () => render(<ExportImportScreen navigation={mockNavigation as any} />)++const stage = async (api: ReturnType<typeof renderScreen>, over: Record<string, unknown> = {}) => {+ mockPickImportSource.mockResolvedValue({ uri: "content://file" })+ mockImportLocationsFromFile.mockResolvedValue(preview(over))+ fireEvent.press(api.getByTestId("import-file-btn"))+ await waitFor(() => expect(mockImportLocationsFromFile).toHaveBeenCalled())+}++beforeEach(() => {+ jest.clearAllMocks()+ mockGetStats.mockResolvedValue(stats())+ mockGetAutoExportStatus.mockResolvedValue(auto())+ mockShowConfirm.mockResolvedValue(true)+ mockCancelImport.mockResolvedValue(undefined)+ mockCommitImport.mockResolvedValue(3481)+ mockExportToFile.mockResolvedValue({+ filePath: "/cache/x.geojson",+ mimeType: "application/geo+json",+ rowCount: 12483+ })+ mockShareFile.mockResolvedValue(undefined)+})++describe("ExportImportScreen", () => {+ describe("what it says before anything is touched", () => {+ it("opens with the ledger and both verbs, and stages nothing", async () => {+ const api = renderScreen()++ expect(await api.findByText("12,483")).toBeTruthy()+ expect(api.getByText("3.42 MB")).toBeTruthy()+ expect(api.getByTestId("export-all-btn")).toBeTruthy()+ expect(api.getByTestId("import-file-btn")).toBeTruthy()+ expect(api.queryByTestId("import-commit-btn")).toBeNull()+ expect(mockPickImportSource).not.toHaveBeenCalled()+ })++ it("does not report an empty device while the first read is still running", async () => {+ mockGetStats.mockReturnValue(new Promise(() => {}))+ const api = renderScreen()++ // Both figures wait, rather than one of them claiming zero.+ expect(api.getAllByText("…")).toHaveLength(2)+ expect(api.queryByText("Nothing to export yet.")).toBeNull()+ })++ // The import half has no format control, so the sentence saying so has to be unconditionally true.+ it("offers no format control for an import", async () => {+ const api = renderScreen()+ await api.findByText("12,483")++ expect(api.getByText(/there is nothing to choose/)).toBeTruthy()+ })++ it("carries the auto-export state on the row that opens it", async () => {+ const api = renderScreen()++ expect(await api.findByText("Daily · GeoJSON · 10 files kept")).toBeTruthy()+ })++ it("disables the export with nothing to export, and says so", async () => {+ mockGetStats.mockResolvedValue(stats({ total: 0 }))+ const api = renderScreen()++ expect(await api.findByText("Nothing to export yet.")).toBeTruthy()+ expect(api.getByTestId("export-all-btn").props.accessibilityState.disabled).toBe(true)+ })+ })++ describe("export", () => {+ it("picks a format, writes the file and reports what went", async () => {+ const api = renderScreen()+ await api.findByText("12,483")++ fireEvent.press(api.getByTestId("export-all-btn"))+ fireEvent.press(api.getByTestId("pick-geojson"))++ await waitFor(() => expect(mockExportToFile).toHaveBeenCalledWith("geojson"))+ expect(await api.findByText("Exported 12,483 locations as GeoJSON and handed the file over.")).toBeTruthy()+ })++ // The share was caught and logged, so a hand-off that never happened looked like a success.+ it("says the file was written but nothing took it", async () => {+ mockShareFile.mockRejectedValue(new Error("no activity"))+ const api = renderScreen()+ await api.findByText("12,483")++ fireEvent.press(api.getByTestId("export-all-btn"))+ fireEvent.press(api.getByTestId("pick-geojson"))++ const line = await api.findByText(/no app took it/)+ expect(line.props.accessibilityValue.text).toBe("error")+ })+ })++ describe("import", () => {+ it("stages a file as a count and one line for what it skips", async () => {+ const api = renderScreen()+ await api.findByText("12,483")++ await stage(api)++ expect(await api.findByText("3,481 new locations")).toBeTruthy()+ expect(api.getByText("Skipping 12,415 duplicates and 12 unusable rows.")).toBeTruthy()+ expect(api.getByTestId("import-commit-btn")).toBeTruthy()+ expect(api.queryByTestId("import-file-btn")).toBeNull()+ })++ // The reasoning moved off the card into the confirmation, so it has to actually arrive there.+ it("puts the consequences in the confirmation, not on the card", async () => {+ const api = renderScreen()+ await api.findByText("12,483")+ await stage(api)++ fireEvent.press(api.getByTestId("import-commit-btn"))++ await waitFor(() =>+ expect(mockShowConfirm).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Import 3,481 locations?",+ message: expect.stringContaining("skipped rather than merged"),+ destructive: false+ })+ )+ )+ expect(mockCommitImport).toHaveBeenCalledWith(false)+ })++ it("carries the queue choice into the commit and the confirmation", async () => {+ const api = renderScreen()+ await api.findByText("12,483")+ await stage(api)++ fireEvent.press(api.getByTestId("queue-toggle"))+ fireEvent.press(api.getByTestId("import-commit-btn"))++ await waitFor(() => expect(mockCommitImport).toHaveBeenCalledWith(true))+ expect(mockShowConfirm).toHaveBeenCalledWith(expect.objectContaining({ confirmText: "Import and queue" }))+ })++ it("commits nothing when the confirmation is dismissed", async () => {+ mockShowConfirm.mockResolvedValue(false)+ const api = renderScreen()+ await api.findByText("12,483")+ await stage(api)++ fireEvent.press(api.getByTestId("import-commit-btn"))++ await waitFor(() => expect(mockShowConfirm).toHaveBeenCalled())+ expect(mockCommitImport).not.toHaveBeenCalled()+ })++ it("hides the queue switch when there is no server to queue to", async () => {+ const api = renderScreen()+ await api.findByText("12,483")++ await stage(api, { canQueueForSync: false })++ expect(await api.findByText("3,481 new locations")).toBeTruthy()+ expect(api.queryByTestId("queue-toggle")).toBeNull()+ })++ // Three reasons that all read as "no locations were found" before.+ it("separates an empty file from one whose rows were all unusable", async () => {+ const api = renderScreen()+ await api.findByText("12,483")++ await stage(api, { newRows: 0, totalParsed: 0, invalid: 12004, duplicates: 0 })++ expect(await api.findByText(/12,004 rows had no usable time or coordinates/)).toBeTruthy()+ expect(api.queryByTestId("import-commit-btn")).toBeNull()+ })++ it("frees the native stash when the file is discarded", async () => {+ const api = renderScreen()+ await api.findByText("12,483")+ await stage(api)++ fireEvent.press(api.getByTestId("import-discard-btn"))++ await waitFor(() => expect(mockCancelImport).toHaveBeenCalled())+ expect(api.getByTestId("import-file-btn")).toBeTruthy()+ })++ // The stash sits in native memory on a 15 minute timer, so leaving the screen has to free it.+ it("frees the native stash when the screen goes", async () => {+ const api = renderScreen()+ await api.findByText("12,483")+ await stage(api)++ api.unmount()++ expect(mockCancelImport).toHaveBeenCalled()+ })++ it("says why a file could not be read, in the scope the lock actually has", async () => {+ mockPickImportSource.mockResolvedValue({ uri: "content://file" })+ mockImportLocationsFromFile.mockRejectedValue({ code: "E_BUSY" })+ const api = renderScreen()+ await api.findByText("12,483")++ fireEvent.press(api.getByTestId("import-file-btn"))++ expect(await api.findByText("Another import is already running.")).toBeTruthy()+ })+ })++ it("re-reads the ledger on focus and on a new fix", async () => {+ const api = renderScreen()+ await api.findByText("12,483")++ mockGetStats.mockResolvedValue(stats({ total: 12500 }))+ act(() => {+ DeviceEventEmitter.emit("onLocationUpdate", {})+ })++ expect(await api.findByText("12,500")).toBeTruthy()++ mockGetStats.mockResolvedValue(stats({ total: 12600 }))+ await act(async () => {+ mockRefocus?.()+ })++ expect(await api.findByText("12,600")).toBeTruthy()+ })+})diff --git a/apps/mobile/src/screens/__tests__/ExportLocationsScreen.test.tsx b/apps/mobile/src/screens/__tests__/ExportLocationsScreen.test.tsxdeleted file mode 100644index dc4a913c..00000000--- a/apps/mobile/src/screens/__tests__/ExportLocationsScreen.test.tsx+++ /dev/null@@ -1,307 +0,0 @@-import React from "react"-import { render, fireEvent, waitFor } from "@testing-library/react-native"--// --- Mocks -----jest.mock("../../hooks/useTheme", () => ({- useTheme: () => ({- colors: {- primary: "#0d9488",- primaryDark: "#115E59",- text: "#000",- textSecondary: "#6b7280",- textLight: "#9ca3af",- card: "#fff",- border: "#e5e7eb",- background: "#fff",- backgroundElevated: "#f9fafb",- success: "#22c55e",- warning: "#f59e0b",- info: "#3b82f6",- error: "#ef4444",- placeholder: "#9ca3af",- textOnPrimary: "#fff",- overlay: "rgba(0,0,0,0.5)"- }- })-}))--const mockGetStats = jest.fn().mockResolvedValue({ total: 100 })-const mockExportToFile = jest.fn().mockResolvedValue({- filePath: "/path/file.csv",- mimeType: "text/csv",- rowCount: 100-})-const mockShareFile = jest.fn().mockResolvedValue(undefined)--jest.mock("../../services/NativeLocationService", () => ({- __esModule: true,- default: {- getStats: function () {- return mockGetStats.apply(null, arguments)- },- exportToFile: function () {- return mockExportToFile.apply(null, arguments)- },- shareFile: function () {- return mockShareFile.apply(null, arguments)- },- getAutoExportStatus: jest.fn().mockResolvedValue({- enabled: false,- format: "geojson",- interval: "daily",- uri: null,- mode: "all",- lastExportTimestamp: 0,- nextExportTimestamp: 0,- fileCount: 0,- retentionCount: 10- })- }-}))--const mockShowAlert = jest.fn()-const mockShowConfirm = jest.fn().mockResolvedValue(true)--jest.mock("../../services/modalService", () => ({- showAlert: function () {- return mockShowAlert.apply(null, arguments)- },- showConfirm: function () {- return mockShowConfirm.apply(null, arguments)- }-}))--jest.mock("../../utils/exportConverters", () => ({- EXPORT_FORMATS: {- csv: {- label: "CSV",- subtitle: "Spreadsheet Format",- description: "Excel, Google Sheets, data analysis",- icon: function () {- return null- },- extension: ".csv",- mimeType: "text/csv"- },- geojson: {- label: "GeoJSON",- subtitle: "Geographic Data",- description: "Mapbox, Leaflet, QGIS, ArcGIS",- icon: function () {- return null- },- extension: ".geojson",- mimeType: "application/json"- },- gpx: {- label: "GPX",- subtitle: "GPS Exchange",- description: "Garmin, Strava, Google Earth",- icon: function () {- return null- },- extension: ".gpx",- mimeType: "application/gpx+xml"- },- kml: {- label: "KML",- subtitle: "Keyhole Markup Language",- description: "Google Earth, Google Maps, ArcGIS",- icon: function () {- return null- },- extension: ".kml",- mimeType: "application/vnd.google-earth.kml+xml"- }- }-}))--jest.mock("../../utils/logger", () => ({- logger: { error: jest.fn(), warn: jest.fn() }-}))--jest.mock("../../components", () => {- const R = require("react")- const RN = require("react-native")- const { EXPORT_FORMATS } = require("../../utils/exportConverters")- return {- Container: function (props: any) {- return R.createElement(RN.View, null, props.children)- },- Card: function (props: any) {- return R.createElement(RN.View, null, props.children)- },- SectionTitle: function (props: any) {- return R.createElement(RN.Text, null, props.children)- },- Divider: function () {- return R.createElement(RN.View, null)- },- Button: function (props: any) {- return R.createElement(- RN.Pressable,- { onPress: props.onPress, disabled: props.disabled, accessibilityRole: "button" },- R.createElement(RN.Text, null, props.title)- )- },- FormatSelector: function ({ onSelectFormat }: any) {- return R.createElement(- RN.View,- null,- Object.entries(EXPORT_FORMATS).map(function ([key, config]: any) {- return R.createElement(- RN.Pressable,- {- key: key,- onPress: function () {- onSelectFormat(key)- }- },- R.createElement(RN.Text, null, config.label)- )- })- )- },- LoadingOverlay: function (props: any) {- if (!props.visible) return null- return R.createElement(- RN.View,- { testID: "loading-overlay" },- R.createElement(RN.Text, null, props.title),- props.message ? R.createElement(RN.Text, null, props.message) : null- )- }- }-})--jest.mock("lucide-react-native", () => {- const R = require("react")- const RN = require("react-native")- function stub(name: any) {- return function () {- return R.createElement(RN.Text, null, name)- }- }- return {- Download: stub("Download"),- MapPinOff: stub("MapPinOff"),- ChevronRight: stub("ChevronRight"),- Clock: stub("Clock"),- Table2: stub("Table2"),- Globe: stub("Globe"),- MapPin: stub("MapPin"),- Earth: stub("Earth")- }-})--import { ExportLocationsScreen } from "../ExportLocationsScreen"--describe("ExportLocationsScreen", () => {- beforeEach(() => {- jest.clearAllMocks()- mockGetStats.mockResolvedValue({ total: 100 })- mockExportToFile.mockResolvedValue({- filePath: "/path/file.csv",- mimeType: "text/csv",- rowCount: 100- })- })-- const mockNavigation = { navigate: jest.fn() } as any-- function renderScreen() {- return render(<ExportLocationsScreen navigation={mockNavigation} />)- }-- it("renders the format selector", async () => {- // The "Export Locations" page title lives in the navigation header, not the screen- // body, so this smoke test asserts on the SectionTitle that anchors the page content.- const { getByText } = renderScreen()-- await waitFor(() => {- expect(getByText("Select Format")).toBeTruthy()- })- })-- it("shows empty state when no locations", async () => {- mockGetStats.mockResolvedValue({ total: 0 })-- const { getByText } = renderScreen()-- await waitFor(() => {- expect(getByText("No Locations")).toBeTruthy()- expect(getByText("Start tracking to record locations that can be exported.")).toBeTruthy()- })- })-- it("shows total location count", async () => {- const { getByText } = renderScreen()-- await waitFor(() => {- expect(getByText("Total Locations")).toBeTruthy()- expect(getByText("100")).toBeTruthy()- })- })-- it("renders all format options", async () => {- const { getByText } = renderScreen()-- await waitFor(() => {- expect(getByText("CSV")).toBeTruthy()- expect(getByText("GeoJSON")).toBeTruthy()- expect(getByText("GPX")).toBeTruthy()- expect(getByText("KML")).toBeTruthy()- })- })-- it("selecting a format shows the export button", async () => {- const { getByText } = renderScreen()-- await waitFor(() => {- expect(getByText("CSV")).toBeTruthy()- })-- fireEvent.press(getByText("CSV"))-- await waitFor(() => {- expect(getByText("Export CSV")).toBeTruthy()- })- })-- it("shows loading overlay during export", async () => {- // Make exportToFile hang so we can observe the loading state- mockExportToFile.mockImplementation(() => new Promise(() => {}))-- const { getByText } = renderScreen()-- await waitFor(() => {- expect(getByText("CSV")).toBeTruthy()- })-- fireEvent.press(getByText("CSV"))-- await waitFor(() => {- expect(getByText("Export CSV")).toBeTruthy()- })-- fireEvent.press(getByText("Export CSV"))-- await waitFor(() => {- expect(getByText("Exporting Data")).toBeTruthy()- })- })-- it("shows alert when exporting with no data", async () => {- mockGetStats.mockResolvedValue({ total: 0 })-- const { getByText, queryByText } = renderScreen()-- await waitFor(() => {- expect(getByText("No Locations")).toBeTruthy()- })-- // totalLocations is 0 so the format cards are not rendered and no export button exists- expect(queryByText("CSV")).toBeNull()- })-})diff --git a/apps/mobile/src/screens/index.ts b/apps/mobile/src/screens/index.tsindex 65760100..7f54a9ca 100644--- a/apps/mobile/src/screens/index.ts+++ b/apps/mobile/src/screens/index.ts@@ -10,8 +10,6 @@ export { AuthSettingsScreen } from "./AuthSettingsScreen"export { MtlsSettingsScreen } from "./MtlsSettingsScreen"export { DashboardScreen } from "./DashboardScreen"export { DataManagementScreen } from "./DataManagementScreen"-export { ExportLocationsScreen } from "./ExportLocationsScreen"-export { ImportLocationsScreen } from "./ImportLocationsScreen"export { GeofenceScreen } from "./GeofenceScreen"export { GeofenceEditorScreen } from "./GeofenceEditorScreen"export { LocationHistoryScreen } from "./LocationInspectorScreen"@@ -30,3 +28,4 @@ export { OfflineMapsScreen } from "./OfflineMapsScreen"export { BackupRestoreScreen } from "./BackupRestoreScreen"export { BackendTemplateScreen } from "./BackendTemplateScreen"export { PlaceZoneScreen } from "./PlaceZoneScreen"+export { ExportImportScreen } from "./ExportImportScreen"diff --git a/apps/mobile/src/types/navigation.ts b/apps/mobile/src/types/navigation.tsindex bf70ef57..93508c21 100644--- a/apps/mobile/src/types/navigation.ts+++ b/apps/mobile/src/types/navigation.ts@@ -24,8 +24,7 @@ export type RootStackParamList = {"Place Zone": { name: string; radius: number; lat?: number; lon?: number }"Location History": { initialTab?: InspectorTab; initialDate?: string } | undefined"Location Summary": undefined- "Export Locations": undefined- "Import Locations": undefined+ "Export & Import": undefined"Auto-Export": undefined"Data Management": undefined"Tracking Profiles": undefineddiff --git a/apps/mobile/src/utils/__tests__/exportConverters.test.ts b/apps/mobile/src/utils/__tests__/exportConverters.test.tsindex 4e2183cb..f4e5a7da 100644--- a/apps/mobile/src/utils/__tests__/exportConverters.test.ts+++ b/apps/mobile/src/utils/__tests__/exportConverters.test.ts@@ -40,7 +40,6 @@ describe("export format registry", () => {expect(exportable).toEqual([...EXPORT_FORMAT_KEYS].sort())EXPORT_FORMAT_KEYS.forEach((key) => {expect(EXPORT_FORMATS[key].mimeType).toBeTruthy()- expect(EXPORT_FORMATS[key].subtitle).toBeTruthy()})})})diff --git a/apps/mobile/src/utils/__tests__/locationTransfer.test.ts b/apps/mobile/src/utils/__tests__/locationTransfer.test.tsnew file mode 100644index 00000000..fbcd255f--- /dev/null+++ b/apps/mobile/src/utils/__tests__/locationTransfer.test.ts@@ -0,0 +1,238 @@+import type { ImportPreview } from "../../services/ImportService"+import { FILE_FORMATS, IMPORT_FORMAT_ORDER } from "../fileFormats"+import { formatDateWithYear } from "../geo"+import {+ autoExportSub,+ backupFirstSub,+ commitConfirm,+ commitLabel,+ emptyPreviewCopy,+ exportLine,+ exportResultLine,+ importErrorMessage,+ importSourceLine,+ previewHeadline,+ queueHint,+ readableFormats,+ skippedLine,+ transferRowSub+} from "../locationTransfer"++const START = 1552348800+const END = 1788854400++const preview = (over: Partial<ImportPreview> = {}): ImportPreview => ({+ format: "geojson",+ totalParsed: 15908,+ invalid: 12,+ duplicates: 12415,+ newRows: 3481,+ dateRangeStartSec: START,+ dateRangeEndSec: END,+ canQueueForSync: true,+ ...over+})++const auto = (over: Record<string, unknown> = {}) => ({+ enabled: true,+ running: false,+ format: "geojson",+ interval: "daily",+ uri: "content://tree/Documents%2FColota",+ lastError: null as string | null,+ retentionCount: 10,+ ...over+})++describe("readableFormats", () => {+ it("comes from the shared table, so a new format lands without touching a screen", () => {+ expect(readableFormats()).toBe("GeoJSON, GPX, KML, Google Timeline, CSV")+ })++ it("folds the legacy Timeline parser into its sibling rather than naming one noun twice", () => {+ expect(IMPORT_FORMAT_ORDER).toContain("google_timeline_legacy")+ expect(FILE_FORMATS.google_timeline_legacy.label).toBe("Google Timeline (legacy)")+ expect(readableFormats().match(/Google Timeline/g)).toHaveLength(1)+ })+})++describe("exportLine", () => {+ it("names the scope and says the file is handed over, never saved", () => {+ const line = exportLine(12483)+ expect(line).toContain("All 12,483 locations in one file, oldest first.")+ expect(line).toContain("is not kept here")+ expect(line).not.toMatch(/saved/i)+ })++ it("has a line for an empty database instead of a whole empty screen", () => {+ expect(exportLine(0)).toBe("Nothing to export yet.")+ })++ it("reports the format the run actually wrote", () => {+ expect(exportResultLine(12483, "gpx")).toBe("Exported 12,483 locations as GPX and handed the file over.")+ })+})++describe("importSourceLine", () => {+ it("says the format is not a choice, because the parser decides from the file", () => {+ const line = importSourceLine()+ expect(line).toContain("The format is read from the file, so there is nothing to choose.")+ })++ // The CSV caveat is the one thing a user has to prepare by hand, so it comes from the table+ // verbatim rather than being rewritten here.+ it("carries the CSV header caveat from the shared table", () => {+ expect(importSourceLine()).toContain(FILE_FORMATS.csv.importHint as string)+ })+})++describe("backupFirstSub", () => {+ it("says the only way back is a restore, since the commit is INSERT-only", () => {+ expect(backupFirstSub()).toBe("An import cannot be undone. A backup is the only way back.")+ })+})++describe("previewHeadline", () => {+ it("leads with the number that decides the press, then where it came from", () => {+ expect(previewHeadline(preview())).toEqual({+ label: "3,481 new locations",+ caption: `GeoJSON · ${formatDateWithYear(START)} to ${formatDateWithYear(END)}`+ })+ })++ it("drops the span when the file carried no dates rather than printing a placeholder", () => {+ const { caption } = previewHeadline(preview({ dateRangeStartSec: null, dateRangeEndSec: null }))+ expect(caption).toBe("GeoJSON")+ })+})++describe("skippedLine", () => {+ it("folds both skip reasons into one sentence", () => {+ expect(skippedLine(preview())).toBe("Skipping 12,415 duplicates and 12 unusable rows.")+ })++ it("names only the reason that applies, and agrees with a count of one", () => {+ expect(skippedLine(preview({ invalid: 0 }))).toBe("Skipping 12,415 duplicates.")+ expect(skippedLine(preview({ duplicates: 0 }))).toBe("Skipping 12 unusable rows.")+ expect(skippedLine(preview({ duplicates: 1, invalid: 0 }))).toBe("Skipping 1 duplicate.")+ })++ // Three permanent counts made the card a ledger of zeroes. Nothing skipped means nothing said.+ it("says nothing when the import takes everything", () => {+ expect(skippedLine(preview({ duplicates: 0, invalid: 0 }))).toBeUndefined()+ })+})++describe("commitConfirm", () => {+ it("carries the reasoning the staged card no longer shows", () => {+ const copy = commitConfirm(preview(), false)+ expect(copy.title).toBe("Import 3,481 locations?")+ expect(copy.message).toContain("Nothing already stored is changed or removed.")+ expect(copy.message).toContain("skipped rather than merged")+ expect(copy.message).toContain("Recording pauses")+ expect(copy.confirmText).toBe("Import")+ })++ // sentFlag = 1 puts them in the exact bucket clearSentHistory empties.+ it("says a plain import lands in the bucket Delete synced locations takes", () => {+ expect(commitConfirm(preview(), false).message).toContain("Delete synced locations")+ })++ it("says the queued variant reaches a server that cannot be asked to give them back", () => {+ const copy = commitConfirm(preview(), true)+ expect(copy.title).toBe("Import and queue 3,481 locations?")+ expect(copy.message).toContain("cannot recall what your server has already taken")+ expect(copy.confirmText).toBe("Import and queue")+ })++ it("mentions rejected rows only when there were some", () => {+ expect(commitConfirm(preview(), false).message).toContain("no usable time or coordinates")+ expect(commitConfirm(preview({ invalid: 0 }), false).message).not.toContain("no usable time")+ })+})++describe("commitLabel", () => {+ it("carries the count on the button, both ways", () => {+ expect(commitLabel(3481, false)).toBe("Import 3,481 locations")+ expect(commitLabel(3481, true)).toBe("Import and queue 3,481")+ expect(commitLabel(1, false)).toBe("Import 1 location")+ })+})++describe("queueHint", () => {+ it("says where they go", () => {+ expect(queueHint(3481)).toBe("Sends 3,481 locations to your server too.")+ })+})++describe("emptyPreviewCopy", () => {+ // The shipped screen said "no locations were found" for all three of these.+ it("separates an empty file from a file of unusable rows", () => {+ expect(emptyPreviewCopy(preview({ totalParsed: 0, invalid: 0, duplicates: 0, newRows: 0 }))).toBe(+ "No locations were found in this file."+ )+ expect(emptyPreviewCopy(preview({ totalParsed: 0, invalid: 12004, duplicates: 0, newRows: 0 }))).toContain(+ "12,004 rows had no usable time or coordinates"+ )+ })++ it("says duplicates were counted against the file too, not only against history", () => {+ const line = emptyPreviewCopy(preview({ newRows: 0, duplicates: 3481 }))+ expect(line).toContain("counted both inside the file and against what is already stored")+ })+})++describe("importErrorMessage", () => {+ it("derives the format list rather than keeping a second copy, and names the DOCTYPE refusal", () => {+ const line = importErrorMessage("E_IMPORT_UNSUPPORTED")+ expect(line).toContain(readableFormats())+ expect(line).toContain("DOCTYPE")+ })++ // The old string claimed a lock over backup and restore that the import mutex does not hold.+ it("claims only the scope the import mutex actually has", () => {+ expect(importErrorMessage("E_BUSY")).toBe("Another import is already running.")+ })++ it("has a sentence for an expired stash and a fallback for anything else", () => {+ expect(importErrorMessage("E_IMPORT_NO_PENDING")).toContain("expired")+ expect(importErrorMessage(undefined)).toBe("The file could not be read.")+ })+})++describe("autoExportSub", () => {+ it("reports the schedule, the format and how many files survive", () => {+ expect(autoExportSub(auto())).toBe("Daily · GeoJSON · 10 files kept")+ })++ it("names a missing folder, which is what blocks the switch", () => {+ expect(autoExportSub(auto({ uri: null }))).toBe("No folder chosen")+ })++ // The worker turns the feature off and sets the flag, so "Off" alone hid the one real failure.+ it("tells a lost folder grant apart from the user turning it off", () => {+ expect(autoExportSub(auto({ enabled: false, lastError: "permission" }))).toBe("Stopped, folder access lost")+ expect(autoExportSub(auto({ enabled: false, lastError: null }))).toBe("Off")+ })++ it("says a run is in progress and carries a failed last run", () => {+ expect(autoExportSub(auto({ running: true }))).toBe("Export running")+ expect(autoExportSub(auto({ lastError: "Folder not writable" }))).toContain("last export failed")+ })+})++describe("transferRowSub", () => {+ // The auto-export row left the hub, so this row is the only place its failure can surface.+ it("carries the auto-export state when there is one", () => {+ // Only the first word is lowered, or the format name comes out as "geojson".+ expect(transferRowSub(auto())).toBe("Auto-export daily · GeoJSON · 10 files kept")+ expect(transferRowSub(auto({ enabled: false, lastError: "permission" }))).toBe(+ "Auto-export stopped, folder access lost"+ )+ })++ it("falls back to the nouns inside the screen when nothing is scheduled", () => {+ expect(transferRowSub(null)).toBe(`${readableFormats()} in, and out`)+ expect(transferRowSub(auto({ enabled: false, lastError: null }))).toContain("in, and out")+ })+})diff --git a/apps/mobile/src/utils/exportConverters.ts b/apps/mobile/src/utils/exportConverters.tsindex 5cbf46d4..79e3b424 100644--- a/apps/mobile/src/utils/exportConverters.ts+++ b/apps/mobile/src/utils/exportConverters.ts@@ -18,7 +18,6 @@ export const EXPORT_FORMAT_KEYS: ExportFormat[] = IMPORT_FORMAT_ORDER.filter(export interface ExportFormatConfig {label: string- subtitle: stringdescription: stringicon: LucideIconextension: string@@ -30,7 +29,6 @@ export const EXPORT_FORMATS: Record<ExportFormat, ExportFormatConfig> = EXPORT_Fconst f = FILE_FORMATS[key]acc[key] = {label: f.label,- subtitle: f.subtitle!,description: f.description,icon: f.icon,extension: f.extension,diff --git a/apps/mobile/src/utils/fileFormats.ts b/apps/mobile/src/utils/fileFormats.tsindex 23931e15..775fac26 100644--- a/apps/mobile/src/utils/fileFormats.ts+++ b/apps/mobile/src/utils/fileFormats.ts@@ -17,7 +17,6 @@ export interface FileFormat {extension: stringexportable: booleanmimeType?: string // present for every exportable format- subtitle?: string // export picker onlydescription: stringimportHint?: string}@@ -29,8 +28,8 @@ export const FILE_FORMATS: Record<ImportFormat, FileFormat> = {extension: ".geojson",exportable: true,mimeType: "application/geo+json",- subtitle: "Geographic Data",- description: "Mapbox, Leaflet, QGIS. Best for backups - re-imports into Colota without losing data."+ description:+ "QGIS, Mapbox, Leaflet. One point per recording, and the only format Colota re-imports without losing a field."},google_timeline_legacy: {label: "Google Timeline (legacy)",@@ -53,7 +52,6 @@ export const FILE_FORMATS: Record<ImportFormat, FileFormat> = {extension: ".gpx",exportable: true,mimeType: "application/gpx+xml",- subtitle: "GPS Exchange",description: "GPS Exchange Format - Garmin, Strava, sport watches, tracking apps."},kml: {@@ -62,7 +60,6 @@ export const FILE_FORMATS: Record<ImportFormat, FileFormat> = {extension: ".kml",exportable: true,mimeType: "application/vnd.google-earth.kml+xml",- subtitle: "Keyhole Markup Language",description: "Google Earth, Google Maps, ArcGIS.",importHint: "Only timestamped placemarks are read - LineString-only tracks are skipped."},@@ -72,16 +69,11 @@ export const FILE_FORMATS: Record<ImportFormat, FileFormat> = {extension: ".csv",exportable: true,mimeType: "text/csv",- subtitle: "Spreadsheet Format",description: "Comma-separated table - Excel, Google Sheets, data analysis.",importHint: "The header must include latitude, longitude and a time column."}}-export function importDescription(f: FileFormat): string {- return f.importHint ? `${f.description} ${f.importHint}` : f.description-}-export const IMPORT_FORMAT_ORDER: ImportFormat[] = ["geojson","gpx",diff --git a/apps/mobile/src/utils/locationTransfer.ts b/apps/mobile/src/utils/locationTransfer.tsnew file mode 100644index 00000000..b9c43eed--- /dev/null+++ b/apps/mobile/src/utils/locationTransfer.ts@@ -0,0 +1,174 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import type { ImportPreview } from "../services/ImportService"+import { FILE_FORMATS, IMPORT_FORMAT_ORDER } from "./fileFormats"+import { plural } from "./format"+import { formatDateWithYear } from "./geo"++/**+ * What moving locations across this device's file boundary takes and leaves, in the words the+ * controls and their confirmations use.+ *+ * The wording is pinned to what the code does, not to the old labels: an import is INSERT-only with+ * no unique constraint, so it adds and never merges and cannot be undone one point at a time; its+ * duplicate count covers both the file and what is stored; and an export writes to the cache and+ * hands the file to another app rather than saving it. A test pins every sentence without rendering.+ */++type AutoExportState = {+ enabled: boolean+ running: boolean+ format: string+ interval: string+ uri: string | null+ lastError: string | null+ retentionCount: number+}++const formatLabel = (format: string) => FILE_FORMATS[format as keyof typeof FILE_FORMATS]?.label ?? format.toUpperCase()++/** The formats a file can be read as, from the one table, with the legacy Timeline name folded in. */+export function readableFormats(): string {+ const labels = IMPORT_FORMAT_ORDER.map((format) => FILE_FORMATS[format].label.replace(" (legacy)", ""))+ return [...new Set(labels)].join(", ")+}++/** The line under the export button: the scope, and what happens to the file. */+export function exportLine(total: number): string {+ if (total === 0) return "Nothing to export yet."+ return `All ${plural(total, "location")} in one file, oldest first. The file goes to the app you pick and is not kept here.`+}++/** After a run. Nothing here claims the file was saved, because nothing saved it. */+export function exportResultLine(rowCount: number, format: string): string {+ return `Exported ${plural(rowCount, "location")} as ${formatLabel(format)} and handed the file over.`+}++/** A share the system never started. Logged and swallowed before, so it read as a success. */+export const SHARE_FAILED_LINE = "The file was written but no app took it. Try again and pick a different app."++/** The line under Choose a file. There is no format control, because the parser decides. */+export function importSourceLine(): string {+ return `Reads ${readableFormats()}. The format is read from the file, so there is nothing to choose. ${FILE_FORMATS.csv.importHint}`+}++/** The sub on the row above the import verb. The only route back is a whole-database restore. */+export function backupFirstSub(): string {+ return "An import cannot be undone. A backup is the only way back."+}++/** The staged file, as a state line: the number that matters, then what it came from and when. */+export function previewHeadline(preview: ImportPreview): { label: string; caption: string } {+ const span =+ preview.dateRangeStartSec != null && preview.dateRangeEndSec != null+ ? ` · ${formatDateWithYear(preview.dateRangeStartSec)} to ${formatDateWithYear(preview.dateRangeEndSec)}`+ : ""+ return {+ label: `${plural(preview.newRows, "new location")}`,+ caption: `${formatLabel(preview.format)}${span}`+ }+}++/**+ * One line for everything the import will not take, and nothing at all when it takes everything.+ * Three permanent counts made the card a ledger of zeroes.+ */+export function skippedLine(preview: ImportPreview): string | undefined {+ const parts: string[] = []+ if (preview.duplicates > 0) parts.push(plural(preview.duplicates, "duplicate"))+ if (preview.invalid > 0) parts.push(plural(preview.invalid, "unusable row"))+ if (parts.length === 0) return undefined+ return `Skipping ${parts.join(" and ")}.`+}++/** The sub under the queue switch. One upload per row is the part that surprises people. */+export function queueHint(newRows: number): string {+ return `Sends ${plural(newRows, "location")} to your server too.`+}++export function commitLabel(newRows: number, queued: boolean): string {+ return queued ? `Import and queue ${newRows.toLocaleString()}` : `Import ${plural(newRows, "location")}`+}++export interface ConfirmCopy {+ title: string+ message: string+ confirmText: string+}++/**+ * The confirmation carries the reasoning the staged card no longer shows. It is read once, at the+ * moment it decides something, rather than standing on the screen while the user is still reading+ * the file they picked.+ */+export function commitConfirm(preview: ImportPreview, queued: boolean): ConfirmCopy {+ const rejected = preview.invalid > 0 ? " A rejected row had no usable time or coordinates." : ""+ const shared = `Nothing already stored is changed or removed. Duplicates are counted inside the file and against what is stored, and a duplicate is skipped rather than merged.${rejected} Recording pauses while these are written, and an import cannot be undone one point at a time.`+ if (!queued) {+ return {+ title: `Import ${plural(preview.newRows, "location")}?`,+ message: `${shared} They are marked as already uploaded, so Delete synced locations in Data management would take them too.`,+ confirmText: "Import"+ }+ }+ return {+ title: `Import and queue ${preview.newRows.toLocaleString()} locations?`,+ message: `${shared} Every one becomes an upload to your server, and Colota cannot recall what your server has already taken.`,+ confirmText: "Import and queue"+ }+}++/** A parse that staged nothing. Three different reasons that all read as "nothing found" before. */+export function emptyPreviewCopy(preview: ImportPreview): string {+ if (preview.totalParsed === 0 && preview.invalid === 0) return "No locations were found in this file."+ if (preview.totalParsed === 0) {+ return `No usable locations. ${preview.invalid.toLocaleString()} rows had no usable time or coordinates.`+ }+ return `Nothing new. ${preview.duplicates.toLocaleString()} points were skipped as duplicates, counted both inside the file and against what is already stored.`+}++/** Native error codes, worded from what each one means rather than from a hand-kept list. */+export function importErrorMessage(code: string | undefined): string {+ switch (code) {+ case "E_IMPORT_UNSUPPORTED":+ return `Colota did not recognise this file. It reads ${readableFormats()}, and it refuses an XML file that declares a DOCTYPE.`+ case "E_BUSY":+ return "Another import is already running."+ case "E_IMPORT_NO_PENDING":+ return "The file you picked expired. Choose it again."+ case "E_IMPORT_SYNC_UNAVAILABLE":+ return "There is no server to queue to. Import without queueing, or set one up on Connection first."+ default:+ return "The file could not be read."+ }+}++/** The Automatic export row, and the hub row that now carries its state. */+export function autoExportSub(status: AutoExportState | null): string {+ if (!status) return "Not set up yet"+ if (status.uri === null) return "No folder chosen"+ if (!status.enabled) {+ return status.lastError ? "Stopped, folder access lost" : "Off"+ }+ if (status.running) return "Export running"+ const interval = status.interval.charAt(0).toUpperCase() + status.interval.slice(1)+ const kept = status.retentionCount > 0 ? ` · ${plural(status.retentionCount, "file")} kept` : ""+ return `${interval} · ${formatLabel(status.format)}${kept}${status.lastError ? " · last export failed" : ""}`+}++/**+ * The Settings hub row. It reports the auto-export state when there is one, because that row left+ * the hub and its one real failure would otherwise be reachable only by opening two screens.+ */+export function transferRowSub(status: AutoExportState | null): string {+ if (status && status.uri !== null && status.enabled) {+ // Only the first word is lowered. Lowering the whole line would print "geojson".+ const state = autoExportSub(status)+ return `Auto-export ${state.charAt(0).toLowerCase()}${state.slice(1)}`+ }+ if (status?.lastError && !status.enabled) return "Auto-export stopped, folder access lost"+ return `${readableFormats()} in, and out`+}