Colota - Android GPS Location tracker
feat(annotations): add per-point notes (#445)
Max Dietrich5a92d128f93a
diff --git a/apps/docs/docs/introduction.md b/apps/docs/docs/introduction.mdindex 1fba8f61..8c399b1a 100644--- a/apps/docs/docs/introduction.md+++ b/apps/docs/docs/introduction.md@@ -15,7 +15,7 @@ Colota is a self-hosted GPS tracking app for Android. It sends your location to- **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 locations, settings, geofences and credentials.-- **Location History** - View daily summaries, trip segmentation, calendar with activity dots and per-trip export.+- **Location History** - View daily summaries, trip segmentation, calendar with activity dots, per-trip export and notes on individual points.- **Reliable Tracking** - Foreground service, auto-start on boot and exponential backoff retry.- **Geofencing** - Pause zones that stop recording locations. Optionally stop GPS entirely when on WiFi or when the device is motionless.- **Tracking Profiles** - Automatically adjust GPS interval, distance filter and sync settings based on conditions like charging, Android Auto, speed or stationary detection.@@ -43,7 +43,7 @@ Colota has twenty-two screens, each focused on a specific task:| **Offline Maps** | Download map areas to the device for use without an internet connection || **Tracking Profiles** | Create and manage condition-based profiles that automatically adjust tracking settings || **Profile Editor** | Configure profile name, condition trigger, GPS interval, distance filter, sync interval, priority, and deactivation delay |-| **Location History** | Browse recorded locations on a track map with calendar day picker and trip-colored segments, view segmented trips with per-trip stats |+| **Location History** | Browse recorded locations on a track map with calendar day picker and trip-colored segments, view segmented trips with per-trip stats; tap a point to add a note || **Trip Detail** | Full trip view with dedicated map, stats grid (distance, duration, avg speed, elevation), speed and elevation profile charts, export, and delete || **Location Summary** | Aggregated stats (total distance, trips, active days, avg distance) for selectable periods with daily breakdown and tap-to-inspect navigation || **Export Data** | Export tracked locations as CSV, GeoJSON, GPX, or KML |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.ktindex 2e8a78d0..20f9abeb 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@@ -357,6 +357,12 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :}}+ @ReactMethod+ fun updateLocationNote(id: Double, note: String?, promise: Promise) = executeAsync(promise) {+ dbHelper.updateLocationNote(id.toLong(), note?.takeIf { it.isNotBlank() })+ true+ }+@ReactMethodfun getDaysWithData(startTimestamp: Double, endTimestamp: Double, promise: Promise) =executeAsync(promise) {diff --git a/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.ktindex a7b75f2b..d8667219 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@@ -234,6 +234,7 @@ class DatabaseHelper private constructor(context: Context) :// Stationary profiles existed before this column with a fixed 60s detection window;// backfill that value so they keep behaving the same now that it is a stored field.db.execSQL("UPDATE $TABLE_PROFILES SET activation_delay_seconds = 60 WHERE condition_type = 'stationary'")+ db.execSQL("ALTER TABLE $TABLE_LOCATIONS ADD COLUMN note TEXT")}}@@ -263,6 +264,7 @@ class DatabaseHelper private constructor(context: Context) :timestamp INTEGER NOT NULL,endpoint TEXT,sent INTEGER NOT NULL DEFAULT 0,+ note TEXT,created_at INTEGER NOT NULL)""")@@ -689,6 +691,13 @@ class DatabaseHelper private constructor(context: Context) :writableDatabase.delete(TABLE_LOCATIONS, "id IN ($placeholders)", args)}+ /** Sets or clears the free-text note on a single location. Pass null to clear. */+ fun updateLocationNote(id: Long, note: String?) {+ requireNotRestoring()+ val values = ContentValues().apply { put("note", note) }+ writableDatabase.update(TABLE_LOCATIONS, values, "id = ?", arrayOf(id.toString()))+ }+fun incrementRetryCount(queueId: Long, error: String? = null) {requireNotRestoring()writableDatabase.execSQL(diff --git a/apps/mobile/android/app/src/main/java/com/colota/export/ExportConverters.kt b/apps/mobile/android/app/src/main/java/com/colota/export/ExportConverters.ktindex 69064e0d..396359a6 100644--- a/apps/mobile/android/app/src/main/java/com/colota/export/ExportConverters.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/export/ExportConverters.kt@@ -76,6 +76,30 @@ object ExportConverters {else -> null}+ /** Escape free text for XML element content (GPX/KML notes). */+ private fun xmlEscape(s: String): String = buildString(s.length) {+ for (c in s) {+ when (c) {+ '&' -> append("&")+ '<' -> append("<")+ '>' -> append(">")+ '"' -> append(""")+ '\'' -> append("'")+ else -> append(c)+ }+ }+ }++ /** RFC-4180 CSV field: quote+double-escape only when the value contains a delimiter. */+ private fun csvField(value: Any?): String {+ val s = value?.toString() ?: return ""+ return if (s.any { it == ',' || it == '"' || it == '\n' || it == '\r' }) {+ "\"" + s.replace("\"", "\"\"") + "\""+ } else {+ s+ }+ }+private fun escapeJson(s: String): String = buildString(s.length) {for (c in s) {when (c) {@@ -101,6 +125,7 @@ object ExportConverters {val bearing: Any?,val battery: Any?,val batteryStatus: Any?,+ val note: String?,) {companion object {fun from(row: Map<String, Any?>): ExportRow = ExportRow(@@ -113,6 +138,7 @@ object ExportConverters {bearing = row["bearing"],battery = row["battery"],batteryStatus = row["battery_status"],+ note = row["note"] as? String,)}}@@ -130,13 +156,13 @@ object ExportConverters {private object CsvFormat : FormatWriter(".csv", "text/csv") {override fun writeHeader(w: Writer) {- w.write("id,timestamp,iso_time,latitude,longitude,accuracy,altitude,speed,bearing,battery,battery_status\n")+ w.write("id,timestamp,iso_time,latitude,longitude,accuracy,altitude,speed,bearing,battery,battery_status,note\n")}override fun writeRow(w: Writer, row: ExportRow, globalIndex: Int, kml: KmlCoordsCollector?) {w.write(listOf(globalIndex, row.ts, isoTime(row.ts), jsNum(row.lat), jsNum(row.lon),numOrZero(row.accuracy), numOrZero(row.altitude), numOrZero(row.speed), numOrZero(row.bearing), numOrZero(row.battery),- batteryStatusLabel(row.batteryStatus) ?: ""+ batteryStatusLabel(row.batteryStatus) ?: "", csvField(row.note)).joinToString(","))w.write("\n")}@@ -163,6 +189,7 @@ object ExportConverters {"bearing": ${jsonValue(row.bearing)},"battery": ${jsonValue(row.battery)},"battery_status": ${jsonValue(batteryStatusLabel(row.batteryStatus))},+ "note": ${jsonValue(row.note)},"time": "${isoTime(row.ts)}"}}""")@@ -197,6 +224,7 @@ object ExportConverters {<bearing>${numOrZero(row.bearing)}</bearing><battery>${numOrZero(row.battery)}</battery><battery_status>${batteryStatusLabel(row.batteryStatus) ?: ""}</battery_status>+ <note>${row.note?.let { xmlEscape(it) } ?: ""}</note></extensions></trkpt>""")@@ -237,6 +265,7 @@ object ExportConverters {<Data name="bearing"><value>${numOrZero(row.bearing)}</value></Data><Data name="battery"><value>${numOrZero(row.battery)}</value></Data><Data name="battery_status"><value>${batteryStatusLabel(row.batteryStatus) ?: ""}</value></Data>+ <Data name="note"><value>${row.note?.let { xmlEscape(it) } ?: ""}</value></Data></ExtendedData><Point><coordinates>${jsNum(row.lon)},${jsNum(row.lat)},${numOrZero(row.altitude)}</coordinates>@@ -403,7 +432,7 @@ object ExportConverters {}private fun tripsToCsv(trips: List<TripExport>): String {- val sb = StringBuilder("trip,id,timestamp,iso_time,latitude,longitude,accuracy,altitude,speed,bearing,battery,battery_status\n")+ val sb = StringBuilder("trip,id,timestamp,iso_time,latitude,longitude,accuracy,altitude,speed,bearing,battery,battery_status,note\n")val rows = ArrayList<String>()for (trip in trips) {trip.rows.forEachIndexed { i, row ->@@ -414,7 +443,7 @@ object ExportConverters {numOrZero(row["latitude"]), numOrZero(row["longitude"]),numOrZero(row["accuracy"]), numOrZero(row["altitude"]),numOrZero(row["speed"]), numOrZero(row["bearing"]), numOrZero(row["battery"]),- batteryStatusLabel(row["battery_status"]) ?: ""+ batteryStatusLabel(row["battery_status"]) ?: "", csvField(row["note"])).joinToString(","))}@@ -447,6 +476,7 @@ object ExportConverters {" \"bearing\": ${jsonNum(row["bearing"])},\n" +" \"battery\": ${jsonNum(row["battery"])},\n" +" \"battery_status\": ${jsonValue(batteryStatusLabel(row["battery_status"]))},\n" ++ " \"note\": ${jsonValue(row["note"])},\n" +" \"time\": \"${isoTime(ts)}\"\n" +" }\n" +" }"@@ -480,6 +510,7 @@ object ExportConverters {sb.append("\n <bearing>${numOrZero(row["bearing"])}</bearing>")sb.append("\n <battery>${numOrZero(row["battery"])}</battery>")sb.append("\n <battery_status>${batteryStatusLabel(row["battery_status"]) ?: ""}</battery_status>")+ sb.append("\n <note>${(row["note"] as? String)?.let { xmlEscape(it) } ?: ""}</note>")sb.append("\n </extensions>")sb.append("\n </trkpt>")}@@ -531,6 +562,7 @@ object ExportConverters {sb.append("\n <Data name=\"bearing\"><value>${numOrZero(row["bearing"])}</value></Data>")sb.append("\n <Data name=\"battery\"><value>${numOrZero(row["battery"])}</value></Data>")sb.append("\n <Data name=\"battery_status\"><value>${batteryStatusLabel(row["battery_status"]) ?: ""}</value></Data>")+ sb.append("\n <Data name=\"note\"><value>${(row["note"] as? String)?.let { xmlEscape(it) } ?: ""}</value></Data>")sb.append("\n </ExtendedData>")sb.append("\n <Point>")sb.append("\n <coordinates>${numOrZero(row["longitude"])},${numOrZero(row["latitude"])},${numOrZero(row["altitude"])}</coordinates>")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.ktindex c5af5d3e..998d9596 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@@ -132,6 +132,8 @@ class DatabaseHelperSQLiteTest {('Parked', 1800000, 0, 0, 40, 'stationary', 0, 0)""".trimIndent())+ // v5-era locations table (no `note` column yet) for the v6 note ALTER to apply to+ old.execSQL("CREATE TABLE locations (id INTEGER PRIMARY KEY AUTOINCREMENT, latitude REAL NOT NULL, longitude REAL NOT NULL, accuracy INTEGER, altitude INTEGER, speed INTEGER, bearing REAL, battery INTEGER, battery_status INTEGER, timestamp INTEGER NOT NULL, endpoint TEXT, sent INTEGER NOT NULL DEFAULT 0, created_at INTEGER NOT NULL)")old.version = 5}@@ -175,6 +177,13 @@ class DatabaseHelperSQLiteTest {SQLiteDatabase.openDatabase(candidate.absolutePath, null, SQLiteDatabase.OPEN_READONLY).use { migrated ->assertEquals(6, migrated.version)+ migrated.rawQuery("PRAGMA table_info(locations)", null).use { locCursor ->+ val locCols = mutableSetOf<String>()+ while (locCursor.moveToNext()) {+ locCols.add(locCursor.getString(locCursor.getColumnIndexOrThrow("name")))+ }+ assertTrue(locCols.contains("note"))+ }migrated.rawQuery("PRAGMA table_info(tracking_profiles)", null).use { cursor ->val cols = mutableSetOf<String>()while (cursor.moveToNext()) {@@ -271,6 +280,24 @@ class DatabaseHelperSQLiteTest {}}+ @Test+ fun `updateLocationNote sets and clears the note`() {+ val id = db.saveLocation(latitude = 52.52, longitude = 13.405, timestamp = 1700000000L)++ db.updateLocationNote(id, "saw a deer")+ val rawDb = db.readableDatabase+ rawDb.rawQuery("SELECT note FROM ${DatabaseHelper.TABLE_LOCATIONS} WHERE id = ?", arrayOf(id.toString())).use { cursor ->+ assertTrue(cursor.moveToFirst())+ assertEquals("saw a deer", cursor.getString(0))+ }++ db.updateLocationNote(id, null)+ rawDb.rawQuery("SELECT note FROM ${DatabaseHelper.TABLE_LOCATIONS} WHERE id = ?", arrayOf(id.toString())).use { cursor ->+ assertTrue(cursor.moveToFirst())+ assertTrue(cursor.isNull(0))+ }+ }+@Testfun `getRawMostRecentLocation returns latest by timestamp`() {db.saveLocation(latitude = 52.0, longitude = 13.0, accuracy = 5.0, timestamp = 1000L)diff --git a/apps/mobile/android/app/src/test/java/com/Colota/export/ExportConvertersTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/export/ExportConvertersTest.ktindex cfcf06ac..d417cd46 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/export/ExportConvertersTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/export/ExportConvertersTest.kt@@ -68,7 +68,7 @@ class ExportConvertersTest {fun `convert CSV contains header row`() {val csv = ExportConverters.convert("csv", sampleRows)val lines = csv.lines()- assertEquals("id,timestamp,iso_time,latitude,longitude,accuracy,altitude,speed,bearing,battery,battery_status", lines[0])+ assertEquals("id,timestamp,iso_time,latitude,longitude,accuracy,altitude,speed,bearing,battery,battery_status,note", lines[0])}@Test@@ -159,6 +159,47 @@ class ExportConvertersTest {assertEquals(3, placemarkCount) // 1 track + 2 point placemarks}+ // --- Note annotation (#257) ---++ // A note with every char that needs escaping in some format (comma, quotes, angle brackets,+ // ampersand, newline), so a dropped-escaping regression fails here instead of corrupting exports.+ private val noteRows = listOf(+ mapOf(+ "latitude" to 52.52, "longitude" to 13.405, "timestamp" to 1700000000L,+ "note" to "deer, \"big\" <antlers> & a\nnewline"+ ),+ mapOf("latitude" to 48.8566, "longitude" to 2.3522, "timestamp" to 1700003600L)+ )++ @Test+ fun `CSV quotes a note containing commas quotes and newlines`() {+ val csv = ExportConverters.convert("csv", noteRows)+ assertTrue(csv.contains("\"deer, \"\"big\"\" <antlers> & a\nnewline\""))+ }++ @Test+ fun `GeoJSON JSON-escapes the note and emits null when absent`() {+ val json = ExportConverters.convert("geojson", noteRows)+ assertTrue(json.contains("\\\"big\\\""))+ assertTrue(json.contains("\"note\": null")) // the second point has no note+ }++ @Test+ fun `GPX writes an XML-escaped note in extensions, empty when absent`() {+ val gpx = ExportConverters.convert("gpx", noteRows)+ assertTrue(gpx.contains("<note>deer, "big" <antlers> & a\nnewline</note>"))+ assertTrue(gpx.contains("<note></note>")) // empty for the point without a note+ assertEquals(2, Regex("<note>").findAll(gpx).count()) // one per point, like the other extensions+ }++ @Test+ fun `KML writes an escaped note Data entry, empty when absent`() {+ val kml = ExportConverters.convert("kml", noteRows)+ assertTrue(kml.contains("<antlers>"))+ // note Data sits in the existing per-point ExtendedData, like battery_status+ assertEquals(2, Regex("<Data name=\"note\">").findAll(kml).count())+ }+// --- JSON escaping ---@Test@@ -250,7 +291,7 @@ class ExportConvertersTest {fun `streaming CSV produces header and data rows`() {val result = streamToString("csv", sampleRows)val lines = result.lines().filter { it.isNotBlank() }- assertEquals("id,timestamp,iso_time,latitude,longitude,accuracy,altitude,speed,bearing,battery,battery_status", lines[0])+ assertEquals("id,timestamp,iso_time,latitude,longitude,accuracy,altitude,speed,bearing,battery,battery_status,note", lines[0])assertEquals(3, lines.size)assertTrue(lines[1].startsWith("0,1700000000,"))assertTrue(lines[1].contains("52.52"))@@ -341,7 +382,7 @@ class ExportConvertersTest {@Testfun `convert includes bearing and battery_status across formats`() {val csv = ExportConverters.convert("csv", sampleRows)- assertTrue(csv.lines()[1].endsWith(",Charging")) // battery_status label, last column+ assertTrue(csv.lines()[1].endsWith(",Charging,")) // battery_status label, then empty note (last column)val gj = ExportConverters.convert("geojson", sampleRows)assertTrue(gj.contains("\"bearing\": 180")) // whole double -> no trailing ".0"assertTrue(gj.contains("\"battery_status\": \"Charging\""))@@ -397,12 +438,34 @@ class ExportConvertersTest {assertEquals(norm(golden("trip.kml")), norm(ExportConverters.convertTrips("kml", tripFixture)))}+ @Test+ fun `convertTrips writes the note in every format and escapes per format`() {+ // Trip serializers are separate from the flat writers and the golden fixture is note-free,+ // so cover note placement and per-format escaping here.+ val trips = listOf(ExportConverters.TripExport(1, "#3B82F6", listOf(+ mapOf("latitude" to 52.52, "longitude" to 13.405, "timestamp" to 1700000000L, "note" to "deer, \"big\" <antlers>"),+ mapOf("latitude" to 48.8566, "longitude" to 2.3522, "timestamp" to 1700003600L)+ )))+ val csv = ExportConverters.convertTrips("csv", trips)+ assertTrue(csv.contains("\"deer, \"\"big\"\" <antlers>\""))+ val gj = ExportConverters.convertTrips("geojson", trips)+ assertTrue(gj.contains("\\\"big\\\""))+ assertTrue(gj.contains("\"note\": null")) // the second point has no note+ val gpx = ExportConverters.convertTrips("gpx", trips)+ assertTrue(gpx.contains("<note>deer, "big" <antlers></note>"))+ assertTrue(gpx.contains("<note></note>"))+ assertEquals(2, Regex("<note>").findAll(gpx).count())+ val kml = ExportConverters.convertTrips("kml", trips)+ assertTrue(kml.contains("<antlers>"))+ assertEquals(2, Regex("<Data name=\"note\">").findAll(kml).count())+ }+// --- Trip-export edge cases (no trips / empty trip) ---@Testfun `convertTrips with no trips produces valid empty output`() {assertEquals(- "trip,id,timestamp,iso_time,latitude,longitude,accuracy,altitude,speed,bearing,battery,battery_status",+ "trip,id,timestamp,iso_time,latitude,longitude,accuracy,altitude,speed,bearing,battery,battery_status,note",ExportConverters.convertTrips("csv", emptyList()).trim())assertTrue(ExportConverters.convertTrips("geojson", emptyList()).contains("\"features\": []"))diff --git a/apps/mobile/android/app/src/test/resources/golden/export/trip.csv b/apps/mobile/android/app/src/test/resources/golden/export/trip.csvindex d10ceb58..d171ebba 100644--- a/apps/mobile/android/app/src/test/resources/golden/export/trip.csv+++ b/apps/mobile/android/app/src/test/resources/golden/export/trip.csv@@ -1,5 +1,5 @@-trip,id,timestamp,iso_time,latitude,longitude,accuracy,altitude,speed,bearing,battery,battery_status-1,0,1700000000,2023-11-14T22:13:20.000Z,48.137154,11.576124,8.5,520.2,1.4,270.5,91,Charging-1,1,1700000060,2023-11-14T22:14:20.000Z,48.138001,11.577003,12,525,2,275,90,Full-2,0,1700001000,2023-11-14T22:30:00.000Z,48.14,11.58,5,530,3,10,88,Unplugged/Discharging-2,1,1700001060,2023-11-14T22:31:00.000Z,48.1405,11.5811,6.2,0,0,0,87,Unknown\ No newline at end of file+trip,id,timestamp,iso_time,latitude,longitude,accuracy,altitude,speed,bearing,battery,battery_status,note+1,0,1700000000,2023-11-14T22:13:20.000Z,48.137154,11.576124,8.5,520.2,1.4,270.5,91,Charging,+1,1,1700000060,2023-11-14T22:14:20.000Z,48.138001,11.577003,12,525,2,275,90,Full,+2,0,1700001000,2023-11-14T22:30:00.000Z,48.14,11.58,5,530,3,10,88,Unplugged/Discharging,+2,1,1700001060,2023-11-14T22:31:00.000Z,48.1405,11.5811,6.2,0,0,0,87,Unknown,\ No newline at end of filediff --git a/apps/mobile/android/app/src/test/resources/golden/export/trip.geojson b/apps/mobile/android/app/src/test/resources/golden/export/trip.geojsonindex 89803ce5..67c97a83 100644--- a/apps/mobile/android/app/src/test/resources/golden/export/trip.geojson+++ b/apps/mobile/android/app/src/test/resources/golden/export/trip.geojson@@ -19,6 +19,7 @@"bearing": 270.5,"battery": 91,"battery_status": "Charging",+ "note": null,"time": "2023-11-14T22:13:20.000Z"}},@@ -40,6 +41,7 @@"bearing": 275,"battery": 90,"battery_status": "Full",+ "note": null,"time": "2023-11-14T22:14:20.000Z"}},@@ -61,6 +63,7 @@"bearing": 10,"battery": 88,"battery_status": "Unplugged/Discharging",+ "note": null,"time": "2023-11-14T22:30:00.000Z"}},@@ -82,6 +85,7 @@"bearing": 0,"battery": 87,"battery_status": "Unknown",+ "note": null,"time": "2023-11-14T22:31:00.000Z"}}diff --git a/apps/mobile/android/app/src/test/resources/golden/export/trip.gpx b/apps/mobile/android/app/src/test/resources/golden/export/trip.gpxindex 22bd722d..81b5ab4d 100644--- a/apps/mobile/android/app/src/test/resources/golden/export/trip.gpx+++ b/apps/mobile/android/app/src/test/resources/golden/export/trip.gpx@@ -16,6 +16,7 @@<bearing>270.5</bearing><battery>91</battery><battery_status>Charging</battery_status>+ <note></note></extensions></trkpt><trkpt lat="48.138001" lon="11.577003">@@ -27,6 +28,7 @@<bearing>275</bearing><battery>90</battery><battery_status>Full</battery_status>+ <note></note></extensions></trkpt></trkseg>@@ -43,6 +45,7 @@<bearing>10</bearing><battery>88</battery><battery_status>Unplugged/Discharging</battery_status>+ <note></note></extensions></trkpt><trkpt lat="48.140500" lon="11.581100">@@ -54,6 +57,7 @@<bearing>0</bearing><battery>87</battery><battery_status>Unknown</battery_status>+ <note></note></extensions></trkpt></trkseg>diff --git a/apps/mobile/android/app/src/test/resources/golden/export/trip.kml b/apps/mobile/android/app/src/test/resources/golden/export/trip.kmlindex fa47d824..667a7e86 100644--- a/apps/mobile/android/app/src/test/resources/golden/export/trip.kml+++ b/apps/mobile/android/app/src/test/resources/golden/export/trip.kml@@ -32,6 +32,7 @@<Data name="bearing"><value>270.5</value></Data><Data name="battery"><value>91</value></Data><Data name="battery_status"><value>Charging</value></Data>+ <Data name="note"><value></value></Data></ExtendedData><Point><coordinates>11.576124,48.137154,520.2</coordinates>@@ -47,6 +48,7 @@<Data name="bearing"><value>275</value></Data><Data name="battery"><value>90</value></Data><Data name="battery_status"><value>Full</value></Data>+ <Data name="note"><value></value></Data></ExtendedData><Point><coordinates>11.577003,48.138001,525</coordinates>@@ -82,6 +84,7 @@<Data name="bearing"><value>10</value></Data><Data name="battery"><value>88</value></Data><Data name="battery_status"><value>Unplugged/Discharging</value></Data>+ <Data name="note"><value></value></Data></ExtendedData><Point><coordinates>11.58,48.14,530</coordinates>@@ -97,6 +100,7 @@<Data name="bearing"><value>0</value></Data><Data name="battery"><value>87</value></Data><Data name="battery_status"><value>Unknown</value></Data>+ <Data name="note"><value></value></Data></ExtendedData><Point><coordinates>11.5811,48.1405,0</coordinates>diff --git a/apps/mobile/src/components/features/inspector/LocationTable.tsx b/apps/mobile/src/components/features/inspector/LocationTable.tsxindex 26f3147d..f44c84b8 100644--- a/apps/mobile/src/components/features/inspector/LocationTable.tsx+++ b/apps/mobile/src/components/features/inspector/LocationTable.tsx@@ -19,7 +19,7 @@ interface TableRow extends LocationCoords {}const ROW_HEIGHT = 36-const TABLE_WIDTH = 730+const TABLE_WIDTH = 870function val(v?: number | null, decimals = 0): string {if (v == null) return "-"@@ -75,6 +75,9 @@ const LocationRow = React.memo(<Text style={[styles.cell, styles.cellStatus, { color: colors.text }]} numberOfLines={1}>{item.battery_status != null ? (BATTERY_STATUS[item.battery_status] ?? String(item.battery_status)) : "-"}</Text>+ <Text style={[styles.cell, styles.cellNote, { color: colors.text }]} numberOfLines={1}>+ {item.note ? item.note : "-"}+ </Text></View>))@@ -135,6 +138,7 @@ export function LocationTable({ locations, colors }: Props) {<Text style={[styles.cell, styles.cellStatus, styles.headerText, { color: colors.textSecondary }]}>Charge</Text>+ <Text style={[styles.cell, styles.cellNote, styles.headerText, { color: colors.textSecondary }]}>Note</Text></View><FlatList@@ -201,6 +205,9 @@ const styles = StyleSheet.create({cellStatus: {width: 90},+ cellNote: {+ width: 140+ },tableWrapper: {width: TABLE_WIDTH,flex: 1diff --git a/apps/mobile/src/components/features/inspector/TrackMap.tsx b/apps/mobile/src/components/features/inspector/TrackMap.tsxindex 773d0f5d..139c69b7 100644--- a/apps/mobile/src/components/features/inspector/TrackMap.tsx+++ b/apps/mobile/src/components/features/inspector/TrackMap.tsx@@ -4,10 +4,10 @@*/import React, { useRef, useEffect, useMemo, useState, useCallback } from "react"-import { View, StyleSheet, Text, Pressable } from "react-native"+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 } from "lucide-react-native"+import { MapPinOff, X, Check } from "lucide-react-native"import { ThemeColors, Trip } from "../../../types/global"import { getTripColor } from "../../../utils/trips"import { fonts } from "../../../styles/typography"@@ -37,9 +37,11 @@ interface Props {trips?: Trip[]trackColor: stringfitVersion?: number+ /** When provided, the point popup gains an editable note field. Omit for read-only maps. */+ onPointNoteChange?: (id: number, note: string | null) => void}-export function TrackMap({ locations, colors, trips, trackColor, fitVersion }: Props) {+export function TrackMap({ locations, colors, trips, trackColor, fitVersion, onPointNoteChange }: Props) {const mapRef = useRef<ColotaMapRef>(null)const [isCentered, setIsCentered] = useState(true)const [selectedPoint, setSelectedPoint] = useState<{@@ -54,8 +56,14 @@ export function TrackMap({ locations, colors, trips, trackColor, fitVersion }: Paccuracy: numberaltitude: numbercolor: string+ id: number+ note: string} | null>(null)+ const [noteDraft, setNoteDraft] = useState("")const [mapReady, setMapReady] = useState(false)+ // Note edits made here, keyed by id; read on press so a note change doesn't rebuild the+ // points source (and re-render the map). Reset on reload.+ const noteEditsRef = useRef<Record<number, string>>({})// Fit map to track bounds when fitVersion changes (date change, trip select)const bounds = useMemo(() => computeTrackBounds(locations), [locations])@@ -77,10 +85,11 @@ export function TrackMap({ locations, colors, trips, trackColor, fitVersion }: Pconst handleMapReady = useCallback(() => setMapReady(true), [])- // Clear popup and highlight when underlying locations change (new day / different trip)+ // Clear popup, highlight and session note edits when the locations change (new day / different trip)useEffect(() => {setPopup(null)setSelectedPoint(null)+ noteEditsRef.current = {}}, [locations])const handleFitTrack = useCallback(() => {@@ -177,19 +186,35 @@ export function TrackMap({ locations, colors, trips, trackColor, fitVersion }: Pconst geom = feature.geometry as GeoJSON.Pointconst coord = geom.coordinates as [number, number]const color = feature.properties.color ?? trackColor+ const id = (feature.properties.id as number | undefined) ?? -1+ // Prefer an edit made this session; the points source keeps the loaded value.+ const note = id >= 0 && id in noteEditsRef.current ? noteEditsRef.current[id] : (feature.properties.note ?? "")setSelectedPoint({ longitude: coord[0], latitude: coord[1], color })+ setNoteDraft(note)setPopup({coordinate: coord,speed: feature.properties.speed,timestamp: feature.properties.timestamp,accuracy: feature.properties.accuracy,altitude: feature.properties.altitude,- color+ color,+ id,+ note})},[trackColor])+ const handleSaveNote = useCallback(() => {+ if (!popup || popup.id < 0 || !onPointNoteChange) return+ const saved = noteDraft.trim()+ onPointNoteChange(popup.id, saved || null)+ // popup is a snapshot and the points source is unchanged, so reflect the save here; re-taps read the overlay+ noteEditsRef.current[popup.id] = saved+ setPopup((p) => (p ? { ...p, note: saved } : p))+ setNoteDraft(saved)+ }, [popup, noteDraft, onPointNoteChange])+const handleMapPress = useCallback(() => {if (Date.now() - lastPointPressRef.current < 200) returnsetPopup(null)@@ -291,6 +316,34 @@ export function TrackMap({ locations, colors, trips, trackColor, fitVersion }: P<Text style={[styles.popupLabel, { color: colors.textSecondary }]}>Altitude</Text><Text style={[styles.popupValue, { color: colors.text }]}>{popup.altitude.toFixed(0)}m</Text></View>+ {popup.id >= 0 && (onPointNoteChange || popup.note !== "") && (+ <View style={[styles.noteSection, { borderTopColor: colors.border }]}>+ <Text style={[styles.popupLabel, { color: colors.textSecondary }]}>Note</Text>+ {onPointNoteChange ? (+ <View style={styles.noteRow}>+ <TextInput+ value={noteDraft}+ onChangeText={setNoteDraft}+ placeholder="Add a note"+ placeholderTextColor={colors.textSecondary}+ style={[styles.noteInput, { color: colors.text, borderColor: colors.border }]}+ multiline+ />+ {noteDraft.trim() !== popup.note && (+ <Pressable+ onPress={handleSaveNote}+ hitSlop={HIT_SLOP_MD}+ style={({ pressed }) => [styles.noteSaveBtn, pressed && { opacity: colors.pressedOpacity }]}+ >+ <Check size={18} color={colors.primary} />+ </Pressable>+ )}+ </View>+ ) : (+ <Text style={[styles.popupValue, { color: colors.text }]}>{popup.note}</Text>+ )}+ </View>+ )}</View>)}@@ -383,6 +436,30 @@ const styles = StyleSheet.create({fontWeight: "500",fontSize: 12},+ noteSection: {+ marginTop: 6,+ paddingTop: 6,+ borderTopWidth: StyleSheet.hairlineWidth+ },+ noteRow: {+ flexDirection: "row",+ alignItems: "flex-end",+ gap: 6,+ marginTop: 4+ },+ noteInput: {+ flex: 1,+ fontSize: 13,+ paddingVertical: 2,+ paddingHorizontal: 6,+ borderWidth: 1,+ borderRadius: 6,+ minHeight: 32,+ maxHeight: 80+ },+ noteSaveBtn: {+ padding: 6+ },legend: {position: "absolute",bottom: 30,diff --git a/apps/mobile/src/components/features/map/__tests__/mapUtils.test.ts b/apps/mobile/src/components/features/map/__tests__/mapUtils.test.tsindex 7e718f96..0639b6a6 100644--- a/apps/mobile/src/components/features/map/__tests__/mapUtils.test.ts+++ b/apps/mobile/src/components/features/map/__tests__/mapUtils.test.ts@@ -221,17 +221,21 @@ describe("buildTrackPointsGeoJSON", () => {})it("includes metadata properties on each point", () => {- const locs = [{ latitude: 52.52, longitude: 13.405, speed: 3, timestamp: 1000, accuracy: 5, altitude: 34 }]+ const locs = [+ { id: 42, latitude: 52.52, longitude: 13.405, speed: 3, timestamp: 1000, accuracy: 5, altitude: 34, note: "deer" }+ ]const result = buildTrackPointsGeoJSON(locs, colors)const props = result.features[0].propertiesexpect(props?.speed).toBe(3)expect(props?.timestamp).toBe(1000)expect(props?.accuracy).toBe(5)expect(props?.altitude).toBe(34)+ expect(props?.id).toBe(42)+ expect(props?.note).toBe("deer")expect(props?.color).toBeDefined()})- it("defaults missing optional fields to 0", () => {+ it("defaults missing optional fields to 0 (id to -1, note to empty)", () => {const locs = [{ latitude: 52.52, longitude: 13.405 }]const result = buildTrackPointsGeoJSON(locs, colors)const props = result.features[0].properties@@ -239,6 +243,9 @@ describe("buildTrackPointsGeoJSON", () => {expect(props?.timestamp).toBe(0)expect(props?.accuracy).toBe(0)expect(props?.altitude).toBe(0)+ // -1 marks a point with no DB row; the popup treats it as non-editable+ expect(props?.id).toBe(-1)+ expect(props?.note).toBe("")})it("uses locationColors when provided", () => {diff --git a/apps/mobile/src/components/features/map/mapUtils.ts b/apps/mobile/src/components/features/map/mapUtils.tsindex d9997e7f..8d2fc54e 100644--- a/apps/mobile/src/components/features/map/mapUtils.ts+++ b/apps/mobile/src/components/features/map/mapUtils.ts@@ -83,12 +83,14 @@ export function createCirclePolygon(// ============================================================================export interface TrackLocation {+ id?: numberlatitude: numberlongitude: numbertimestamp?: numberaccuracy?: numberspeed?: numberaltitude?: number+ note?: string}interface TrackSegmentOptions {@@ -167,10 +169,12 @@ export function buildTrackPointsGeoJSON(features: locations.map((loc, i) => ({type: "Feature" as const,properties: {+ id: loc.id ?? -1,speed: loc.speed ?? 0,timestamp: loc.timestamp ?? 0,accuracy: loc.accuracy ?? 0,altitude: loc.altitude ?? 0,+ note: loc.note ?? "",color: locationColors ? locationColors[i] : getSpeedColor(loc.speed ?? 0, colors)},geometry: {diff --git a/apps/mobile/src/screens/LocationInspectorScreen.tsx b/apps/mobile/src/screens/LocationInspectorScreen.tsxindex 4042bd67..c8a6eb81 100644--- a/apps/mobile/src/screens/LocationInspectorScreen.tsx+++ b/apps/mobile/src/screens/LocationInspectorScreen.tsx@@ -37,6 +37,9 @@ export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Loreturn initialDate ? new Date(initialDate) : new Date()})const [trackLocations, setTrackLocations] = useState<LocationCoords[]>([])+ // 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 [selectedTrip, setSelectedTrip] = useState<Trip | null>(null)const [fitVersion, setFitVersion] = useState(0)@@ -125,6 +128,7 @@ export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Loconst result = await NativeLocationService.getLocationsByDateRange(startTimestamp, endTimestamp)if (id === fetchTrackIdRef.current) {setTrackLocations(result || [])+ setNoteOverrides({})setSelectedTrip(null)setFitVersion((v) => v + 1)}@@ -132,6 +136,7 @@ export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Lologger.error("[LocationHistory] Track fetch error:", err)if (id === fetchTrackIdRef.current) {setTrackLocations([])+ setNoteOverrides({})setSelectedTrip(null)setFitVersion((v) => v + 1)}@@ -227,8 +232,27 @@ export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Lo[mapDate, fetchTrackData, fetchDaysWithData])+ const handlePointNoteChange = useCallback(async (id: number, note: string | null) => {+ try {+ await NativeLocationService.updateLocationNote(id, note)+ setNoteOverrides((prev) => ({ ...prev, [id]: note ?? undefined }))+ } catch (error) {+ logger.error("[LocationHistory] Note update failed:", error)+ showAlert("Save Failed", "Unable to save note. Please try again.", "error")+ }+ }, [])+const mapLocations = selectedTrip ? (selectedTrip.locations as LocationCoords[]) : trackLocations+ // Apply note edits for the Data tab table only; the map reads notes via its own overlay.+ const tableLocations = useMemo(+ () =>+ Object.keys(noteOverrides).length === 0+ ? trackLocations+ : trackLocations.map((l) => (l.id != null && l.id in noteOverrides ? { ...l, note: noteOverrides[l.id] } : l)),+ [trackLocations, noteOverrides]+ )+const calendarPicker = useMemo(() => (<CalendarPicker@@ -264,6 +288,7 @@ export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Lotrips={selectedTrip ? undefined : trips}trackColor={colors.primary}fitVersion={fitVersion}+ onPointNoteChange={handlePointNoteChange}/>{selectedTrip && (<Pressable@@ -299,7 +324,7 @@ export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Lo{activeTab === "data" && (<View style={styles.mapContainer}>{calendarPicker}- <LocationTable locations={trackLocations} colors={colors} />+ <LocationTable locations={tableLocations} colors={colors} /></View>)}</Container>diff --git a/apps/mobile/src/screens/TripDetailScreen.tsx b/apps/mobile/src/screens/TripDetailScreen.tsxindex 5a89ac3d..0d6fa8d2 100644--- a/apps/mobile/src/screens/TripDetailScreen.tsx+++ b/apps/mobile/src/screens/TripDetailScreen.tsx@@ -83,6 +83,16 @@ export function TripDetailScreen({ route, navigation }: RootScreenProps<"Trip De[navigation])+ // Just persist: TrackMap overlays the value for re-taps, and export reads the DB.+ const handlePointNoteChange = useCallback(async (id: number, note: string | null) => {+ try {+ await NativeLocationService.updateLocationNote(id, note)+ } catch (error) {+ logger.error("[TripDetail] Note update failed:", error)+ showAlert("Save Failed", "Unable to save note. Please try again.", "error")+ }+ }, [])+const handleExport = useCallback(async (format: ExportFormat) => {try {@@ -170,7 +180,13 @@ export function TripDetailScreen({ route, navigation }: RootScreenProps<"Trip Dereturn (<Container><View style={styles.mapContainer}>- <TrackMap locations={trip.locations} colors={colors} trackColor={tripColor} fitVersion={trip.index} />+ <TrackMap+ locations={trip.locations}+ colors={colors}+ trackColor={tripColor}+ fitVersion={trip.index}+ onPointNoteChange={handlePointNoteChange}+ /></View><ScrollView contentContainerStyle={styles.content}>{/* Header */}diff --git a/apps/mobile/src/services/NativeLocationService.ts b/apps/mobile/src/services/NativeLocationService.tsindex d43a35ec..f487a627 100644--- a/apps/mobile/src/services/NativeLocationService.ts+++ b/apps/mobile/src/services/NativeLocationService.ts@@ -182,6 +182,15 @@ class NativeLocationService {)}+ /**+ * Sets or clears the free-text note on a single location. Pass null to clear.+ */+ static async updateLocationNote(id: number, note: string | null): Promise<void> {+ this.ensureModule()+ logger.debug(`[NativeLocationService] Updating note for location ${id}`)+ await LocationServiceModule.updateLocationNote(id, note)+ }+/*** Gets the most recent location from the database*/diff --git a/apps/mobile/src/types/global.ts b/apps/mobile/src/types/global.tsindex e0c368b0..3ac832c8 100644--- a/apps/mobile/src/types/global.ts+++ b/apps/mobile/src/types/global.ts@@ -21,6 +21,7 @@ export type { ThemeColors, ThemeMode } from "@colota/shared"// ============================================================================export interface LocationCoords {+ id?: numberlatitude: numberlongitude: numberaltitude?: number@@ -31,6 +32,8 @@ export interface LocationCoords {battery_status?: number/** Unix epoch seconds */timestamp?: number+ /** User-entered free-text note (POI annotation). Local-only, not synced. */+ note?: string}export interface Geofence {diff --git a/fastlane/metadata/android/en-US/changelogs/40.txt b/fastlane/metadata/android/en-US/changelogs/40.txtnew file mode 100644index 00000000..47575771--- /dev/null+++ b/fastlane/metadata/android/en-US/changelogs/40.txt@@ -0,0 +1,2 @@+- Add notes to individual points. Tap a point on the map in Location History or a trip to annotate it.+- Exports now include bearing and battery status for every point, in all formats.