Skip to content

Colota - Android GPS Location tracker

feat: multi-select trips for bulk export and delete (#387) (#409)

Max Dietrich83a3e3b7c7f2
diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.md
index b5a2b126..0d1628a1 100644
--- a/apps/docs/docs/development/architecture.md
+++ b/apps/docs/docs/development/architecture.md
@@ -293,7 +293,7 @@ For backups, two `internal` methods support the export/import flow without expos
| `GeofenceEditorScreen` | Configure a zone: name, radius, record pause, WiFi pause, motionless pause and timeout, stationary heartbeat |
| `TrackingProfilesScreen` | List and manage condition-based tracking profiles |
| `ProfileEditorScreen` | Create/edit a profile's name, condition, GPS settings, priority, and deactivation delay |
-| `LocationInspectorScreen` | Calendar day picker with activity dots, map tab with trip-colored tracks, trips tab with trip cards and export |
+| `LocationInspectorScreen` | Calendar day picker with activity dots, map tab with trip-colored tracks, trips tab with trip cards, per-trip and multi-select export and multi-select delete |
| `TripDetailScreen` | Full trip view with dedicated map, stats grid, speed and elevation profile charts, per-trip export, and per-trip delete |
| `LocationSummaryScreen` | Aggregated stats for selectable periods (week/month/30 days) with daily breakdown and tap-to-inspect navigation |
| `ExportLocationsScreen` | Export all tracked locations via native streaming converters as CSV, GeoJSON, GPX, or KML |
@@ -328,7 +328,7 @@ The app uses [MapLibre GL Native](https://github.com/maplibre/maplibre-react-nat
| `DashboardMap` | Live tracking map with user marker, accuracy circle, today's track overlay with toggle button, geofence polygons with labels, auto-center, and center button |
| `TrackMap` | Location history map with trip-colored track segments, tappable point markers with detail popups, fit-to-track bounds, and trip legend |
| `CalendarPicker` | Day picker with month navigation, dot indicators for days with data, and daily distance/count display |
-| `TripList` | Segmented trip cards with distance, duration, avg speed, elevation gain/loss, and per-trip or bulk export |
+| `TripList` | Segmented trip cards with distance, duration, avg speed, elevation gain/loss. Per-trip share icon plus a long-press contextual action bar for multi-select export and delete |
| `GeofenceLayers` | Shared geofence rendering (fill polygons, stroke outlines, labels) used by DashboardMap and GeofenceScreen |
| `UserLocationOverlay` | User position dot with accuracy circle, used by DashboardMap and GeofenceScreen |
| `MapCenterButton` | Reusable button overlay to re-center the map |
diff --git a/apps/docs/docs/guides/data-export.md b/apps/docs/docs/guides/data-export.md
index 52ab244d..c47be0fa 100644
--- a/apps/docs/docs/guides/data-export.md
+++ b/apps/docs/docs/guides/data-export.md
@@ -32,12 +32,20 @@ Data Export produces shareable, human-readable formats (CSV, GeoJSON, GPX, KML)
### Trip Export
-1. Go to **Location History** → **Trips** tab
-2. Tap the export icon to export all trips for the selected day, or tap a trip card and export that single trip
-3. Select the format
-4. Share via Android's share menu
+Go to **Location History** -> **Trips** tab. 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.
+
+For a single trip you can also tap the card to open **Trip Detail**, then 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.
+
+### Delete Trips
+
+From the **Trips** tab, long-press a trip card to enter selection mode, add any other trips you want to remove, then tap the trash icon in the selection header. You'll be asked to confirm before the underlying location points are permanently deleted from the device.
-Trip exports include a `trip` column/property so each location is tagged with its trip number.
+Single-trip delete is also available from the **Trip Detail** screen via the trash icon in the header.
import ScreenshotGallery from '@site/src/components/ScreenshotGallery'
diff --git a/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt
index ecc79de5..d0a0f2fd 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt
@@ -39,6 +39,7 @@ import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
+import com.facebook.react.bridge.ReadableArray
import com.facebook.react.bridge.ReadableMap
import com.facebook.react.bridge.WritableMap
import com.facebook.react.modules.core.DeviceEventManagerModule
@@ -413,6 +414,18 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
fun deleteLocationsInRange(startTs: Double, endTs: Double, promise: Promise) = executeAsync(promise) {
deleteThenVacuum(refresh = true) { dbHelper.deleteInRange(startTs.toLong(), endTs.toLong()) }
}
+
+ @ReactMethod
+ fun deleteLocationsInRanges(ranges: ReadableArray, promise: Promise) = executeAsync(promise) {
+ val pairs = mutableListOf<Pair<Long, Long>>()
+ for (i in 0 until ranges.size()) {
+ val r = ranges.getMap(i) ?: continue
+ val start = r.getDouble("start").toLong()
+ val end = r.getDouble("end").toLong()
+ pairs.add(start to end)
+ }
+ deleteThenVacuum(refresh = true) { dbHelper.deleteInRanges(pairs) }
+ }
@ReactMethod
fun vacuumDatabase(promise: Promise) = executeAsync(promise) {
diff --git a/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt
index 83c3c5ea..570d4c53 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt
@@ -794,6 +794,28 @@ class DatabaseHelper private constructor(context: Context) :
)
}
+ /** Single-transaction multi-range delete. All ranges succeed or none do. */
+ fun deleteInRanges(ranges: List<Pair<Long, Long>>): Int {
+ requireNotRestoring()
+ if (ranges.isEmpty()) return 0
+ val db = writableDatabase
+ var total = 0
+ db.beginTransaction()
+ try {
+ for ((startTs, endTs) in ranges) {
+ total += db.delete(
+ TABLE_LOCATIONS,
+ "timestamp >= ? AND timestamp <= ?",
+ arrayOf(startTs.toString(), endTs.toString())
+ )
+ }
+ db.setTransactionSuccessful()
+ } finally {
+ db.endTransaction()
+ }
+ return total
+ }
+
/** Reclaims unused space. Call from background thread only. */
fun vacuum() {
requireNotRestoring()
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/data/DatabaseHelperSQLiteTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/data/DatabaseHelperSQLiteTest.kt
index 64e58f91..0124a5a5 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/data/DatabaseHelperSQLiteTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/data/DatabaseHelperSQLiteTest.kt
@@ -805,6 +805,37 @@ class DatabaseHelperSQLiteTest {
assertEquals(setOf(1000L, 4000L), timestamps)
}
+ // ========================================================================
+ // deleteInRanges
+ // ========================================================================
+
+ @Test
+ fun `deleteInRanges removes locations across non-contiguous ranges atomically`() {
+ db.saveLocation(latitude = 50.0, longitude = 10.0, timestamp = 1000L) // in range 1
+ db.saveLocation(latitude = 51.0, longitude = 11.0, timestamp = 1500L) // in range 1
+ db.saveLocation(latitude = 52.0, longitude = 12.0, timestamp = 2500L) // gap, retained
+ db.saveLocation(latitude = 53.0, longitude = 13.0, timestamp = 3500L) // in range 2
+ db.saveLocation(latitude = 54.0, longitude = 14.0, timestamp = 4500L) // after, retained
+
+ val deleted = db.deleteInRanges(listOf(1000L to 2000L, 3000L to 4000L))
+ assertEquals(3, deleted)
+
+ val remaining = db.getTableData(DatabaseHelper.TABLE_LOCATIONS, 100, 0)
+ val timestamps = remaining.map { (it["timestamp"] as Number).toLong() }.toSet()
+ assertEquals(setOf(2500L, 4500L), timestamps)
+ }
+
+ @Test
+ fun `deleteInRanges with empty list deletes nothing`() {
+ db.saveLocation(latitude = 50.0, longitude = 10.0, timestamp = 1000L)
+
+ val deleted = db.deleteInRanges(emptyList())
+ assertEquals(0, deleted)
+
+ val remaining = db.getTableData(DatabaseHelper.TABLE_LOCATIONS, 100, 0)
+ assertEquals(1, remaining.size)
+ }
+
// ========================================================================
// Helpers
// ========================================================================
diff --git a/apps/mobile/src/components/features/inspector/TripList.tsx b/apps/mobile/src/components/features/inspector/TripList.tsx
index ba706b64..08cc50cf 100644
--- a/apps/mobile/src/components/features/inspector/TripList.tsx
+++ b/apps/mobile/src/components/features/inspector/TripList.tsx
@@ -3,9 +3,9 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
-import React, { useState, useCallback, useMemo } from "react"
-import { View, Text, FlatList, Pressable, StyleSheet } from "react-native"
-import { Clock, Route, Share, TrendingUp, TrendingDown, Gauge } from "lucide-react-native"
+import React, { useState, useCallback, useMemo, useEffect, useRef } from "react"
+import { View, Text, FlatList, Pressable, StyleSheet, BackHandler } from "react-native"
+import { Clock, Route, Share, TrendingUp, TrendingDown, Gauge, Trash2, X } from "lucide-react-native"
import { Card } from "../../ui/Card"
import { fonts } from "../../../styles/typography"
import { formatDistance, formatDuration, formatSpeed, formatTime } from "../../../utils/geo"
@@ -19,13 +19,122 @@ interface TripListProps {
colors: ThemeColors
onTripSelect: (trip: Trip) => void
selectedTripIndex?: number | null
- onExport?: (format: ExportFormat) => void
- onExportTrip?: (format: ExportFormat, trip: Trip) => void
+ onExport?: (format: ExportFormat, trips: Trip[]) => void
+ onDelete?: (trips: Trip[]) => Promise<void>
}
-export function TripList({ trips, colors, onTripSelect, selectedTripIndex, onExport, onExportTrip }: TripListProps) {
+interface TripRowProps {
+ trip: Trip
+ colors: ThemeColors
+ stats: TripStats | undefined
+ selectionMode: boolean
+ isCabSelected: boolean
+ isMapSelected: boolean
+ onPress: (trip: Trip) => void
+ onLongPress: (trip: Trip) => void
+}
+
+const TripRow = React.memo(function TripRow({
+ trip,
+ colors,
+ stats,
+ selectionMode,
+ isCabSelected,
+ isMapSelected,
+ onPress,
+ onLongPress
+}: TripRowProps) {
+ const duration = trip.endTime - trip.startTime
+ const tripColor = getTripColor(trip.index)
+ const selectedBorderColor = isCabSelected ? colors.primary : isMapSelected ? tripColor : null
+
+ const cardStyle = [
+ styles.tripCard,
+ selectedBorderColor && [styles.tripCardSelected, { borderColor: selectedBorderColor }]
+ ]
+
+ const accessibilityRole = selectionMode ? "checkbox" : "button"
+ const accessibilityState = selectionMode ? { checked: isCabSelected } : undefined
+ const accessibilityLabel = selectionMode
+ ? `Trip ${trip.index}, ${formatDistance(trip.distance)}, ${formatDuration(duration)}`
+ : `Trip ${trip.index}, ${formatDistance(trip.distance)}, ${formatDuration(duration)}, open details`
+
+ return (
+ <Card
+ variant="interactive"
+ onPress={() => onPress(trip)}
+ onLongPress={() => onLongPress(trip)}
+ style={cardStyle}
+ accessibilityRole={accessibilityRole}
+ accessibilityState={accessibilityState}
+ accessibilityLabel={accessibilityLabel}
+ accessibilityHint={selectionMode ? undefined : "Long-press to select multiple trips"}
+ >
+ <View style={styles.tripHeader}>
+ <View style={styles.tripTitleRow}>
+ <View style={[styles.tripDot, { backgroundColor: tripColor }]} />
+ <Text style={[styles.tripTitle, { color: colors.text }]}>Trip {trip.index}</Text>
+ </View>
+ <Text style={[styles.tripTime, { color: colors.textSecondary }]}>
+ {formatTime(trip.startTime)} - {formatTime(trip.endTime)}
+ </Text>
+ </View>
+
+ <View style={styles.tripStats}>
+ <View style={styles.stat}>
+ <Route size={13} color={colors.textSecondary} />
+ <Text style={[styles.statText, { color: colors.text }]}>{formatDistance(trip.distance)}</Text>
+ </View>
+ <View style={styles.stat}>
+ <Clock size={13} color={colors.textSecondary} />
+ <Text style={[styles.statText, { color: colors.text }]}>{formatDuration(duration)}</Text>
+ </View>
+ {stats && stats.avgSpeed > 0 && (
+ <View style={styles.stat}>
+ <Gauge size={13} color={colors.textSecondary} />
+ <Text style={[styles.statText, { color: colors.text }]}>{formatSpeed(stats.avgSpeed)}</Text>
+ </View>
+ )}
+ {stats && stats.elevationGain > 0 && (
+ <View style={styles.stat}>
+ <TrendingUp size={13} color={colors.textSecondary} />
+ <Text style={[styles.statText, { color: colors.text }]}>{Math.round(stats.elevationGain)}m</Text>
+ </View>
+ )}
+ {stats && stats.elevationLoss > 0 && (
+ <View style={styles.stat}>
+ <TrendingDown size={13} color={colors.textSecondary} />
+ <Text style={[styles.statText, { color: colors.text }]}>{Math.round(stats.elevationLoss)}m</Text>
+ </View>
+ )}
+ </View>
+ </Card>
+ )
+})
+
+export function TripList({ trips, colors, onTripSelect, selectedTripIndex, onExport, onDelete }: TripListProps) {
const [showExport, setShowExport] = useState(false)
- const [exportingTripIndex, setExportingTripIndex] = useState<number | null>(null)
+ const [selected, setSelected] = useState<Set<number>>(new Set())
+ const selectionMode = selected.size > 0
+
+ useEffect(() => {
+ setSelected(new Set())
+ setShowExport(false)
+ }, [trips])
+
+ useEffect(() => {
+ if (!selectionMode) return
+ const sub = BackHandler.addEventListener("hardwareBackPress", () => {
+ setSelected(new Set())
+ setShowExport(false)
+ return true
+ })
+ return () => sub.remove()
+ }, [selectionMode])
+
+ const selectedTrips = useMemo(() => trips.filter((t) => selected.has(t.index)), [trips, selected])
+ const allSelected = selectionMode && selected.size === trips.length
+
const totalDistance = trips.reduce((sum, t) => sum + t.distance, 0)
const statsCache = useMemo(() => {
@@ -36,94 +145,69 @@ export function TripList({ trips, colors, onTripSelect, selectedTripIndex, onExp
return map
}, [trips])
- const renderTrip = useCallback(
- ({ item }: { item: Trip }) => {
- const duration = item.endTime - item.startTime
- const tripColor = getTripColor(item.index)
- const isSelected = selectedTripIndex === item.index
- const showTripExport = exportingTripIndex === item.index
- const stats = statsCache.get(item.index)
+ const selectionModeRef = useRef(selectionMode)
+ selectionModeRef.current = selectionMode
+ const onTripSelectRef = useRef(onTripSelect)
+ onTripSelectRef.current = onTripSelect
- return (
- <Card
- variant="interactive"
- onPress={() => onTripSelect(item)}
- style={[styles.tripCard, isSelected && [styles.tripCardSelected, { borderColor: tripColor }]]}
- >
- <View style={styles.tripHeader}>
- <View style={styles.tripTitleRow}>
- <View style={[styles.tripDot, { backgroundColor: tripColor }]} />
- <Text style={[styles.tripTitle, { color: colors.text }]}>Trip {item.index}</Text>
- </View>
- <View style={styles.tripTitleRow}>
- <Text style={[styles.tripTime, { color: colors.textSecondary }]}>
- {formatTime(item.startTime)} - {formatTime(item.endTime)}
- </Text>
- {onExportTrip && (
- <Pressable
- onPress={() => setExportingTripIndex((prev) => (prev === item.index ? null : item.index))}
- hitSlop={HIT_SLOP_SM}
- style={({ pressed }) => pressed && { opacity: colors.pressedOpacity }}
- >
- <Share size={14} color={showTripExport ? colors.primary : colors.textSecondary} />
- </Pressable>
- )}
- </View>
- </View>
+ const handleRowPress = useCallback((trip: Trip) => {
+ if (selectionModeRef.current) {
+ setSelected((prev) => {
+ const next = new Set(prev)
+ if (next.has(trip.index)) next.delete(trip.index)
+ else next.add(trip.index)
+ return next
+ })
+ } else {
+ onTripSelectRef.current(trip)
+ }
+ }, [])
- {showTripExport && onExportTrip && (
- <View style={styles.tripExportRow}>
- {EXPORT_FORMAT_KEYS.map((fmt) => (
- <Pressable
- key={fmt}
- onPress={() => {
- onExportTrip(fmt, item)
- setExportingTripIndex(null)
- }}
- style={({ pressed }) => [
- styles.exportChip,
- { backgroundColor: colors.primary + "12", borderColor: colors.primary + "30" },
- pressed && { opacity: colors.pressedOpacity }
- ]}
- >
- <Text style={[styles.exportChipText, { color: colors.primary }]}>{EXPORT_FORMATS[fmt].label}</Text>
- </Pressable>
- ))}
- </View>
- )}
+ const handleRowLongPress = useCallback((trip: Trip) => {
+ setSelected((prev) => {
+ const next = new Set(prev)
+ next.add(trip.index)
+ return next
+ })
+ setShowExport(false)
+ }, [])
- <View style={styles.tripStats}>
- <View style={styles.stat}>
- <Route size={13} color={colors.textSecondary} />
- <Text style={[styles.statText, { color: colors.text }]}>{formatDistance(item.distance)}</Text>
- </View>
- <View style={styles.stat}>
- <Clock size={13} color={colors.textSecondary} />
- <Text style={[styles.statText, { color: colors.text }]}>{formatDuration(duration)}</Text>
- </View>
- {stats && stats.avgSpeed > 0 && (
- <View style={styles.stat}>
- <Gauge size={13} color={colors.textSecondary} />
- <Text style={[styles.statText, { color: colors.text }]}>{formatSpeed(stats.avgSpeed)}</Text>
- </View>
- )}
- {stats && stats.elevationGain > 0 && (
- <View style={styles.stat}>
- <TrendingUp size={13} color={colors.textSecondary} />
- <Text style={[styles.statText, { color: colors.text }]}>{Math.round(stats.elevationGain)}m</Text>
- </View>
- )}
- {stats && stats.elevationLoss > 0 && (
- <View style={styles.stat}>
- <TrendingDown size={13} color={colors.textSecondary} />
- <Text style={[styles.statText, { color: colors.text }]}>{Math.round(stats.elevationLoss)}m</Text>
- </View>
- )}
- </View>
- </Card>
- )
- },
- [colors, onTripSelect, selectedTripIndex, onExportTrip, exportingTripIndex, statsCache]
+ const handleSelectAllToggle = useCallback(() => {
+ setSelected((prev) => (prev.size === trips.length ? new Set() : new Set(trips.map((t) => t.index))))
+ }, [trips])
+
+ const handleCancelSelection = useCallback(() => {
+ setSelected(new Set())
+ setShowExport(false)
+ }, [])
+
+ const deletingRef = useRef(false)
+ const handleDeleteSelected = useCallback(async () => {
+ if (!onDelete || selectedTrips.length === 0 || deletingRef.current) return
+ deletingRef.current = true
+ try {
+ await onDelete(selectedTrips)
+ setSelected(new Set())
+ setShowExport(false)
+ } finally {
+ deletingRef.current = false
+ }
+ }, [onDelete, selectedTrips])
+
+ const renderTrip = useCallback(
+ ({ item }: { item: Trip }) => (
+ <TripRow
+ trip={item}
+ colors={colors}
+ stats={statsCache.get(item.index)}
+ selectionMode={selectionMode}
+ isCabSelected={selected.has(item.index)}
+ isMapSelected={!selectionMode && selectedTripIndex === item.index}
+ onPress={handleRowPress}
+ onLongPress={handleRowLongPress}
+ />
+ ),
+ [colors, statsCache, selectionMode, selected, selectedTripIndex, handleRowPress, handleRowLongPress]
)
if (trips.length === 0) {
@@ -138,36 +222,99 @@ export function TripList({ trips, colors, onTripSelect, selectedTripIndex, onExp
return (
<View style={styles.container}>
- <View style={styles.headerRow}>
- <Text style={[styles.summary, { color: colors.textSecondary }]}>
- {trips.length} {trips.length === 1 ? "trip" : "trips"} · {formatDistance(totalDistance)}
- </Text>
- {onExport && (
- <Pressable
- onPress={() => setShowExport((prev) => !prev)}
- style={({ pressed }) => [styles.exportAllBtn, pressed && { opacity: colors.pressedOpacity }]}
- >
- <Share size={14} color={showExport ? colors.primary : colors.textSecondary} />
- <Text style={[styles.exportAllLabel, { color: showExport ? colors.primary : colors.textSecondary }]}>
- Export All
- </Text>
- </Pressable>
- )}
- </View>
+ {selectionMode ? (
+ <View style={[styles.headerRow, { backgroundColor: colors.primary + "12" }]}>
+ <View style={styles.cabLeft}>
+ <Pressable
+ onPress={handleCancelSelection}
+ hitSlop={HIT_SLOP_SM}
+ style={({ pressed }) => [styles.cabIconBtn, pressed && { opacity: colors.pressedOpacity }]}
+ accessibilityRole="button"
+ accessibilityLabel="Cancel selection"
+ >
+ <X size={18} color={colors.text} />
+ </Pressable>
+ <Text style={[styles.cabSummary, { color: colors.text }]}>{selected.size} selected</Text>
+ </View>
+ <View style={styles.cabActions}>
+ <Pressable
+ onPress={handleSelectAllToggle}
+ hitSlop={HIT_SLOP_SM}
+ style={({ pressed }) => [styles.cabTextBtn, pressed && { opacity: colors.pressedOpacity }]}
+ accessibilityRole="button"
+ accessibilityLabel={allSelected ? "Clear selection" : "Select all trips"}
+ >
+ <Text style={[styles.cabTextBtnLabel, { color: allSelected ? colors.primary : colors.text }]}>
+ {allSelected ? "Clear" : "All"}
+ </Text>
+ </Pressable>
+ {onExport && (
+ <Pressable
+ onPress={() => setShowExport((prev) => !prev)}
+ hitSlop={HIT_SLOP_SM}
+ style={({ pressed }) => [styles.cabIconBtn, pressed && { opacity: colors.pressedOpacity }]}
+ accessibilityRole="button"
+ accessibilityLabel="Export selected trips"
+ accessibilityState={{ expanded: showExport }}
+ >
+ <Share size={18} color={showExport ? colors.primary : colors.text} />
+ </Pressable>
+ )}
+ {onDelete && (
+ <Pressable
+ onPress={handleDeleteSelected}
+ hitSlop={HIT_SLOP_SM}
+ style={({ pressed }) => [styles.cabIconBtn, pressed && { opacity: colors.pressedOpacity }]}
+ accessibilityRole="button"
+ accessibilityLabel="Delete selected trips"
+ >
+ <Trash2 size={18} color={colors.error} />
+ </Pressable>
+ )}
+ </View>
+ </View>
+ ) : (
+ <View style={styles.headerRow}>
+ <Text style={[styles.summary, { color: colors.textSecondary }]}>
+ {trips.length} {trips.length === 1 ? "trip" : "trips"} · {formatDistance(totalDistance)}
+ </Text>
+ {onExport && (
+ <Pressable
+ onPress={() => setShowExport((prev) => !prev)}
+ style={({ pressed }) => [styles.exportAllBtn, pressed && { opacity: colors.pressedOpacity }]}
+ accessibilityRole="button"
+ accessibilityLabel="Export all trips"
+ accessibilityState={{ expanded: showExport }}
+ >
+ <Share size={14} color={showExport ? colors.primary : colors.textSecondary} />
+ <Text style={[styles.exportAllLabel, { color: showExport ? colors.primary : colors.textSecondary }]}>
+ Export All
+ </Text>
+ </Pressable>
+ )}
+ </View>
+ )}
{showExport && onExport && (
<View style={styles.exportRow}>
{EXPORT_FORMAT_KEYS.map((fmt) => (
<Pressable
key={fmt}
onPress={() => {
- onExport(fmt)
+ onExport(fmt, selectionMode ? selectedTrips : trips)
setShowExport(false)
+ if (selectionMode) setSelected(new Set())
}}
style={({ pressed }) => [
styles.exportChip,
{ backgroundColor: colors.primary + "12", borderColor: colors.primary + "30" },
pressed && { opacity: colors.pressedOpacity }
]}
+ accessibilityRole="button"
+ accessibilityLabel={
+ selectionMode
+ ? `Export ${selectedTrips.length} selected trips as ${EXPORT_FORMATS[fmt].label}`
+ : `Export all trips as ${EXPORT_FORMATS[fmt].label}`
+ }
>
<Text style={[styles.exportChipText, { color: colors.primary }]}>{EXPORT_FORMATS[fmt].label}</Text>
</Pressable>
@@ -179,6 +326,7 @@ export function TripList({ trips, colors, onTripSelect, selectedTripIndex, onExp
renderItem={renderTrip}
keyExtractor={(item) => `trip-${item.index}`}
contentContainerStyle={styles.list}
+ extraData={selected}
/>
</View>
)
@@ -193,8 +341,40 @@ const styles = StyleSheet.create({
alignItems: "center",
justifyContent: "space-between",
paddingHorizontal: 16,
- paddingTop: 12,
- paddingBottom: 8
+ paddingTop: 10,
+ paddingBottom: 14,
+ minHeight: 54
+ },
+ cabLeft: {
+ flexDirection: "row",
+ alignItems: "center",
+ gap: 4,
+ flexShrink: 1
+ },
+ cabSummary: {
+ fontSize: 13,
+ ...fonts.semiBold
+ },
+ cabActions: {
+ flexDirection: "row",
+ alignItems: "center",
+ gap: 4
+ },
+ cabIconBtn: {
+ minWidth: 48,
+ minHeight: 48,
+ alignItems: "center",
+ justifyContent: "center"
+ },
+ cabTextBtn: {
+ minHeight: 48,
+ paddingHorizontal: 10,
+ alignItems: "center",
+ justifyContent: "center"
+ },
+ cabTextBtnLabel: {
+ fontSize: 13,
+ ...fonts.semiBold
},
summary: {
fontSize: 12,
@@ -204,7 +384,8 @@ const styles = StyleSheet.create({
flexDirection: "row",
alignItems: "center",
gap: 4,
- padding: 6
+ paddingHorizontal: 12,
+ minHeight: 48
},
exportAllLabel: {
fontSize: 11,
@@ -214,7 +395,8 @@ const styles = StyleSheet.create({
flexDirection: "row",
gap: 8,
paddingHorizontal: 16,
- paddingBottom: 8
+ paddingTop: 10,
+ paddingBottom: 12
},
exportChip: {
paddingHorizontal: 10,
@@ -226,12 +408,6 @@ const styles = StyleSheet.create({
fontSize: 11,
...fonts.bold
},
- tripExportRow: {
- flexDirection: "row",
- flexWrap: "wrap",
- gap: 6,
- marginBottom: 8
- },
list: {
paddingHorizontal: 12,
paddingBottom: 16
diff --git a/apps/mobile/src/components/features/inspector/__tests__/TripList.test.tsx b/apps/mobile/src/components/features/inspector/__tests__/TripList.test.tsx
new file mode 100644
index 00000000..50f157d5
--- /dev/null
+++ b/apps/mobile/src/components/features/inspector/__tests__/TripList.test.tsx
@@ -0,0 +1,276 @@
+import React from "react"
+import { render, fireEvent, act } from "@testing-library/react-native"
+import type { Trip } from "../../../../types/global"
+import type { ExportFormat } from "../../../../utils/exportConverters"
+
+jest.mock("../../../../utils/geo", () => ({
+ formatDistance: (m: number) => `${(m / 1000).toFixed(1)} km`,
+ formatDuration: (s: number) => `${Math.round(s / 60)}m`,
+ formatSpeed: (s: number) => `${s} m/s`,
+ formatTime: (_ts: number) => "12:00"
+}))
+
+jest.mock("../../../../utils/trips", () => ({
+ getTripColor: (i: number) => `#color${i}`,
+ computeTripStats: () => ({ avgSpeed: 0, elevationGain: 0, elevationLoss: 0 })
+}))
+
+jest.mock("../../../../styles/typography", () => ({
+ fonts: { regular: {}, bold: {}, semiBold: {} }
+}))
+
+jest.mock("../../../../utils/exportConverters", () => ({
+ EXPORT_FORMATS: {
+ csv: { label: "CSV" },
+ geojson: { label: "GeoJSON" },
+ gpx: { label: "GPX" },
+ kml: { label: "KML" }
+ },
+ EXPORT_FORMAT_KEYS: ["csv", "geojson", "gpx", "kml"]
+}))
+
+jest.mock("../../../../hooks/useTheme", () => ({
+ useTheme: () => ({
+ colors: {
+ primary: "#0d9488",
+ text: "#000",
+ textSecondary: "#6b7280",
+ textDisabled: "#9ca3af",
+ border: "#e5e7eb",
+ card: "#fff",
+ cardElevated: "#f9fafb",
+ error: "#ef4444",
+ pressedOpacity: 0.7
+ }
+ })
+}))
+
+jest.mock("lucide-react-native", () => {
+ const R = require("react")
+ const { Text } = require("react-native")
+ const stub = (name: string) => (_props: any) => R.createElement(Text, null, name)
+ return {
+ Clock: stub("Clock"),
+ Route: stub("Route"),
+ Share: stub("Share"),
+ TrendingUp: stub("TrendingUp"),
+ TrendingDown: stub("TrendingDown"),
+ Gauge: stub("Gauge"),
+ Trash2: stub("Trash2"),
+ X: stub("X"),
+ CheckSquare: stub("CheckSquare"),
+ Square: stub("Square")
+ }
+})
+
+import { TripList } from "../TripList"
+
+const colors = {
+ primary: "#0d9488",
+ text: "#000",
+ textSecondary: "#6b7280",
+ textDisabled: "#9ca3af",
+ border: "#e5e7eb",
+ card: "#fff",
+ error: "#ef4444",
+ pressedOpacity: 0.7
+} as any
+
+function makeTrip(index: number, distance = 1000): Trip {
+ return {
+ index,
+ locations: [],
+ startTime: index * 100,
+ endTime: index * 100 + 60,
+ distance,
+ locationCount: 5
+ }
+}
+
+function makeTrips(n: number): Trip[] {
+ return Array.from({ length: n }, (_, i) => makeTrip(i + 1))
+}
+
+describe("TripList - CAB selection", () => {
+ beforeEach(() => jest.clearAllMocks())
+
+ it("renders idle header with Export All when trips exist", () => {
+ const { getByLabelText, queryByLabelText } = render(
+ <TripList trips={makeTrips(3)} colors={colors} onTripSelect={jest.fn()} onExport={jest.fn()} />
+ )
+ expect(getByLabelText("Export all trips")).toBeTruthy()
+ expect(queryByLabelText("Cancel selection")).toBeNull()
+ })
+
+ it("long-press on a card enters selection mode and shows CAB", () => {
+ const { getByLabelText, queryByLabelText } = render(
+ <TripList
+ trips={makeTrips(3)}
+ colors={colors}
+ onTripSelect={jest.fn()}
+ onExport={jest.fn()}
+ onDelete={jest.fn().mockResolvedValue(undefined)}
+ />
+ )
+
+ fireEvent(getByLabelText(/Trip 1,/), "longPress")
+
+ expect(getByLabelText("Cancel selection")).toBeTruthy()
+ expect(getByLabelText("Export selected trips")).toBeTruthy()
+ expect(getByLabelText("Delete selected trips")).toBeTruthy()
+ expect(queryByLabelText("Export all trips")).toBeNull()
+ })
+
+ it("tap in selection mode toggles, does not navigate", () => {
+ const onTripSelect = jest.fn()
+ const { getByLabelText } = render(
+ <TripList trips={makeTrips(3)} colors={colors} onTripSelect={onTripSelect} onExport={jest.fn()} />
+ )
+
+ fireEvent(getByLabelText(/Trip 1,/), "longPress")
+ fireEvent.press(getByLabelText(/Trip 2,/))
+
+ expect(onTripSelect).not.toHaveBeenCalled()
+ })
+
+ it("tap when idle navigates via onTripSelect", () => {
+ const onTripSelect = jest.fn()
+ const { getByLabelText } = render(
+ <TripList trips={makeTrips(3)} colors={colors} onTripSelect={onTripSelect} onExport={jest.fn()} />
+ )
+
+ fireEvent.press(getByLabelText(/Trip 2,/))
+
+ expect(onTripSelect).toHaveBeenCalledTimes(1)
+ expect(onTripSelect.mock.calls[0][0].index).toBe(2)
+ })
+
+ it("Select all selects every trip, then deselect all clears", () => {
+ const onExport = jest.fn()
+ const { getByLabelText } = render(
+ <TripList trips={makeTrips(3)} colors={colors} onTripSelect={jest.fn()} onExport={onExport} />
+ )
+
+ fireEvent(getByLabelText(/Trip 1,/), "longPress")
+ fireEvent.press(getByLabelText("Select all trips"))
+ fireEvent.press(getByLabelText("Export selected trips"))
+ fireEvent.press(getByLabelText(/Export 3 selected trips as GPX/))
+
+ expect(onExport).toHaveBeenCalledTimes(1)
+ const [, trips] = onExport.mock.calls[0]
+ expect(trips.map((t: Trip) => t.index)).toEqual([1, 2, 3])
+ })
+
+ it("CAB Share exports only the selected subset (non-contiguous)", () => {
+ const onExport = jest.fn()
+ const trips = makeTrips(3)
+ const { getByLabelText } = render(
+ <TripList trips={trips} colors={colors} onTripSelect={jest.fn()} onExport={onExport} />
+ )
+
+ fireEvent(getByLabelText(/Trip 1,/), "longPress")
+ fireEvent.press(getByLabelText(/Trip 3,/))
+ fireEvent.press(getByLabelText("Export selected trips"))
+ fireEvent.press(getByLabelText(/Export 2 selected trips as GeoJSON/))
+
+ expect(onExport).toHaveBeenCalledTimes(1)
+ const [fmt, exported] = onExport.mock.calls[0] as [ExportFormat, Trip[]]
+ expect(fmt).toBe("geojson")
+ expect(exported.map((t) => t.index)).toEqual([1, 3])
+ })
+
+ it("CAB Trash fires onDelete with the selected subset", async () => {
+ const onDelete = jest.fn().mockResolvedValue(undefined)
+ const { getByLabelText } = render(
+ <TripList
+ trips={makeTrips(3)}
+ colors={colors}
+ onTripSelect={jest.fn()}
+ onExport={jest.fn()}
+ onDelete={onDelete}
+ />
+ )
+
+ fireEvent(getByLabelText(/Trip 2,/), "longPress")
+ await act(async () => {
+ fireEvent.press(getByLabelText("Delete selected trips"))
+ })
+
+ expect(onDelete).toHaveBeenCalledTimes(1)
+ expect(onDelete.mock.calls[0][0].map((t: Trip) => t.index)).toEqual([2])
+ })
+
+ it("double-press Trash does not fire onDelete twice while in-flight", async () => {
+ let resolve!: () => void
+ const onDelete = jest.fn().mockImplementation(
+ () =>
+ new Promise<void>((r) => {
+ resolve = r
+ })
+ )
+ const { getByLabelText } = render(
+ <TripList
+ trips={makeTrips(3)}
+ colors={colors}
+ onTripSelect={jest.fn()}
+ onExport={jest.fn()}
+ onDelete={onDelete}
+ />
+ )
+
+ fireEvent(getByLabelText(/Trip 1,/), "longPress")
+
+ await act(async () => {
+ fireEvent.press(getByLabelText("Delete selected trips"))
+ fireEvent.press(getByLabelText("Delete selected trips"))
+ })
+
+ expect(onDelete).toHaveBeenCalledTimes(1)
+
+ await act(async () => {
+ resolve()
+ })
+ })
+
+ it("Cancel X clears selection and returns to idle header", () => {
+ const { getByLabelText, queryByLabelText } = render(
+ <TripList trips={makeTrips(3)} colors={colors} onTripSelect={jest.fn()} onExport={jest.fn()} />
+ )
+
+ fireEvent(getByLabelText(/Trip 1,/), "longPress")
+ expect(getByLabelText("Cancel selection")).toBeTruthy()
+
+ fireEvent.press(getByLabelText("Cancel selection"))
+
+ expect(queryByLabelText("Cancel selection")).toBeNull()
+ expect(getByLabelText("Export all trips")).toBeTruthy()
+ })
+
+ it("changing the trips prop clears the selection", () => {
+ const { getByLabelText, queryByLabelText, rerender } = render(
+ <TripList trips={makeTrips(3)} colors={colors} onTripSelect={jest.fn()} onExport={jest.fn()} />
+ )
+
+ fireEvent(getByLabelText(/Trip 1,/), "longPress")
+ expect(getByLabelText("Cancel selection")).toBeTruthy()
+
+ rerender(<TripList trips={makeTrips(2)} colors={colors} onTripSelect={jest.fn()} onExport={jest.fn()} />)
+
+ expect(queryByLabelText("Cancel selection")).toBeNull()
+ })
+
+ it("idle Export All exports the full trips array", () => {
+ const onExport = jest.fn()
+ const { getByLabelText, getByText } = render(
+ <TripList trips={makeTrips(3)} colors={colors} onTripSelect={jest.fn()} onExport={onExport} />
+ )
+
+ fireEvent.press(getByLabelText("Export all trips"))
+ fireEvent.press(getByText("KML"))
+
+ expect(onExport).toHaveBeenCalledTimes(1)
+ const [fmt, exported] = onExport.mock.calls[0] as [ExportFormat, Trip[]]
+ expect(fmt).toBe("kml")
+ expect(exported).toHaveLength(3)
+ })
+})
diff --git a/apps/mobile/src/components/ui/Card.tsx b/apps/mobile/src/components/ui/Card.tsx
index 9ceebba7..1953bf87 100644
--- a/apps/mobile/src/components/ui/Card.tsx
+++ b/apps/mobile/src/components/ui/Card.tsx
@@ -4,7 +4,7 @@
*/
import React from "react"
-import { View, Pressable, StyleSheet, ViewStyle, StyleProp } from "react-native"
+import { View, Pressable, StyleSheet, ViewStyle, StyleProp, AccessibilityRole, AccessibilityState } from "react-native"
import { useTheme } from "../../hooks/useTheme"
type CardVariant = "default" | "elevated" | "outlined" | "interactive"
@@ -15,9 +15,25 @@ type CardProps = {
danger?: boolean
variant?: CardVariant
onPress?: () => void
+ onLongPress?: () => void
+ accessibilityRole?: AccessibilityRole
+ accessibilityLabel?: string
+ accessibilityHint?: string
+ accessibilityState?: AccessibilityState
}
-export function Card({ children, style, danger = false, variant = "default", onPress }: CardProps) {
+export function Card({
+ children,
+ style,
+ danger = false,
+ variant = "default",
+ onPress,
+ onLongPress,
+ accessibilityRole,
+ accessibilityLabel,
+ accessibilityHint,
+ accessibilityState
+}: CardProps) {
const { colors } = useTheme()
const getVariantStyles = (): ViewStyle => {
@@ -64,9 +80,17 @@ export function Card({ children, style, danger = false, variant = "default", onP
const cardView = <View style={[styles.card, getVariantStyles(), style]}>{children}</View>
- if (variant === "interactive" && onPress) {
+ if (variant === "interactive" && (onPress || onLongPress)) {
return (
- <Pressable onPress={onPress} style={({ pressed }) => ({ opacity: pressed ? colors.pressedOpacity : 1 })}>
+ <Pressable
+ onPress={onPress}
+ onLongPress={onLongPress}
+ accessibilityRole={accessibilityRole}
+ accessibilityLabel={accessibilityLabel}
+ accessibilityHint={accessibilityHint}
+ accessibilityState={accessibilityState}
+ style={({ pressed }) => ({ opacity: pressed ? colors.pressedOpacity : 1 })}
+ >
{cardView}
</Pressable>
)
diff --git a/apps/mobile/src/screens/LocationInspectorScreen.tsx b/apps/mobile/src/screens/LocationInspectorScreen.tsx
index 1c659366..dad57a40 100644
--- a/apps/mobile/src/screens/LocationInspectorScreen.tsx
+++ b/apps/mobile/src/screens/LocationInspectorScreen.tsx
@@ -21,7 +21,7 @@ import { formatDistance } from "../utils/geo"
import { pad2 } from "../utils/format"
import { segmentTrips } from "../utils/trips"
import { TRIP_CONVERTERS, EXPORT_FORMATS, type ExportFormat } from "../utils/exportConverters"
-import { showAlert } from "../services/modalService"
+import { showAlert, showConfirm } from "../services/modalService"
import type { RootScreenProps } from "../types/navigation"
interface TabProps {
@@ -200,10 +200,34 @@ export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Lo
setFitVersion((v) => v + 1)
}, [])
- const handleTripExport = useCallback((format: ExportFormat) => exportTrips(format, trips), [exportTrips, trips])
- const handleSingleTripExport = useCallback(
- (format: ExportFormat, trip: Trip) => exportTrips(format, [trip]),
- [exportTrips]
+ const handleDeleteTrips = useCallback(
+ async (toDelete: Trip[]) => {
+ if (toDelete.length === 0) return
+ const totalPoints = toDelete.reduce((n, t) => n + t.locationCount, 0)
+ const confirmed = await showConfirm({
+ title: toDelete.length === 1 ? `Delete Trip ${toDelete[0].index}?` : `Delete ${toDelete.length} trips?`,
+ message: `Removes ${totalPoints} location point${
+ totalPoints === 1 ? "" : "s"
+ } from this device only. Already-synced points remain on your server. Unsent points will not be uploaded.`,
+ confirmText: "Delete",
+ destructive: true
+ })
+ if (!confirmed) return
+ try {
+ await NativeLocationService.deleteLocationsInRanges(
+ toDelete.map((t) => ({ start: t.startTime, end: t.endTime }))
+ )
+ const key = `${mapDate.getFullYear()}-${pad2(mapDate.getMonth() + 1)}`
+ daysCache.current.delete(key)
+ distanceCache.current.delete(key)
+ await fetchTrackData()
+ await fetchDaysWithData(mapDate.getFullYear(), mapDate.getMonth())
+ } catch (error) {
+ logger.error("[LocationHistory] Trip delete failed:", error)
+ showAlert("Delete Failed", "Unable to delete selection. Please try again.", "error")
+ }
+ },
+ [mapDate, fetchTrackData, fetchDaysWithData]
)
const mapLocations = selectedTrip ? (selectedTrip.locations as LocationCoords[]) : trackLocations
@@ -268,8 +292,8 @@ export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Lo
colors={colors}
onTripSelect={handleTripSelect}
selectedTripIndex={selectedTrip?.index ?? null}
- onExport={handleTripExport}
- onExportTrip={handleSingleTripExport}
+ onExport={exportTrips}
+ onDelete={handleDeleteTrips}
/>
</View>
)}
diff --git a/apps/mobile/src/screens/__tests__/LocationHistoryScreen.test.tsx b/apps/mobile/src/screens/__tests__/LocationHistoryScreen.test.tsx
index f2faf507..9c618db1 100644
--- a/apps/mobile/src/screens/__tests__/LocationHistoryScreen.test.tsx
+++ b/apps/mobile/src/screens/__tests__/LocationHistoryScreen.test.tsx
@@ -7,9 +7,11 @@ jest.mock("../../services/NativeLocationService", () => ({
__esModule: true,
default: {
getDaysWithData: jest.fn().mockResolvedValue([]),
+ getDailyStats: jest.fn().mockResolvedValue([]),
getLocationsByDateRange: jest.fn().mockResolvedValue([]),
writeFile: jest.fn(),
- shareFile: jest.fn()
+ shareFile: jest.fn(),
+ deleteLocationsInRange: jest.fn().mockResolvedValue(0)
}
}))
@@ -27,7 +29,8 @@ jest.mock("../../utils/exportConverters", () => ({
}))
jest.mock("../../services/modalService", () => ({
- showAlert: jest.fn()
+ showAlert: jest.fn(),
+ showConfirm: jest.fn().mockResolvedValue(false)
}))
jest.mock("../../hooks/useTheme", () => ({
diff --git a/apps/mobile/src/services/NativeLocationService.ts b/apps/mobile/src/services/NativeLocationService.ts
index fe772d3a..7d28c16d 100644
--- a/apps/mobile/src/services/NativeLocationService.ts
+++ b/apps/mobile/src/services/NativeLocationService.ts
@@ -276,6 +276,17 @@ class NativeLocationService {
return LocationServiceModule.deleteLocationsInRange(startTs, endTs)
}
+ /**
+ * Deletes locations across multiple inclusive timestamp ranges in one transaction (seconds since epoch)
+ * @returns Count of deleted records
+ */
+ static async deleteLocationsInRanges(ranges: Array<{ start: number; end: number }>): Promise<number> {
+ this.ensureModule()
+ if (ranges.length === 0) return 0
+ logger.debug(`[NativeLocationService] Deleting locations across ${ranges.length} ranges`)
+ return LocationServiceModule.deleteLocationsInRanges(ranges)
+ }
+
/**
* Runs SQLite VACUUM to reclaim disk space
*/
diff --git a/fastlane/metadata/android/en-US/changelogs/39.txt b/fastlane/metadata/android/en-US/changelogs/39.txt
new file mode 100644
index 00000000..6ae60523
--- /dev/null
+++ b/fastlane/metadata/android/en-US/changelogs/39.txt
@@ -0,0 +1 @@
+- Multi-select trips in Location History: long-press a trip card to select multiple trips, then bulk export as CSV/GeoJSON/GPX/KML or delete them in one go.