Colota - Android GPS Location tracker
fix(inspector): keep notes saved on the map after switching tabs (#610)
Max Dietrich4c570fe6cc32
diff --git a/apps/mobile/src/components/features/inspector/TrackMap.tsx b/apps/mobile/src/components/features/inspector/TrackMap.tsxindex e7b97020..15518d8f 100644--- a/apps/mobile/src/components/features/inspector/TrackMap.tsx+++ b/apps/mobile/src/components/features/inspector/TrackMap.tsx@@ -38,6 +38,8 @@ interface Props {trips?: Trip[]trackColor: stringfitVersion?: number+ /** Notes saved this session, by id. Held by the parent because the tabs unmount this map. */+ noteOverrides?: Record<number, string | undefined>/** When provided, the point popup gains an editable note field. Omit for read-only maps. */onPointNoteChange?: (id: number, note: string | null) => void/** When provided, the point popup gains a delete action. Omit for read-only maps. */@@ -52,6 +54,7 @@ export function TrackMap({trips,trackColor,fitVersion,+ noteOverrides,onPointNoteChange,onPointDelete,onPointSplit@@ -75,7 +78,6 @@ export function TrackMap({} | null>(null)const [noteDraft, setNoteDraft] = useState("")const [mapReady, setMapReady] = useState(false)- 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])@@ -111,11 +113,10 @@ export function TrackMap({const handleMapReady = useCallback(() => setMapReady(true), [])- // Clear popup, highlight and session note edits when the locations change (new day / different trip)+ // Clear popup and highlight when the locations change (new day / different trip)useEffect(() => {setPopup(null)setSelectedPoint(null)- setNoteEdits({})}, [locations])const handleFitTrack = useCallback(() => {@@ -166,11 +167,11 @@ export function TrackMap({)const pointsGeoJSON = useMemo(() => {const locs =- Object.keys(noteEdits).length === 0+ !noteOverrides || Object.keys(noteOverrides).length === 0? locations- : locations.map((l) => (l.id != null && l.id in noteEdits ? { ...l, note: noteEdits[l.id] } : l))+ : locations.map((l) => (l.id != null && l.id in noteOverrides ? { ...l, note: noteOverrides[l.id] } : l))return buildTrackPointsGeoJSON(locs, colors, locationColors)- }, [locations, colors, locationColors, noteEdits])+ }, [locations, colors, locationColors, noteOverrides])// Highlight GeoJSON for selected pointconst highlightGeoJSON = useMemo(() => {@@ -232,7 +233,6 @@ export function TrackMap({if (!popup || popup.id < 0 || !onPointNoteChange) returnconst saved = noteDraft.trim()onPointNoteChange(popup.id, saved || null)- setNoteEdits((prev) => ({ ...prev, [popup.id]: saved }))setPopup((p) => (p ? { ...p, note: saved } : p))setNoteDraft(saved)}, [popup, noteDraft, onPointNoteChange])@@ -370,6 +370,7 @@ export function TrackMap({{onPointNoteChange ? (<View style={styles.noteRow}><TextInput+ testID="popup-note-input"value={noteDraft}onChangeText={setNoteDraft}placeholder="Add a note"@@ -379,6 +380,7 @@ export function TrackMap({/>{noteDraft.trim() !== popup.note && (<Pressable+ testID="popup-note-save"onPress={handleSaveNote}hitSlop={HIT_SLOP_MD}style={({ pressed }) => [styles.noteSaveBtn, pressed && { opacity: colors.pressedOpacity }]}diff --git a/apps/mobile/src/components/features/inspector/__tests__/TrackMap.test.tsx b/apps/mobile/src/components/features/inspector/__tests__/TrackMap.test.tsxindex d06d0e0b..5231694c 100644--- a/apps/mobile/src/components/features/inspector/__tests__/TrackMap.test.tsx+++ b/apps/mobile/src/components/features/inspector/__tests__/TrackMap.test.tsx@@ -7,6 +7,7 @@ import type { Trip } from "../../../../types/global"const mockFitBounds = jest.fn()const mockSetStop = jest.fn()const mockBuildSegments = jest.fn()+const mockBuildPoints = jest.fn()jest.mock("../../map/mapUtils", () => {const actual = jest.requireActual("../../map/mapUtils")@@ -15,6 +16,10 @@ jest.mock("../../map/mapUtils", () => {buildTrackSegmentsGeoJSON: (...args: any[]) => {mockBuildSegments(...args)return actual.buildTrackSegmentsGeoJSON(...args)+ },+ buildTrackPointsGeoJSON: (...args: any[]) => {+ mockBuildPoints(...args)+ return actual.buildTrackPointsGeoJSON(...args)}}})@@ -251,3 +256,83 @@ describe("TrackMap trip coloring", () => {expect([...options.skipIndices].sort((a: number, b: number) => a - b)).toEqual([2, 3, 4, 5])})})++describe("TrackMap note overrides", () => {+ /** The tabs unmount this map, so a note saved here used to come back stale. */+ it("renders a note saved this session instead of the stored one", () => {+ mockBuildPoints.mockClear()+ render(+ <TrackMap+ locations={[{ ...loc(52.5, 13.4), id: 42, note: "stored" }] as any}+ colors={colors}+ trackColor="#000"+ noteOverrides={{ 42: "saved this session" }}+ onPointNoteChange={jest.fn()}+ />+ )++ const [locationsPassed] = mockBuildPoints.mock.calls.at(-1)!+ expect(locationsPassed[0].note).toBe("saved this session")+ })++ /** Cleared notes are stored as undefined, so the merge has to test presence, not truthiness. */+ it("shows a note cleared this session as cleared, not as the stored text", () => {+ mockBuildPoints.mockClear()+ render(+ <TrackMap+ locations={[{ ...loc(52.5, 13.4), id: 42, note: "stored" }] as any}+ colors={colors}+ trackColor="#000"+ noteOverrides={{ 42: undefined }}+ onPointNoteChange={jest.fn()}+ />+ )++ const [locationsPassed] = mockBuildPoints.mock.calls.at(-1)!+ expect(locationsPassed[0].note).toBeUndefined()+ })++ /**+ * Merging notes into locations instead would hand the map a new array on every save, and the+ * effect that clears the popup on a day change would close it mid-edit.+ */+ it("keeps the popup open when a note is saved", () => {+ const { getByTestId, queryByTestId } = render(+ <TrackMap+ locations={[{ ...loc(52.5, 13.4), id: 42, note: "" }] as any}+ colors={colors}+ trackColor="#000"+ onPointNoteChange={jest.fn()}+ />+ )+ fireEvent(getByTestId("track-points"), "press", {+ nativeEvent: {+ features: [+ {+ properties: { id: 42, color: "#000", speed: 0, timestamp: 1000, accuracy: 5, altitude: 10, note: "" },+ geometry: { type: "Point", coordinates: [13.4, 52.5] }+ }+ ]+ }+ })+ fireEvent.changeText(getByTestId("popup-note-input"), "lunch")+ fireEvent.press(getByTestId("popup-note-save"))++ expect(queryByTestId("popup-note-input")).not.toBeNull()+ })++ it("leaves the stored note alone when nothing was edited", () => {+ mockBuildPoints.mockClear()+ render(+ <TrackMap+ locations={[{ ...loc(52.5, 13.4), id: 42, note: "stored" }] as any}+ colors={colors}+ trackColor="#000"+ onPointNoteChange={jest.fn()}+ />+ )++ const [locationsPassed] = mockBuildPoints.mock.calls.at(-1)!+ expect(locationsPassed[0].note).toBe("stored")+ })+})diff --git a/apps/mobile/src/screens/LocationInspectorScreen.tsx b/apps/mobile/src/screens/LocationInspectorScreen.tsxindex 3870a041..0d032696 100644--- a/apps/mobile/src/screens/LocationInspectorScreen.tsx+++ b/apps/mobile/src/screens/LocationInspectorScreen.tsx@@ -45,8 +45,17 @@ export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Lo})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.+ // close its popup). Applied wherever a location's note is shown: the table, the map and the+ // trip handed to Trip Detail.const [noteOverrides, setNoteOverrides] = useState<Record<number, string | undefined>>({})+ const withNotes = useCallback(+ (locs: LocationCoords[]) =>+ Object.keys(noteOverrides).length === 0+ ? locs+ : locs.map((l) => (l.id != null && l.id in noteOverrides ? { ...l, note: noteOverrides[l.id] } : l)),+ [noteOverrides]+ )+const [boundaryOverrides, setBoundaryOverrides] = useState<Map<string, BoundaryAction>>(() => new Map())const [selectedTrip, setSelectedTrip] = useState<Trip | null>(null)const [fitVersion, setFitVersion] = useState(0)@@ -183,11 +192,13 @@ export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Lo)/** Tap a trip card -> open detail screen */+ // Trip Detail renders what it is handed, so notes saved this visit have to travel with it.const handleTripSelect = useCallback((trip: Trip) => {- navigation.navigate("Trip Detail", { trip, trips })+ const withSessionNotes = (t: Trip) => ({ ...t, locations: withNotes(t.locations) })+ navigation.navigate("Trip Detail", { trip: withSessionNotes(trip), trips: trips.map(withSessionNotes) })},- [navigation, trips]+ [navigation, trips, withNotes])/** Export trips (all or single) */@@ -382,14 +393,9 @@ export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Loconst 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]- )+ // The map gets the overrides as a prop rather than merged in here, because a new locations+ // identity closes its open popup.+ const tableLocations = useMemo(() => withNotes(trackLocations), [trackLocations, withNotes])const calendarPicker = useMemo(() => (@@ -433,6 +439,7 @@ export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Lo<TrackMaplocations={mapLocations}colors={colors}+ noteOverrides={noteOverrides}trips={selectedTrip ? undefined : trips}trackColor={colors.primary}fitVersion={fitVersion}diff --git a/apps/mobile/src/screens/TripDetailScreen.tsx b/apps/mobile/src/screens/TripDetailScreen.tsxindex 34e4fb1c..fea3da00 100644--- a/apps/mobile/src/screens/TripDetailScreen.tsx+++ b/apps/mobile/src/screens/TripDetailScreen.tsx@@ -58,6 +58,9 @@ export function TripDetailScreen({ route, navigation }: RootScreenProps<"Trip Deconst trips: Trip[] = route.params.tripsconst tripColor = getTripColor(trip.index)const [deleting, setDeleting] = useState(false)+ // The map reads a note back when the point is re-tapped, and the chevrons swap in a trip from+ // route.params, so a saved note has to be held here rather than inside the map.+ const [noteOverrides, setNoteOverrides] = useState<Record<number, string | undefined>>({})const stats = useMemo(() => computeTripStats(trip.locations), [trip])const duration = trip.endTime - trip.startTime@@ -104,10 +107,10 @@ 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)+ setNoteOverrides((prev) => ({ ...prev, [id]: note ?? undefined }))} catch (error) {logger.error("[TripDetail] Note update failed:", error)showAlert("Save Failed", "Unable to save note. Please try again.", "error")@@ -253,6 +256,7 @@ export function TripDetailScreen({ route, navigation }: RootScreenProps<"Trip Decolors={colors}trackColor={tripColor}fitVersion={trip.index}+ noteOverrides={noteOverrides}onPointNoteChange={handlePointNoteChange}onPointSplit={handlePointSplit}/>diff --git a/apps/mobile/src/screens/__tests__/LocationHistoryScreen.test.tsx b/apps/mobile/src/screens/__tests__/LocationHistoryScreen.test.tsxindex 594a2ffd..5de1e911 100644--- a/apps/mobile/src/screens/__tests__/LocationHistoryScreen.test.tsx+++ b/apps/mobile/src/screens/__tests__/LocationHistoryScreen.test.tsx@@ -1,6 +1,9 @@import React from "react"import { render, fireEvent, waitFor } from "@testing-library/react-native"+// Every locations array the map is handed, so a test can assert the identity survives a save+const mockMapLocationsSeen: any[] = []+// --- Mocks ---jest.mock("../../services/NativeLocationService", () => ({@@ -15,7 +18,8 @@ jest.mock("../../services/NativeLocationService", () => ({deleteLocationsInRange: jest.fn().mockResolvedValue(0),deleteLocationsByIds: jest.fn().mockResolvedValue(0),getBoundaryOverrides: jest.fn().mockResolvedValue([]),- addBoundaryOverrides: jest.fn().mockResolvedValue(undefined)+ addBoundaryOverrides: jest.fn().mockResolvedValue(undefined),+ updateLocationNote: jest.fn().mockResolvedValue(undefined)}}))@@ -94,10 +98,19 @@ jest.mock("../../components/features/inspector/CalendarPicker", () => {jest.mock("../../components/features/inspector/TrackMap", () => {const R = require("react")- const { View, Pressable } = require("react-native")+ const { View, Pressable, Text } = require("react-native")return {- TrackMap: (props: any) =>- R.createElement(View, { testID: "TrackMap" }, [+ TrackMap: (props: any) => {+ mockMapLocationsSeen.push(props.locations)+ return R.createElement(View, { testID: "TrackMap" }, [+ R.createElement(Text, { key: "o", testID: "TrackMap-overrides" }, JSON.stringify(props.noteOverrides ?? {})),+ props.onPointNoteChange+ ? R.createElement(Pressable, {+ key: "n",+ testID: "trigger-point-note",+ onPress: () => props.onPointNoteChange(1, "lunch")+ })+ : null,props.onPointDelete? R.createElement(Pressable, {key: "d",@@ -120,6 +133,7 @@ jest.mock("../../components/features/inspector/TrackMap", () => {}): null])+ }}})@@ -135,9 +149,17 @@ jest.mock("../../components/features/inspector/TripList", () => {{ testID: "TripList" },props.onMerge? R.createElement(Pressable, {+ key: "m",testID: "trigger-trip-merge",onPress: () => props.onMerge([TRIP_A, TRIP_B])})+ : null,+ props.onTripSelect+ ? R.createElement(Pressable, {+ key: "t",+ testID: "trigger-trip-select",+ onPress: () => props.onTripSelect(props.trips?.[0])+ }): null)}@@ -402,3 +424,68 @@ describe("LocationHistoryScreen", () => {expect(getByTestId("LocationTable")).toBeTruthy()})})++describe("LocationHistoryScreen - notes saved on the map", () => {+ beforeEach(() => jest.clearAllMocks())++ /** The tabs unmount the map, so the screen has to hold the note and hand it back. */+ it("passes a note saved this session back to the map", async () => {+ ;(NativeLocationService.getLocationsByDateRange as jest.Mock).mockResolvedValueOnce(DAY_POINTS)+ const { getByTestId } = render(<LocationHistoryScreen {...createProps()} />)+ await waitFor(() => expect(NativeLocationService.getLocationsByDateRange).toHaveBeenCalled())++ fireEvent.press(getByTestId("trigger-point-note"))++ await waitFor(() => expect(getByTestId("TrackMap-overrides").props.children).toContain("lunch"))+ })++ /**+ * Trip Detail renders the trip it is handed and has no way back to this screen's state, so a+ * note saved here and then edited there would otherwise be overwritten from the stale base.+ */+ /**+ * Merging notes into the map's locations would hand it a new array on every save, and the+ * effect keyed on that array closes the open popup - the user would lose the field mid-edit.+ */+ it("does not hand the map a new locations array when a note is saved", async () => {+ ;(NativeLocationService.getLocationsByDateRange as jest.Mock).mockResolvedValueOnce(DAY_POINTS)+ const { getByTestId } = render(<LocationHistoryScreen {...createProps()} />)+ await waitFor(() => expect(NativeLocationService.getLocationsByDateRange).toHaveBeenCalled())+ const before = mockMapLocationsSeen[mockMapLocationsSeen.length - 1]++ fireEvent.press(getByTestId("trigger-point-note"))+ // Wait for the override to reach the map, so the re-render under test has actually happened+ await waitFor(() => expect(getByTestId("TrackMap-overrides").props.children).toContain("lunch"))++ expect(mockMapLocationsSeen[mockMapLocationsSeen.length - 1]).toBe(before)+ })++ it("hands Trip Detail the notes saved this session", async () => {+ ;(segmentTrips as jest.Mock).mockReturnValue([{ ...DAY_TRIP, locations: DAY_POINTS }])+ ;(NativeLocationService.getLocationsByDateRange as jest.Mock).mockResolvedValueOnce(DAY_POINTS)+ const props = createProps()+ const { getByTestId, getByText } = render(<LocationHistoryScreen {...props} />)+ await waitFor(() => expect(NativeLocationService.getLocationsByDateRange).toHaveBeenCalled())++ fireEvent.press(getByTestId("trigger-point-note"))+ await waitFor(() => expect(NativeLocationService.updateLocationNote).toHaveBeenCalledWith(1, "lunch"))+ fireEvent.press(getByText("Trips"))+ fireEvent.press(getByTestId("trigger-trip-select"))++ expect(props.navigation.navigate).toHaveBeenCalledWith(+ "Trip Detail",+ expect.objectContaining({+ trip: expect.objectContaining({+ locations: expect.arrayContaining([expect.objectContaining({ id: 1, note: "lunch" })])+ }),+ // Trip Detail's prev/next chevrons render straight out of this array, so an unmerged+ // copy here is the same data loss one navigation step later+ trips: expect.arrayContaining([+ expect.objectContaining({+ locations: expect.arrayContaining([expect.objectContaining({ id: 1, note: "lunch" })])+ })+ ])+ })+ )+ })+})diff --git a/apps/mobile/src/screens/__tests__/TripDetailScreen.test.tsx b/apps/mobile/src/screens/__tests__/TripDetailScreen.test.tsxindex 88e85e3d..61a281da 100644--- a/apps/mobile/src/screens/__tests__/TripDetailScreen.test.tsx+++ b/apps/mobile/src/screens/__tests__/TripDetailScreen.test.tsx@@ -26,12 +26,19 @@ jest.mock("../../utils/logger", () => ({// Exposes the point popup's split action without a real mapjest.mock("../../components/features/inspector/TrackMap", () => {const R = require("react")- const { View, Pressable } = require("react-native")+ const { View, Pressable, Text } = require("react-native")return {TrackMap: (props: any) =>R.createElement(View,{ testID: "TrackMap" },+ R.createElement(Text, { testID: "TrackMap-overrides" }, JSON.stringify(props.noteOverrides ?? {})),+ props.onPointNoteChange+ ? R.createElement(Pressable, {+ testID: "trigger-point-note",+ onPress: () => props.onPointNoteChange(props.locations?.[0]?.id, "lunch")+ })+ : null,props.onPointSplit? [R.createElement(Pressable, {@@ -234,3 +241,18 @@ describe("TripDetailScreen - split from the map", () => {expect(props.navigation.goBack).not.toHaveBeenCalled()})})++describe("TripDetailScreen - notes saved on the map", () => {+ beforeEach(() => jest.clearAllMocks())++ /** The map is unmounted when this screen is left, so a saved note has to live in the screen. */+ it("hands a note saved this session back to the map", async () => {+ const { getByTestId } = render(<TripDetailScreen {...makeProps(makeTrip(3))} />)+ await act(async () => {})++ fireEvent.press(getByTestId("trigger-point-note"))++ await waitFor(() => expect(NativeLocationService.updateLocationNote).toHaveBeenCalledWith(1, "lunch"))+ await waitFor(() => expect(getByTestId("TrackMap-overrides").props.children).toContain("lunch"))+ })+})diff --git a/fastlane/metadata/android/en-US/changelogs/46.txt b/fastlane/metadata/android/en-US/changelogs/46.txtindex 6eaeaa6a..fb065697 100644--- a/fastlane/metadata/android/en-US/changelogs/46.txt+++ b/fastlane/metadata/android/en-US/changelogs/46.txt@@ -2,3 +2,4 @@- Tracking no longer refuses to start when notifications are turned off- Geofence heartbeat keeps recording while the phone sleeps- Tracking restarts itself when Android kills it in the background+- Notes saved on the map no longer disappear when you switch tabs