Skip to content

Colota - Android GPS Location tracker

feat(trips): merge and split trips manually (#582)

Max Dietrichdb1a89a9547b
diff --git a/README.md b/README.md
index 334ba993..9e6665b3 100644
--- a/README.md
+++ b/README.md
@@ -20,7 +20,7 @@ Colota sends your location to your own server over HTTP(S). It works offline, su
- **Offline Maps** - Download map areas to your device for use without an internet connection.
- **Scheduled Export** - Automatic daily, weekly or monthly exports to a local directory with file retention management.
- **Encrypted Backup** - Single password-encrypted archive of all data (locations, settings, geofences, credentials) for migration or offsite storage.
-- **Location History** - View daily summaries, trip segmentation, calendar with activity dots and per-trip export.
+- **Location History** - View daily summaries, trip segmentation with manual merge and split, calendar with activity dots and per-trip export.
- **Reliable Tracking** - Foreground service, auto-start on boot and exponential backoff retry.
- **Geofencing** - Pause zones that automatically stop recording locations.
- **Tracking Profiles** - Automatically adjust GPS interval, distance filter and sync settings based on conditions like charging, car mode or speed.
diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.md
index 5bc15d48..dcdec646 100644
--- a/apps/docs/docs/development/architecture.md
+++ b/apps/docs/docs/development/architecture.md
@@ -167,15 +167,16 @@ Handles all notification logic for the tracking service:
### DatabaseHelper
-SQLite database singleton with five tables:
+SQLite database singleton with six tables:
-| Table | Purpose |
-| ------------------- | -------------------------------------------- |
-| `locations` | All recorded GPS locations |
-| `queue` | Locations pending upload |
-| `settings` | App configuration key-value pairs |
-| `geofences` | Pause zone definitions |
-| `tracking_profiles` | Condition-based tracking profile definitions |
+| Table | Purpose |
+| ------------------------- | -------------------------------------------- |
+| `locations` | All recorded GPS locations |
+| `queue` | Locations pending upload |
+| `settings` | App configuration key-value pairs |
+| `geofences` | Pause zone definitions |
+| `tracking_profiles` | Condition-based tracking profile definitions |
+| `trip_boundary_overrides` | Manual trip merges and splits |
Uses WAL (Write-Ahead Logging) mode and prepared statements for performance.
@@ -369,7 +370,7 @@ Supporting utilities in `mapUtils.ts`:
| `logger` | Environment-aware logging - suppresses debug/info console output in production via `__DEV__`, always logs warn/error to console. All levels are always captured in a ring buffer (2000 entries) for the Logging screen |
| `geo` | Haversine distance, speed/distance/duration/time formatting with configurable unit system (metric/imperial) and time format (12h/24h), auto-detected from locale on first use |
| `exportConverters` | Export-format metadata (labels, icons, extensions, MIME types) for the export UI. Serialization itself is native - see `ExportConverters.kt` |
-| `trips` | Trip segmentation via time-gap detection (15-min threshold), dropping segments whose bounding box spans under 100 m so stationary heartbeat runs do not become trips, plus distance computation, trip stats (avg speed, elevation gain/loss), and trip color assignment. `getDailyStats` in `DatabaseHelper.kt` mirrors both thresholds for the calendar and summary |
+| `trips` | Trip segmentation via time-gap detection (15-min threshold), dropping segments whose bounding box spans under 100 m so stationary heartbeat runs do not become trips, plus distance computation, trip stats (avg speed, elevation gain/loss), and trip color assignment. Manual `trip_boundary_overrides` take priority over the gap threshold, and a segment abutting a forced split is exempt from the 100 m filter so an explicit edit is never silently dropped. `getDailyStats` in `DatabaseHelper.kt` mirrors all of this for the calendar and summary |
| `queueStatus` | Maps sync queue size to color indicators for the dashboard |
| `settingsValidation` | URL validation and security checks for endpoint configuration |
diff --git a/apps/docs/docs/guides/backup-restore.md b/apps/docs/docs/guides/backup-restore.md
index b67c8d16..8db20269 100644
--- a/apps/docs/docs/guides/backup-restore.md
+++ b/apps/docs/docs/guides/backup-restore.md
@@ -15,6 +15,7 @@ Use this when you want a full archive of your data, when you're moving to a new
| Location history (the full SQLite database) | mTLS client certificate (private key in OS keystore - re-import the `.p12` after restore) |
| Settings (sync, GPS, server, appearance) | Offline map tiles (re-download after restore) |
| Geofences and tracking profiles | Cached map tiles |
+| Manual trip merges and splits (see [Editing Trips](editing-trips.md)) | |
| Auth credentials (Basic, Bearer, custom headers) | |
| mTLS Trusted Server CA (public cert bytes) | |
diff --git a/apps/docs/docs/guides/data-management.md b/apps/docs/docs/guides/data-management.md
index 1f23dbd9..4bd0e678 100644
--- a/apps/docs/docs/guides/data-management.md
+++ b/apps/docs/docs/guides/data-management.md
@@ -36,12 +36,16 @@ From the **Trips** tab, long-press a trip card to enter selection mode, add any
Single-trip delete is also available from the **Trip Detail** screen via the trash icon in the header.
+To correct how points are grouped into trips rather than remove them, see [Editing Trips](editing-trips.md).
+
### Single points
A stray fix can land far from where you actually were, which drags the track and the day's distance with it. On the **Map** tab, tap the point to open its popup, check the time and accuracy to make sure it is the one you mean, then tap the trash icon next to the close button. You'll be asked to confirm.
Only that one point is removed, so the rest of the trip stays intact. If the point had not synced yet, its pending upload is dropped with it.
+The same popup carries a split icon, which starts a new trip at that point instead of removing it - see [Editing Trips](editing-trips.md).
+
Deleting locally does not remove anything already uploaded to your server.
## Imported locations and the queue
diff --git a/apps/docs/docs/guides/editing-trips.md b/apps/docs/docs/guides/editing-trips.md
new file mode 100644
index 00000000..e8b20cca
--- /dev/null
+++ b/apps/docs/docs/guides/editing-trips.md
@@ -0,0 +1,70 @@
+---
+sidebar_position: 4
+---
+
+# Editing Trips
+
+Colota groups location history into trips automatically. A new trip starts after **15 minutes or more without a fix**. Where that guess is wrong, merge and split correct it. Neither changes your location data.
+
+Two cases the gap threshold gets wrong:
+
+- **One journey split up** - a long stop, bad signal indoors, a slow queue
+- **Two journeys run together** - driving to a trailhead and then hiking is one unbroken stream of fixes
+
+## Merging Trips
+
+1. Go to **Location History → Trips**
+2. Long-press a trip card to enter selection mode
+3. Tap the other trips you want to join
+4. Tap the merge icon in the selection header and confirm
+
+Merge is only available for trips next to each other in the list. Merging trips 1 and 3 would absorb trip 2, so select the whole run instead.
+
+No points are moved or deleted. Trips are renumbered afterwards, so a day with four trips shows three.
+
+## Splitting a Trip
+
+Split from the map, on either the **Map** tab or **Trip Detail**.
+
+1. Tap the point where the new trip should start
+2. Tap the split icon in the popup
+3. Confirm
+
+The previous trip ends at the point before the one you picked. The confirmation names that point's time, since the dialog covers the popup.
+
+On the Map tab the track is coloured per trip, so points from the split onwards change colour immediately. Splitting from Trip Detail returns you to the day view, because the trip you were viewing is now two.
+
+Zoom in first where points are bunched together, which happens wherever you moved slowly or stopped. The time in the popup identifies the exact point.
+
+### Points that cannot be split
+
+A split makes two trips and each needs at least two points. So the first two and last two points of a trip are unavailable, and a trip with fewer than **four points** cannot be split at all.
+
+The Map tab also draws points that belong to no trip, from runs that never travelled far enough to count as one. Those cannot be split either.
+
+Colota says which case applies instead of doing nothing.
+
+## What Edits Survive
+
+Edits are stored separately from location data, keyed by the timestamps either side of the boundary rather than by a specific point.
+
+| Survives | Does not survive |
+| ----------------------------------------------- | ------------------------------ |
+| Deleting points near an edited boundary | Delete All Locations |
+| Backup and restore, including to another device | Export and re-import elsewhere |
+
+Deleting a point next to an edited boundary keeps the edit valid. If the deletion leaves one side of a split with a single point, that side stops being shown as a trip. Exported files hold location points only, so importing them elsewhere gives you automatic segmentation.
+
+Editing the same boundary twice keeps the last action: splitting a boundary you previously merged overrides it, and the reverse also works. Trips are recomputed each time you open a day, so any edit can be undone with the opposite action.
+
+## Effect on Statistics
+
+The calendar and summary screens use the same boundaries as the trip list, so edits show up there too.
+
+Colota normally discards trips that never travel more than 100 m, which keeps stationary GPS jitter out of your history. A trip you split by hand is exempt, so a short segment you deliberately separated is kept.
+
+## Related
+
+- [Data Management](data-management.md) - deleting trips and individual points
+- [Backup & Restore](backup-restore.md) - what a backup includes
+- [Troubleshooting](troubleshooting.md) - other history and tracking issues
diff --git a/apps/docs/docs/guides/troubleshooting.md b/apps/docs/docs/guides/troubleshooting.md
index 05de1ca7..135704d1 100644
--- a/apps/docs/docs/guides/troubleshooting.md
+++ b/apps/docs/docs/guides/troubleshooting.md
@@ -33,6 +33,10 @@ Colota stops tracking below 5% (when unplugged) and resumes automatically once y
- Check if **High Accuracy** is enabled in device location settings
- Enable **Filter Inaccurate Locations** in app settings
+## Trips are split or merged in the wrong place
+
+Colota starts a new trip after a 15-minute gap in fixes, so a long stop can break one journey into several and two back-to-back activities can end up as one trip. Correct either case by hand from the Trips tab - see [Editing Trips](editing-trips.md).
+
## Server sync not working
1. Check endpoint URL format - must be `https://` for public endpoints, or `http://` for private/local addresses
diff --git a/apps/docs/sidebars.ts b/apps/docs/sidebars.ts
index 58eee49d..ce17f66f 100644
--- a/apps/docs/sidebars.ts
+++ b/apps/docs/sidebars.ts
@@ -51,6 +51,7 @@ const sidebars: SidebarsConfig = {
"guides/data-import",
"guides/data-export",
"guides/data-management",
+ "guides/editing-trips",
"guides/backup-restore",
"guides/deep-link-setup",
"guides/battery-optimization",
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 dc2fa8b5..ec07a427 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
@@ -457,6 +457,31 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
deleted
}
+ @ReactMethod
+ fun addBoundaryOverrides(overrides: ReadableArray, promise: Promise) = executeAsync(promise) {
+ val rows = mutableListOf<Triple<Long, Long, Int>>()
+ for (i in 0 until overrides.size()) {
+ val o = overrides.getMap(i) ?: continue
+ val before = o.getDouble("before_timestamp").toLong()
+ val after = o.getDouble("after_timestamp").toLong()
+ rows.add(Triple(before, after, o.getInt("action")))
+ }
+ dbHelper.addBoundaryOverrides(rows)
+ }
+
+ @ReactMethod
+ fun getBoundaryOverrides(promise: Promise) = executeAsync(promise) {
+ Arguments.createArray().apply {
+ dbHelper.getBoundaryOverrides().forEach { (before, after, action) ->
+ pushMap(Arguments.createMap().apply {
+ putDouble("before_timestamp", before.toDouble())
+ putDouble("after_timestamp", after.toDouble())
+ putInt("action", action)
+ })
+ }
+ }
+ }
+
@ReactMethod
fun vacuumDatabase(promise: Promise) = executeAsync(promise) {
dbHelper.vacuum()
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 ce477f57..2a6a9caf 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
@@ -32,13 +32,17 @@ class DatabaseHelper private constructor(context: Context) :
companion object {
const val DATABASE_NAME = "Colota.db"
- const val DATABASE_VERSION = 6
+ const val DATABASE_VERSION = 7
const val TABLE_LOCATIONS = "locations"
const val TABLE_QUEUE = "queue"
const val TABLE_SETTINGS = "settings"
const val TABLE_GEOFENCES = "geofences"
const val TABLE_PROFILES = "tracking_profiles"
+ const val TABLE_BOUNDARY_OVERRIDES = "trip_boundary_overrides"
+
+ const val BOUNDARY_ACTION_MERGE = 0
+ const val BOUNDARY_ACTION_SPLIT = 1
private val DEFAULT_FIELD_MAP = mapOf(
"lat" to "lat", "lon" to "lon", "acc" to "acc",
"alt" to "alt", "vel" to "vel", "batt" to "batt",
@@ -86,6 +90,18 @@ class DatabaseHelper private constructor(context: Context) :
private const val CREATE_PROFILES_INDEX =
"CREATE INDEX IF NOT EXISTS idx_profiles_enabled ON $TABLE_PROFILES(enabled, priority DESC)"
+ // Keyed by the timestamp pair either side of a boundary rather than by row id, so deleting
+ // a location leaves the override harmless instead of dangling.
+ private const val CREATE_BOUNDARY_OVERRIDES_TABLE = """
+ CREATE TABLE IF NOT EXISTS $TABLE_BOUNDARY_OVERRIDES (
+ before_timestamp INTEGER NOT NULL,
+ after_timestamp INTEGER NOT NULL,
+ action INTEGER NOT NULL,
+ created_at INTEGER NOT NULL,
+ PRIMARY KEY (before_timestamp, after_timestamp)
+ )
+ """
+
@Volatile
private var INSTANCE: DatabaseHelper? = null
@@ -237,6 +253,9 @@ class DatabaseHelper private constructor(context: Context) :
db.execSQL("UPDATE $TABLE_PROFILES SET activation_delay_seconds = 60 WHERE condition_type = 'stationary'")
db.execSQL("ALTER TABLE $TABLE_LOCATIONS ADD COLUMN note TEXT")
}
+ if (oldVersion < 7) {
+ db.execSQL(CREATE_BOUNDARY_OVERRIDES_TABLE)
+ }
}
@JvmStatic
@@ -310,6 +329,7 @@ class DatabaseHelper private constructor(context: Context) :
""")
db.execSQL(CREATE_PROFILES_TABLE)
+ db.execSQL(CREATE_BOUNDARY_OVERRIDES_TABLE)
db.execSQL("CREATE INDEX idx_queue_created ON $TABLE_QUEUE(created_at)")
db.execSQL("CREATE INDEX idx_queue_location ON $TABLE_QUEUE(location_id)")
@@ -813,9 +833,57 @@ class DatabaseHelper private constructor(context: Context) :
fun clearAllLocations(): Int {
requireNotRestoring()
writableDatabase.delete(TABLE_QUEUE, null, null) // FK constraint: queue references locations
+ writableDatabase.delete(TABLE_BOUNDARY_OVERRIDES, null, null) // derived state, no point keeping
return writableDatabase.delete(TABLE_LOCATIONS, null, null)
}
+ /**
+ * Persists manual trip boundary edits. Existing pairs are overwritten, so splitting a boundary
+ * the user previously merged (or the reverse) resolves to whichever action came last.
+ */
+ fun addBoundaryOverrides(overrides: List<Triple<Long, Long, Int>>): Int {
+ requireNotRestoring()
+ if (overrides.isEmpty()) return 0
+ val now = System.currentTimeMillis() / 1000
+ val db = writableDatabase
+ var written = 0
+ db.beginTransaction()
+ try {
+ db.compileStatement(
+ "INSERT OR REPLACE INTO $TABLE_BOUNDARY_OVERRIDES " +
+ "(before_timestamp, after_timestamp, action, created_at) VALUES (?, ?, ?, ?)"
+ ).use { stmt ->
+ for ((before, after, action) in overrides) {
+ stmt.clearBindings()
+ stmt.bindLong(1, before)
+ stmt.bindLong(2, after)
+ stmt.bindLong(3, action.toLong())
+ stmt.bindLong(4, now)
+ if (stmt.executeInsert() != -1L) written++
+ }
+ }
+ db.setTransactionSuccessful()
+ } finally {
+ db.endTransaction()
+ }
+ return written
+ }
+
+ fun getBoundaryOverrides(): List<Triple<Long, Long, Int>> {
+ val out = mutableListOf<Triple<Long, Long, Int>>()
+ readableDatabase.query(
+ TABLE_BOUNDARY_OVERRIDES,
+ arrayOf("before_timestamp", "after_timestamp", "action"),
+ null, null, null, null,
+ "before_timestamp ASC"
+ ).use { c ->
+ while (c.moveToNext()) {
+ out.add(Triple(c.getLong(0), c.getLong(1), c.getInt(2)))
+ }
+ }
+ return out
+ }
+
fun deleteOlderThan(days: Int): Int {
requireNotRestoring()
val cutoff = (System.currentTimeMillis() - days.toLong() * 24 * 60 * 60 * 1000) / 1000
@@ -980,6 +1048,14 @@ class DatabaseHelper private constructor(context: Context) :
*/
fun getDailyStats(startTimestamp: Long, endTimestamp: Long): List<Map<String, Any>> {
val stats = mutableListOf<Map<String, Any>>()
+ // Kept out of the block below: failing to read manual edits should fall back to plain
+ // automatic segmentation, not blank the caller's whole calendar month.
+ val overrides = try {
+ getBoundaryOverrides().associate { (before, after, action) -> (before to after) to action }
+ } catch (e: Exception) {
+ AppLogger.e(TAG, "Error loading trip boundary overrides", e)
+ emptyMap()
+ }
try {
readableDatabase.rawQuery(
"""
@@ -1009,14 +1085,25 @@ class DatabaseHelper private constructor(context: Context) :
var segMaxLon = 0.0
var segDistance = 0.0
var segCounted = false
+ var segForced = false
+ var segPoints = 0
+
+ fun countSegment() {
+ tripCount++
+ segCounted = true
+ distance += segDistance
+ segDistance = 0.0
+ }
- fun startSegment(lat: Double, lon: Double) {
+ fun startSegment(lat: Double, lon: Double, forced: Boolean = false) {
segMinLat = lat
segMaxLat = lat
segMinLon = lon
segMaxLon = lon
segDistance = 0.0
segCounted = false
+ segForced = forced
+ segPoints = 1
}
fun emitDay() {
@@ -1053,19 +1140,27 @@ class DatabaseHelper private constructor(context: Context) :
} else {
count++
endTime = ts
- if (ts - prevTs >= TRIP_GAP_SECONDS) {
- startSegment(lat, lon)
+ val override = overrides[prevTs to ts]
+ val forcedSplit = override == BOUNDARY_ACTION_SPLIT
+ if (forcedSplit || (override == null && ts - prevTs >= TRIP_GAP_SECONDS)) {
+ // The segment ending here abuts the split, so it is exempt from the
+ // extent filter too - but a lone point is still not a trip.
+ if (forcedSplit && !segCounted && segPoints >= 2) countSegment()
+ startSegment(lat, lon, forcedSplit)
} else {
+ segPoints++
segDistance += haversineDistance(prevLat, prevLon, lat, lon)
if (lat < segMinLat) segMinLat = lat
if (lat > segMaxLat) segMaxLat = lat
if (lon < segMinLon) segMinLon = lon
if (lon > segMaxLon) segMaxLon = lon
+ // Counting a forced segment is deferred to here, its second point, so a
+ // split left dangling by a later delete cannot conjure a one-point trip.
if (!segCounted &&
- haversineDistance(segMinLat, segMinLon, segMaxLat, segMaxLon) >= MIN_TRIP_EXTENT_METERS
+ (segForced ||
+ haversineDistance(segMinLat, segMinLon, segMaxLat, segMaxLon) >= MIN_TRIP_EXTENT_METERS)
) {
- tripCount++
- segCounted = true
+ countSegment()
}
if (segCounted) {
distance += segDistance
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 eb12ee1e..0ce6906e 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
@@ -20,8 +20,11 @@ import java.io.File
/**
* SQLite integration tests for DatabaseHelper using Robolectric.
- * Tests actual insert/query/delete, onUpgrade migration, WAL mode,
- * transaction handling, and foreign key cascades against a real SQLite DB.
+ * Tests actual insert/query/delete, WAL mode, transaction handling, and foreign key cascades
+ * against a real SQLite DB.
+ *
+ * Migrations are covered through `migrateCandidate`, the backup-restore entry point. `onUpgrade`
+ * delegates to the same `applyMigrations`, so the SQL is covered either way.
*/
@RunWith(RobolectricTestRunner::class)
class DatabaseHelperSQLiteTest {
@@ -59,13 +62,14 @@ class DatabaseHelperSQLiteTest {
// ========================================================================
@Test
- fun `onCreate creates all five tables`() {
+ fun `onCreate creates all six tables`() {
val tables = queryTableNames()
assertTrue(tables.contains("locations"))
assertTrue(tables.contains("queue"))
assertTrue(tables.contains("settings"))
assertTrue(tables.contains("geofences"))
assertTrue(tables.contains("tracking_profiles"))
+ assertTrue(tables.contains("trip_boundary_overrides"))
}
@Test
@@ -140,7 +144,10 @@ class DatabaseHelperSQLiteTest {
DatabaseHelper.migrateCandidate(candidate)
SQLiteDatabase.openDatabase(candidate.absolutePath, null, SQLiteDatabase.OPEN_READONLY).use { migrated ->
- assertEquals(6, migrated.version)
+ assertEquals(7, migrated.version)
+ // migrateCandidate stamps the version unconditionally, so the version alone proves
+ // nothing about the v7 step. This is the restore-an-older-backup path.
+ assertMigratedTableExists(migrated, DatabaseHelper.TABLE_BOUNDARY_OVERRIDES)
migrated.rawQuery(
"SELECT name, activation_delay_seconds FROM tracking_profiles",
null
@@ -176,7 +183,8 @@ class DatabaseHelperSQLiteTest {
DatabaseHelper.migrateCandidate(candidate)
SQLiteDatabase.openDatabase(candidate.absolutePath, null, SQLiteDatabase.OPEN_READONLY).use { migrated ->
- assertEquals(6, migrated.version)
+ assertEquals(7, migrated.version)
+ assertMigratedTableExists(migrated, DatabaseHelper.TABLE_BOUNDARY_OVERRIDES)
migrated.rawQuery("PRAGMA table_info(locations)", null).use { locCursor ->
val locCols = mutableSetOf<String>()
while (locCursor.moveToNext()) {
@@ -980,6 +988,127 @@ class DatabaseHelperSQLiteTest {
assertTrue("Distance should be < 40km, was $distance", distance < 40000)
}
+ // ========================================================================
+ // trip boundary overrides
+ // ========================================================================
+
+ @Test
+ fun `addBoundaryOverrides and getBoundaryOverrides round-trip`() {
+ db.addBoundaryOverrides(listOf(
+ Triple(1000L, 2000L, DatabaseHelper.BOUNDARY_ACTION_MERGE),
+ Triple(3000L, 4000L, DatabaseHelper.BOUNDARY_ACTION_SPLIT)
+ ))
+
+ val stored = db.getBoundaryOverrides()
+ assertEquals(2, stored.size)
+ assertEquals(Triple(1000L, 2000L, DatabaseHelper.BOUNDARY_ACTION_MERGE), stored[0])
+ assertEquals(Triple(3000L, 4000L, DatabaseHelper.BOUNDARY_ACTION_SPLIT), stored[1])
+ }
+
+ @Test
+ fun `writing the same boundary twice keeps the latest action`() {
+ // Splitting a boundary the user previously merged has to win outright - otherwise the
+ // edit silently does nothing and there is no separate cleanup step to fall back on.
+ db.addBoundaryOverrides(listOf(Triple(1000L, 2000L, DatabaseHelper.BOUNDARY_ACTION_MERGE)))
+ db.addBoundaryOverrides(listOf(Triple(1000L, 2000L, DatabaseHelper.BOUNDARY_ACTION_SPLIT)))
+
+ val stored = db.getBoundaryOverrides()
+ assertEquals(1, stored.size)
+ assertEquals(DatabaseHelper.BOUNDARY_ACTION_SPLIT, stored[0].third)
+ }
+
+ @Test
+ fun `addBoundaryOverrides is no-op for empty list`() {
+ assertEquals(0, db.addBoundaryOverrides(emptyList()))
+ assertTrue(db.getBoundaryOverrides().isEmpty())
+ }
+
+ @Test
+ fun `deleting a location leaves its override behind as an inert no-op`() {
+ // Overrides are keyed by timestamp, not row id. The contract is that a stale row must
+ // never break segmentation.
+ db.saveLocation(latitude = 52.52, longitude = 13.405, timestamp = 1000L)
+ db.addBoundaryOverrides(listOf(Triple(1000L, 2000L, DatabaseHelper.BOUNDARY_ACTION_MERGE)))
+
+ db.deleteInRange(1000L, 1000L)
+
+ assertEquals(1, db.getBoundaryOverrides().size)
+ val stats = db.getDailyStats(0L, 9999999L)
+ assertTrue(stats.isEmpty())
+ }
+
+ @Test
+ fun `clearAllLocations also drops boundary overrides`() {
+ db.saveLocation(latitude = 52.52, longitude = 13.405, timestamp = 1000L)
+ db.addBoundaryOverrides(listOf(Triple(1000L, 2000L, DatabaseHelper.BOUNDARY_ACTION_MERGE)))
+
+ db.clearAllLocations()
+
+ assertTrue(db.getBoundaryOverrides().isEmpty())
+ }
+
+ @Test
+ fun `getDailyStats merges two trips across a merged boundary`() {
+ // The calendar's trip count has to agree with the trip list, or the same day reports
+ // two different numbers depending on which screen you are on.
+ db.saveLocation(latitude = 52.52, longitude = 13.405, timestamp = 1708344000L)
+ db.saveLocation(latitude = 52.60, longitude = 13.405, timestamp = 1708344060L)
+ db.saveLocation(latitude = 52.70, longitude = 13.405, timestamp = 1708346000L) // 1940s gap
+ db.saveLocation(latitude = 52.80, longitude = 13.405, timestamp = 1708346060L)
+
+ assertEquals(2, db.getDailyStats(1708300000L, 1708400000L)[0]["tripCount"])
+
+ db.addBoundaryOverrides(listOf(
+ Triple(1708344060L, 1708346000L, DatabaseHelper.BOUNDARY_ACTION_MERGE)
+ ))
+ assertEquals(1, db.getDailyStats(1708300000L, 1708400000L)[0]["tripCount"])
+ }
+
+ @Test
+ fun `getDailyStats splits a trip at a manually split boundary`() {
+ db.saveLocation(latitude = 52.52, longitude = 13.405, timestamp = 1708344000L)
+ db.saveLocation(latitude = 52.60, longitude = 13.405, timestamp = 1708344060L)
+ db.saveLocation(latitude = 52.70, longitude = 13.405, timestamp = 1708344120L)
+ db.saveLocation(latitude = 52.80, longitude = 13.405, timestamp = 1708344180L)
+
+ assertEquals(1, db.getDailyStats(1708300000L, 1708400000L)[0]["tripCount"])
+
+ db.addBoundaryOverrides(listOf(
+ Triple(1708344060L, 1708344120L, DatabaseHelper.BOUNDARY_ACTION_SPLIT)
+ ))
+ assertEquals(2, db.getDailyStats(1708300000L, 1708400000L)[0]["tripCount"])
+ }
+
+ @Test
+ fun `getDailyStats drops a one-point segment even though a split forces it`() {
+ // Mirrors the JS segmenter: a split only gets written where both sides have two points,
+ // but a later delete can leave one side with a single fix. A lone point is not a trip.
+ db.saveLocation(latitude = 52.52, longitude = 13.405, timestamp = 1708344000L)
+ db.saveLocation(latitude = 52.60, longitude = 13.405, timestamp = 1708344060L)
+ db.saveLocation(latitude = 52.600001, longitude = 13.405, timestamp = 1708344120L)
+
+ db.addBoundaryOverrides(listOf(
+ Triple(1708344000L, 1708344060L, DatabaseHelper.BOUNDARY_ACTION_SPLIT)
+ ))
+ // The two-point side survives on the exemption; the one-point side does not
+ assertEquals(1, db.getDailyStats(1708300000L, 1708400000L)[0]["tripCount"])
+ }
+
+ @Test
+ fun `getDailyStats counts both sides of a manual split even when one is stationary`() {
+ // Mirrors the JS segmenter's exemption: an explicit split must not be swallowed by the
+ // stationary-jitter filter, or the user's edit looks like it did nothing.
+ db.saveLocation(latitude = 52.52, longitude = 13.405, timestamp = 1708344000L)
+ db.saveLocation(latitude = 52.60, longitude = 13.405, timestamp = 1708344060L)
+ db.saveLocation(latitude = 52.600001, longitude = 13.405, timestamp = 1708344120L)
+ db.saveLocation(latitude = 52.600002, longitude = 13.405, timestamp = 1708344180L)
+
+ db.addBoundaryOverrides(listOf(
+ Triple(1708344060L, 1708344120L, DatabaseHelper.BOUNDARY_ACTION_SPLIT)
+ ))
+ assertEquals(2, db.getDailyStats(1708300000L, 1708400000L)[0]["tripCount"])
+ }
+
// ========================================================================
// deleteOlderThan
// ========================================================================
@@ -1054,6 +1183,16 @@ class DatabaseHelperSQLiteTest {
// Helpers
// ========================================================================
+ /** Asserts against a migrated candidate file rather than the live singleton. */
+ private fun assertMigratedTableExists(migrated: SQLiteDatabase, table: String) {
+ migrated.rawQuery(
+ "SELECT name FROM sqlite_master WHERE type='table' AND name=?",
+ arrayOf(table)
+ ).use { cursor ->
+ assertTrue("Migration must create $table", cursor.moveToFirst())
+ }
+ }
+
private fun queryTableNames(): Set<String> {
val tables = mutableSetOf<String>()
db.readableDatabase.rawQuery(
diff --git a/apps/mobile/src/components/features/inspector/TrackMap.tsx b/apps/mobile/src/components/features/inspector/TrackMap.tsx
index abab70e3..e7b97020 100644
--- a/apps/mobile/src/components/features/inspector/TrackMap.tsx
+++ b/apps/mobile/src/components/features/inspector/TrackMap.tsx
@@ -7,7 +7,7 @@ import React, { useRef, useEffect, useMemo, useState, useCallback } from "react"
import { View, StyleSheet, Text, Pressable, TextInput } from "react-native"
import { GeoJSONSource, Layer, type PressEventWithFeatures } from "@maplibre/maplibre-react-native"
import type { NativeSyntheticEvent } from "react-native"
-import { MapPinOff, X, Check, Trash2 } from "lucide-react-native"
+import { MapPinOff, X, Check, Trash2, Split } from "lucide-react-native"
import { ThemeColors, Trip } from "../../../types/global"
import { getTripColor } from "../../../utils/trips"
import { fonts } from "../../../styles/typography"
@@ -42,6 +42,8 @@ interface Props {
onPointNoteChange?: (id: number, note: string | null) => void
/** When provided, the point popup gains a delete action. Omit for read-only maps. */
onPointDelete?: (id: number) => void
+ /** When provided, the point popup gains a "start a new trip here" action. */
+ onPointSplit?: (id: number) => void
}
export function TrackMap({
@@ -51,7 +53,8 @@ export function TrackMap({
trackColor,
fitVersion,
onPointNoteChange,
- onPointDelete
+ onPointDelete,
+ onPointSplit
}: Props) {
const mapRef = useRef<ColotaMapRef>(null)
const [isCentered, setIsCentered] = useState(true)
@@ -308,6 +311,18 @@ export function TrackMap({
{popup.timestamp ? new Date(popup.timestamp * 1000).toLocaleTimeString() : "-"}
</Text>
<View style={styles.popupActions}>
+ {onPointSplit && popup.id >= 0 && (
+ <Pressable
+ testID="popup-split-point"
+ onPress={() => onPointSplit(popup.id)}
+ hitSlop={HIT_SLOP_MD}
+ style={({ pressed }) => pressed && { opacity: colors.pressedOpacity }}
+ accessibilityRole="button"
+ accessibilityLabel="Start a new trip at this point"
+ >
+ <Split size={16} color={colors.text} />
+ </Pressable>
+ )}
{onPointDelete && popup.id >= 0 && (
<Pressable
testID="popup-delete-point"
diff --git a/apps/mobile/src/components/features/inspector/TripList.tsx b/apps/mobile/src/components/features/inspector/TripList.tsx
index 08cc50cf..c0554e03 100644
--- a/apps/mobile/src/components/features/inspector/TripList.tsx
+++ b/apps/mobile/src/components/features/inspector/TripList.tsx
@@ -5,7 +5,7 @@
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 { Clock, Route, Share, TrendingUp, TrendingDown, Gauge, Trash2, X, Merge } from "lucide-react-native"
import { Card } from "../../ui/Card"
import { fonts } from "../../../styles/typography"
import { formatDistance, formatDuration, formatSpeed, formatTime } from "../../../utils/geo"
@@ -21,6 +21,7 @@ interface TripListProps {
selectedTripIndex?: number | null
onExport?: (format: ExportFormat, trips: Trip[]) => void
onDelete?: (trips: Trip[]) => Promise<void>
+ onMerge?: (trips: Trip[]) => Promise<void>
}
interface TripRowProps {
@@ -112,7 +113,15 @@ const TripRow = React.memo(function TripRow({
)
})
-export function TripList({ trips, colors, onTripSelect, selectedTripIndex, onExport, onDelete }: TripListProps) {
+export function TripList({
+ trips,
+ colors,
+ onTripSelect,
+ selectedTripIndex,
+ onExport,
+ onDelete,
+ onMerge
+}: TripListProps) {
const [showExport, setShowExport] = useState(false)
const [selected, setSelected] = useState<Set<number>>(new Set())
const selectionMode = selected.size > 0
@@ -134,6 +143,14 @@ export function TripList({ trips, colors, onTripSelect, selectedTripIndex, onExp
const selectedTrips = useMemo(() => trips.filter((t) => selected.has(t.index)), [trips, selected])
const allSelected = selectionMode && selected.size === trips.length
+ // Merging a non-contiguous set would silently swallow the trips in between
+ const isAdjacentSelection = useMemo(() => {
+ if (selectedTrips.length < 2) return false
+ for (let i = 1; i < selectedTrips.length; i++) {
+ if (selectedTrips[i].index !== selectedTrips[i - 1].index + 1) return false
+ }
+ return true
+ }, [selectedTrips])
const totalDistance = trips.reduce((sum, t) => sum + t.distance, 0)
@@ -194,6 +211,21 @@ export function TripList({ trips, colors, onTripSelect, selectedTripIndex, onExp
}
}, [onDelete, selectedTrips])
+ const mergingRef = useRef(false)
+ const handleMergeSelected = useCallback(async () => {
+ if (!onMerge || !isAdjacentSelection || mergingRef.current) return
+ mergingRef.current = true
+ try {
+ await onMerge(selectedTrips)
+ setSelected(new Set())
+ setShowExport(false)
+ } catch {
+ // Caller surfaces its own error UI. Preserve selection so the user can retry.
+ } finally {
+ mergingRef.current = false
+ }
+ }, [onMerge, selectedTrips, isAdjacentSelection])
+
const renderTrip = useCallback(
({ item }: { item: Trip }) => (
<TripRow
@@ -260,6 +292,20 @@ export function TripList({ trips, colors, onTripSelect, selectedTripIndex, onExp
<Share size={18} color={showExport ? colors.primary : colors.text} />
</Pressable>
)}
+ {onMerge && trips.length >= 2 && (
+ <Pressable
+ onPress={handleMergeSelected}
+ disabled={!isAdjacentSelection}
+ hitSlop={HIT_SLOP_SM}
+ style={({ pressed }) => [styles.cabIconBtn, pressed && { opacity: colors.pressedOpacity }]}
+ accessibilityRole="button"
+ accessibilityLabel="Merge selected trips"
+ accessibilityHint={isAdjacentSelection ? undefined : "Select two or more adjacent trips to merge them"}
+ accessibilityState={{ disabled: !isAdjacentSelection }}
+ >
+ <Merge size={18} color={isAdjacentSelection ? colors.text : colors.textDisabled} />
+ </Pressable>
+ )}
{onDelete && (
<Pressable
onPress={handleDeleteSelected}
diff --git a/apps/mobile/src/components/features/inspector/__tests__/TrackMap.test.tsx b/apps/mobile/src/components/features/inspector/__tests__/TrackMap.test.tsx
index b7458eb9..d06d0e0b 100644
--- a/apps/mobile/src/components/features/inspector/__tests__/TrackMap.test.tsx
+++ b/apps/mobile/src/components/features/inspector/__tests__/TrackMap.test.tsx
@@ -182,6 +182,55 @@ describe("TrackMap point deletion", () => {
expect(queryByTestId("popup-delete-point")).toBeNull()
})
+
+ it("reports the tapped point's id to the split handler", () => {
+ // The id, not the timestamp: the caller resolves the boundary from it and two fixes
+ // in one trip can share a second
+ const onPointSplit = jest.fn()
+ const { getByTestId } = render(
+ <TrackMap locations={[loc(52.5, 13.4)]} colors={colors} trackColor="#000" onPointSplit={onPointSplit} />
+ )
+
+ tapPoint(getByTestId("track-points"), 42)
+ fireEvent.press(getByTestId("popup-split-point"))
+
+ expect(onPointSplit).toHaveBeenCalledWith(42)
+ })
+
+ it("offers no split action on a read-only map", () => {
+ const { getByTestId, queryByTestId } = render(
+ <TrackMap locations={[loc(52.5, 13.4)]} colors={colors} trackColor="#000" />
+ )
+
+ tapPoint(getByTestId("track-points"), 42)
+
+ expect(queryByTestId("popup-split-point")).toBeNull()
+ })
+
+ it("offers no split action for a point with no row id", () => {
+ // Without a row id there is no way to locate the point in the day's array
+ const { getByTestId, queryByTestId } = render(
+ <TrackMap locations={[loc(52.5, 13.4)]} colors={colors} trackColor="#000" onPointSplit={jest.fn()} />
+ )
+
+ tapPoint(getByTestId("track-points"), -1)
+
+ expect(queryByTestId("popup-split-point")).toBeNull()
+ })
+
+ it("offers the split action on every point with a row id", () => {
+ // The map has no view of the surrounding day, so it cannot tell which points are splittable.
+ // The screen takes every tap and explains the ones it cannot act on.
+ const { getByTestId, queryByTestId } = render(
+ <TrackMap locations={[loc(52.5, 13.4)]} colors={colors} trackColor="#000" onPointSplit={jest.fn()} />
+ )
+
+ tapPoint(getByTestId("track-points"), 42)
+
+ expect(getByTestId("popup-split-point")).toBeTruthy()
+ // Delete is a separate opt-in and stays absent on a map that didn't ask for it
+ expect(queryByTestId("popup-delete-point")).toBeNull()
+ })
})
describe("TrackMap trip coloring", () => {
diff --git a/apps/mobile/src/components/features/inspector/__tests__/TripList.test.tsx b/apps/mobile/src/components/features/inspector/__tests__/TripList.test.tsx
index f926e5fa..a040ee05 100644
--- a/apps/mobile/src/components/features/inspector/__tests__/TripList.test.tsx
+++ b/apps/mobile/src/components/features/inspector/__tests__/TripList.test.tsx
@@ -58,6 +58,7 @@ jest.mock("lucide-react-native", () => {
Gauge: stub("Gauge"),
Trash2: stub("Trash2"),
X: stub("X"),
+ Merge: stub("Merge"),
CheckSquare: stub("CheckSquare"),
Square: stub("Square")
}
@@ -233,6 +234,74 @@ describe("TripList - CAB selection", () => {
})
})
+ it("CAB Merge fires onMerge with the selected adjacent trips", async () => {
+ const onMerge = jest.fn().mockResolvedValue(undefined)
+ const { getByLabelText } = render(
+ <TripList trips={makeTrips(4)} colors={colors} onTripSelect={jest.fn()} onMerge={onMerge} />
+ )
+
+ fireEvent(getByLabelText(/Trip 2,/), "longPress")
+ fireEvent.press(getByLabelText(/Trip 3,/))
+ await act(async () => {
+ fireEvent.press(getByLabelText("Merge selected trips"))
+ })
+
+ expect(onMerge).toHaveBeenCalledTimes(1)
+ expect(onMerge.mock.calls[0][0].map((t: Trip) => t.index)).toEqual([2, 3])
+ })
+
+ it("does not merge a non-contiguous selection", async () => {
+ // Merging trips 1 and 3 would have to swallow trip 2, which the user never asked for
+ const onMerge = jest.fn().mockResolvedValue(undefined)
+ const { getByLabelText } = render(
+ <TripList trips={makeTrips(3)} colors={colors} onTripSelect={jest.fn()} onMerge={onMerge} />
+ )
+
+ fireEvent(getByLabelText(/Trip 1,/), "longPress")
+ fireEvent.press(getByLabelText(/Trip 3,/))
+
+ const mergeBtn = getByLabelText("Merge selected trips")
+ expect(mergeBtn.props.accessibilityState.disabled).toBe(true)
+ await act(async () => {
+ fireEvent.press(mergeBtn)
+ })
+ expect(onMerge).not.toHaveBeenCalled()
+ })
+
+ it("does not merge a single trip", async () => {
+ const onMerge = jest.fn().mockResolvedValue(undefined)
+ const { getByLabelText } = render(
+ <TripList trips={makeTrips(3)} colors={colors} onTripSelect={jest.fn()} onMerge={onMerge} />
+ )
+
+ fireEvent(getByLabelText(/Trip 2,/), "longPress")
+
+ expect(getByLabelText("Merge selected trips").props.accessibilityState.disabled).toBe(true)
+ await act(async () => {
+ fireEvent.press(getByLabelText("Merge selected trips"))
+ })
+ expect(onMerge).not.toHaveBeenCalled()
+ })
+
+ it("keeps the selection when a merge fails so the user can retry", async () => {
+ const onMerge = jest.fn().mockRejectedValue(new Error("bridge down"))
+ const { getByLabelText } = render(
+ <TripList trips={makeTrips(3)} colors={colors} onTripSelect={jest.fn()} onMerge={onMerge} />
+ )
+
+ fireEvent(getByLabelText(/Trip 1,/), "longPress")
+ fireEvent.press(getByLabelText(/Trip 2,/))
+ await act(async () => {
+ fireEvent.press(getByLabelText("Merge selected trips"))
+ })
+
+ expect(getByLabelText("Cancel selection")).toBeTruthy()
+ await act(async () => {
+ fireEvent.press(getByLabelText("Merge selected trips"))
+ })
+ expect(onMerge).toHaveBeenCalledTimes(2)
+ })
+
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()} />
diff --git a/apps/mobile/src/screens/LocationInspectorScreen.tsx b/apps/mobile/src/screens/LocationInspectorScreen.tsx
index d10f4989..3870a041 100644
--- a/apps/mobile/src/screens/LocationInspectorScreen.tsx
+++ b/apps/mobile/src/screens/LocationInspectorScreen.tsx
@@ -11,7 +11,7 @@ import { BarChart2 } from "lucide-react-native"
import { Container } from "../components"
import { Tab } from "../components/ui/Tab"
import { useTheme } from "../hooks/useTheme"
-import { Trip, LocationCoords } from "../types/global"
+import { Trip, LocationCoords, BoundaryAction, BOUNDARY_ACTION_SPLIT } from "../types/global"
import NativeLocationService from "../services/NativeLocationService"
import { logger } from "../utils/logger"
import { CalendarPicker } from "../components/features/inspector/CalendarPicker"
@@ -20,7 +20,14 @@ import { TripList } from "../components/features/inspector/TripList"
import { LocationTable } from "../components/features/inspector/LocationTable"
import { formatDistance, formatTime, startOfDaySec, endOfDaySec } from "../utils/geo"
import { pad2 } from "../utils/format"
-import { segmentTrips, getTripColor } from "../utils/trips"
+import {
+ segmentTrips,
+ getTripColor,
+ buildBoundaryOverrideMap,
+ gapsBetweenTrips,
+ splitBlockedReason,
+ SPLIT_BLOCKED_NOT_A_TRIP
+} from "../utils/trips"
import { EXPORT_FORMATS, type ExportFormat } from "../utils/exportConverters"
import { showAlert, showConfirm } from "../services/modalService"
import type { RootScreenProps } from "../types/navigation"
@@ -40,6 +47,7 @@ export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Lo
// Note edits, kept out of trackLocations so a save doesn't hand the map a new array (which would
// re-render it). Used only by the Data tab; the map reads notes through its own overlay.
const [noteOverrides, setNoteOverrides] = useState<Record<number, string | undefined>>({})
+ const [boundaryOverrides, setBoundaryOverrides] = useState<Map<string, BoundaryAction>>(() => new Map())
const [selectedTrip, setSelectedTrip] = useState<Trip | null>(null)
const [fitVersion, setFitVersion] = useState(0)
@@ -51,7 +59,10 @@ export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Lo
const distanceCache = useRef<Map<string, Map<string, number>>>(new Map())
// Trip segmentation from already-fetched day data
- const trips = useMemo(() => segmentTrips(trackLocations), [trackLocations])
+ const trips = useMemo(
+ () => segmentTrips(trackLocations, undefined, boundaryOverrides),
+ [trackLocations, boundaryOverrides]
+ )
// Sum of per-trip distances (excludes gap jumps between trips)
const dailyDistance = useMemo(() => {
@@ -131,9 +142,13 @@ export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Lo
const startTimestamp = startOfDaySec(mapDate)
const endTimestamp = endOfDaySec(mapDate)
- const result = await NativeLocationService.getLocationsByDateRange(startTimestamp, endTimestamp)
+ const [result, overrides] = await Promise.all([
+ NativeLocationService.getLocationsByDateRange(startTimestamp, endTimestamp),
+ NativeLocationService.getBoundaryOverrides()
+ ])
if (id === fetchTrackIdRef.current) {
setTrackLocations(result || [])
+ setBoundaryOverrides(buildBoundaryOverrideMap(overrides))
setNoteOverrides({})
setSelectedTrip(null)
setFitVersion((v) => v + 1)
@@ -142,6 +157,7 @@ export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Lo
logger.error("[LocationHistory] Track fetch error:", err)
if (id === fetchTrackIdRef.current) {
setTrackLocations([])
+ setBoundaryOverrides(new Map())
setNoteOverrides({})
setSelectedTrip(null)
setFitVersion((v) => v + 1)
@@ -209,7 +225,7 @@ export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Lo
setFitVersion((v) => v + 1)
}, [])
- const refreshAfterDelete = useCallback(async () => {
+ const refreshAfterEdit = useCallback(async () => {
const key = `${mapDate.getFullYear()}-${pad2(mapDate.getMonth() + 1)}`
daysCache.current.delete(key)
notesCache.current.delete(key)
@@ -218,6 +234,37 @@ export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Lo
await fetchDaysWithData(mapDate.getFullYear(), mapDate.getMonth())
}, [mapDate, fetchTrackData, fetchDaysWithData])
+ const handleMergeTrips = useCallback(
+ async (toMerge: Trip[]) => {
+ if (toMerge.length < 2) return
+ const sorted = [...toMerge].sort((a, b) => a.index - b.index)
+ // TripList enforces an adjacency invariant before calling us, so sorted indices are contiguous.
+ const first = sorted[0].index
+ const last = sorted[sorted.length - 1].index
+ const confirmed = await showConfirm({
+ title: `Merge ${sorted.length} trips?`,
+ message: `${sorted.length === 2 ? `Trips ${first} and ${last}` : `Trips ${first}-${last}`} will be combined into one.`,
+ confirmText: "Merge"
+ })
+ if (!confirmed) return
+ // Each displayed pair can span more than one gap: trips dropped by the extent filter still
+ // have their points in trackLocations, and every gap across them has to be suppressed.
+ const overrides = sorted
+ .slice(1)
+ .flatMap((trip, i) => gapsBetweenTrips(trackLocations, sorted[i], trip, boundaryOverrides))
+ try {
+ await NativeLocationService.addBoundaryOverrides(overrides)
+ await refreshAfterEdit()
+ } catch (error) {
+ logger.error("[LocationHistory] Trip merge failed:", error)
+ showAlert("Merge Failed", "Unable to merge the selected trips. Please try again.", "error")
+ // Re-throw so TripList's CAB preserves the selection and lets the user retry.
+ throw error
+ }
+ },
+ [trackLocations, boundaryOverrides, refreshAfterEdit]
+ )
+
const handleDeleteTrips = useCallback(
async (toDelete: Trip[]) => {
if (toDelete.length === 0) return
@@ -235,13 +282,57 @@ export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Lo
await NativeLocationService.deleteLocationsInRanges(
toDelete.map((t) => ({ start: t.startTime, end: t.endTime }))
)
- await refreshAfterDelete()
+ await refreshAfterEdit()
} catch (error) {
logger.error("[LocationHistory] Trip delete failed:", error)
showAlert("Delete Failed", "Unable to delete selection. Please try again.", "error")
}
},
- [refreshAfterDelete]
+ [refreshAfterEdit]
+ )
+
+ const splittingPointRef = useRef(false)
+ const handlePointSplit = useCallback(
+ async (id: number) => {
+ if (splittingPointRef.current) return
+ // Match on row id, not timestamp: two fixes can land in the same second
+ const idx = trackLocations.findIndex((l) => l.id === id)
+ // The map draws runs the extent filter dropped, so a tap can land outside every trip.
+ // Splitting there would exempt both halves from that filter and conjure trips from jitter.
+ const inTrip = trips.some((t) => idx >= t.startIndex && idx < t.startIndex + t.locationCount)
+ const blocked = inTrip ? splitBlockedReason(trackLocations, idx, boundaryOverrides) : SPLIT_BLOCKED_NOT_A_TRIP
+ if (blocked) {
+ showAlert("Cannot Split Here", blocked, "info")
+ return
+ }
+ const at = trackLocations[idx].timestamp
+ const confirmed = await showConfirm({
+ // The confirm covers the popup, so name the point in it
+ title: at ? `Start a new trip at ${formatTime(at, true)}?` : "Split Trip?",
+ message:
+ "Everything from this point onwards becomes a separate trip. Your location data is not changed, and you can undo this by merging the two trips again.",
+ confirmText: "Split"
+ })
+ if (!confirmed) return
+ splittingPointRef.current = true
+ try {
+ await NativeLocationService.addBoundaryOverrides([
+ {
+ before_timestamp: trackLocations[idx - 1].timestamp ?? 0,
+ after_timestamp: trackLocations[idx].timestamp ?? 0,
+ action: BOUNDARY_ACTION_SPLIT
+ }
+ ])
+ // Re-segmenting recolours the track at the tapped point, which is the confirmation
+ await refreshAfterEdit()
+ } catch (error) {
+ logger.error("[LocationHistory] Trip split failed:", error)
+ showAlert("Split Failed", "Unable to split the trip here. Please try again.", "error")
+ } finally {
+ splittingPointRef.current = false
+ }
+ },
+ [trackLocations, trips, boundaryOverrides, refreshAfterEdit]
)
const handlePointDelete = useCallback(
@@ -261,7 +352,7 @@ export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Lo
deletingPointRef.current = true
try {
await NativeLocationService.deleteLocationsByIds([id])
- await refreshAfterDelete()
+ await refreshAfterEdit()
} catch (error) {
logger.error("[LocationHistory] Point delete failed:", error)
showAlert("Delete Failed", "Unable to delete point. Please try again.", "error")
@@ -269,7 +360,7 @@ export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Lo
deletingPointRef.current = false
}
},
- [trackLocations, refreshAfterDelete]
+ [trackLocations, refreshAfterEdit]
)
const handlePointNoteChange = useCallback(
@@ -347,6 +438,7 @@ export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Lo
fitVersion={fitVersion}
onPointNoteChange={handlePointNoteChange}
onPointDelete={handlePointDelete}
+ onPointSplit={handlePointSplit}
/>
{selectedTrip && (
<Pressable
@@ -375,6 +467,7 @@ export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Lo
selectedTripIndex={selectedTrip?.index ?? null}
onExport={exportTrips}
onDelete={handleDeleteTrips}
+ onMerge={handleMergeTrips}
/>
</View>
)}
diff --git a/apps/mobile/src/screens/TripDetailScreen.tsx b/apps/mobile/src/screens/TripDetailScreen.tsx
index 0d6fa8d2..34e4fb1c 100644
--- a/apps/mobile/src/screens/TripDetailScreen.tsx
+++ b/apps/mobile/src/screens/TripDetailScreen.tsx
@@ -3,7 +3,7 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
-import React, { useMemo, useState, useCallback, useLayoutEffect, useEffect } from "react"
+import React, { useMemo, useState, useCallback, useLayoutEffect, useEffect, useRef } from "react"
import { View, Text, StyleSheet, ScrollView, Pressable } from "react-native"
import {
Route,
@@ -24,14 +24,15 @@ import { Card } from "../components/ui/Card"
import { Container } from "../components/ui/Container"
import { TrackMap } from "../components/features/inspector/TrackMap"
import { InteractiveLineChart } from "../components/features/inspector/InteractiveLineChart"
-import { getTripColor, computeTripStats } from "../utils/trips"
+import { getTripColor, computeTripStats, buildBoundaryOverrideMap, splitBlockedReason } from "../utils/trips"
import { formatDate, formatDistance, formatDuration, formatSpeed, formatTime } from "../utils/geo"
import { EXPORT_FORMATS, EXPORT_FORMAT_KEYS, type ExportFormat } from "../utils/exportConverters"
import { HIT_SLOP_LG } from "../constants"
import { showAlert, showConfirm } from "../services/modalService"
import { logger } from "../utils/logger"
import NativeLocationService from "../services/NativeLocationService"
-import type { Trip, ThemeColors } from "../types/global"
+import { BOUNDARY_ACTION_SPLIT } from "../types/global"
+import type { Trip, ThemeColors, BoundaryAction } from "../types/global"
import type { RootScreenProps } from "../types/navigation"
const MAX_BARS = 120
@@ -64,6 +65,26 @@ export function TripDetailScreen({ route, navigation }: RootScreenProps<"Trip De
const [showExport, setShowExport] = useState(false)
const [chartActiveIndex, setChartActiveIndex] = useState<number | null>(null)
+ // Without these, a boundary the user merged reads as a plain gap and refuses to split
+ const [boundaryOverrides, setBoundaryOverrides] = useState<Map<string, BoundaryAction>>(() => new Map())
+ // Splitting before they arrive would judge a merged boundary as a plain gap and refuse a legal split
+ const [boundariesLoaded, setBoundariesLoaded] = useState(false)
+
+ useEffect(() => {
+ let active = true
+ NativeLocationService.getBoundaryOverrides()
+ .then((o) => {
+ if (active) setBoundaryOverrides(buildBoundaryOverrideMap(o))
+ })
+ // Split stays available on plain gaps; only merged boundaries stop being offered
+ .catch((error) => logger.error("[TripDetail] Boundary override load failed:", error))
+ .finally(() => {
+ if (active) setBoundariesLoaded(true)
+ })
+ return () => {
+ active = false
+ }
+ }, [])
const currentIdx = trips.findIndex((t) => t.index === trip.index)
const prevTrip = currentIdx > 0 ? trips[currentIdx - 1] : null
@@ -93,6 +114,53 @@ export function TripDetailScreen({ route, navigation }: RootScreenProps<"Trip De
}
}, [])
+ const splittingRef = useRef(false)
+ const handlePointSplit = useCallback(
+ async (id: number) => {
+ if (splittingRef.current) return
+ if (!boundariesLoaded) {
+ showAlert("Cannot Split Here", "Still loading this trip's edits. Try again in a moment.", "info")
+ return
+ }
+ // A trip's locations are a contiguous run of the day, so the preceding point is the one
+ // that ends the trip.
+ const idx = trip.locations.findIndex((l) => l.id === id)
+ const blocked = splitBlockedReason(trip.locations, idx, boundaryOverrides)
+ if (blocked) {
+ showAlert("Cannot Split Here", blocked, "info")
+ return
+ }
+ const at = trip.locations[idx].timestamp
+ const confirmed = await showConfirm({
+ // The confirm covers the popup, so name the point in it
+ title: at ? `Start a new trip at ${formatTime(at, true)}?` : "Split Trip?",
+ message:
+ "Everything from this point onwards becomes a separate trip. Your location data is not changed, and you can undo this by merging the two trips again.",
+ confirmText: "Split"
+ })
+ if (!confirmed) return
+ splittingRef.current = true
+ try {
+ await NativeLocationService.addBoundaryOverrides([
+ {
+ before_timestamp: trip.locations[idx - 1].timestamp ?? 0,
+ after_timestamp: trip.locations[idx].timestamp ?? 0,
+ action: BOUNDARY_ACTION_SPLIT
+ }
+ ])
+ // This trip no longer exists in the form we are showing, and the day view refetches
+ // on focus, so going back is what applies the new boundary.
+ navigation.goBack()
+ } catch (error) {
+ logger.error("[TripDetail] Split failed:", error)
+ showAlert("Split Failed", "Unable to split the trip here. Please try again.", "error")
+ } finally {
+ splittingRef.current = false
+ }
+ },
+ [trip, boundaryOverrides, boundariesLoaded, navigation]
+ )
+
const handleExport = useCallback(
async (format: ExportFormat) => {
try {
@@ -186,6 +254,7 @@ export function TripDetailScreen({ route, navigation }: RootScreenProps<"Trip De
trackColor={tripColor}
fitVersion={trip.index}
onPointNoteChange={handlePointNoteChange}
+ onPointSplit={handlePointSplit}
/>
</View>
<ScrollView contentContainerStyle={styles.content}>
diff --git a/apps/mobile/src/screens/__tests__/LocationHistoryScreen.test.tsx b/apps/mobile/src/screens/__tests__/LocationHistoryScreen.test.tsx
index be88e624..594a2ffd 100644
--- a/apps/mobile/src/screens/__tests__/LocationHistoryScreen.test.tsx
+++ b/apps/mobile/src/screens/__tests__/LocationHistoryScreen.test.tsx
@@ -13,17 +13,28 @@ jest.mock("../../services/NativeLocationService", () => ({
exportTripsToFile: jest.fn().mockResolvedValue("/tmp/export"),
shareFile: jest.fn(),
deleteLocationsInRange: jest.fn().mockResolvedValue(0),
- deleteLocationsByIds: jest.fn().mockResolvedValue(0)
+ deleteLocationsByIds: jest.fn().mockResolvedValue(0),
+ getBoundaryOverrides: jest.fn().mockResolvedValue([]),
+ addBoundaryOverrides: jest.fn().mockResolvedValue(undefined)
}
}))
+// boundarySplits stays real - the split guard's correctness is what the tests below check
jest.mock("../../utils/trips", () => ({
+ ...jest.requireActual("../../utils/trips"),
segmentTrips: jest.fn().mockReturnValue([]),
- getTripColor: jest.fn().mockReturnValue("#3B82F6")
+ getTripColor: jest.fn().mockReturnValue("#3B82F6"),
+ buildBoundaryOverrideMap: jest.fn().mockReturnValue(new Map()),
+ gapsBetweenTrips: jest.fn().mockReturnValue([])
}))
+// The screen uses all four. A partial mock throws inside fetchTrackData's own catch, which
+// skips the fetch without failing anything.
jest.mock("../../utils/geo", () => ({
- formatDistance: jest.fn().mockReturnValue("0 km")
+ formatDistance: jest.fn().mockReturnValue("0 km"),
+ formatTime: jest.fn().mockReturnValue("12:00"),
+ startOfDaySec: jest.fn().mockReturnValue(0),
+ endOfDaySec: jest.fn().mockReturnValue(86399)
}))
jest.mock("../../utils/exportConverters", () => ({
@@ -86,21 +97,49 @@ jest.mock("../../components/features/inspector/TrackMap", () => {
const { View, Pressable } = require("react-native")
return {
TrackMap: (props: any) =>
- R.createElement(
- View,
- { testID: "TrackMap" },
+ R.createElement(View, { testID: "TrackMap" }, [
props.onPointDelete
- ? R.createElement(Pressable, { testID: "trigger-point-delete", onPress: () => props.onPointDelete(7) })
+ ? R.createElement(Pressable, {
+ key: "d",
+ testID: "trigger-point-delete",
+ onPress: () => props.onPointDelete(7)
+ })
+ : null,
+ props.onPointSplit
+ ? R.createElement(Pressable, {
+ key: "s",
+ testID: "trigger-point-split",
+ onPress: () => props.onPointSplit(props.locations?.[2]?.id ?? 7)
+ })
+ : null,
+ props.onPointSplit
+ ? R.createElement(Pressable, {
+ key: "s0",
+ testID: "trigger-point-split-first",
+ onPress: () => props.onPointSplit(props.locations?.[0]?.id ?? 7)
+ })
: null
- )
+ ])
}
})
jest.mock("../../components/features/inspector/TripList", () => {
const R = require("react")
- const { View } = require("react-native")
+ const { View, Pressable } = require("react-native")
+ const TRIP_A = { index: 1, locations: [], startTime: 100, endTime: 200, distance: 0, locationCount: 2, startIndex: 0 }
+ const TRIP_B = { index: 2, locations: [], startTime: 900, endTime: 950, distance: 0, locationCount: 2, startIndex: 5 }
return {
- TripList: (_props: any) => R.createElement(View, { testID: "TripList" })
+ TripList: (props: any) =>
+ R.createElement(
+ View,
+ { testID: "TripList" },
+ props.onMerge
+ ? R.createElement(Pressable, {
+ testID: "trigger-trip-merge",
+ onPress: () => props.onMerge([TRIP_A, TRIP_B])
+ })
+ : null
+ )
}
})
@@ -126,7 +165,9 @@ jest.mock("@react-navigation/native", () => ({
import { LocationHistoryScreen } from "../LocationInspectorScreen"
import NativeLocationService from "../../services/NativeLocationService"
-import { showConfirm } from "../../services/modalService"
+import { showConfirm, showAlert } from "../../services/modalService"
+import { gapsBetweenTrips, segmentTrips } from "../../utils/trips"
+import { BOUNDARY_ACTION_SPLIT } from "../../types/global"
const createProps = () =>
({
@@ -139,6 +180,25 @@ const createProps = () =>
}
}) as any
+// Five points 100s apart: one trip, with index 2 the only point a split can apply to
+const DAY_TRIP = {
+ index: 1,
+ locations: [],
+ startTime: 1000,
+ endTime: 1400,
+ distance: 500,
+ locationCount: 5,
+ startIndex: 0
+}
+
+const DAY_POINTS = [
+ { id: 1, latitude: 52.52, longitude: 13.405, timestamp: 1000 },
+ { id: 2, latitude: 52.53, longitude: 13.405, timestamp: 1100 },
+ { id: 3, latitude: 52.54, longitude: 13.405, timestamp: 1200 },
+ { id: 4, latitude: 52.55, longitude: 13.405, timestamp: 1300 },
+ { id: 5, latitude: 52.56, longitude: 13.405, timestamp: 1400 }
+]
+
describe("LocationHistoryScreen", () => {
beforeEach(() => {
jest.clearAllMocks()
@@ -174,6 +234,123 @@ describe("LocationHistoryScreen", () => {
expect(NativeLocationService.deleteLocationsByIds).not.toHaveBeenCalled()
})
+ it("splits at the tapped point, keyed off the point before it", async () => {
+ // Resolved through the day's array, so the boundary matches a gap segmentTrips will see
+ ;(showConfirm as jest.Mock).mockResolvedValueOnce(true)
+ ;(segmentTrips as jest.Mock).mockReturnValue([DAY_TRIP])
+ ;(NativeLocationService.getLocationsByDateRange as jest.Mock).mockResolvedValueOnce(DAY_POINTS)
+ const { getByTestId } = render(<LocationHistoryScreen {...createProps()} />)
+ await waitFor(() => expect(NativeLocationService.getLocationsByDateRange).toHaveBeenCalled())
+
+ fireEvent.press(getByTestId("trigger-point-split"))
+
+ await waitFor(() =>
+ expect(NativeLocationService.addBoundaryOverrides).toHaveBeenCalledWith([
+ { before_timestamp: 1100, after_timestamp: 1200, action: BOUNDARY_ACTION_SPLIT }
+ ])
+ )
+ })
+
+ it("does not split a run that is not a displayed trip", async () => {
+ // The map draws stationary runs the extent filter dropped. Splitting inside one would exempt
+ // both halves from that filter and turn GPS jitter into trips, with its path length counted
+ // as distance - exactly what the filter exists to prevent.
+ ;(segmentTrips as jest.Mock).mockReturnValue([])
+ ;(NativeLocationService.getLocationsByDateRange as jest.Mock).mockResolvedValueOnce(DAY_POINTS)
+ const { getByTestId } = render(<LocationHistoryScreen {...createProps()} />)
+ await waitFor(() => expect(NativeLocationService.getLocationsByDateRange).toHaveBeenCalled())
+
+ fireEvent.press(getByTestId("trigger-point-split"))
+
+ await waitFor(() => expect(showAlert).toHaveBeenCalledWith("Cannot Split Here", expect.any(String), "info"))
+ expect(showConfirm).not.toHaveBeenCalled()
+ expect(NativeLocationService.addBoundaryOverrides).not.toHaveBeenCalled()
+ })
+
+ it("splits nothing when the split confirm is dismissed", async () => {
+ ;(segmentTrips as jest.Mock).mockReturnValue([DAY_TRIP])
+ ;(NativeLocationService.getLocationsByDateRange as jest.Mock).mockResolvedValueOnce(DAY_POINTS)
+ const { getByTestId } = render(<LocationHistoryScreen {...createProps()} />)
+ await waitFor(() => expect(NativeLocationService.getLocationsByDateRange).toHaveBeenCalled())
+
+ fireEvent.press(getByTestId("trigger-point-split"))
+
+ await waitFor(() => expect(showConfirm).toHaveBeenCalled())
+ expect(NativeLocationService.addBoundaryOverrides).not.toHaveBeenCalled()
+ })
+
+ it("does not split at a boundary that already splits", async () => {
+ // Forcing a split where the gap threshold already splits is not a harmless no-op: a forced
+ // split exempts the segments either side from the extent filter, so a stationary run the
+ // segmenter drops on purpose would reappear as a trip in both the list and the calendar.
+ ;(segmentTrips as jest.Mock).mockReturnValue([
+ { ...DAY_TRIP, locationCount: 2 },
+ { ...DAY_TRIP, index: 2, locationCount: 3, startIndex: 2 }
+ ])
+ ;(NativeLocationService.getLocationsByDateRange as jest.Mock).mockResolvedValueOnce([
+ { id: 1, latitude: 52.52, longitude: 13.405, timestamp: 1000 },
+ { id: 2, latitude: 52.53, longitude: 13.405, timestamp: 1100 },
+ // 1000s later, over the 900s threshold, so index 2 already starts a trip
+ { id: 3, latitude: 52.54, longitude: 13.405, timestamp: 2100 },
+ { id: 4, latitude: 52.55, longitude: 13.405, timestamp: 2200 },
+ { id: 5, latitude: 52.56, longitude: 13.405, timestamp: 2300 }
+ ])
+ const { getByTestId } = render(<LocationHistoryScreen {...createProps()} />)
+ await waitFor(() => expect(NativeLocationService.getLocationsByDateRange).toHaveBeenCalled())
+
+ fireEvent.press(getByTestId("trigger-point-split"))
+
+ // Explains rather than doing nothing
+ await waitFor(() => expect(showAlert).toHaveBeenCalledWith("Cannot Split Here", expect.any(String), "info"))
+ expect(showConfirm).not.toHaveBeenCalled()
+ expect(NativeLocationService.addBoundaryOverrides).not.toHaveBeenCalled()
+ })
+
+ it("does not split at the first point of the day", async () => {
+ // There is no earlier point to end a trip on, so the boundary would be meaningless
+ ;(segmentTrips as jest.Mock).mockReturnValue([DAY_TRIP])
+ ;(NativeLocationService.getLocationsByDateRange as jest.Mock).mockResolvedValueOnce(DAY_POINTS)
+ const { getByTestId } = render(<LocationHistoryScreen {...createProps()} />)
+ await waitFor(() => expect(NativeLocationService.getLocationsByDateRange).toHaveBeenCalled())
+
+ fireEvent.press(getByTestId("trigger-point-split-first"))
+
+ await waitFor(() => expect(NativeLocationService.getBoundaryOverrides).toHaveBeenCalled())
+ // Bails before the dialog: there is no question worth asking
+ expect(showConfirm).not.toHaveBeenCalled()
+ expect(NativeLocationService.addBoundaryOverrides).not.toHaveBeenCalled()
+ })
+
+ it("merges nothing when the merge confirm is dismissed", async () => {
+ const props = createProps()
+ const { getByText, getByTestId } = render(<LocationHistoryScreen {...props} />)
+
+ fireEvent.press(getByText("Trips"))
+ fireEvent.press(getByTestId("trigger-trip-merge"))
+
+ await waitFor(() => expect(showConfirm).toHaveBeenCalled())
+ expect(NativeLocationService.addBoundaryOverrides).not.toHaveBeenCalled()
+ })
+
+ it("passes whatever gapsBetweenTrips resolves straight through to the bridge", async () => {
+ // gapsBetweenTrips is mocked, so this covers the plumbing only - which boundaries it picks
+ // is tested against the real function in trips.test.ts
+ ;(showConfirm as jest.Mock).mockResolvedValueOnce(true)
+ const gaps = [
+ { before_timestamp: 200, after_timestamp: 500, action: 0 },
+ { before_timestamp: 500, after_timestamp: 900, action: 0 }
+ ]
+ ;(gapsBetweenTrips as jest.Mock).mockReturnValueOnce(gaps)
+
+ const props = createProps()
+ const { getByText, getByTestId } = render(<LocationHistoryScreen {...props} />)
+
+ fireEvent.press(getByText("Trips"))
+ fireEvent.press(getByTestId("trigger-trip-merge"))
+
+ await waitFor(() => expect(NativeLocationService.addBoundaryOverrides).toHaveBeenCalledWith(gaps))
+ })
+
it("switches to Trips tab on press", () => {
const props = createProps()
const { getByText, getByTestId, queryByTestId } = render(<LocationHistoryScreen {...props} />)
diff --git a/apps/mobile/src/screens/__tests__/TripDetailScreen.test.tsx b/apps/mobile/src/screens/__tests__/TripDetailScreen.test.tsx
new file mode 100644
index 00000000..88e85e3d
--- /dev/null
+++ b/apps/mobile/src/screens/__tests__/TripDetailScreen.test.tsx
@@ -0,0 +1,236 @@
+import React from "react"
+import { render, fireEvent, waitFor, act } from "@testing-library/react-native"
+import type { Trip } from "../../types/global"
+
+jest.mock("../../services/NativeLocationService", () => ({
+ __esModule: true,
+ default: {
+ addBoundaryOverrides: jest.fn().mockResolvedValue(undefined),
+ getBoundaryOverrides: jest.fn().mockResolvedValue([]),
+ deleteLocationsInRange: jest.fn().mockResolvedValue(0),
+ updateLocationNote: jest.fn().mockResolvedValue(undefined),
+ exportTripsToFile: jest.fn().mockResolvedValue("/tmp/export"),
+ shareFile: jest.fn()
+ }
+}))
+
+jest.mock("../../services/modalService", () => ({
+ showAlert: jest.fn(),
+ showConfirm: jest.fn().mockResolvedValue(false)
+}))
+
+jest.mock("../../utils/logger", () => ({
+ logger: { error: jest.fn(), info: jest.fn(), debug: jest.fn() }
+}))
+
+// Exposes the point popup's split action without a real map
+jest.mock("../../components/features/inspector/TrackMap", () => {
+ const R = require("react")
+ const { View, Pressable } = require("react-native")
+ return {
+ TrackMap: (props: any) =>
+ R.createElement(
+ View,
+ { testID: "TrackMap" },
+ props.onPointSplit
+ ? [
+ R.createElement(Pressable, {
+ key: "s",
+ testID: "trigger-point-split",
+ onPress: () => props.onPointSplit(props.locations?.[2]?.id)
+ }),
+ R.createElement(Pressable, {
+ key: "s0",
+ testID: "trigger-point-split-first",
+ onPress: () => props.onPointSplit(props.locations?.[0]?.id)
+ }),
+ R.createElement(Pressable, {
+ key: "sl",
+ testID: "trigger-point-split-last",
+ onPress: () => props.onPointSplit(props.locations?.[props.locations.length - 1]?.id)
+ })
+ ]
+ : null
+ )
+ }
+})
+
+jest.mock("../../components/features/inspector/InteractiveLineChart", () => {
+ const R = require("react")
+ const { View } = require("react-native")
+ return { InteractiveLineChart: (_props: any) => R.createElement(View, { testID: "Chart" }) }
+})
+
+jest.mock("../../components/ui/Container", () => {
+ const R = require("react")
+ const { View } = require("react-native")
+ return { Container: ({ children }: any) => R.createElement(View, null, children) }
+})
+
+jest.mock("../../components/ui/Card", () => {
+ const R = require("react")
+ const { View } = require("react-native")
+ return { Card: ({ children }: any) => R.createElement(View, null, children) }
+})
+
+jest.mock("../../hooks/useTheme", () => ({
+ useTheme: () => ({
+ colors: {
+ primary: "#0d9488",
+ text: "#000",
+ textSecondary: "#6b7280",
+ textDisabled: "#9ca3af",
+ textOnPrimary: "#fff",
+ border: "#e5e7eb",
+ card: "#fff",
+ background: "#fff",
+ error: "#ef4444",
+ pressedOpacity: 0.7,
+ borderRadius: 8
+ }
+ })
+}))
+
+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 {
+ Route: stub("Route"),
+ Clock: stub("Clock"),
+ Gauge: stub("Gauge"),
+ TrendingUp: stub("TrendingUp"),
+ TrendingDown: stub("TrendingDown"),
+ MapPin: stub("MapPin"),
+ Share: stub("Share"),
+ Trash2: stub("Trash2"),
+ ChevronLeft: stub("ChevronLeft"),
+ ChevronRight: stub("ChevronRight")
+ }
+})
+
+import { TripDetailScreen } from "../TripDetailScreen"
+import NativeLocationService from "../../services/NativeLocationService"
+import { showConfirm, showAlert } from "../../services/modalService"
+import { BOUNDARY_ACTION_SPLIT } from "../../types/global"
+
+function makeTrip(pointCount: number): Trip {
+ const locations = Array.from({ length: pointCount }, (_, i) => ({
+ id: i + 1,
+ latitude: 52.52 + i * 0.01,
+ longitude: 13.405,
+ timestamp: 1000 + i * 100
+ }))
+ return {
+ index: 1,
+ locations,
+ startTime: locations[0].timestamp,
+ endTime: locations[locations.length - 1].timestamp,
+ distance: 4000,
+ locationCount: pointCount,
+ startIndex: 0
+ }
+}
+
+const makeProps = (trip: Trip) =>
+ ({
+ navigation: { setOptions: jest.fn(), goBack: jest.fn(), setParams: jest.fn() },
+ route: { params: { trip, trips: [trip] } }
+ }) as any
+
+describe("TripDetailScreen - split from the map", () => {
+ beforeEach(() => jest.clearAllMocks())
+
+ // Splitting is refused until the boundary overrides land, so pressing straight after render
+ // would exercise that guard rather than the reason each test is named for
+ const renderLoaded = async (props: ReturnType<typeof makeProps>) => {
+ const utils = render(<TripDetailScreen {...props} />)
+ await act(async () => {})
+ return utils
+ }
+
+ it("splits at the tapped point, keyed off the point before it", async () => {
+ // A trip's locations are contiguous in the day, so the preceding point is the real boundary.
+ // An off-by-one would write a pair that matches no gap and quietly do nothing.
+ ;(showConfirm as jest.Mock).mockResolvedValueOnce(true)
+ const props = makeProps(makeTrip(4))
+ const { getByTestId } = await renderLoaded(props)
+
+ fireEvent.press(getByTestId("trigger-point-split"))
+
+ await waitFor(() =>
+ expect(NativeLocationService.addBoundaryOverrides).toHaveBeenCalledWith([
+ { before_timestamp: 1100, after_timestamp: 1200, action: BOUNDARY_ACTION_SPLIT }
+ ])
+ )
+ })
+
+ it("returns to the day view, which re-segments on focus", async () => {
+ // Staying would show route.params.trip, a snapshot the split just invalidated
+ ;(showConfirm as jest.Mock).mockResolvedValueOnce(true)
+ const props = makeProps(makeTrip(4))
+ const { getByTestId } = await renderLoaded(props)
+
+ fireEvent.press(getByTestId("trigger-point-split"))
+
+ await waitFor(() => expect(props.navigation.goBack).toHaveBeenCalled())
+ })
+
+ it("splits nothing when the confirm is dismissed", async () => {
+ const props = makeProps(makeTrip(4))
+ const { getByTestId } = await renderLoaded(props)
+
+ fireEvent.press(getByTestId("trigger-point-split"))
+
+ await waitFor(() => expect(showConfirm).toHaveBeenCalled())
+ expect(NativeLocationService.addBoundaryOverrides).not.toHaveBeenCalled()
+ expect(props.navigation.goBack).not.toHaveBeenCalled()
+ })
+
+ it("does not split at the trip's first point", async () => {
+ // That point already starts the trip, so it bails before the dialog - there is no
+ // question worth asking.
+ const props = makeProps(makeTrip(4))
+ const { getByTestId } = await renderLoaded(props)
+
+ fireEvent.press(getByTestId("trigger-point-split-first"))
+
+ expect(showConfirm).not.toHaveBeenCalled()
+ expect(NativeLocationService.addBoundaryOverrides).not.toHaveBeenCalled()
+ })
+
+ it("does not split a two-point trip into a one-point trip", async () => {
+ // A one-point trip has no duration and no distance, and cannot be split again
+ const props = makeProps(makeTrip(2))
+ const { getByTestId } = await renderLoaded(props)
+
+ fireEvent.press(getByTestId("trigger-point-split"))
+
+ // Says why instead of doing nothing
+ expect(showAlert).toHaveBeenCalledWith("Cannot Split Here", expect.any(String), "info")
+ expect(showConfirm).not.toHaveBeenCalled()
+ expect(NativeLocationService.addBoundaryOverrides).not.toHaveBeenCalled()
+ })
+
+ it("does not split at the trip's last point", async () => {
+ const props = makeProps(makeTrip(4))
+ const { getByTestId } = await renderLoaded(props)
+
+ fireEvent.press(getByTestId("trigger-point-split-last"))
+
+ expect(showConfirm).not.toHaveBeenCalled()
+ expect(NativeLocationService.addBoundaryOverrides).not.toHaveBeenCalled()
+ })
+
+ it("keeps the user on the screen when the split fails", async () => {
+ ;(showConfirm as jest.Mock).mockResolvedValueOnce(true)
+ ;(NativeLocationService.addBoundaryOverrides as jest.Mock).mockRejectedValueOnce(new Error("bridge down"))
+ const props = makeProps(makeTrip(4))
+ const { getByTestId } = await renderLoaded(props)
+
+ fireEvent.press(getByTestId("trigger-point-split"))
+
+ await waitFor(() => expect(NativeLocationService.addBoundaryOverrides).toHaveBeenCalled())
+ expect(props.navigation.goBack).not.toHaveBeenCalled()
+ })
+})
diff --git a/apps/mobile/src/services/NativeLocationService.ts b/apps/mobile/src/services/NativeLocationService.ts
index f5c0071e..1b1dab66 100644
--- a/apps/mobile/src/services/NativeLocationService.ts
+++ b/apps/mobile/src/services/NativeLocationService.ts
@@ -16,7 +16,8 @@ import {
Settings,
TestEndpointArgs,
TestEndpointResult,
- TrackingProfile
+ TrackingProfile,
+ TripBoundaryOverride
} from "../types/global"
import { logger } from "../utils/logger"
@@ -320,6 +321,23 @@ class NativeLocationService {
return LocationServiceModule.deleteLocationsByIds(ids)
}
+ /**
+ * Persists manual trip boundary edits. Writing the same boundary twice keeps the latest action,
+ * so a split over a previous merge (or the reverse) resolves without a separate cleanup step.
+ */
+ static async addBoundaryOverrides(overrides: TripBoundaryOverride[]): Promise<void> {
+ this.ensureModule()
+ if (overrides.length === 0) return
+ logger.debug(`[NativeLocationService] Writing ${overrides.length} trip boundary overrides`)
+ await LocationServiceModule.addBoundaryOverrides(overrides)
+ }
+
+ /** Falls back to an empty list so a read failure degrades to plain automatic segmentation. */
+ static async getBoundaryOverrides(): Promise<TripBoundaryOverride[]> {
+ this.ensureModule()
+ return this.safeExecute(() => LocationServiceModule.getBoundaryOverrides(), [], "getBoundaryOverrides failed")
+ }
+
/**
* Runs SQLite VACUUM to reclaim disk space
*/
diff --git a/apps/mobile/src/types/global.ts b/apps/mobile/src/types/global.ts
index 866e1988..1549993a 100644
--- a/apps/mobile/src/types/global.ts
+++ b/apps/mobile/src/types/global.ts
@@ -444,6 +444,23 @@ export interface Trip {
startIndex: number // offset into the day's location array
}
+/**
+ * A manual trip boundary edit, keyed by the timestamps either side of the gap rather than by row
+ * id, so deleting a location leaves it harmless instead of dangling.
+ */
+export interface TripBoundaryOverride {
+ before_timestamp: number
+ after_timestamp: number
+ action: BoundaryAction
+}
+
+/** Suppress the automatic split at this gap. */
+export const BOUNDARY_ACTION_MERGE = 0
+/** Force a split at this gap regardless of its duration. */
+export const BOUNDARY_ACTION_SPLIT = 1
+
+export type BoundaryAction = typeof BOUNDARY_ACTION_MERGE | typeof BOUNDARY_ACTION_SPLIT
+
// ============================================================================
// mTLS - client certificate bridge contract
// ============================================================================
diff --git a/apps/mobile/src/utils/__tests__/trips.test.ts b/apps/mobile/src/utils/__tests__/trips.test.ts
index a03f77d2..641ba9e3 100644
--- a/apps/mobile/src/utils/__tests__/trips.test.ts
+++ b/apps/mobile/src/utils/__tests__/trips.test.ts
@@ -1,5 +1,18 @@
-import { segmentTrips, getTripColor, TRIP_COLORS, computeTripStats } from "../trips"
+import {
+ segmentTrips,
+ getTripColor,
+ TRIP_COLORS,
+ computeTripStats,
+ buildBoundaryOverrideMap,
+ gapsBetweenTrips,
+ boundarySplits,
+ splitBlockedReason,
+ SPLIT_BLOCKED_ALREADY_BOUNDARY,
+ SPLIT_BLOCKED_TOO_SHORT,
+ SPLIT_BLOCKED_TRIP_TOO_SHORT
+} from "../trips"
import { formatDuration, formatTime, formatDate, computeTotalDistance } from "../geo"
+import { BOUNDARY_ACTION_MERGE, BOUNDARY_ACTION_SPLIT, type TripBoundaryOverride } from "../../types/global"
describe("segmentTrips", () => {
it("returns empty array for empty input", () => {
@@ -152,6 +165,278 @@ describe("segmentTrips", () => {
})
})
+describe("manual trip boundary overrides", () => {
+ const overrideMap = (overrides: TripBoundaryOverride[]) => buildBoundaryOverrideMap(overrides)
+
+ it("keeps a merged boundary as one trip even though the gap exceeds the threshold", () => {
+ // The point of a merge: the user says a long stop was still the same journey
+ const locations = [
+ { latitude: 52.52, longitude: 13.405, timestamp: 1000 },
+ { latitude: 52.521, longitude: 13.405, timestamp: 1005 },
+ { latitude: 52.53, longitude: 13.405, timestamp: 1905 }, // 900s gap
+ { latitude: 52.531, longitude: 13.405, timestamp: 1910 }
+ ]
+ expect(segmentTrips(locations)).toHaveLength(2)
+
+ const merged = segmentTrips(
+ locations,
+ undefined,
+ overrideMap([{ before_timestamp: 1005, after_timestamp: 1905, action: BOUNDARY_ACTION_MERGE }])
+ )
+ expect(merged).toHaveLength(1)
+ expect(merged[0].locationCount).toBe(4)
+ })
+
+ it("splits a short gap the user marked, which the threshold would never split on its own", () => {
+ const locations = [
+ { latitude: 52.52, longitude: 13.405, timestamp: 1000 },
+ { latitude: 52.521, longitude: 13.405, timestamp: 1005 },
+ { latitude: 52.53, longitude: 13.405, timestamp: 1010 },
+ { latitude: 52.531, longitude: 13.405, timestamp: 1015 }
+ ]
+ expect(segmentTrips(locations)).toHaveLength(1)
+
+ const split = segmentTrips(
+ locations,
+ undefined,
+ overrideMap([{ before_timestamp: 1005, after_timestamp: 1010, action: BOUNDARY_ACTION_SPLIT }])
+ )
+ expect(split).toHaveLength(2)
+ expect(split[0].endTime).toBe(1005)
+ expect(split[1].startTime).toBe(1010)
+ })
+
+ it("keeps both sides of a manual split even when one is too small to survive the extent filter", () => {
+ // Otherwise the user taps Split, the fragment is dropped as stationary jitter, and the
+ // action looks like it silently did nothing.
+ const locations = [
+ { latitude: 52.52, longitude: 13.405, timestamp: 1000 },
+ { latitude: 52.53, longitude: 13.405, timestamp: 1005 },
+ { latitude: 52.5300001, longitude: 13.405, timestamp: 1010 },
+ { latitude: 52.5300002, longitude: 13.405, timestamp: 1015 }
+ ]
+ const split = segmentTrips(
+ locations,
+ undefined,
+ overrideMap([{ before_timestamp: 1005, after_timestamp: 1010, action: BOUNDARY_ACTION_SPLIT }])
+ )
+ expect(split).toHaveLength(2)
+ expect(split[1].locationCount).toBe(2)
+ // Re-indexed contiguously, so the UI never shows a gap in trip numbering
+ expect(split.map((t) => t.index)).toEqual([1, 2])
+ })
+
+ it("drops a one-point segment even though a split forces it", () => {
+ // A split is only written where both sides have two points, but deleting a point afterwards
+ // can leave one side with a single fix. A lone point has no duration and no distance, so the
+ // forced exemption stops here rather than displaying it.
+ const locations = [
+ { latitude: 52.52, longitude: 13.405, timestamp: 1000 },
+ { latitude: 52.53, longitude: 13.405, timestamp: 1005 },
+ { latitude: 52.5300001, longitude: 13.405, timestamp: 1010 }
+ ]
+ const trips = segmentTrips(
+ locations,
+ undefined,
+ overrideMap([{ before_timestamp: 1000, after_timestamp: 1005, action: BOUNDARY_ACTION_SPLIT }])
+ )
+ // The two-point side survives on the exemption; the one-point side does not
+ expect(trips).toHaveLength(1)
+ expect(trips[0].locationCount).toBe(2)
+ expect(trips[0].startTime).toBe(1005)
+ })
+
+ it("ignores an override whose timestamps no longer exist", () => {
+ // Points can be deleted after an edit; the override has to degrade to a no-op, not misfire
+ const locations = [
+ { latitude: 52.52, longitude: 13.405, timestamp: 1000 },
+ { latitude: 52.521, longitude: 13.405, timestamp: 1005 },
+ { latitude: 52.53, longitude: 13.405, timestamp: 1905 },
+ { latitude: 52.531, longitude: 13.405, timestamp: 1910 }
+ ]
+ const trips = segmentTrips(
+ locations,
+ undefined,
+ overrideMap([{ before_timestamp: 7777, after_timestamp: 8888, action: BOUNDARY_ACTION_MERGE }])
+ )
+ expect(trips).toHaveLength(2)
+ })
+})
+
+describe("gapsBetweenTrips", () => {
+ it("returns the single gap between two directly adjacent trips", () => {
+ const locations = [
+ { latitude: 52.52, longitude: 13.405, timestamp: 1000 },
+ { latitude: 52.521, longitude: 13.405, timestamp: 1005 },
+ { latitude: 52.53, longitude: 13.405, timestamp: 1905 },
+ { latitude: 52.531, longitude: 13.405, timestamp: 1910 }
+ ]
+ const trips = segmentTrips(locations)
+ expect(gapsBetweenTrips(locations, trips[0], trips[1])).toEqual([
+ { before_timestamp: 1005, after_timestamp: 1905, action: BOUNDARY_ACTION_MERGE }
+ ])
+ })
+
+ it("covers every splitting boundary when a filtered-out trip sits between the two trips", () => {
+ // Trips dropped by the extent filter keep their points in the array, so merging across one
+ // spans more than one boundary. Writing only the endpoint pair would match no real gap.
+ const locations = [
+ { latitude: 52.52, longitude: 13.405, timestamp: 1000 },
+ { latitude: 52.522, longitude: 13.405, timestamp: 1005 },
+ // stationary run, dropped by the extent filter
+ { latitude: 52.6, longitude: 13.405, timestamp: 2000 },
+ { latitude: 52.6, longitude: 13.405, timestamp: 2600 },
+ { latitude: 52.6, longitude: 13.405, timestamp: 3200 },
+ { latitude: 52.7, longitude: 13.405, timestamp: 4200 },
+ { latitude: 52.702, longitude: 13.405, timestamp: 4205 }
+ ]
+ const trips = segmentTrips(locations)
+ expect(trips).toHaveLength(2)
+
+ const gaps = gapsBetweenTrips(locations, trips[0], trips[1])
+ // Only the two boundaries that actually split. The 600s steps inside the stationary run are
+ // under the threshold and would never split, so a row for either would be a permanent no-op.
+ expect(gaps.map((g) => [g.before_timestamp, g.after_timestamp])).toEqual([
+ [1005, 2000],
+ [3200, 4200]
+ ])
+
+ // Suppressing exactly those two is still enough to collapse everything into one trip
+ expect(segmentTrips(locations, undefined, buildBoundaryOverrideMap(gaps))).toHaveLength(1)
+ })
+
+ it("returns a boundary the user had split, so merging the two trips undoes the split", () => {
+ const locations = [
+ { latitude: 52.52, longitude: 13.405, timestamp: 1000 },
+ { latitude: 52.53, longitude: 13.405, timestamp: 1005 },
+ { latitude: 52.54, longitude: 13.405, timestamp: 1010 },
+ { latitude: 52.55, longitude: 13.405, timestamp: 1015 }
+ ]
+ const trips = segmentTrips(locations)
+ expect(trips).toHaveLength(1)
+
+ // A short boundary only counts because a SPLIT override is holding it open
+ const overrides = buildBoundaryOverrideMap([
+ { before_timestamp: 1005, after_timestamp: 1010, action: BOUNDARY_ACTION_SPLIT }
+ ])
+ const split = segmentTrips(locations, undefined, overrides)
+ expect(gapsBetweenTrips(locations, split[0], split[1], overrides)).toEqual([
+ { before_timestamp: 1005, after_timestamp: 1010, action: BOUNDARY_ACTION_MERGE }
+ ])
+ })
+})
+
+describe("splitBlockedReason", () => {
+ // 6 points, 5s apart, all one trip
+ const day = Array.from({ length: 6 }, (_, i) => ({
+ id: i + 1,
+ latitude: 52.52 + i * 0.01,
+ longitude: 13.405,
+ timestamp: 1000 + i * 5
+ }))
+
+ it("blocks a split that would leave a one-point trip on either side", () => {
+ // A one-point trip has no duration and no distance, and the forced-split exemption means it
+ // would be displayed rather than dropped by the extent filter
+ expect(splitBlockedReason(day, 1)).toBe(SPLIT_BLOCKED_TOO_SHORT) // leaves [p0] behind
+ expect(splitBlockedReason(day, day.length - 1)).toBe(SPLIT_BLOCKED_TOO_SHORT) // leaves [p5] ahead
+ expect(splitBlockedReason(day, 2)).toBeNull()
+ expect(splitBlockedReason(day, 3)).toBeNull()
+ })
+
+ it("blocks the ends of the array outright", () => {
+ expect(splitBlockedReason(day, 0)).toBe(SPLIT_BLOCKED_ALREADY_BOUNDARY)
+ expect(splitBlockedReason(day, -1)).toBe(SPLIT_BLOCKED_ALREADY_BOUNDARY)
+ expect(splitBlockedReason(day, day.length)).toBe(SPLIT_BLOCKED_ALREADY_BOUNDARY)
+ })
+
+ it("gives a trip too short to split the same answer wherever it is tapped", () => {
+ // Otherwise the first point says "already starts a trip" and the second says "needs two
+ // points a side", sending the user round a loop of points that all refuse
+ const twoPoint = day.slice(0, 2)
+ expect(splitBlockedReason(twoPoint, 0)).toBe(SPLIT_BLOCKED_TRIP_TOO_SHORT)
+ expect(splitBlockedReason(twoPoint, 1)).toBe(SPLIT_BLOCKED_TRIP_TOO_SHORT)
+
+ const threePoint = day.slice(0, 3)
+ expect(threePoint.map((_, i) => splitBlockedReason(threePoint, i))).toEqual([
+ SPLIT_BLOCKED_TRIP_TOO_SHORT,
+ SPLIT_BLOCKED_TRIP_TOO_SHORT,
+ SPLIT_BLOCKED_TRIP_TOO_SHORT
+ ])
+
+ // Four points split down the middle into two two-point trips
+ expect(splitBlockedReason(day.slice(0, 4), 2)).toBeNull()
+ })
+
+ it("reports the short-trip reason from the containing run, not the whole day", () => {
+ // A two-point trip next to a long one is still too short, even though the day has plenty
+ const dayWithShortTrip = [
+ { id: 1, latitude: 52.52, longitude: 13.405, timestamp: 1000 },
+ { id: 2, latitude: 52.53, longitude: 13.405, timestamp: 1005 },
+ { id: 3, latitude: 52.54, longitude: 13.405, timestamp: 1010 },
+ { id: 4, latitude: 52.55, longitude: 13.405, timestamp: 1015 },
+ // 900s gap, then a two-point trip
+ { id: 5, latitude: 52.56, longitude: 13.405, timestamp: 1915 },
+ { id: 6, latitude: 52.57, longitude: 13.405, timestamp: 1920 }
+ ]
+ expect(splitBlockedReason(dayWithShortTrip, 4)).toBe(SPLIT_BLOCKED_TRIP_TOO_SHORT)
+ expect(splitBlockedReason(dayWithShortTrip, 5)).toBe(SPLIT_BLOCKED_TRIP_TOO_SHORT)
+ // The four-point trip beside it is unaffected
+ expect(splitBlockedReason(dayWithShortTrip, 2)).toBeNull()
+ })
+
+ // Two four-point trips either side of a 900s gap, so every run is long enough to split and
+ // the per-point reasons are what's actually under test
+ const twoTrips = [
+ { id: 1, latitude: 52.52, longitude: 13.405, timestamp: 1000 },
+ { id: 2, latitude: 52.53, longitude: 13.405, timestamp: 1005 },
+ { id: 3, latitude: 52.54, longitude: 13.405, timestamp: 1010 },
+ { id: 4, latitude: 52.55, longitude: 13.405, timestamp: 1015 },
+ // 900s gap: index 4 already starts a trip
+ { id: 5, latitude: 52.56, longitude: 13.405, timestamp: 1915 },
+ { id: 6, latitude: 52.57, longitude: 13.405, timestamp: 1920 },
+ { id: 7, latitude: 52.58, longitude: 13.405, timestamp: 1925 },
+ { id: 8, latitude: 52.59, longitude: 13.405, timestamp: 1930 }
+ ]
+
+ it("names the right reason for a boundary that already splits", () => {
+ expect(splitBlockedReason(twoTrips, 4)).toBe(SPLIT_BLOCKED_ALREADY_BOUNDARY)
+ expect(splitBlockedReason(twoTrips, 3)).toBe(SPLIT_BLOCKED_TOO_SHORT) // leaves [p3] alone
+ expect(splitBlockedReason(twoTrips, 5)).toBe(SPLIT_BLOCKED_TOO_SHORT) // leaves [p4] alone
+ expect(splitBlockedReason(twoTrips, 2)).toBeNull()
+ expect(splitBlockedReason(twoTrips, 6)).toBeNull()
+ })
+
+ it("keeps a merged boundary splittable, so a merge can be undone", () => {
+ const merged = buildBoundaryOverrideMap([
+ { before_timestamp: 1015, after_timestamp: 1915, action: BOUNDARY_ACTION_MERGE }
+ ])
+ // Without the override the gap is a real boundary and index 4 is not splittable
+ expect(splitBlockedReason(twoTrips, 4)).toBe(SPLIT_BLOCKED_ALREADY_BOUNDARY)
+ expect(splitBlockedReason(twoTrips, 4, merged)).toBeNull()
+ })
+})
+
+describe("boundarySplits", () => {
+ it("splits on a gap at or over the threshold, and not under it", () => {
+ expect(boundarySplits(1000, 1900)).toBe(true)
+ expect(boundarySplits(1000, 1899)).toBe(false)
+ })
+
+ it("lets an override win over the gap in both directions", () => {
+ // This is what stops the merge and split call sites disagreeing with segmentTrips
+ const merged = buildBoundaryOverrideMap([
+ { before_timestamp: 1000, after_timestamp: 1900, action: BOUNDARY_ACTION_MERGE }
+ ])
+ expect(boundarySplits(1000, 1900, merged)).toBe(false)
+
+ const forced = buildBoundaryOverrideMap([
+ { before_timestamp: 1000, after_timestamp: 1005, action: BOUNDARY_ACTION_SPLIT }
+ ])
+ expect(boundarySplits(1000, 1005, forced)).toBe(true)
+ })
+})
+
describe("formatDuration", () => {
it("formats minutes only", () => {
expect(formatDuration(300)).toBe("5m")
diff --git a/apps/mobile/src/utils/trips.ts b/apps/mobile/src/utils/trips.ts
index 238bb967..f6357a0a 100644
--- a/apps/mobile/src/utils/trips.ts
+++ b/apps/mobile/src/utils/trips.ts
@@ -4,7 +4,8 @@
*/
import { computeTotalDistance, haversine } from "./geo"
-import type { Trip, LocationCoords } from "../types/global"
+import { BOUNDARY_ACTION_MERGE, BOUNDARY_ACTION_SPLIT } from "../types/global"
+import type { Trip, LocationCoords, BoundaryAction, TripBoundaryOverride } from "../types/global"
export const TRIP_COLORS = ["#3B82F6", "#10B981", "#F59E0B", "#EF4444", "#8B5CF6", "#EC4899"]
@@ -12,29 +13,63 @@ export function getTripColor(index: number): string {
return TRIP_COLORS[(index - 1) % TRIP_COLORS.length]
}
-const DEFAULT_GAP_SECONDS = 900 // 15 minutes
+export const DEFAULT_GAP_SECONDS = 900 // 15 minutes
// Total distance is no use here - stationary fixes accumulate it without moving
const MIN_TRIP_EXTENT_METERS = 100 // bbox diagonal, matches DatabaseHelper.getDailyStats
+/** Identifies a boundary by the timestamps of the two locations either side of it. */
+function boundaryKey(beforeTs: number, afterTs: number): string {
+ return `${beforeTs}:${afterTs}`
+}
+
+export function buildBoundaryOverrideMap(overrides: TripBoundaryOverride[]): Map<string, BoundaryAction> {
+ return new Map(overrides.map((o) => [boundaryKey(o.before_timestamp, o.after_timestamp), o.action]))
+}
+
+/**
+ * Whether a new trip starts between these two consecutive points. A manual override wins over
+ * the gap threshold in both directions. This is the single definition of a trip boundary:
+ * segmentTrips applies it, and the merge and split call sites use it to work out which
+ * boundaries are worth writing at all.
+ */
+export function boundarySplits(
+ beforeTs: number,
+ afterTs: number,
+ overrides?: Map<string, BoundaryAction>,
+ gapThresholdSeconds: number = DEFAULT_GAP_SECONDS
+): boolean {
+ const override = overrides?.get(boundaryKey(beforeTs, afterTs))
+ if (override !== undefined) return override === BOUNDARY_ACTION_SPLIT
+ return afterTs - beforeTs >= gapThresholdSeconds
+}
+
/**
* Segments a chronologically-sorted array of locations into trips.
- * A new trip starts when the time gap between consecutive points
- * exceeds gapThresholdSeconds.
+ * A new trip starts when the time gap between consecutive points exceeds gapThresholdSeconds,
+ * unless the user has manually overridden that boundary.
*/
-export function segmentTrips(locations: LocationCoords[], gapThresholdSeconds: number = DEFAULT_GAP_SECONDS): Trip[] {
+export function segmentTrips(
+ locations: LocationCoords[],
+ gapThresholdSeconds: number = DEFAULT_GAP_SECONDS,
+ overrides?: Map<string, BoundaryAction>
+): Trip[] {
if (locations.length === 0) return []
- const trips: Trip[] = []
+ // Kept alongside the trip rather than on it: only the extent filter below cares.
+ const segments: { trip: Trip; forced: boolean }[] = []
let startIndex = 0
+ let startForced = false
let currentTripLocations: LocationCoords[] = [locations[0]]
for (let i = 1; i < locations.length; i++) {
const prevTs = locations[i - 1].timestamp ?? 0
const currTs = locations[i].timestamp ?? 0
+ const forcedSplit = overrides?.get(boundaryKey(prevTs, currTs)) === BOUNDARY_ACTION_SPLIT
- if (currTs - prevTs >= gapThresholdSeconds) {
- trips.push(buildTrip(currentTripLocations, startIndex))
+ if (boundarySplits(prevTs, currTs, overrides, gapThresholdSeconds)) {
+ segments.push({ trip: buildTrip(currentTripLocations, startIndex), forced: startForced || forcedSplit })
startIndex = i
+ startForced = forcedSplit
currentTripLocations = [locations[i]]
} else {
currentTripLocations.push(locations[i])
@@ -42,13 +77,102 @@ export function segmentTrips(locations: LocationCoords[], gapThresholdSeconds: n
}
if (currentTripLocations.length > 0) {
- trips.push(buildTrip(currentTripLocations, startIndex))
+ segments.push({ trip: buildTrip(currentTripLocations, startIndex), forced: startForced })
}
- // Drops stray fixes during long stops as well as stationary runs
- const filtered = trips.filter((t) => trackExtent(t.locations) >= MIN_TRIP_EXTENT_METERS)
+ // Drops stray fixes during long stops as well as stationary runs. A manually split trip is exempt,
+ // so an explicit edit never looks like it did nothing. The exemption stops at one point: a split
+ // stays legal after the points around it are deleted, and a lone point is not a trip.
+ const filtered = segments.filter(
+ (s) => (s.forced && s.trip.locations.length >= 2) || trackExtent(s.trip.locations) >= MIN_TRIP_EXTENT_METERS
+ )
// Re-index after filtering
- return filtered.map((t, i) => ({ ...t, index: i + 1 }))
+ return filtered.map((s, i) => ({ ...s.trip, index: i + 1 }))
+}
+
+export const SPLIT_BLOCKED_NOT_A_TRIP =
+ "This point is not part of a trip. Colota leaves out runs that never travel more than 100 m."
+export const SPLIT_BLOCKED_ALREADY_BOUNDARY = "This point already starts a trip."
+export const SPLIT_BLOCKED_TRIP_TOO_SHORT =
+ "This trip is too short to split. Splitting makes two trips, and each one needs at least two points."
+export const SPLIT_BLOCKED_TOO_SHORT =
+ "A split needs at least two points on each side, so the first two and last two points of a trip cannot start a new one."
+
+/** First and last index of the run of points containing index, bounded by the trip boundaries. */
+function runBounds(
+ locations: LocationCoords[],
+ index: number,
+ overrides?: Map<string, BoundaryAction>,
+ gapThresholdSeconds: number = DEFAULT_GAP_SECONDS
+): [number, number] {
+ const ts = (i: number) => locations[i].timestamp ?? 0
+ const splits = (i: number) => boundarySplits(ts(i), ts(i + 1), overrides, gapThresholdSeconds)
+ let start = index
+ while (start > 0 && !splits(start - 1)) start--
+ let end = index
+ while (end < locations.length - 1 && !splits(end)) end++
+ return [start, end]
+}
+
+/**
+ * Why a split before locations[index] would not produce two usable trips, or null if it would.
+ *
+ * Both sides need two points: a one-point trip has no duration and no distance, and because a
+ * forced split exempts the segments either side from the extent filter it would be displayed
+ * rather than dropped. That rules out the first two and last two points of any trip, so a trip
+ * needs at least four points before it can be split anywhere.
+ *
+ * Returns the reason rather than a boolean so the caller can say why nothing happened; the map
+ * cannot show this state on the point itself.
+ */
+export function splitBlockedReason(
+ locations: LocationCoords[],
+ index: number,
+ overrides?: Map<string, BoundaryAction>,
+ gapThresholdSeconds: number = DEFAULT_GAP_SECONDS
+): string | null {
+ if (index < 0 || index >= locations.length) return SPLIT_BLOCKED_ALREADY_BOUNDARY
+ const ts = (i: number) => locations[i].timestamp ?? 0
+ const splits = (i: number) => boundarySplits(ts(i), ts(i + 1), overrides, gapThresholdSeconds)
+
+ // Checked first so a short trip gives the same answer wherever it is tapped, rather than
+ // sending the user round points that all refuse for different-sounding reasons.
+ const [start, end] = runBounds(locations, index, overrides, gapThresholdSeconds)
+ if (end - start + 1 < 4) return SPLIT_BLOCKED_TRIP_TOO_SHORT
+
+ // Forcing a split where one already happens would only exempt the neighbours from the extent
+ // filter, resurrecting the stationary runs the segmenter drops on purpose.
+ if (index === 0 || splits(index - 1)) return SPLIT_BLOCKED_ALREADY_BOUNDARY
+ // A boundary on either shoulder would leave a one-point trip behind
+ if (index < 2 || index > locations.length - 2) return SPLIT_BLOCKED_TOO_SHORT
+ if (splits(index - 2) || splits(index)) return SPLIT_BLOCKED_TOO_SHORT
+ return null
+}
+
+/**
+ * The merges needed to fuse two displayed trips. Usually one, but trips dropped by the extent
+ * filter still have their locations in the array, so merging across one spans several boundaries.
+ *
+ * Only boundaries that currently split are returned. The points inside a dropped stationary run
+ * are seconds apart and would never split on their own, and writing a row for each of those would
+ * put hundreds of no-op rows in the table for every merge over a long stop.
+ */
+export function gapsBetweenTrips(
+ locations: LocationCoords[],
+ earlier: Trip,
+ later: Trip,
+ overrides?: Map<string, BoundaryAction>,
+ gapThresholdSeconds: number = DEFAULT_GAP_SECONDS
+): TripBoundaryOverride[] {
+ const gaps: TripBoundaryOverride[] = []
+ const from = earlier.startIndex + earlier.locationCount - 1
+ for (let i = from; i < later.startIndex && i + 1 < locations.length; i++) {
+ const beforeTs = locations[i].timestamp ?? 0
+ const afterTs = locations[i + 1].timestamp ?? 0
+ if (!boundarySplits(beforeTs, afterTs, overrides, gapThresholdSeconds)) continue
+ gaps.push({ before_timestamp: beforeTs, after_timestamp: afterTs, action: BOUNDARY_ACTION_MERGE })
+ }
+ return gaps
}
/** Bounding box diagonal, in meters. */
diff --git a/fastlane/metadata/android/en-US/changelogs/45.txt b/fastlane/metadata/android/en-US/changelogs/45.txt
index 28a5fdf9..62430ad5 100644
--- a/fastlane/metadata/android/en-US/changelogs/45.txt
+++ b/fastlane/metadata/android/en-US/changelogs/45.txt
@@ -1,4 +1,6 @@
- Large point counts stay on one line in the settings summary, shown as 123K or 2.0M
- Geofence heartbeat now records points in offline mode and when the server is unreachable
- No duplicate heartbeat point after the app restarts in the background
+- Merge adjacent trips from the Trips selection bar when one journey got split up
+- Split a trip by tapping the point on the map where the new trip should start
- Trips show an average speed instead of 0 km/h when the points carry no speed, including imported tracks