Skip to content

Colota - Android GPS Location tracker

refactor(data): turn the maintenance and delete actions into rows (#865)

Max Dietrichcc86ac3dec33
diff --git a/apps/docs/docs/configuration/server-settings.md b/apps/docs/docs/configuration/server-settings.md
index 8d28b0e1..2dcef562 100644
--- a/apps/docs/docs/configuration/server-settings.md
+++ b/apps/docs/docs/configuration/server-settings.md
@@ -81,7 +81,7 @@ The UI simplifies to remove sync-related elements that don't apply:
- Tracking profiles and geofences
- Data export (CSV, GeoJSON, GPX, KML) - both manual and auto-export
- Database statistics (Total locations, Storage)
-- Data cleanup (Delete older than, Delete all locations, Compact database)
+- Data cleanup (Delete older locations, Delete all locations, Compact database)
### Disabling Offline Mode
diff --git a/apps/docs/docs/guides/data-export.md b/apps/docs/docs/guides/data-export.md
index 81f5396f..d65987b2 100644
--- a/apps/docs/docs/guides/data-export.md
+++ b/apps/docs/docs/guides/data-export.md
@@ -32,8 +32,8 @@ Each recording is written as its own feature so mapping tools can read one row a
### Bulk Export
1. Go to **Settings → Export & import**
-2. Select a format
-3. Tap **Export** and share the file via Android's share menu
+2. Tap **Export all locations** and pick a format
+3. Share the file via Android's share menu
Bulk export always covers your full history. To export a subset, use the trip export below.
diff --git a/apps/docs/docs/guides/data-import.md b/apps/docs/docs/guides/data-import.md
index af7a4834..dde4b3aa 100644
--- a/apps/docs/docs/guides/data-import.md
+++ b/apps/docs/docs/guides/data-import.md
@@ -40,10 +40,10 @@ The exported file is saved to your phone's `Downloads` folder.
## How to Import
1. Go to **Settings → Export & import**
-2. Tap **Choose File** and pick the file you want to import
+2. Tap **Import a file** and pick the file you want to import. A CSV needs a header with latitude, longitude and a time column
3. 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 range
-5. Choose **Import** (or **Import + Queue for Sync** - see below)
+4. Review the preview: new locations, format and date range, and any duplicates or unusable rows being skipped
+5. Optionally switch on **Also queue for upload** (see below), then tap **Import N locations** and confirm
### How duplicates are handled
@@ -64,9 +64,9 @@ Rows are dropped silently as "invalid" when any of the following hold:
The preview shows the invalid count so you can decide whether to proceed.
-## Import vs Import + Queue for Sync
+## Import or import and queue
-If you've configured an optional sync backend in **Settings → Connection**, the confirm dialog offers two import buttons. The choice only affects whether the imported rows are also pushed out to that backend; either way the points land in Colota's local history.
+If you've configured an optional sync backend in **Settings → Connection**, the preview shows an **Also queue for upload** switch. It only affects whether the imported rows are also pushed out to that backend; either way the points land in Colota's local history.
### Import
@@ -74,13 +74,13 @@ If you've configured an optional sync backend in **Settings → Connection**, th
- **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 "Delete synced locations".
-### Import + Queue for Sync
+### Import and queue
- Rows are written into Colota with `sent=0` and enqueued for upload.
- The next sync cycle replicates them to your configured backend.
- Use this when the points are new to your backend - for example, you imported a Google Timeline archive and want the backend copy to mirror it too.
-This button is **only shown when a sync endpoint is configured and offline mode is off**. If it's missing, configure sync in **Settings → Connection** first.
+The switch **only appears when a sync endpoint is configured and offline mode is off**. If it's missing, configure sync in **Settings → Connection** first.
:::warning[Queueing fans the points out to your backend - irreversible there]
@@ -92,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 **Also queue for upload** on, the queue counter in **Data management** reflects the new pending rows; the next sync cycle replicates them to your configured backend.
## Edge Cases
@@ -100,4 +100,3 @@ Once queued, the rows are uploaded as soon as the next sync runs. Removing them
- **GPX without `<time>`** elements are skipped. Same reason - the locations table requires a timestamp.
- **CSV without lat/lon/time columns** is rejected with a clear error rather than silently producing zero rows.
- **Very large files** (500 MB+ Google Timeline exports) parse without loading the full document into memory. Expect the preview phase to take some seconds; the actual commit is fast once you confirm.
-- **The Import + Queue button is greyed out** if you're in offline mode or have no sync endpoint configured - this is intentional, the queue has no destination in that state.
diff --git a/apps/docs/docs/guides/data-management.md b/apps/docs/docs/guides/data-management.md
index cc795681..b6d4d318 100644
--- a/apps/docs/docs/guides/data-management.md
+++ b/apps/docs/docs/guides/data-management.md
@@ -20,10 +20,10 @@ import ScreenshotGallery from '@site/src/components/ScreenshotGallery'
| **Compact database** | Rewrites the database to give unused space back. It deletes nothing. Deleting trips and points from Location History leaves gaps that only this reclaims, so press it after a round of track editing |
| **Delete queued locations** | Deletes the locations waiting to upload, not their pending uploads. Nothing else holds a copy, so they leave Location History too |
| **Delete synced locations** | Deletes locations already on your server. Those days leave Location History, notes included, and imported locations count as synced. Copies on your server stay |
-| **Delete older than** | Deletes every location recorded before the age you pick: 30 days, 90 days, 1 year or a custom number of days. Sync state is ignored, so queued locations go with the rest |
-| **Delete all locations** | Deletes every location and every manual trip split you made. Geofences, profiles and settings stay |
+| **Delete older locations** | Deletes every location recorded before the age you pick: 30 days, 90 days, 1 year or a custom number of days. Sync state is ignored, so queued locations go with the rest |
+| **Delete all locations** | Deletes every location and every manual trip split and merge you made. Geofences, profiles and settings stay |
-Each delete names its own count before you press it. No age is chosen when the screen opens, so nothing is counted until you pick one. Every delete asks you to confirm, and none can be undone.
+Each delete row names its own count before you press it, and Delete all takes the Locations figure at the top. No age is chosen when the screen opens, so nothing is counted until you pick one. Every delete asks you to confirm, and none can be undone.
In [offline mode](/docs/configuration/server-settings#offline-mode) nothing new is queued, so Sync now and both sync-scoped deletes leave the screen. Locations queued before you turned it on are still there, and the age delete and Delete all still reach them.
diff --git a/apps/docs/docs/guides/troubleshooting.md b/apps/docs/docs/guides/troubleshooting.md
index b6e0a01f..d94bfa28 100644
--- a/apps/docs/docs/guides/troubleshooting.md
+++ b/apps/docs/docs/guides/troubleshooting.md
@@ -150,7 +150,7 @@ To change: **Settings > Tracking & sync > Sync only on**.
## Database growing too large
- Use **Delete synced locations** to remove what your server already holds
-- Use **Delete older than** for an age cutoff, which ignores sync state
+- Use **Delete older locations** for an age cutoff, which ignores sync state
- Back up or export first if you want to keep it
- Use **Compact database** to reclaim space after deleting trips or points, which leave gaps nothing else reclaims
diff --git a/apps/mobile/src/components/features/map/__tests__/OfflinePackManager.test.ts b/apps/mobile/src/components/features/map/__tests__/OfflinePackManager.test.ts
index d15796af..9eb9b3b0 100644
--- a/apps/mobile/src/components/features/map/__tests__/OfflinePackManager.test.ts
+++ b/apps/mobile/src/components/features/map/__tests__/OfflinePackManager.test.ts
@@ -24,7 +24,6 @@ jest.mock("../../../../services/NativeLocationService")
import { OfflineManager } from "@maplibre/maplibre-react-native"
import NativeLocationService from "../../../../services/NativeLocationService"
-import { formatBytes } from "../../../../utils/format"
import {
willExceedTileLimit,
estimateSizeLabel,
@@ -71,37 +70,6 @@ describe("constants", () => {
})
})
-// ============================================================================
-// formatBytes
-// ============================================================================
-
-describe("formatBytes", () => {
- it("formats bytes below 1MB as KB", () => {
- expect(formatBytes(512 * 1024)).toBe("512.0 KB")
- })
-
- it("formats zero bytes as B", () => {
- expect(formatBytes(0)).toBe("0 B")
- })
-
- it("formats 1MB as MB", () => {
- expect(formatBytes(1024 * 1024)).toBe("1.0 MB")
- })
-
- it("formats 1.5MB correctly", () => {
- expect(formatBytes(1.5 * 1024 * 1024)).toBe("1.5 MB")
- })
-
- it("formats large values as MB", () => {
- expect(formatBytes(250 * 1024 * 1024)).toBe("250.0 MB")
- })
-
- it("threshold is exactly 1MB - values below are KB, at or above are MB", () => {
- expect(formatBytes(1024 * 1024 - 1)).toMatch(/KB$/)
- expect(formatBytes(1024 * 1024)).toMatch(/MB$/)
- })
-})
-
// ============================================================================
// willExceedTileLimit
// ============================================================================
diff --git a/apps/mobile/src/screens/DataManagementScreen.tsx b/apps/mobile/src/screens/DataManagementScreen.tsx
index 25512ea5..3c64eba7 100644
--- a/apps/mobile/src/screens/DataManagementScreen.tsx
+++ b/apps/mobile/src/screens/DataManagementScreen.tsx
@@ -4,13 +4,11 @@
*/
import React, { useState, useCallback, useRef, useEffect } from "react"
-import { Text, StyleSheet, View, ScrollView, DeviceEventEmitter } from "react-native"
-import { Archive, Clock, CloudUpload, HardDrive, MapPin, Trash2 } from "lucide-react-native"
+import { StyleSheet, View, ScrollView, DeviceEventEmitter } from "react-native"
+import { Archive, CalendarRange, Clock, CloudUpload, HardDrive, MapPin, Minimize2, Trash2 } from "lucide-react-native"
import { useFocusEffect } from "@react-navigation/native"
import { DatabaseStats } from "../types/global"
import type { RootScreenProps } from "../types/navigation"
-import { useTheme } from "../hooks/useTheme"
-import { fonts, fontSizes, lineHeights } from "../styles/typography"
import NativeLocationService from "../services/NativeLocationService"
import { useTracking } from "../contexts/TrackingProvider"
import {
@@ -24,6 +22,7 @@ import {
ListItem,
NumericInput,
SectionTitle,
+ SpinningLoader,
StatRow
} from "../components"
import {
@@ -31,14 +30,16 @@ import {
RETENTION_PRESET_DAYS,
RETENTION_PREVIEW_DEBOUNCE_MS,
SAVE_SUCCESS_DISPLAY_MS,
+ size,
space
} from "../constants"
import { useTimeout } from "../hooks/useTimeout"
import { showAlert, showConfirm } from "../services/modalService"
-import { allSub, deleteCopy, olderSub, scopeSub, type DataScope } from "../utils/dataScope"
+import { deleteCopy, olderSub, scopeSub, type DataScope } from "../utils/dataScope"
import { parseWholeNumber, wholeNumberError } from "../utils/settingsValidation"
import { formatWhen } from "../utils/geo"
import { logger } from "../utils/logger"
+import { formatBytes } from "../utils/format"
/** Only a placeholder in the custom field. Nothing is selected until the user selects it. */
const PLACEHOLDER_DAYS = 90
@@ -60,13 +61,13 @@ const EMPTY_STATS: DatabaseStats = {
}
export function DataManagementScreen({ navigation }: RootScreenProps<"Data Management">) {
- const { colors } = useTheme()
- const { settings, tracking } = useTracking()
+ const { settings } = useTracking()
const isOfflineMode = settings.isOfflineMode
const [stats, setStats] = useState<DatabaseStats>(EMPTY_STATS)
const [loaded, setLoaded] = useState(false)
const [busy, setBusy] = useState<"count" | "flush" | "compact" | "delete" | null>(null)
+ const [busyScope, setBusyScope] = useState<DataScope | null>(null)
const [syncMessage, setSyncMessage] = useState<Message | null>(null)
const [compactMessage, setCompactMessage] = useState<Message | null>(null)
@@ -202,6 +203,7 @@ export function DataManagementScreen({ navigation }: RootScreenProps<"Data Manag
if (busyRef.current) return
busyRef.current = true
setBusy("count")
+ setBusyScope(scope)
try {
const generation = ++statsIssued.current
const fresh = await NativeLocationService.getStats()
@@ -240,6 +242,7 @@ export function DataManagementScreen({ navigation }: RootScreenProps<"Data Manag
} finally {
busyRef.current = false
setBusy(null)
+ setBusyScope(null)
}
},
[days, updateStats, runPreview, applyStats]
@@ -326,7 +329,9 @@ export function DataManagementScreen({ navigation }: RootScreenProps<"Data Manag
const after = await NativeLocationService.getStats()
applyStats(after, afterGeneration)
const freed = before - after.databaseSizeMB
- setCompactMessage({ text: freed > 0.01 ? `Released ${freed.toFixed(2)} MB` : "Nothing to release" })
+ setCompactMessage({
+ text: freed > 0.01 ? `Released ${formatBytes(freed * 1024 * 1024, { decimals: 0 })}` : "Nothing to release"
+ })
compactTimeout.set(() => setCompactMessage(null), SAVE_SUCCESS_DISPLAY_MS)
} catch (err) {
logger.error("[DataManagementScreen] Compact failed:", err)
@@ -344,15 +349,16 @@ export function DataManagementScreen({ navigation }: RootScreenProps<"Data Manag
? `Nothing queued. Last upload ${formatWhen(Math.floor(stats.lastSyncTime / 1000))}.`
: "Nothing queued. New locations upload on their own."
: null
- const syncIdle = `Uploads the ${stats.queued.toLocaleString()} queued location${stats.queued === 1 ? "" : "s"} now, whatever Sync only on says.${
- tracking ? "" : " The tracking notification appears for a moment. Nothing is recorded."
- }`
- const syncLine = busy === "flush" || syncMessage ? syncMessage : { text: syncBlocker ?? syncIdle }
+ const syncIdle = `${stats.queued.toLocaleString()} queued. Uploads ${stats.queued === 1 ? "it" : "them"} now, whatever Sync only on says.`
+ const syncSub = busy === "flush" ? (syncMessage?.text ?? "") : (syncBlocker ?? syncIdle)
+ const syncResult = busy === "flush" ? null : syncMessage
+ const scopeProgress = (scope: DataScope) =>
+ busyScope === scope ? (busy === "delete" ? "Deleting…" : "Counting…") : null
const ageCount = preview && preview.days === days ? preview.total : null
// The field owns its own error; repeating it here would print the same sentence twice.
const ageLine = ageError
- ? "Fix the age above."
+ ? "Fix the age below."
: days === null
? "Choose how old a location must be."
: ageCount === null
@@ -362,10 +368,6 @@ export function DataManagementScreen({ navigation }: RootScreenProps<"Data Manag
return (
<Container>
<ScrollView contentContainerStyle={styles.scrollContent} keyboardShouldPersistTaps="handled">
- <Text style={[styles.intro, { color: colors.textSecondary }]}>
- What this device is storing, and what deleting it takes away.
- </Text>
-
<View style={styles.section}>
<SectionTitle>Stored on this device</SectionTitle>
<Card rows>
@@ -379,39 +381,47 @@ export function DataManagementScreen({ navigation }: RootScreenProps<"Data Manag
<StatRow
icon={HardDrive}
label="Database size"
- value={loaded ? `${stats.databaseSizeMB.toFixed(2)} MB` : "…"}
+ value={loaded ? formatBytes(stats.databaseSizeMB * 1024 * 1024, { decimals: 0 }) : "…"}
testID="stat-size"
/>
</Card>
+ </View>
- {!isOfflineMode && (
- <View>
- <Button
- variant="secondary"
- title="Sync now"
- testID="sync-now-btn"
- loading={busy === "flush"}
- disabled={isProcessing || syncBlocker !== null}
- onPress={handleManualFlush}
- />
- <FieldMessage variant={syncLine?.failed ? "error" : "info"}>{syncLine?.text ?? ""}</FieldMessage>
- </View>
- )}
-
- <View>
- <Button
- variant="ghost"
- title="Compact database"
- testID="compact-btn"
- loading={busy === "compact"}
- disabled={isProcessing}
+ <View style={styles.section}>
+ <SectionTitle>Maintenance</SectionTitle>
+ <Card rows>
+ {!isOfflineMode && (
+ <>
+ <ListItem
+ testID="sync-now-row"
+ icon={Clock}
+ trailingIcon={busy === "flush" ? SpinningLoader : CloudUpload}
+ label="Sync now"
+ sub={syncSub}
+ subLines={2}
+ disabled={busy === "flush" ? false : isProcessing || syncBlocker !== null}
+ accessibilityHint="Uploads the queue now"
+ onPress={handleManualFlush}
+ />
+ <Divider tight inset />
+ </>
+ )}
+ <ListItem
+ testID="compact-row"
+ icon={HardDrive}
+ trailingIcon={busy === "compact" ? SpinningLoader : Minimize2}
+ label="Compact database"
+ sub={busy === "compact" ? "Rewriting the database…" : "Gives unused space back. Deletes nothing."}
+ subLines={2}
+ disabled={busy === "compact" ? false : isProcessing}
+ accessibilityHint="Rewrites the database file"
onPress={handleCompact}
/>
- <FieldMessage>
- {compactMessage?.text ??
- "Rewrites the database to give unused space back. Deleting trips and points leaves gaps that only this reclaims. Nothing is deleted."}
- </FieldMessage>
- </View>
+ </Card>
+ {syncResult ? (
+ <FieldMessage variant={syncResult.failed ? "error" : "info"}>{syncResult.text}</FieldMessage>
+ ) : null}
+ {compactMessage ? <FieldMessage>{compactMessage.text}</FieldMessage> : null}
</View>
<View style={styles.section}>
@@ -439,11 +449,11 @@ export function DataManagementScreen({ navigation }: RootScreenProps<"Data Manag
<ListItem
testID="delete-queued-row"
icon={Clock}
- trailingIcon={Trash2}
+ trailingIcon={busyScope === "queued" ? SpinningLoader : Trash2}
label="Delete queued locations"
- sub={scopeSub("queued", stats.queued)}
+ sub={scopeProgress("queued") ?? scopeSub("queued", stats.queued)}
subLines={2}
- disabled={isProcessing || stats.queued === 0}
+ disabled={busyScope === "queued" ? false : isProcessing || stats.queued === 0}
accessibilityHint="Asks you to confirm, then deletes"
onPress={() => confirmAndDelete("queued", () => NativeLocationService.clearQueue())}
/>
@@ -451,80 +461,70 @@ export function DataManagementScreen({ navigation }: RootScreenProps<"Data Manag
<ListItem
testID="delete-synced-row"
icon={CloudUpload}
- trailingIcon={Trash2}
+ trailingIcon={busyScope === "synced" ? SpinningLoader : Trash2}
label="Delete synced locations"
- sub={scopeSub("synced", stats.sent)}
+ sub={scopeProgress("synced") ?? scopeSub("synced", stats.sent)}
subLines={2}
- disabled={isProcessing || stats.sent === 0}
+ disabled={busyScope === "synced" ? false : isProcessing || stats.sent === 0}
accessibilityHint="Asks you to confirm, then deletes"
onPress={() => confirmAndDelete("synced", () => NativeLocationService.clearSentHistory())}
/>
</>
)}
- </Card>
-
- <Card style={styles.ageCard}>
- <ChipGroup
- accessibilityLabel="Age"
- options={[
- ...RETENTION_PRESET_DAYS.map((preset) => ({
- value: String(preset),
- label: preset === 365 ? "1 year" : `${preset} days`,
- testID: `age-${preset}`
- })),
- { value: "custom", label: "Custom", testID: "age-custom" }
- ]}
- selected={ageChoice}
- onSelect={handleAgeChoice}
+ <Divider tight inset />
+ <ListItem
+ testID="delete-older-row"
+ icon={CalendarRange}
+ trailingIcon={busyScope === "older" ? SpinningLoader : Trash2}
+ label="Delete older locations"
+ sub={scopeProgress("older") ?? ageLine}
+ subLines={2}
+ disabled={busyScope === "older" ? false : isProcessing || !!ageError || days === null || !ageCount}
+ accessibilityHint="Asks you to confirm, then deletes"
+ onPress={() => confirmAndDelete("older", () => NativeLocationService.deleteOlderThan(days as number))}
/>
- {isCustom && (
- <View style={styles.customField}>
- <NumericInput
- label="Delete locations older than"
- testID="retention-days-input"
- value={customText}
- onChange={handleCustomChange}
- onBlur={handleCustomBlur}
- unit="days"
- placeholder={String(PLACEHOLDER_DAYS)}
- hint="At least 1 day."
- error={ageError}
- message={clampNote}
- />
- </View>
- )}
+ <View style={styles.ageControls}>
+ <ChipGroup
+ accessibilityLabel="Age"
+ options={[
+ ...RETENTION_PRESET_DAYS.map((preset) => ({
+ value: String(preset),
+ label: preset === 365 ? "1 year" : `${preset} days`,
+ testID: `age-${preset}`
+ })),
+ { value: "custom", label: "Custom", testID: "age-custom" }
+ ]}
+ selected={ageChoice}
+ onSelect={handleAgeChoice}
+ />
+ {isCustom && (
+ <View style={styles.customField}>
+ <NumericInput
+ label="Delete locations older than"
+ testID="retention-days-input"
+ value={customText}
+ onChange={handleCustomChange}
+ onBlur={handleCustomBlur}
+ unit="days"
+ placeholder={String(PLACEHOLDER_DAYS)}
+ hint="At least 1 day."
+ error={ageError}
+ message={clampNote}
+ />
+ </View>
+ )}
+ </View>
</Card>
- <View>
- <Button
- variant="ghost"
- color={colors.error}
- icon={Trash2}
- testID="delete-older-btn"
- title={
- ageCount && ageCount > 0
- ? `Delete ${ageCount.toLocaleString()} location${ageCount === 1 ? "" : "s"}`
- : "Delete older locations"
- }
- loading={busy === "count" || busy === "delete"}
- disabled={isProcessing || !!ageError || days === null || !ageCount}
- onPress={() => confirmAndDelete("older", () => NativeLocationService.deleteOlderThan(days as number))}
- />
- <FieldMessage variant={ageError ? "error" : "info"}>{ageLine}</FieldMessage>
- </View>
-
- <View>
- <Button
- variant="danger"
- icon={Trash2}
- title="Delete all locations"
- testID="delete-all-btn"
- loading={busy === "count" || busy === "delete"}
- disabled={isProcessing}
- onPress={() => confirmAndDelete("all", () => NativeLocationService.clearAllLocations())}
- />
- <FieldMessage>{allSub(stats.total)}</FieldMessage>
- </View>
+ <Button
+ variant="danger"
+ icon={Trash2}
+ title="Delete all locations"
+ testID="delete-all-btn"
+ loading={busyScope === "all"}
+ disabled={isProcessing}
+ onPress={() => confirmAndDelete("all", () => NativeLocationService.clearAllLocations())}
+ />
</>
)}
</View>
@@ -539,17 +539,13 @@ const styles = StyleSheet.create({
paddingTop: space.lg,
paddingBottom: space.xxl
},
- intro: {
- fontSize: fontSizes.body,
- ...fonts.regular,
- lineHeight: lineHeights.body,
- marginBottom: space.lg
- },
section: {
marginBottom: space.xl
},
- ageCard: {
- marginTop: space.md
+ ageControls: {
+ marginTop: -space.xs,
+ paddingStart: size.icon.md + space.lg,
+ paddingBottom: space.lg
},
customField: {
marginTop: space.lg
diff --git a/apps/mobile/src/screens/ExportImportScreen.tsx b/apps/mobile/src/screens/ExportImportScreen.tsx
index 56919fd1..990c7bd2 100644
--- a/apps/mobile/src/screens/ExportImportScreen.tsx
+++ b/apps/mobile/src/screens/ExportImportScreen.tsx
@@ -3,10 +3,10 @@
* 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 React, { useCallback, useEffect, useRef, useState } from "react"
+import { DeviceEventEmitter, ScrollView, StyleSheet, View } from "react-native"
import { useFocusEffect } from "@react-navigation/native"
-import { Archive, CalendarRange, Clock, Download, HardDrive, MapPin, Upload } from "lucide-react-native"
+import { Archive, CalendarRange, Clock, Download, FileText, HardDrive, MapPin, Upload } from "lucide-react-native"
import {
Button,
Card,
@@ -27,6 +27,7 @@ import NativeLocationService from "../services/NativeLocationService"
import ImportService, { type ImportPreview } from "../services/ImportService"
import { showAlert, showConfirm } from "../services/modalService"
import { logger } from "../utils/logger"
+import { formatBytes } from "../utils/format"
import { type ExportFormat } from "../utils/exportConverters"
import { FILE_FORMATS } from "../utils/fileFormats"
import {
@@ -37,14 +38,14 @@ import {
emptyPreviewCopy,
exportLine,
exportResultLine,
+ exportRowSub,
importErrorMessage,
- importSourceLine,
+ importRowSub,
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"
@@ -68,8 +69,8 @@ export function ExportImportScreen({ navigation }: ScreenProps) {
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 busyRef = useRef<Busy>(null)
+ // Released on unmount, not on blur, so opening Backup & Restore from the preview keeps the staged file.
const stagedRef = useRef(false)
const read = useCallback(async () => {
@@ -90,27 +91,33 @@ export function ExportImportScreen({ navigation }: ScreenProps) {
useCallback(() => {
read()
const sub = DeviceEventEmitter.addListener("onLocationUpdate", read)
- return () => {
- sub.remove()
- if (stagedRef.current) {
- stagedRef.current = false
- ImportService.cancelImport().catch(() => {})
- }
- }
+ return () => sub.remove()
}, [read])
)
- const discard = useCallback(() => {
+ useEffect(
+ () => () => {
+ if (stagedRef.current || busyRef.current === "parse") ImportService.cancelImport().catch(() => {})
+ },
+ []
+ )
+
+ const dropStaged = useCallback(() => {
stagedRef.current = false
setPreview(null)
setQueued(false)
- ImportService.cancelImport().catch(() => {})
}, [])
+ const discard = useCallback(() => {
+ dropStaged()
+ setImportMessage(null)
+ ImportService.cancelImport().catch(() => {})
+ }, [dropStaged])
+
const handleExport = useCallback(async (format: ExportFormat) => {
setFormatOpen(false)
- if (busyRef.current) return
- busyRef.current = true
+ if (busyRef.current !== null) return
+ busyRef.current = "export"
setBusy("export")
setExportMessage(null)
try {
@@ -132,13 +139,13 @@ export function ExportImportScreen({ navigation }: ScreenProps) {
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
+ busyRef.current = null
setBusy(null)
}
}, [])
const handleChooseFile = useCallback(async () => {
- if (busyRef.current) return
+ if (busyRef.current !== null) return
let source: { uri: string } | null = null
try {
source = await ImportService.pickImportSource()
@@ -147,9 +154,9 @@ export function ExportImportScreen({ navigation }: ScreenProps) {
showAlert("Could not open the picker", "The system file picker did not open.", "error")
return
}
- if (!source) return
+ if (!source || busyRef.current !== null) return
- busyRef.current = true
+ busyRef.current = "parse"
setBusy("parse")
setImportMessage(null)
try {
@@ -166,32 +173,33 @@ export function ExportImportScreen({ navigation }: ScreenProps) {
logger.error("[ExportImportScreen] Parse failed:", err)
setImportMessage({ text: importErrorMessage((err as { code?: string }).code), failed: true })
} finally {
- busyRef.current = false
+ busyRef.current = null
setBusy(null)
}
}, [])
const handleCommit = useCallback(async () => {
- if (busyRef.current || !preview) return
+ if (busyRef.current !== null || !preview) return
if (!(await showConfirm({ ...commitConfirm(preview, queued), destructive: false }))) return
- busyRef.current = true
+ busyRef.current = "commit"
setBusy("commit")
try {
const inserted = await ImportService.commitImport(queued)
- stagedRef.current = false
- setPreview(null)
- setQueued(false)
+ dropStaged()
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 })
+ const code = (err as { code?: string }).code
+ // The native stash expired, so the staged card can only fail again.
+ if (code === "E_IMPORT_NO_PENDING") dropStaged()
+ setImportMessage({ text: importErrorMessage(code), failed: true })
} finally {
- busyRef.current = false
+ busyRef.current = null
setBusy(null)
}
- }, [preview, queued, read])
+ }, [preview, queued, read, dropStaged])
const skipped = preview ? skippedLine(preview) : undefined
const headline = preview ? previewHeadline(preview) : null
@@ -200,10 +208,6 @@ export function ExportImportScreen({ navigation }: ScreenProps) {
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>
@@ -217,40 +221,32 @@ export function ExportImportScreen({ navigation }: ScreenProps) {
<StatRow
icon={HardDrive}
label="Database size"
- value={loaded ? `${stats.databaseSizeMB.toFixed(2)} MB` : "…"}
+ value={loaded ? formatBytes(stats.databaseSizeMB * 1024 * 1024, { decimals: 0 }) : "…"}
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"}
+ <SectionTitle>Export</SectionTitle>
+ <Card rows>
+ {/* Before the first stats read the total is 0, which would read as nothing to export. */}
+ <ListItem
+ testID="export-all-row"
+ icon={MapPin}
+ trailingIcon={Upload}
+ label="Export all locations"
+ sub={loaded ? exportRowSub(stats.total) : undefined}
+ accessibilityHint="Picks a format, then hands the file to another app"
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}>
+ <Divider tight inset />
<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}
+ sub="From History"
onPress={() => navigation.navigate("Location History")}
/>
<Divider tight inset />
@@ -263,24 +259,16 @@ export function ExportImportScreen({ navigation }: ScreenProps) {
onPress={() => navigation.navigate("Auto-Export")}
/>
</Card>
+ {exportMessage ? (
+ <FieldMessage variant={exportMessage.failed ? "error" : "info"}>{exportMessage.text}</FieldMessage>
+ ) : null}
</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>
-
+ <SectionTitle>Import</SectionTitle>
{preview && headline ? (
<>
- <Card rows style={styles.afterButton}>
+ <Card rows>
<StateLine
icon={PreviewIcon}
iconColor={colors.primary}
@@ -301,6 +289,15 @@ export function ExportImportScreen({ navigation }: ScreenProps) {
</SettingRow>
</>
)}
+ <Divider tight />
+ <ListItem
+ testID="nav-backup-restore"
+ icon={Archive}
+ label="Back up first"
+ sub={backupFirstSub()}
+ subLines={2}
+ onPress={() => navigation.navigate("Backup & Restore")}
+ />
</Card>
{skipped ? <FieldMessage>{skipped}</FieldMessage> : null}
<Button
@@ -315,28 +312,30 @@ export function ExportImportScreen({ navigation }: ScreenProps) {
<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"}
+ <Card rows>
+ <ListItem
+ testID="import-file-row"
+ icon={FileText}
+ trailingIcon={Download}
+ label="Import a file"
+ sub={importRowSub(busy === "parse")}
+ subLines={2}
+ accessibilityHint="Opens the file picker"
disabled={busy !== null}
onPress={handleChooseFile}
/>
- <FieldMessage variant={importMessage?.failed ? "warning" : "info"}>
- {importMessage?.text ?? importSourceLine()}
- </FieldMessage>
- </View>
+ </Card>
)}
+ {importMessage ? (
+ <FieldMessage variant={importMessage.failed ? "warning" : "info"}>{importMessage.text}</FieldMessage>
+ ) : null}
</View>
</ScrollView>
<ExportFormatDialog
visible={formatOpen}
title="Export format"
- message={`All ${stats.total.toLocaleString()} locations, oldest first.`}
+ message={exportLine(stats.total)}
onSelect={handleExport}
onRequestClose={() => setFormatOpen(false)}
/>
@@ -359,16 +358,7 @@ const styles = StyleSheet.create({
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/__tests__/BackupRestoreScreen.test.tsx b/apps/mobile/src/screens/__tests__/BackupRestoreScreen.test.tsx
index f5d8da3c..5a05625e 100644
--- a/apps/mobile/src/screens/__tests__/BackupRestoreScreen.test.tsx
+++ b/apps/mobile/src/screens/__tests__/BackupRestoreScreen.test.tsx
@@ -148,7 +148,7 @@ describe("BackupRestoreScreen", () => {
const api = renderScreen()
expect(await api.findByText(/^You last backed up /)).toBeTruthy()
- expect(api.getByText("Database: 12,481 locations, 8.42 MB")).toBeTruthy()
+ expect(api.getByText("Database: 12,481 locations, 8 MB")).toBeTruthy()
})
it("says so when there has never been a backup", async () => {
diff --git a/apps/mobile/src/screens/__tests__/DataManagementScreen.test.tsx b/apps/mobile/src/screens/__tests__/DataManagementScreen.test.tsx
index a3935862..60656308 100644
--- a/apps/mobile/src/screens/__tests__/DataManagementScreen.test.tsx
+++ b/apps/mobile/src/screens/__tests__/DataManagementScreen.test.tsx
@@ -76,9 +76,8 @@ jest.mock("../../hooks/useTimeout", () => {
const fireLongTimers = () => mockLongTimers.forEach((t) => t.later?.())
let mockSettings: Settings = { ...DEFAULT_SETTINGS }
-let mockTracking = true
jest.mock("../../contexts/TrackingProvider", () => ({
- useTracking: () => ({ settings: mockSettings, tracking: mockTracking })
+ useTracking: () => ({ settings: mockSettings })
}))
const mockGetStats = jest.fn()
@@ -140,7 +139,7 @@ jest.mock("../../components", () => {
R.createElement(View, null, R.createElement(Text, null, title), R.createElement(Text, null, hint)),
FieldMessage: ({ children, variant }: any) =>
R.createElement(Text, { accessibilityValue: { text: variant ?? "info" } }, children),
- Button: ({ title, onPress, disabled, testID, variant, color }: any) =>
+ Button: ({ title, onPress, disabled, testID, variant, color, loading }: any) =>
R.createElement(
Pressable,
{
@@ -148,7 +147,7 @@ jest.mock("../../components", () => {
onPress,
disabled,
accessibilityRole: "button",
- accessibilityState: { disabled: !!disabled },
+ accessibilityState: { disabled: !!disabled, busy: !!loading },
accessibilityValue: { text: `${variant ?? "primary"}${color ? "/error" : ""}` }
},
R.createElement(Text, null, title)
@@ -162,11 +161,12 @@ jest.mock("../../components", () => {
disabled,
accessibilityRole: "button",
accessibilityState: { disabled: !!disabled },
- accessibilityValue: { text: trailingIcon ? "trash" : "chevron" }
+ accessibilityValue: { text: trailingIcon?.displayName ?? "chevron" }
},
R.createElement(Text, null, label),
R.createElement(Text, null, sub)
),
+ SpinningLoader: Object.assign(() => null, { displayName: "SpinningLoader" }),
ChipGroup: ({ options, selected, onSelect }: any) =>
R.createElement(
View,
@@ -217,7 +217,6 @@ describe("DataManagementScreen", () => {
beforeEach(() => {
jest.clearAllMocks()
mockSettings = { ...DEFAULT_SETTINGS, endpoint: "https://api.example.com/track" }
- mockTracking = true
mockGetStats.mockResolvedValue(stats())
mockCountOlderThan.mockResolvedValue({ total: 3120, cutoffSeconds: CUTOFF })
mockCountUnsentOlderThan.mockResolvedValue(96)
@@ -235,7 +234,7 @@ describe("DataManagementScreen", () => {
const api = renderScreen()
expect(await api.findByText("12,480")).toBeTruthy()
- expect(api.getByText("3.42 MB")).toBeTruthy()
+ expect(api.getByText("3 MB")).toBeTruthy()
})
it("carries no Sent, Queued or Today figure, because those parts never sum to the total", async () => {
@@ -278,14 +277,17 @@ describe("DataManagementScreen", () => {
).toBeTruthy()
})
- it("names the trip splits and merges under Delete all, which no label, hint or dialog named", async () => {
+ it("names the trip splits and merges in the Delete all confirmation", async () => {
const api = renderScreen()
+ await api.findByText("12,480")
- expect(
- await api.findByText(
- "All 12,480 locations and every trip split and merge you made. Geofences, profiles and settings stay."
+ fireEvent.press(api.getByTestId("delete-all-btn"))
+
+ await waitFor(() =>
+ expect(mockShowConfirm).toHaveBeenCalledWith(
+ expect.objectContaining({ message: expect.stringContaining("every manual trip split and merge you made") })
)
- ).toBeTruthy()
+ )
})
it("explains a disabled row in the same slot rather than leaving it blank", async () => {
@@ -350,18 +352,32 @@ describe("DataManagementScreen", () => {
expect(mockShowAlert).not.toHaveBeenCalled()
})
- it("runs the native delete behind the age button once an age is chosen and confirmed", async () => {
+ it("runs the native delete behind the age row once an age is chosen and confirmed", async () => {
const api = renderScreen()
await api.findByText("12,480")
fireEvent.press(api.getByTestId("age-90"))
- await api.findByText("Delete 3,120 locations")
+ await api.findByText(/^3,120 locations recorded before /)
- fireEvent.press(api.getByTestId("delete-older-btn"))
+ fireEvent.press(api.getByTestId("delete-older-row"))
await waitFor(() => expect(mockDeleteOlderThan).toHaveBeenCalledWith(90))
expect(mockShowAlert).not.toHaveBeenCalled()
})
+ it("spins the pressed delete row and leaves Delete all alone", async () => {
+ mockShowConfirm.mockReturnValue(new Promise(() => {}))
+ const api = renderScreen()
+ await api.findByText("12,480")
+
+ fireEvent.press(api.getByTestId("delete-queued-row"))
+
+ expect(await api.findByText("Counting…")).toBeTruthy()
+ const row = api.getByTestId("delete-queued-row")
+ expect(row.props.accessibilityValue.text).toBe("SpinningLoader")
+ expect(row.props.accessibilityState.disabled).toBe(false)
+ expect(api.getByTestId("delete-all-btn").props.accessibilityState.busy).toBe(false)
+ })
+
it("reports a failure instead of leaving the screen looking successful", async () => {
// The rejection has to come from native. A handler that threw before reaching it would raise
// the same alert, which is how a dead button once passed this test.
@@ -381,12 +397,12 @@ describe("DataManagementScreen", () => {
expect(mockClearQueue).toHaveBeenCalled()
})
- it("spends the one filled danger button on Delete all and keeps the age delete a text button", async () => {
+ it("spends the one filled danger button on Delete all and makes the age delete a trash row", async () => {
const api = renderScreen()
await api.findByText("12,480")
expect(api.getByTestId("delete-all-btn").props.accessibilityValue.text).toBe("danger")
- expect(api.getByTestId("delete-older-btn").props.accessibilityValue.text).toBe("ghost/error")
+ expect(api.getByTestId("delete-older-row").props.accessibilityValue.text).toBe("Trash2")
})
})
@@ -399,7 +415,7 @@ describe("DataManagementScreen", () => {
expect(mockCountOlderThan).not.toHaveBeenCalled()
expect(api.getByText("Choose how old a location must be.")).toBeTruthy()
- expect(api.getByTestId("delete-older-btn").props.accessibilityState.disabled).toBe(true)
+ expect(api.getByTestId("delete-older-row").props.accessibilityState.disabled).toBe(true)
})
it("counts once an age is chosen, and names the boundary it counted at", async () => {
@@ -408,7 +424,7 @@ describe("DataManagementScreen", () => {
fireEvent.press(api.getByTestId("age-90"))
- expect(await api.findByText("Delete 3,120 locations")).toBeTruthy()
+ expect(await api.findByText(/^3,120 locations recorded before /)).toBeTruthy()
expect(mockCountOlderThan).toHaveBeenCalledWith(90)
})
@@ -418,11 +434,11 @@ describe("DataManagementScreen", () => {
await api.findByText("12,480")
fireEvent.press(api.getByTestId("age-90"))
- await api.findByText("Delete 3,120 locations")
+ await api.findByText(/^3,120 locations recorded before /)
expect(mockCountUnsentOlderThan).not.toHaveBeenCalled()
- fireEvent.press(api.getByTestId("delete-older-btn"))
+ fireEvent.press(api.getByTestId("delete-older-row"))
await waitFor(() => expect(mockCountUnsentOlderThan).toHaveBeenCalledWith(90))
expect(mockShowConfirm).toHaveBeenCalledWith(
@@ -434,12 +450,12 @@ describe("DataManagementScreen", () => {
const api = renderScreen()
await api.findByText("12,480")
fireEvent.press(api.getByTestId("age-90"))
- await api.findByText("Delete 3,120 locations")
+ await api.findByText(/^3,120 locations recorded before /)
mockCountOlderThan.mockResolvedValue({ total: 40, cutoffSeconds: CUTOFF })
fireEvent.press(api.getByTestId("age-365"))
- expect(await api.findByText("Delete 40 locations")).toBeTruthy()
+ expect(await api.findByText(/^40 locations recorded before /)).toBeTruthy()
expect(mockCountOlderThan).toHaveBeenLastCalledWith(365)
})
@@ -451,7 +467,7 @@ describe("DataManagementScreen", () => {
fireEvent.press(api.getByTestId("age-90"))
expect(await api.findByText("Nothing on this device is older than 90 days.")).toBeTruthy()
- expect(api.getByTestId("delete-older-btn").props.accessibilityState.disabled).toBe(true)
+ expect(api.getByTestId("delete-older-row").props.accessibilityState.disabled).toBe(true)
})
it("rejects a decimal instead of silently deleting by its integer part", async () => {
@@ -462,9 +478,8 @@ describe("DataManagementScreen", () => {
fireEvent.changeText(api.getByTestId("retention-days-input"), "1.5")
expect(await api.findByText("A whole number")).toBeTruthy()
- // The field owns the error; the button points at it rather than printing it twice.
- expect(api.getByText("Fix the age above.")).toBeTruthy()
- expect(api.getByTestId("delete-older-btn").props.accessibilityState.disabled).toBe(true)
+ expect(api.getByText("Fix the age below.")).toBeTruthy()
+ expect(api.getByTestId("delete-older-row").props.accessibilityState.disabled).toBe(true)
})
it("restores the last settled age on blur, never the minimum, so an emptied box cannot arm a one-day delete", async () => {
@@ -505,14 +520,14 @@ describe("DataManagementScreen", () => {
const api = renderScreen()
await api.findByText("12,480")
fireEvent.press(api.getByTestId("age-90"))
- await api.findByText("Delete 3,120 locations")
+ await api.findByText(/^3,120 locations recorded before /)
await act(async () => {
mockRefocus?.()
})
- expect(api.getByText("Delete 3,120 locations")).toBeTruthy()
- expect(api.getByTestId("delete-older-btn").props.accessibilityState.disabled).toBe(false)
+ expect(api.getByText(/^3,120 locations recorded before /)).toBeTruthy()
+ expect(api.getByTestId("delete-older-row").props.accessibilityState.disabled).toBe(false)
})
// Nothing has settled, so there is nothing to fall back to and nothing may be armed.
@@ -524,7 +539,7 @@ describe("DataManagementScreen", () => {
fireEvent(api.getByTestId("retention-days-input"), "blur")
expect(api.getByTestId("retention-days-input").props.value).toBe("")
- expect(api.getByTestId("delete-older-btn").props.accessibilityState.disabled).toBe(true)
+ expect(api.getByTestId("delete-older-row").props.accessibilityState.disabled).toBe(true)
expect(mockCountOlderThan).not.toHaveBeenCalled()
})
})
@@ -535,15 +550,17 @@ describe("DataManagementScreen", () => {
mockLongArms = 0
})
- it("says what it overrides, and that a flush records nothing", async () => {
- mockTracking = false
+ it("says how many are queued and what it overrides", async () => {
const api = renderScreen()
- expect(
- await api.findByText(
- "Uploads the 412 queued locations now, whatever Sync only on says. The tracking notification appears for a moment. Nothing is recorded."
- )
- ).toBeTruthy()
+ expect(await api.findByText("412 queued. Uploads them now, whatever Sync only on says.")).toBeTruthy()
+ })
+
+ it("agrees with itself at one queued location", async () => {
+ mockGetStats.mockResolvedValue(stats({ queued: 1 }))
+ const api = renderScreen()
+
+ expect(await api.findByText("1 queued. Uploads it now, whatever Sync only on says.")).toBeTruthy()
})
it("is disabled with the reason when no server is configured, since native does nothing", async () => {
@@ -551,14 +568,14 @@ describe("DataManagementScreen", () => {
const api = renderScreen()
expect(await api.findByText("No server configured. Set one on Connection.")).toBeTruthy()
- expect(api.getByTestId("sync-now-btn").props.accessibilityState.disabled).toBe(true)
+ expect(api.getByTestId("sync-now-row").props.accessibilityState.disabled).toBe(true)
})
it("reports the run from the progress event and never claims success after failures", async () => {
const api = renderScreen()
await api.findByText("12,480")
- fireEvent.press(api.getByTestId("sync-now-btn"))
+ fireEvent.press(api.getByTestId("sync-now-row"))
await waitFor(() => expect(mockManualFlush).toHaveBeenCalled())
// Native's real shape: ticks while it works, then one event carrying `remaining` to end the pass.
@@ -576,7 +593,7 @@ describe("DataManagementScreen", () => {
const api = renderScreen()
await api.findByText("12,480")
- fireEvent.press(api.getByTestId("sync-now-btn"))
+ fireEvent.press(api.getByTestId("sync-now-row"))
await waitFor(() => expect(mockManualFlush).toHaveBeenCalled())
act(() => {
DeviceEventEmitter.emit("onSyncProgress", { sent: 500, failed: 0, total: 500, remaining: 120 })
@@ -592,7 +609,7 @@ describe("DataManagementScreen", () => {
const api = renderScreen()
await api.findByText("12,480")
- fireEvent.press(api.getByTestId("sync-now-btn"))
+ fireEvent.press(api.getByTestId("sync-now-row"))
await waitFor(() => expect(mockManualFlush).toHaveBeenCalled())
act(() => {
DeviceEventEmitter.emit("onSyncProgress", { sent: 500, failed: 0, total: 5000, remaining: 4500 })
@@ -600,14 +617,14 @@ describe("DataManagementScreen", () => {
expect(await api.findByText("Sent 500 of 5,000. 4,500 still queued; press again.")).toBeTruthy()
expect(api.queryByText("No answer from the tracking service. The queue is unchanged.")).toBeNull()
- await waitFor(() => expect(api.getByTestId("sync-now-btn").props.accessibilityState.disabled).toBe(false))
+ await waitFor(() => expect(api.getByTestId("sync-now-row").props.accessibilityState.disabled).toBe(false))
})
it("says the queue emptied when it did, and nothing about pressing again", async () => {
const api = renderScreen()
await api.findByText("12,480")
- fireEvent.press(api.getByTestId("sync-now-btn"))
+ fireEvent.press(api.getByTestId("sync-now-row"))
await waitFor(() => expect(mockManualFlush).toHaveBeenCalled())
mockGetStats.mockResolvedValue(stats({ queued: 0 }))
act(() => {
@@ -625,7 +642,7 @@ describe("DataManagementScreen", () => {
const api = renderScreen()
await api.findByText("12,480")
- fireEvent.press(api.getByTestId("sync-now-btn"))
+ fireEvent.press(api.getByTestId("sync-now-row"))
await waitFor(() => expect(mockManualFlush).toHaveBeenCalled())
act(() => {
DeviceEventEmitter.emit("onSyncProgress", { sent: 0, failed: 412, total: 412, remaining: 412 })
@@ -641,7 +658,7 @@ describe("DataManagementScreen", () => {
const api = renderScreen()
await api.findByText("12,480")
- fireEvent.press(api.getByTestId("sync-now-btn"))
+ fireEvent.press(api.getByTestId("sync-now-row"))
await waitFor(() => expect(mockLongArms).toBe(1))
act(() => {
@@ -656,7 +673,7 @@ describe("DataManagementScreen", () => {
const api = renderScreen()
await api.findByText("12,480")
- fireEvent.press(api.getByTestId("sync-now-btn"))
+ fireEvent.press(api.getByTestId("sync-now-row"))
await waitFor(() => expect(mockManualFlush).toHaveBeenCalled())
await act(async () => {
fireLongTimers()
@@ -664,13 +681,26 @@ describe("DataManagementScreen", () => {
const line = await api.findByText("No answer from the tracking service. Check the queued count above.")
expect(line.props.accessibilityValue.text).toBe("error")
- await waitFor(() => expect(api.getByTestId("sync-now-btn").props.accessibilityState.disabled).toBe(false))
+ await waitFor(() => expect(api.getByTestId("sync-now-row").props.accessibilityState.disabled).toBe(false))
+ })
+
+ it("keeps the running row enabled with a spinner instead of greying it out", async () => {
+ mockManualFlush.mockReturnValue(new Promise(() => {}))
+ const api = renderScreen()
+ await api.findByText("12,480")
+
+ fireEvent.press(api.getByTestId("sync-now-row"))
+
+ expect(await api.findByText("Sent 0 of 412.")).toBeTruthy()
+ const row = api.getByTestId("sync-now-row")
+ expect(row.props.accessibilityValue.text).toBe("SpinningLoader")
+ expect(row.props.accessibilityState.disabled).toBe(false)
})
it("stops listening for progress once the screen is gone", async () => {
const api = renderScreen()
await api.findByText("12,480")
- fireEvent.press(api.getByTestId("sync-now-btn"))
+ fireEvent.press(api.getByTestId("sync-now-row"))
await waitFor(() => expect(mockManualFlush).toHaveBeenCalled())
const during = DeviceEventEmitter.listenerCount("onSyncProgress")
@@ -684,7 +714,7 @@ describe("DataManagementScreen", () => {
const api = renderScreen()
await api.findByText("12,480")
- expect(api.queryByTestId("sync-now-btn")).toBeNull()
+ expect(api.queryByTestId("sync-now-row")).toBeNull()
expect(api.queryByTestId("delete-queued-row")).toBeNull()
expect(api.getByTestId("delete-all-btn")).toBeTruthy()
})
@@ -756,14 +786,23 @@ describe("DataManagementScreen", () => {
})
describe("compact", () => {
- it("says it deletes nothing and that the deletes already do this", async () => {
+ it("says it is rewriting while it runs, on a row that stays enabled", async () => {
+ mockVacuumDatabase.mockReturnValue(new Promise(() => {}))
const api = renderScreen()
+ await api.findByText("12,480")
- expect(
- await api.findByText(
- "Rewrites the database to give unused space back. Deleting trips and points leaves gaps that only this reclaims. Nothing is deleted."
- )
- ).toBeTruthy()
+ fireEvent.press(api.getByTestId("compact-row"))
+
+ expect(await api.findByText("Rewriting the database…")).toBeTruthy()
+ const row = api.getByTestId("compact-row")
+ expect(row.props.accessibilityValue.text).toBe("SpinningLoader")
+ expect(row.props.accessibilityState.disabled).toBe(false)
+ })
+
+ it("says it gives space back and deletes nothing", async () => {
+ const api = renderScreen()
+
+ expect(await api.findByText("Gives unused space back. Deletes nothing.")).toBeTruthy()
})
it("measures both sizes at the same moment, and says nothing rather than claiming a non-event", async () => {
@@ -771,7 +810,7 @@ describe("DataManagementScreen", () => {
const api = renderScreen()
await api.findByText("12,480")
- fireEvent.press(api.getByTestId("compact-btn"))
+ fireEvent.press(api.getByTestId("compact-row"))
expect(await api.findByText("Nothing to release")).toBeTruthy()
})
@@ -782,9 +821,9 @@ describe("DataManagementScreen", () => {
// Queued only once the mount read has landed, so the sizes pair with the two reads compact takes.
mockGetStats.mockResolvedValueOnce(stats()).mockResolvedValue(stats({ databaseSizeMB: 3.0 }))
- fireEvent.press(api.getByTestId("compact-btn"))
+ fireEvent.press(api.getByTestId("compact-row"))
- expect(await api.findByText(/^Released 0\.4\d MB$/)).toBeTruthy()
+ expect(await api.findByText(/^Released 43\d KB$/)).toBeTruthy()
})
})
@@ -794,7 +833,7 @@ describe("DataManagementScreen", () => {
expect(await api.findByText("Nothing stored")).toBeTruthy()
expect(api.queryByTestId("delete-all-btn")).toBeNull()
- expect(api.getByText("0.02 MB")).toBeTruthy()
- expect(api.getByTestId("compact-btn")).toBeTruthy()
+ expect(api.getByText("20 KB")).toBeTruthy()
+ expect(api.getByTestId("compact-row")).toBeTruthy()
})
})
diff --git a/apps/mobile/src/screens/__tests__/ExportImportScreen.test.tsx b/apps/mobile/src/screens/__tests__/ExportImportScreen.test.tsx
index 8a983cc3..f2a693e1 100644
--- a/apps/mobile/src/screens/__tests__/ExportImportScreen.test.tsx
+++ b/apps/mobile/src/screens/__tests__/ExportImportScreen.test.tsx
@@ -88,10 +88,10 @@ jest.mock("../../components", () => {
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) =>
+ ListItem: ({ label, sub, testID, onPress, disabled }: any) =>
R.createElement(
Pressable,
- { testID, onPress },
+ { testID, onPress, disabled, accessibilityState: { disabled: !!disabled } },
R.createElement(Text, null, label),
R.createElement(Text, null, sub)
),
@@ -102,18 +102,20 @@ jest.mock("../../components", () => {
R.createElement(Text, null, title)
),
LoadingOverlay: ({ visible, title }: any) => (visible ? R.createElement(Text, null, title) : null),
- ExportFormatDialog: ({ visible, onSelect }: any) =>
+ ExportFormatDialog: ({ visible, onSelect, message }: any) =>
visible
? R.createElement(
Pressable,
{ testID: "pick-geojson", onPress: () => onSelect("geojson") },
- R.createElement(Text, null, "Export format")
+ R.createElement(Text, null, "Export format"),
+ R.createElement(Text, null, message)
)
: null
}
})
import { ExportImportScreen } from "../ExportImportScreen"
+import { exportLine, readableFormats } from "../../utils/locationTransfer"
const stats = (over: Record<string, number> = {}) => ({ total: 12483, databaseSizeMB: 3.42, ...over })
@@ -147,7 +149,7 @@ const renderScreen = () => render(<ExportImportScreen navigation={mockNavigation
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"))
+ fireEvent.press(api.getByTestId("import-file-row"))
await waitFor(() => expect(mockImportLocationsFromFile).toHaveBeenCalled())
}
@@ -172,9 +174,9 @@ describe("ExportImportScreen", () => {
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.getByText("3 MB")).toBeTruthy()
+ expect(api.getByTestId("export-all-row")).toBeTruthy()
+ expect(api.getByTestId("import-file-row")).toBeTruthy()
expect(api.queryByTestId("import-commit-btn")).toBeNull()
expect(mockPickImportSource).not.toHaveBeenCalled()
})
@@ -185,15 +187,24 @@ describe("ExportImportScreen", () => {
// Both figures wait, rather than one of them claiming zero.
expect(api.getAllByText("…")).toHaveLength(2)
- expect(api.queryByText("Nothing to export yet.")).toBeNull()
+ 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 () => {
+ // There is no format picker; the parser detects the format.
+ it("names the formats an import reads on the row that starts one", async () => {
const api = renderScreen()
await api.findByText("12,483")
- expect(api.getByText(/there is nothing to choose/)).toBeTruthy()
+ expect(api.getByText(readableFormats())).toBeTruthy()
+ })
+
+ it("shows no standing caption between the cards", async () => {
+ const api = renderScreen()
+ await api.findByText("12,483")
+
+ expect(api.queryByText(/is not kept here/)).toBeNull()
+ expect(api.queryByText(/12,483 locations/)).toBeNull()
+ expect(api.queryByText(/An import cannot be undone/)).toBeNull()
})
it("carries the auto-export state on the row that opens it", async () => {
@@ -206,8 +217,8 @@ describe("ExportImportScreen", () => {
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)
+ expect(await api.findByText("Nothing to export yet")).toBeTruthy()
+ expect(api.getByTestId("export-all-row").props.accessibilityState.disabled).toBe(true)
})
})
@@ -216,7 +227,8 @@ describe("ExportImportScreen", () => {
const api = renderScreen()
await api.findByText("12,483")
- fireEvent.press(api.getByTestId("export-all-btn"))
+ fireEvent.press(api.getByTestId("export-all-row"))
+ expect(api.getByText(exportLine(12483))).toBeTruthy()
fireEvent.press(api.getByTestId("pick-geojson"))
await waitFor(() => expect(mockExportToFile).toHaveBeenCalledWith("geojson"))
@@ -229,7 +241,7 @@ describe("ExportImportScreen", () => {
const api = renderScreen()
await api.findByText("12,483")
- fireEvent.press(api.getByTestId("export-all-btn"))
+ fireEvent.press(api.getByTestId("export-all-row"))
fireEvent.press(api.getByTestId("pick-geojson"))
const line = await api.findByText(/no app took it/)
@@ -247,7 +259,7 @@ describe("ExportImportScreen", () => {
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()
+ expect(api.queryByTestId("import-file-row")).toBeNull()
})
// The reasoning moved off the card into the confirmation, so it has to actually arrive there.
@@ -294,6 +306,73 @@ describe("ExportImportScreen", () => {
expect(mockCommitImport).not.toHaveBeenCalled()
})
+ it("offers the backup with the staged file, not before", async () => {
+ const api = renderScreen()
+ await api.findByText("12,483")
+ expect(api.queryByTestId("nav-backup-restore")).toBeNull()
+
+ await stage(api)
+ fireEvent.press(await api.findByTestId("nav-backup-restore"))
+
+ expect(mockNavigation.navigate).toHaveBeenCalledWith("Backup & Restore")
+ })
+
+ it("says the file is being read and blocks a second pick while it is", async () => {
+ mockPickImportSource.mockResolvedValue({ uri: "content://file" })
+ mockImportLocationsFromFile.mockReturnValue(new Promise(() => {}))
+ const api = renderScreen()
+ await api.findByText("12,483")
+
+ fireEvent.press(api.getByTestId("import-file-row"))
+
+ expect(await api.findByText("Reading the file…")).toBeTruthy()
+ expect(api.getByTestId("import-file-row").props.accessibilityState.disabled).toBe(true)
+ })
+
+ // Opening Backup & Restore blurs this screen without unmounting it.
+ it("keeps the staged file across a trip to Backup & Restore", async () => {
+ const api = renderScreen()
+ await api.findByText("12,483")
+ await stage(api)
+
+ fireEvent.press(await api.findByTestId("nav-backup-restore"))
+ await act(async () => {
+ mockRefocus?.()
+ })
+ fireEvent.press(api.getByTestId("import-commit-btn"))
+
+ await waitFor(() => expect(mockCommitImport).toHaveBeenCalledWith(false))
+ expect(mockCancelImport).not.toHaveBeenCalled()
+ })
+
+ // Native drops a staged file after 15 minutes.
+ it("drops the card and says so when the staged file has expired", async () => {
+ mockCommitImport.mockRejectedValue({ code: "E_IMPORT_NO_PENDING" })
+ const api = renderScreen()
+ await api.findByText("12,483")
+ await stage(api)
+
+ fireEvent.press(api.getByTestId("import-commit-btn"))
+
+ expect(await api.findByText("The file you picked expired. Choose it again.")).toBeTruthy()
+ expect(api.queryByTestId("import-commit-btn")).toBeNull()
+ expect(api.getByTestId("import-file-row")).toBeTruthy()
+ })
+
+ // A running parse holds the import lock, so leaving the screen has to release it.
+ it("cancels a parse still running when the screen closes", async () => {
+ mockPickImportSource.mockResolvedValue({ uri: "content://file" })
+ mockImportLocationsFromFile.mockReturnValue(new Promise(() => {}))
+ const api = renderScreen()
+ await api.findByText("12,483")
+
+ fireEvent.press(api.getByTestId("import-file-row"))
+ await waitFor(() => expect(mockImportLocationsFromFile).toHaveBeenCalled())
+ api.unmount()
+
+ expect(mockCancelImport).toHaveBeenCalled()
+ })
+
it("hides the queue switch when there is no server to queue to", async () => {
const api = renderScreen()
await api.findByText("12,483")
@@ -323,7 +402,7 @@ describe("ExportImportScreen", () => {
fireEvent.press(api.getByTestId("import-discard-btn"))
await waitFor(() => expect(mockCancelImport).toHaveBeenCalled())
- expect(api.getByTestId("import-file-btn")).toBeTruthy()
+ expect(api.getByTestId("import-file-row")).toBeTruthy()
})
// The stash sits in native memory on a 15 minute timer, so leaving the screen has to free it.
@@ -343,7 +422,7 @@ describe("ExportImportScreen", () => {
const api = renderScreen()
await api.findByText("12,483")
- fireEvent.press(api.getByTestId("import-file-btn"))
+ fireEvent.press(api.getByTestId("import-file-row"))
expect(await api.findByText("Another import is already running.")).toBeTruthy()
})
diff --git a/apps/mobile/src/screens/__tests__/SettingsScreen.test.tsx b/apps/mobile/src/screens/__tests__/SettingsScreen.test.tsx
index b375b4cf..1b6a795b 100644
--- a/apps/mobile/src/screens/__tests__/SettingsScreen.test.tsx
+++ b/apps/mobile/src/screens/__tests__/SettingsScreen.test.tsx
@@ -298,7 +298,7 @@ describe("SettingsScreen", () => {
it("prints the cadence, the appearance and the ledger's own numbers", async () => {
const api = renderScreen()
- expect(await api.findByText("12,480 locations · 3.42 MB")).toBeTruthy()
+ expect(await api.findByText("12,480 locations · 3 MB")).toBeTruthy()
expect(api.getByText("Every 5 s, any movement · syncs each fix")).toBeTruthy()
expect(api.getByText("Dark · Metric · 24h")).toBeTruthy()
})
@@ -339,7 +339,7 @@ describe("SettingsScreen", () => {
mockGetAutoExportStatus.mockRejectedValue(new Error("bridge"))
const api = renderScreen()
- expect(await api.findByText("12,480 locations · 3.42 MB")).toBeTruthy()
+ expect(await api.findByText("12,480 locations · 3 MB")).toBeTruthy()
expect(api.getByText("File logging on · 2.4 MB")).toBeTruthy()
expect(api.getByText("No saved areas")).toBeTruthy()
// The export status never landed, so the row falls back to the nouns inside the screen.
@@ -359,7 +359,7 @@ describe("SettingsScreen", () => {
it("re-reads only the two cheap values on a sync event, not the pack walk", async () => {
const api = renderScreen()
- await api.findByText("12,480 locations · 3.42 MB")
+ await api.findByText("12,480 locations · 3 MB")
const packWalks = mockLoadOfflineAreas.mock.calls.length
mockGetStats.mockResolvedValue({
@@ -375,7 +375,7 @@ describe("SettingsScreen", () => {
DeviceEventEmitter.emit("onLocationUpdate", {})
})
- expect(await api.findByText("12,481 locations · 3.42 MB")).toBeTruthy()
+ expect(await api.findByText("12,481 locations · 3 MB")).toBeTruthy()
expect(mockLoadOfflineAreas.mock.calls.length).toBe(packWalks)
})
diff --git a/apps/mobile/src/utils/__tests__/backupState.test.ts b/apps/mobile/src/utils/__tests__/backupState.test.ts
index 1d42ba99..93d45f1f 100644
--- a/apps/mobile/src/utils/__tests__/backupState.test.ts
+++ b/apps/mobile/src/utils/__tests__/backupState.test.ts
@@ -33,7 +33,7 @@ describe("backupState", () => {
it("says when the last backup was, and what a new one would hold", () => {
const line = backupState(Date.parse(MADE_AT), { total: 12481, databaseSizeMB: 8.42 })
expect(line.label).toBe(`You last backed up ${formatDateWithYear(MADE_SECONDS)}`)
- expect(line.caption).toBe("Database: 12,481 locations, 8.42 MB")
+ expect(line.caption).toBe("Database: 12,481 locations, 8 MB")
expect(line.tone).toBe("ok")
})
diff --git a/apps/mobile/src/utils/__tests__/dataScope.test.ts b/apps/mobile/src/utils/__tests__/dataScope.test.ts
index 3df8f2de..8d6d61ac 100644
--- a/apps/mobile/src/utils/__tests__/dataScope.test.ts
+++ b/apps/mobile/src/utils/__tests__/dataScope.test.ts
@@ -1,4 +1,4 @@
-import { allSub, deleteCopy, olderSub, scopeSub } from "../dataScope"
+import { deleteCopy, olderSub, scopeSub } from "../dataScope"
import { formatDateWithYear, loadDisplayPreferences } from "../geo"
const mockGetSetting = jest.fn()
@@ -40,8 +40,8 @@ describe("scopeSub", () => {
})
describe("olderSub", () => {
- it("names the boundary the count used", () => {
- expect(olderSub(3120, 90, CUTOFF)).toBe(`Recorded before ${formatDateWithYear(CUTOFF)}.`)
+ it("names the count and the boundary it used", () => {
+ expect(olderSub(3120, 90, CUTOFF)).toBe(`3,120 locations recorded before ${formatDateWithYear(CUTOFF)}.`)
})
// Counting those reads every matching row, so the confirmation is the only place worth taking it.
@@ -55,15 +55,6 @@ describe("olderSub", () => {
})
})
-describe("allSub", () => {
- it("names the trip splits and merges, which no label, hint or dialog has ever named", () => {
- // clearAllLocations empties boundary_overrides as well as locations and the queue.
- expect(allSub(12480)).toBe(
- "All 12,480 locations and every trip split and merge you made. Geofences, profiles and settings stay."
- )
- })
-})
-
describe("deleteCopy", () => {
it("tells the queued case that the recordings go, not the pending uploads", () => {
const copy = deleteCopy("queued", 412)
diff --git a/apps/mobile/src/utils/__tests__/exportConverters.test.ts b/apps/mobile/src/utils/__tests__/exportConverters.test.ts
index f4e5a7da..58947e1c 100644
--- a/apps/mobile/src/utils/__tests__/exportConverters.test.ts
+++ b/apps/mobile/src/utils/__tests__/exportConverters.test.ts
@@ -1,4 +1,3 @@
-import { formatBytes } from "../format"
import {
EXPORT_FORMAT_KEYS,
EXPORT_FORMATS,
@@ -11,25 +10,7 @@ import { FILE_FORMATS } from "../fileFormats"
// Trip serialization moved to native ExportConverters.kt; parity is covered by
// the golden-fixture tests in ExportConvertersTest.kt. This file now only covers
-// the byte formatter and the export-format metadata registry.
-
-describe("formatBytes", () => {
- it("formats bytes", () => {
- expect(formatBytes(0)).toBe("0 B")
- expect(formatBytes(500)).toBe("500 B")
- expect(formatBytes(1023)).toBe("1023 B")
- })
-
- it("formats kilobytes", () => {
- expect(formatBytes(1024)).toBe("1.0 KB")
- expect(formatBytes(1536)).toBe("1.5 KB")
- })
-
- it("formats megabytes", () => {
- expect(formatBytes(1048576)).toBe("1.0 MB")
- expect(formatBytes(1572864)).toBe("1.5 MB")
- })
-})
+// the export-format metadata registry.
describe("export format registry", () => {
it("exportable formats are fully wired for export", () => {
diff --git a/apps/mobile/src/utils/__tests__/format.test.ts b/apps/mobile/src/utils/__tests__/format.test.ts
index 272150ed..33de23a3 100644
--- a/apps/mobile/src/utils/__tests__/format.test.ts
+++ b/apps/mobile/src/utils/__tests__/format.test.ts
@@ -1,4 +1,4 @@
-import { formatCount } from "../format"
+import { formatBytes, formatCount } from "../format"
describe("formatCount", () => {
it("keeps counts that fit a stat column exact to the digit", () => {
@@ -27,3 +27,32 @@ describe("formatCount", () => {
expect(formatCount(12_345_678)).toBe("12.3M")
})
})
+
+describe("formatBytes", () => {
+ it("steps up through KB, MB and GB at 1024", () => {
+ expect(formatBytes(0, { locale: "en-US" })).toBe("0 B")
+ expect(formatBytes(512, { locale: "en-US" })).toBe("512 B")
+ expect(formatBytes(1023, { locale: "en-US" })).toBe("1023 B")
+ expect(formatBytes(1024, { locale: "en-US" })).toBe("1.0 KB")
+ expect(formatBytes(1536, { locale: "en-US" })).toBe("1.5 KB")
+ expect(formatBytes(1024 * 1024 - 1, { locale: "en-US" })).toMatch(/KB$/)
+ expect(formatBytes(1024 * 1024, { locale: "en-US" })).toBe("1.0 MB")
+ expect(formatBytes(3.42 * 1024 * 1024, { locale: "en-US" })).toBe("3.4 MB")
+ expect(formatBytes(1.2 * 1024 ** 3, { locale: "en-US" })).toBe("1.2 GB")
+ })
+
+ it("uses the locale's decimal separator, so a size never reads as a grouped count", () => {
+ expect(formatBytes(195.3 * 1024 * 1024, { locale: "de-DE" })).toBe("195,3 MB")
+ expect(formatBytes(1536, { locale: "de-DE" })).toBe("1,5 KB")
+ })
+
+ it("drops the decimal when asked, as the database size does", () => {
+ expect(formatBytes(195.3 * 1024 * 1024, { decimals: 0, locale: "de-DE" })).toBe("195 MB")
+ expect(formatBytes(1.2 * 1024 ** 3, { decimals: 0, locale: "en-US" })).toBe("1 GB")
+ })
+
+ // Callers convert megabytes, which can leave a fraction of a byte.
+ it("rounds a fraction of a byte instead of printing it", () => {
+ expect(formatBytes(524.288, { locale: "en-US" })).toBe("524 B")
+ })
+})
diff --git a/apps/mobile/src/utils/__tests__/locationTransfer.test.ts b/apps/mobile/src/utils/__tests__/locationTransfer.test.ts
index fbcd255f..e8ab27c3 100644
--- a/apps/mobile/src/utils/__tests__/locationTransfer.test.ts
+++ b/apps/mobile/src/utils/__tests__/locationTransfer.test.ts
@@ -9,8 +9,9 @@ import {
emptyPreviewCopy,
exportLine,
exportResultLine,
+ exportRowSub,
importErrorMessage,
- importSourceLine,
+ importRowSub,
previewHeadline,
queueHint,
readableFormats,
@@ -73,16 +74,23 @@ describe("exportLine", () => {
})
})
-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.")
+describe("exportRowSub", () => {
+ it("describes the file without repeating the count", () => {
+ expect(exportRowSub(12483)).toBe("Every location in one file")
})
- // 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)
+ it("says there is nothing to export on an empty database", () => {
+ expect(exportRowSub(0)).toBe("Nothing to export yet")
+ })
+})
+
+describe("importRowSub", () => {
+ it("lists the formats from the shared table, since the parser decides and there is no picker", () => {
+ expect(importRowSub(false)).toBe(readableFormats())
+ })
+
+ it("says the file is being read while the parse runs", () => {
+ expect(importRowSub(true)).toBe("Reading the file…")
})
})
@@ -189,6 +197,13 @@ describe("importErrorMessage", () => {
expect(line).toContain("DOCTYPE")
})
+ // A CSV with a bad header is refused before any preview exists.
+ it("names the CSV header the parser needs when it refuses a file", () => {
+ expect(importErrorMessage("E_IMPORT_UNSUPPORTED")).toContain(
+ "In a CSV, the header must include latitude, longitude and a time column."
+ )
+ })
+
// 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.")
diff --git a/apps/mobile/src/utils/__tests__/settingsRow.test.ts b/apps/mobile/src/utils/__tests__/settingsRow.test.ts
index 297ef681..c4d50062 100644
--- a/apps/mobile/src/utils/__tests__/settingsRow.test.ts
+++ b/apps/mobile/src/utils/__tests__/settingsRow.test.ts
@@ -41,11 +41,11 @@ describe("loggingRowSub", () => {
})
describe("dataRowSub", () => {
- it("formats exactly as the ledger it opens, two decimals and a grouped count", () => {
- expect(dataRowSub(12480, 3.4213)).toBe("12,480 locations · 3.42 MB")
+ it("formats exactly as the ledger it opens, whole megabytes and a grouped count", () => {
+ expect(dataRowSub(12480, 3.4213)).toBe("12,480 locations · 3 MB")
})
- it("words the zero rather than printing 0 locations · 0.00 MB", () => {
+ it("words the zero count even when the database has a size", () => {
expect(dataRowSub(0, 0.02)).toBe("No locations recorded")
})
})
diff --git a/apps/mobile/src/utils/backupState.ts b/apps/mobile/src/utils/backupState.ts
index 0296042b..da7e701c 100644
--- a/apps/mobile/src/utils/backupState.ts
+++ b/apps/mobile/src/utils/backupState.ts
@@ -5,6 +5,7 @@
import type { BackupManifest, PasswordStrengthResult } from "../services/BackupService"
import { formatDateWithYear } from "./geo"
+import { formatBytes } from "./format"
/**
* What a backup holds and what restoring one replaces, in the words the screen prints.
@@ -35,7 +36,7 @@ export function backupState(
lastBackupAtMs: number | null,
stats: { total: number; databaseSizeMB: number }
): BackupStateLine {
- const caption = `Database: ${plural(stats.total, "location")}, ${stats.databaseSizeMB.toFixed(2)} MB`
+ const caption = `Database: ${plural(stats.total, "location")}, ${formatBytes(stats.databaseSizeMB * 1024 * 1024, { decimals: 0 })}`
const when = whenBackedUp(lastBackupAtMs)
if (when) return { label: `You last backed up ${when}`, caption, tone: "ok" }
if (stats.total === 0) return { label: "You have never backed up", caption, tone: "empty" }
diff --git a/apps/mobile/src/utils/dataScope.ts b/apps/mobile/src/utils/dataScope.ts
index e59a1192..bc9551a5 100644
--- a/apps/mobile/src/utils/dataScope.ts
+++ b/apps/mobile/src/utils/dataScope.ts
@@ -38,18 +38,13 @@ export function scopeSub(scope: "queued" | "synced", count: number): string {
}
/**
- * The line under the age button: the boundary the count used. How many of them have no copy on the
- * server is not here, because that count reads every matching row and is only worth taking once, on
- * the press, where `deleteCopy` says it.
+ * The sub on the Delete older locations row. How many of them have no copy on the server is not here,
+ * because that count reads every matching row and is only worth taking once, on the press, where
+ * `deleteCopy` says it.
*/
export function olderSub(count: number, days: number, cutoffSeconds: number): string {
if (count === 0) return `Nothing on this device is older than ${plural(days, "day")}.`
- return `Recorded before ${formatDateWithYear(cutoffSeconds)}.`
-}
-
-/** The line under Delete all: the two things it takes that no label has ever named. */
-export function allSub(total: number): string {
- return `All ${plural(total, "location")} and every trip split and merge you made. Geofences, profiles and settings stay.`
+ return `${plural(count, "location")} recorded before ${formatDateWithYear(cutoffSeconds)}.`
}
export interface OlderArgs {
diff --git a/apps/mobile/src/utils/format.ts b/apps/mobile/src/utils/format.ts
index 3d3f7472..bfdefbc6 100644
--- a/apps/mobile/src/utils/format.ts
+++ b/apps/mobile/src/utils/format.ts
@@ -3,11 +3,17 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
-/** Formats a byte count as B / KB / MB. */
-export const formatBytes = (bytes: number): string => {
- if (bytes < 1024) return `${bytes} B`
- if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
- return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
+/** B, KB, MB or GB in the device locale's separators, with one decimal unless `decimals` says otherwise. */
+export const formatBytes = (
+ bytes: number,
+ { decimals = 1, locale }: { decimals?: number; locale?: string } = {}
+): string => {
+ const scaled = (n: number) =>
+ n.toLocaleString(locale, { minimumFractionDigits: decimals, maximumFractionDigits: decimals })
+ if (bytes < 1024) return `${Math.round(bytes)} B`
+ if (bytes < 1024 ** 2) return `${scaled(bytes / 1024)} KB`
+ if (bytes < 1024 ** 3) return `${scaled(bytes / 1024 ** 2)} MB`
+ return `${scaled(bytes / 1024 ** 3)} GB`
}
/**
diff --git a/apps/mobile/src/utils/locationTransfer.ts b/apps/mobile/src/utils/locationTransfer.ts
index b9c43eed..d08979fd 100644
--- a/apps/mobile/src/utils/locationTransfer.ts
+++ b/apps/mobile/src/utils/locationTransfer.ts
@@ -36,12 +36,17 @@ export function readableFormats(): string {
return [...new Set(labels)].join(", ")
}
-/** The line under the export button: the scope, and what happens to the file. */
+/** The format dialog's message, and the result line when an export finds nothing. */
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.`
}
+/** The sub on the Export all locations row. */
+export function exportRowSub(total: number): string {
+ return total === 0 ? "Nothing to export yet" : "Every location in one file"
+}
+
/** 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.`
@@ -50,12 +55,12 @@ export function exportResultLine(rowCount: number, format: string): string {
/** 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 Import a file row. */
+export function importRowSub(reading: boolean): string {
+ return reading ? "Reading the file…" : readableFormats()
}
-/** The sub on the row above the import verb. The only route back is a whole-database restore. */
+/** The sub on the Back up first row in the staged preview. */
export function backupFirstSub(): string {
return "An import cannot be undone. A backup is the only way back."
}
@@ -133,8 +138,12 @@ export function emptyPreviewCopy(preview: ImportPreview): string {
/** 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_IMPORT_UNSUPPORTED": {
+ // A CSV with a bad header is refused here, before any preview exists.
+ const hint = FILE_FORMATS.csv.importHint
+ const csv = hint ? ` In a CSV, ${hint.charAt(0).toLowerCase()}${hint.slice(1)}` : ""
+ return `Colota did not recognise this file. It reads ${readableFormats()}, and it refuses an XML file that declares a DOCTYPE.${csv}`
+ }
case "E_BUSY":
return "Another import is already running."
case "E_IMPORT_NO_PENDING":
diff --git a/apps/mobile/src/utils/settingsRow.ts b/apps/mobile/src/utils/settingsRow.ts
index 680d85dd..efbe3538 100644
--- a/apps/mobile/src/utils/settingsRow.ts
+++ b/apps/mobile/src/utils/settingsRow.ts
@@ -31,7 +31,7 @@ export function loggingRowSub(enabled: boolean, bytes: number): string {
/** Formatted exactly as the ledger it opens, so the row and the screen cannot disagree. */
export function dataRowSub(total: number, databaseSizeMB: number): string {
if (total === 0) return "No locations recorded"
- return `${total.toLocaleString()} locations · ${databaseSizeMB.toFixed(2)} MB`
+ return `${total.toLocaleString()} locations · ${formatBytes(databaseSizeMB * 1024 * 1024, { decimals: 0 })}`
}
/** The build a user is running, as `versionLine` and `buildLine` name it after the version. */