Skip to content

Colota - Android GPS Location tracker

Feat/annotation visual hints (#511)

Max Dietrich7e6cf5b08521
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 c71dab60..bdbe2ace 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
@@ -373,6 +373,15 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
}
}
+ @ReactMethod
+ fun getDaysWithNotes(startTimestamp: Double, endTimestamp: Double, promise: Promise) =
+ executeAsync(promise) {
+ val days = dbHelper.getDaysWithNotes(startTimestamp.toLong(), endTimestamp.toLong())
+ Arguments.createArray().apply {
+ days.forEach { pushString(it) }
+ }
+ }
+
@ReactMethod
fun getDailyStats(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.kt
index d8667219..4fd37369 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
@@ -944,6 +944,32 @@ class DatabaseHelper private constructor(context: Context) :
return days
}
+ /**
+ * Returns date strings (YYYY-MM-DD) in the range with at least one annotated
+ * location (non-empty note). Used by the calendar to flag days that have notes.
+ */
+ fun getDaysWithNotes(startTimestamp: Long, endTimestamp: Long): List<String> {
+ val days = mutableListOf<String>()
+ try {
+ readableDatabase.rawQuery(
+ """
+ SELECT DISTINCT strftime('%Y-%m-%d', timestamp, 'unixepoch', 'localtime') as day
+ FROM $TABLE_LOCATIONS
+ WHERE timestamp >= ? AND timestamp <= ? AND note IS NOT NULL AND note != ''
+ ORDER BY day ASC
+ """.trimIndent(),
+ arrayOf(startTimestamp.toString(), endTimestamp.toString())
+ ).use { cursor ->
+ while (cursor.moveToNext()) {
+ days.add(cursor.getString(0))
+ }
+ }
+ } catch (e: Exception) {
+ AppLogger.e(TAG, "Error getting days with notes", e)
+ }
+ return days
+ }
+
/**
* Returns per-day aggregated stats for a date range in a single query.
* Computes distance (haversine) and trip count (15-min gap threshold) inline
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 998d9596..162693c9 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
@@ -828,6 +828,36 @@ class DatabaseHelperSQLiteTest {
assertEquals(1, days.size)
}
+ // ========================================================================
+ // getDaysWithNotes
+ // ========================================================================
+
+ @Test
+ fun `getDaysWithNotes returns only days with non-empty notes`() {
+ val annotated = db.saveLocation(latitude = 52.0, longitude = 13.0, timestamp = 1708344000L) // day A, midday
+ db.saveLocation(latitude = 52.1, longitude = 13.1, timestamp = 1708344060L) // day A, no note
+ db.saveLocation(latitude = 53.0, longitude = 14.0, timestamp = 1708430400L) // day B (+1 day), no note
+ db.updateLocationNote(annotated, "lunch spot")
+
+ // Full range: only day A carries a note
+ assertEquals(1, db.getDaysWithNotes(1708300000L, 1708500000L).size)
+ // Narrowed to day A: the annotated day is returned
+ assertEquals(1, db.getDaysWithNotes(1708300000L, 1708387200L).size)
+ // Narrowed to day B: has points but none annotated
+ assertTrue(db.getDaysWithNotes(1708387200L, 1708500000L).isEmpty())
+ }
+
+ @Test
+ fun `getDaysWithNotes excludes empty and cleared notes`() {
+ val emptied = db.saveLocation(latitude = 52.0, longitude = 13.0, timestamp = 1708344000L)
+ val cleared = db.saveLocation(latitude = 53.0, longitude = 14.0, timestamp = 1708430400L)
+ db.updateLocationNote(emptied, "") // empty string
+ db.updateLocationNote(cleared, null) // cleared back to null
+
+ val days = db.getDaysWithNotes(1708300000L, 1708500000L)
+ assertTrue(days.isEmpty())
+ }
+
// ========================================================================
// getDailyStats
// ========================================================================
diff --git a/apps/mobile/src/components/features/inspector/CalendarPicker.tsx b/apps/mobile/src/components/features/inspector/CalendarPicker.tsx
index ace910b1..05881862 100644
--- a/apps/mobile/src/components/features/inspector/CalendarPicker.tsx
+++ b/apps/mobile/src/components/features/inspector/CalendarPicker.tsx
@@ -19,6 +19,7 @@ interface CalendarPickerProps {
distance?: string
colors: ThemeColors
daysWithData: Set<string>
+ daysWithNotes?: Set<string>
dayDistances?: Map<string, number>
onMonthChange: (year: number, month: number) => void
onPrefetchMonth?: (year: number, month: number) => void
@@ -41,6 +42,7 @@ export function CalendarPicker({
distance,
colors,
daysWithData,
+ daysWithNotes,
dayDistances,
onMonthChange,
onPrefetchMonth
@@ -251,6 +253,7 @@ export function CalendarPicker({
const dateKey = formatDateKey(viewYear, viewMonth, cell.day)
const hasData = daysWithData.has(dateKey)
+ const hasNote = daysWithNotes?.has(dateKey) ?? false
const dist = dayDistances?.get(dateKey)
const cellDate = new Date(viewYear, viewMonth, cell.day)
const isSelected = isSameDay(cellDate, date)
@@ -274,6 +277,9 @@ export function CalendarPicker({
>
{cell.day}
</Text>
+ {hasNote && (
+ <View style={[styles.noteDot, { backgroundColor: colors.primary, borderColor: colors.card }]} />
+ )}
</View>
{dist != null && dist > 0 ? (
<Text
@@ -409,5 +415,14 @@ const styles = StyleSheet.create({
height: 4,
borderRadius: 2,
marginTop: 2
+ },
+ noteDot: {
+ position: "absolute",
+ top: 1,
+ right: 1,
+ width: 7,
+ height: 7,
+ borderRadius: 3.5,
+ borderWidth: 1
}
})
diff --git a/apps/mobile/src/components/features/inspector/TrackMap.tsx b/apps/mobile/src/components/features/inspector/TrackMap.tsx
index 139c69b7..697b5bb0 100644
--- a/apps/mobile/src/components/features/inspector/TrackMap.tsx
+++ b/apps/mobile/src/components/features/inspector/TrackMap.tsx
@@ -23,12 +23,13 @@ import {
import { getSpeedUnit } from "../../../utils/geo"
import { HIT_SLOP_MD, MAP_ANIMATION_DURATION_MS } from "../../../constants"
+const HAS_NOTE = ["!=", ["get", "note"], ""]
const trackPointStyle: any = {
- circleRadius: 4,
+ circleRadius: ["case", HAS_NOTE, 5, 4],
circleColor: ["get", "color"],
- circleOpacity: 0.4,
+ circleOpacity: ["case", HAS_NOTE, 1, 0.4],
circleStrokeColor: ["get", "color"],
- circleStrokeWidth: 1.5
+ circleStrokeWidth: ["case", HAS_NOTE, 2, 1.5]
}
interface Props {
@@ -61,9 +62,7 @@ export function TrackMap({ locations, colors, trips, trackColor, fitVersion, onP
} | 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>>({})
+ const [noteEdits, setNoteEdits] = useState<Record<number, string>>({})
// Fit map to track bounds when fitVersion changes (date change, trip select)
const bounds = useMemo(() => computeTrackBounds(locations), [locations])
@@ -89,7 +88,7 @@ export function TrackMap({ locations, colors, trips, trackColor, fitVersion, onP
useEffect(() => {
setPopup(null)
setSelectedPoint(null)
- noteEditsRef.current = {}
+ setNoteEdits({})
}, [locations])
const handleFitTrack = useCallback(() => {
@@ -143,10 +142,13 @@ export function TrackMap({ locations, colors, trips, trackColor, fitVersion, onP
() => buildTrackSegmentsGeoJSON(locations, colors, { skipIndices, locationColors }),
[locations, colors, skipIndices, locationColors]
)
- const pointsGeoJSON = useMemo(
- () => buildTrackPointsGeoJSON(locations, colors, locationColors),
- [locations, colors, locationColors]
- )
+ const pointsGeoJSON = useMemo(() => {
+ const locs =
+ Object.keys(noteEdits).length === 0
+ ? locations
+ : locations.map((l) => (l.id != null && l.id in noteEdits ? { ...l, note: noteEdits[l.id] } : l))
+ return buildTrackPointsGeoJSON(locs, colors, locationColors)
+ }, [locations, colors, locationColors, noteEdits])
// Highlight GeoJSON for selected point
const highlightGeoJSON = useMemo(() => {
@@ -187,8 +189,7 @@ export function TrackMap({ locations, colors, trips, trackColor, fitVersion, onP
const 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 ?? "")
+ const note = feature.properties.note ?? ""
setSelectedPoint({ longitude: coord[0], latitude: coord[1], color })
setNoteDraft(note)
setPopup({
@@ -209,8 +210,7 @@ export function TrackMap({ locations, colors, trips, trackColor, fitVersion, onP
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
+ setNoteEdits((prev) => ({ ...prev, [popup.id]: saved }))
setPopup((p) => (p ? { ...p, note: saved } : p))
setNoteDraft(saved)
}, [popup, noteDraft, onPointNoteChange])
diff --git a/apps/mobile/src/screens/LocationInspectorScreen.tsx b/apps/mobile/src/screens/LocationInspectorScreen.tsx
index c8a6eb81..a8b91847 100644
--- a/apps/mobile/src/screens/LocationInspectorScreen.tsx
+++ b/apps/mobile/src/screens/LocationInspectorScreen.tsx
@@ -45,7 +45,9 @@ export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Lo
// Calendar state
const [daysWithData, setDaysWithData] = useState<Set<string>>(new Set())
+ const [daysWithNotes, setDaysWithNotes] = useState<Set<string>>(new Set())
const daysCache = useRef<Map<string, Set<string>>>(new Map())
+ const notesCache = useRef<Map<string, Set<string>>>(new Map())
const distanceCache = useRef<Map<string, Map<string, number>>>(new Map())
// Trip segmentation from already-fetched day data
@@ -86,12 +88,14 @@ export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Lo
const end = new Date(year, month + 1, 0, 23, 59, 59)
const startTs = Math.floor(start.getTime() / 1000)
const endTs = Math.floor(end.getTime() / 1000)
- const [days, stats] = await Promise.all([
+ const [days, stats, noteDays] = await Promise.all([
NativeLocationService.getDaysWithData(startTs, endTs),
- NativeLocationService.getDailyStats(startTs, endTs)
+ NativeLocationService.getDailyStats(startTs, endTs),
+ NativeLocationService.getDaysWithNotes(startTs, endTs)
])
const daySet = new Set(days)
daysCache.current.set(key, daySet)
+ notesCache.current.set(key, new Set(noteDays))
const distances = new Map<string, number>()
for (const stat of stats) {
if (stat.distanceMeters > 0) distances.set(stat.day, stat.distanceMeters)
@@ -109,6 +113,7 @@ export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Lo
async (year: number, month: number) => {
const daySet = await prefetchMonth(year, month)
setDaysWithData(daySet)
+ setDaysWithNotes(notesCache.current.get(`${year}-${pad2(month + 1)}`) ?? new Set())
},
[prefetchMonth]
)
@@ -153,6 +158,7 @@ export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Lo
useCallback(() => {
const key = `${mapDate.getFullYear()}-${pad2(mapDate.getMonth() + 1)}`
daysCache.current.delete(key)
+ notesCache.current.delete(key)
distanceCache.current.delete(key)
fetchTrackData()
fetchDaysWithData(mapDate.getFullYear(), mapDate.getMonth())
@@ -221,6 +227,7 @@ export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Lo
)
const key = `${mapDate.getFullYear()}-${pad2(mapDate.getMonth() + 1)}`
daysCache.current.delete(key)
+ notesCache.current.delete(key)
distanceCache.current.delete(key)
await fetchTrackData()
await fetchDaysWithData(mapDate.getFullYear(), mapDate.getMonth())
@@ -232,15 +239,22 @@ 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 handlePointNoteChange = useCallback(
+ async (id: number, note: string | null) => {
+ try {
+ await NativeLocationService.updateLocationNote(id, note)
+ setNoteOverrides((prev) => ({ ...prev, [id]: note ?? undefined }))
+ const key = `${mapDate.getFullYear()}-${pad2(mapDate.getMonth() + 1)}`
+ daysCache.current.delete(key)
+ notesCache.current.delete(key)
+ fetchDaysWithData(mapDate.getFullYear(), mapDate.getMonth())
+ } catch (error) {
+ logger.error("[LocationHistory] Note update failed:", error)
+ showAlert("Save Failed", "Unable to save note. Please try again.", "error")
+ }
+ },
+ [mapDate, fetchDaysWithData]
+ )
const mapLocations = selectedTrip ? (selectedTrip.locations as LocationCoords[]) : trackLocations
@@ -262,12 +276,22 @@ export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Lo
distance={dailyDistance}
colors={colors}
daysWithData={daysWithData}
+ daysWithNotes={daysWithNotes}
dayDistances={distanceCache.current.get(`${mapDate.getFullYear()}-${pad2(mapDate.getMonth() + 1)}`)}
onMonthChange={fetchDaysWithData}
onPrefetchMonth={prefetchMonth}
/>
),
- [mapDate, trackLocations.length, dailyDistance, colors, daysWithData, fetchDaysWithData, prefetchMonth]
+ [
+ mapDate,
+ trackLocations.length,
+ dailyDistance,
+ colors,
+ daysWithData,
+ daysWithNotes,
+ fetchDaysWithData,
+ prefetchMonth
+ ]
)
return (
diff --git a/apps/mobile/src/screens/__tests__/LocationHistoryScreen.test.tsx b/apps/mobile/src/screens/__tests__/LocationHistoryScreen.test.tsx
index a3e396d2..30a760af 100644
--- a/apps/mobile/src/screens/__tests__/LocationHistoryScreen.test.tsx
+++ b/apps/mobile/src/screens/__tests__/LocationHistoryScreen.test.tsx
@@ -7,6 +7,7 @@ jest.mock("../../services/NativeLocationService", () => ({
__esModule: true,
default: {
getDaysWithData: jest.fn().mockResolvedValue([]),
+ getDaysWithNotes: jest.fn().mockResolvedValue([]),
getDailyStats: jest.fn().mockResolvedValue([]),
getLocationsByDateRange: jest.fn().mockResolvedValue([]),
exportTripsToFile: jest.fn().mockResolvedValue("/tmp/export"),
diff --git a/apps/mobile/src/services/NativeLocationService.ts b/apps/mobile/src/services/NativeLocationService.ts
index f487a627..c2096834 100644
--- a/apps/mobile/src/services/NativeLocationService.ts
+++ b/apps/mobile/src/services/NativeLocationService.ts
@@ -212,6 +212,19 @@ class NativeLocationService {
)
}
+ /**
+ * Returns date strings (YYYY-MM-DD) in the range that have at least one annotated point.
+ * Used by the calendar view to flag days with notes.
+ */
+ static async getDaysWithNotes(startTimestamp: number, endTimestamp: number): Promise<string[]> {
+ this.ensureModule()
+ return this.safeExecute(
+ () => LocationServiceModule.getDaysWithNotes(startTimestamp, endTimestamp),
+ [],
+ "getDaysWithNotes failed"
+ )
+ }
+
/**
* Returns per-day aggregated stats for a date range.
* Each entry: { day, count, startTime, endTime, distanceMeters, tripCount }