Colota - Android GPS Location tracker
refactor(history): a daybook with one spine per day (#852)
Max Dietrich7efbba20931a
diff --git a/apps/docs/docs/guides/editing-trips.md b/apps/docs/docs/guides/editing-trips.mdindex e8b20cca..6bb71b9c 100644--- a/apps/docs/docs/guides/editing-trips.md+++ b/apps/docs/docs/guides/editing-trips.md@@ -14,7 +14,7 @@ Two cases the gap threshold gets wrong:## Merging Trips1. Go to **Location History → Trips**-2. Long-press a trip card to enter selection mode+2. Long-press a trip to enter selection mode3. Tap the other trips you want to join4. Tap the merge icon in the selection header and confirm@@ -24,17 +24,17 @@ No points are moved or deleted. Trips are renumbered afterwards, so a day with f## Splitting a Trip-Split from the map, on either the **Map** tab or **Trip Detail**.+Split from the map on **Trip Detail**; the Location History map shows a point's details but does not split.1. Tap the point where the new trip should start-2. Tap the split icon in the popup+2. Tap the split icon in the card that opens over the map3. 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.+The previous trip ends at the point before the one you picked. The confirmation names that point's time, since the dialog covers the card.-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.+Splitting returns you to the day view, where the track is coloured per trip, 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.+Zoom in first where points are bunched together, which happens wherever you moved slowly or stopped. The time in the card identifies the exact point.### Points that cannot be split@@ -65,6 +65,6 @@ Colota normally discards trips that never travel more than 100 m, which keeps st## Related-- [Data Management](data-management.md) - deleting trips and individual points-- [Backup & Restore](backup-restore.md) - what a backup includes+- [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 issuesdiff --git a/apps/mobile/src/components/features/inspector/CalendarPicker.tsx b/apps/mobile/src/components/features/inspector/CalendarPicker.tsxindex 05881862..a752b540 100644--- a/apps/mobile/src/components/features/inspector/CalendarPicker.tsx+++ b/apps/mobile/src/components/features/inspector/CalendarPicker.tsx@@ -3,29 +3,42 @@* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.*/-import React, { useState, useMemo, useCallback, useRef } from "react"-import { View, Text, Pressable, StyleSheet, LayoutAnimation } from "react-native"-import { ChevronLeft, ChevronRight, Calendar } from "lucide-react-native"-import { ThemeColors } from "../../../types/global"-import { fonts } from "../../../styles/typography"-import { formatDistance } from "../../../utils/geo"+import React, { useState, useMemo, useCallback, useRef, useEffect } from "react"+import { View, Text, Pressable, StyleSheet, LayoutAnimation, ScrollView, type ScrollViewInstance } from "react-native"+import { ChevronLeft, ChevronRight, ChevronDown, ChevronUp } from "lucide-react-native"+import { DailyStat, ThemeColors } from "../../../types/global"+import { fontSizes, fonts, lineHeights } from "../../../styles/typography"+import { spokenDistance } from "../../../utils/geo"import { pad2 } from "../../../utils/format"-import { HIT_SLOP_LG } from "../../../constants"+import { size, space, STATE_LAYER_ALPHA } from "../../../constants"+import { radius } from "@colota/shared"+import { IconButton } from "../../ui/IconButton"interface CalendarPickerProps {date: Date- onDateChange: (date: Date) => void- locationCount: number- distance?: string+ onSelectDay: (date: Date) => voidcolors: ThemeColorsdaysWithData: Set<string>- daysWithNotes?: Set<string>- dayDistances?: Map<string, number>+ dayStats: ReadonlyMap<string, DailyStat>onMonthChange: (year: number, month: number) => voidonPrefetchMonth?: (year: number, month: number) => void}const WEEKDAYS = ["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"]+const WEEK_LENGTH = WEEKDAYS.length+const MONTH_LABELS = Array.from({ length: 12 }, (_, m) =>+ new Date(2000, m, 1).toLocaleDateString(undefined, { month: "short" })+)++// Nothing on the bridge reports the oldest recorded point, so the year list runs to a floor+// instead. Material's own date picker defaults to 1900-2100, so a scrolling range is the norm.+const EARLIEST_YEAR = 2000+const YEAR_COLUMNS = 3+// A row is size.row so the cell inside still clears the 48dp touch target after its padding.+const YEAR_ROW_HEIGHT = size.row+const YEAR_PANE_ROWS = 5++type Pane = "days" | "months" | "years"function isSameDay(a: Date, b: Date): boolean {return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate()@@ -35,52 +48,43 @@ function formatDateKey(year: number, month: number, day: number): string {return `${year}-${pad2(month + 1)}-${pad2(day)}`}+function plural(count: number, noun: string): string {+ return `${count} ${count === 1 ? noun : `${noun}s`}`+}++export function dayCellLabel(cellDate: Date, stat: DailyStat | undefined, isToday: boolean): string {+ const weekday = cellDate.toLocaleDateString(undefined, { weekday: "long" })+ const month = cellDate.toLocaleDateString(undefined, { month: "long" })+ const parts = [`${weekday} ${cellDate.getDate()} ${month}`]+ if (!stat || stat.count === 0) {+ parts.push("no data")+ } else if (stat.tripCount === 0) {+ parts.push("no trips", plural(stat.count, "point"))+ } else {+ parts.push(plural(stat.tripCount, "trip"), spokenDistance(stat.distanceMeters), plural(stat.count, "point"))+ }+ if (isToday) parts.push("today")+ return parts.join(", ")+}+export function CalendarPicker({date,- onDateChange,- locationCount,- distance,+ onSelectDay,colors,daysWithData,- daysWithNotes,- dayDistances,+ dayStats,onMonthChange,onPrefetchMonth}: CalendarPickerProps) {- const [isExpanded, setIsExpanded] = useState(false)const [viewYear, setViewYear] = useState(date.getFullYear())const [viewMonth, setViewMonth] = useState(date.getMonth())+ const [pane, setPane] = useState<Pane>("days")+ const [pickerYear, setPickerYear] = useState(viewYear)+ const yearScrollRef = useRef<ScrollViewInstance>(null)const today = new Date()const todayRef = useRef(today)todayRef.current = today- const isToday = isSameDay(date, today)-- const goBack = useCallback(() => {- const prev = new Date(date)- prev.setDate(prev.getDate() - 1)- onDateChange(prev)- }, [date, onDateChange])-- const goForward = useCallback(() => {- if (isSameDay(date, todayRef.current)) return- const next = new Date(date)- next.setDate(next.getDate() + 1)- onDateChange(next)- }, [date, onDateChange])-- const goToToday = useCallback(() => {- onDateChange(new Date())- }, [onDateChange])-- const toggleExpanded = useCallback(() => {- LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut)- if (!isExpanded) {- setViewYear(date.getFullYear())- setViewMonth(date.getMonth())- }- setIsExpanded((prev) => !prev)- }, [isExpanded, date])const navigateMonth = useCallback((delta: number) => {@@ -112,131 +116,191 @@ export function CalendarPicker({[viewMonth, viewYear, onMonthChange, onPrefetchMonth])+ // The header always goes up a level: days to years, years back to days, months back to years.+ const goUp = useCallback(() => {+ LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut)+ if (pane === "days") {+ setPickerYear(viewYear)+ setPane("years")+ } else if (pane === "months") {+ setPane("years")+ } else {+ setPane("days")+ }+ }, [pane, viewYear])++ const selectYear = useCallback((year: number) => {+ LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut)+ setPickerYear(year)+ setPane("months")+ }, [])++ // A jump has no direction, so unlike navigateMonth it prefetches no neighbour.+ const selectMonth = useCallback(+ (month: number) => {+ LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut)+ setViewYear(pickerYear)+ setViewMonth(month)+ setPane("days")+ onMonthChange(pickerYear, month)+ },+ [pickerYear, onMonthChange]+ )+const selectDay = useCallback((day: number) => {const selected = new Date(viewYear, viewMonth, day)if (selected > todayRef.current) return- LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut)- onDateChange(selected)- setIsExpanded(false)+ onSelectDay(selected)},- [viewYear, viewMonth, onDateChange]+ [viewYear, viewMonth, onSelectDay])- const calendarGrid = useMemo(() => {+ const weeks = useMemo(() => {const firstDay = new Date(viewYear, viewMonth, 1)let startOffset = firstDay.getDay() - 1if (startOffset < 0) startOffset = 6const daysInMonth = new Date(viewYear, viewMonth + 1, 0).getDate()- const cells: { day: number | null; key: string }[] = []- for (let i = 0; i < startOffset; i++) {- cells.push({ day: null, key: `empty-${i}` })- }- for (let d = 1; d <= daysInMonth; d++) {- cells.push({ day: d, key: `day-${d}` })- }- return cells+ const cells: (number | null)[] = Array.from({ length: startOffset }, () => null)+ for (let d = 1; d <= daysInMonth; d++) cells.push(d)+ while (cells.length % WEEK_LENGTH !== 0) cells.push(null)++ const rows: (number | null)[][] = []+ for (let i = 0; i < cells.length; i += WEEK_LENGTH) rows.push(cells.slice(i, i + WEEK_LENGTH))+ return rows}, [viewYear, viewMonth])const monthLabel = useMemo(() => {return new Date(viewYear, viewMonth, 1).toLocaleDateString(undefined, { month: "long", year: "numeric" })}, [viewYear, viewMonth])- const formatted = useMemo(- () =>- date.toLocaleDateString(undefined, {- weekday: "short",- month: "short",- day: "numeric",- year: "numeric"- }),- [date]- )-const isFutureMonth =viewYear > today.getFullYear() || (viewYear === today.getFullYear() && viewMonth >= today.getMonth())- return (- <View style={[styles.container, { borderBottomColor: colors.border }]}>- {/* Compact header row */}- <View style={styles.row}>- <Pressable- onPress={goBack}- hitSlop={HIT_SLOP_LG}- style={({ pressed }) => [styles.navBtn, pressed && { opacity: colors.pressedOpacity }]}- >- <ChevronLeft size={22} color={colors.primary} />- </Pressable>+ const todayYear = today.getFullYear()+ const todayMonth = today.getMonth()+ const pickerYearLabel = new Date(pickerYear, 0, 1).toLocaleDateString(undefined, { year: "numeric" })- <Pressable- onPress={toggleExpanded}- style={({ pressed }) => [styles.dateContainer, pressed && { opacity: colors.pressedOpacity }]}- >- <View style={styles.dateLabelRow}>- <Text style={[styles.dateText, { color: colors.text }]}>{formatted}</Text>- {isToday && (- <View style={[styles.todayBadge, { backgroundColor: colors.primary + "20" }]}>- <Text style={[styles.todayBadgeText, { color: colors.primary }]}>Today</Text>- </View>- )}- <Calendar size={14} color={colors.textSecondary} style={styles.calendarIcon} />- </View>- <Text style={[styles.countText, { color: colors.textSecondary }]}>- {locationCount} {locationCount === 1 ? "location" : "locations"}- {distance ? ` · ${distance}` : ""}- </Text>- </Pressable>+ const years = useMemo(+ () => Array.from({ length: todayYear - EARLIEST_YEAR + 1 }, (_, i) => todayYear - i),+ [todayYear]+ )++ // The list is long, so it opens on the year in view rather than at the top.+ useEffect(() => {+ if (pane !== "years") return+ const index = years.indexOf(pickerYear)+ const row = index < 0 ? 0 : Math.floor(index / YEAR_COLUMNS)+ const y = Math.max(0, row - Math.floor(YEAR_PANE_ROWS / 2)) * YEAR_ROW_HEIGHT+ yearScrollRef.current?.scrollTo({ y, animated: false })+ }, [pane, pickerYear, years])++ const headerLabel = pane === "months" ? pickerYearLabel : monthLabel+ const headerHint =+ pane === "days" ? "Opens the year picker" : pane === "years" ? "Closes the year picker" : "Back to the year picker"+ return (+ <View testID="calendar-picker">+ <View style={styles.monthRow}>+ {pane === "days" ? (+ <IconButton+ testID="prev-month-btn"+ icon={ChevronLeft}+ onPress={() => navigateMonth(-1)}+ accessibilityLabel="Previous month"+ />+ ) : (+ <View style={styles.monthNavSpacer} />+ )}<Pressable- onPress={goForward}- hitSlop={HIT_SLOP_LG}- style={({ pressed }) => [styles.navBtn, pressed && { opacity: colors.pressedOpacity }]}- disabled={isToday}+ testID="calendar-pane-btn"+ onPress={goUp}+ accessibilityRole="button"+ accessibilityHint={headerHint}+ android_ripple={{ color: colors.text + STATE_LAYER_ALPHA, borderless: true }}+ style={styles.monthLabelBtn}>- <ChevronRight size={22} color={isToday ? colors.textDisabled : colors.primary} />+ <Text style={[styles.monthLabel, { color: colors.text }]}>{headerLabel}</Text>+ {pane === "days" ? (+ <ChevronDown size={size.icon.sm} color={colors.textSecondary} />+ ) : (+ <ChevronUp size={size.icon.sm} color={colors.textSecondary} />+ )}</Pressable>+ {pane === "days" ? (+ <IconButton+ testID="next-month-btn"+ icon={ChevronRight}+ onPress={() => navigateMonth(1)}+ accessibilityLabel="Next month"+ disabled={isFutureMonth}+ />+ ) : (+ <View style={styles.monthNavSpacer} />+ )}</View>- {!isToday && !isExpanded && (- <Pressable- onPress={goToToday}- hitSlop={HIT_SLOP_LG}- style={({ pressed }) => [- styles.todayBtn,- { backgroundColor: colors.primary + "15" },- pressed && { opacity: colors.pressedOpacity }- ]}- >- <Text style={[styles.todayText, { color: colors.primary }]}>Today</Text>- </Pressable>+ {pane === "years" && (+ <ScrollView ref={yearScrollRef} style={styles.pane} testID="year-pane">+ <View style={styles.paneGrid}>+ {years.map((year) => {+ const isViewed = year === pickerYear+ const isCurrent = year === todayYear+ const content = isViewed ? colors.onPrimaryContainer : colors.text+ return (+ <View key={year} style={styles.paneCell}>+ <Pressable+ testID={`year-${year}`}+ onPress={() => selectYear(year)}+ accessibilityRole="radio"+ accessibilityState={{ checked: isViewed }}+ android_ripple={{ color: content + STATE_LAYER_ALPHA }}+ style={[+ styles.paneCellBtn,+ isViewed && { backgroundColor: colors.primaryContainer },+ isCurrent && !isViewed && { borderColor: colors.primary }+ ]}+ >+ <Text style={[styles.paneCellText, { color: content }, isCurrent && !isViewed && fonts.bold]}>+ {year}+ </Text>+ </Pressable>+ </View>+ )+ })}+ </View>+ </ScrollView>)}- {/* Expanded calendar grid */}- {isExpanded && (- <View style={styles.calendarContainer}>- {/* Month navigation */}- <View style={styles.monthRow}>- <Pressable- onPress={() => navigateMonth(-1)}- hitSlop={HIT_SLOP_LG}- style={({ pressed }) => [styles.monthNav, pressed && { opacity: colors.pressedOpacity }]}- >- <ChevronLeft size={18} color={colors.primary} />- </Pressable>- <Text style={[styles.monthLabel, { color: colors.text }]}>{monthLabel}</Text>- <Pressable- onPress={() => navigateMonth(1)}- hitSlop={HIT_SLOP_LG}- style={({ pressed }) => [styles.monthNav, pressed && { opacity: colors.pressedOpacity }]}- disabled={isFutureMonth}- >- <ChevronRight size={18} color={isFutureMonth ? colors.textDisabled : colors.primary} />- </Pressable>- </View>+ {pane === "months" && (+ <View style={[styles.pane, styles.paneGrid]} testID="month-pane">+ {MONTH_LABELS.map((label, m) => {+ const isFuture = pickerYear > todayYear || (pickerYear === todayYear && m > todayMonth)+ const isViewed = pickerYear === viewYear && m === viewMonth+ const content = isFuture ? colors.textDisabled : isViewed ? colors.onPrimaryContainer : colors.text+ return (+ <View key={m} style={styles.paneCell}>+ <Pressable+ testID={`month-${m}`}+ onPress={() => selectMonth(m)}+ disabled={isFuture}+ accessibilityRole="radio"+ accessibilityState={{ checked: isViewed, disabled: isFuture }}+ android_ripple={isFuture ? undefined : { color: content + STATE_LAYER_ALPHA }}+ style={[styles.paneCellBtn, isViewed && { backgroundColor: colors.primaryContainer }]}+ >+ <Text style={[styles.paneCellText, { color: content }]}>{label}</Text>+ </Pressable>+ </View>+ )+ })}+ </View>+ )}- {/* Weekday headers */}- <View style={styles.weekdayRow}>+ {pane === "days" && (+ <>+ <View style={styles.weekRow}>{WEEKDAYS.map((day) => (<Text key={day} style={[styles.weekdayText, { color: colors.textSecondary }]}>{day}@@ -244,185 +308,154 @@ export function CalendarPicker({))}</View>- {/* Day cells */}- <View style={styles.daysGrid}>- {calendarGrid.map((cell) => {- if (cell.day === null) {- return <View key={cell.key} style={styles.dayCell} />- }-- 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)- const isCellToday = isSameDay(cellDate, today)- const isFuture = cellDate > today+ {weeks.map((week, w) => (+ <View key={`week-${w}`} style={styles.weekRow}>+ {week.map((day, i) => {+ if (day === null) {+ return <View key={`empty-${i}`} style={styles.dayCell} />+ }- return (- <Pressable- key={cell.key}- style={styles.dayCell}- onPress={() => selectDay(cell.day!)}- disabled={isFuture}- >- <View style={[styles.dayCircle, isSelected && { backgroundColor: colors.primary }]}>- <Text+ const cellDate = new Date(viewYear, viewMonth, day)+ const dateKey = formatDateKey(viewYear, viewMonth, day)+ const hasData = daysWithData.has(dateKey)+ const isSelected = isSameDay(cellDate, date)+ const isCellToday = isSameDay(cellDate, today)+ const isFuture = cellDate > today+ const numeralColor = isFuture+ ? colors.textDisabled+ : isSelected+ ? colors.textOnPrimary+ : isCellToday || hasData+ ? colors.text+ : colors.textLight+ const numeralWeight =+ isCellToday && !isSelected ? fonts.bold : hasData || isSelected ? fonts.semiBold : fonts.regular++ return (+ <Pressable+ key={dateKey}+ testID={`day-${day}`}+ accessibilityRole="button"+ accessibilityLabel={dayCellLabel(cellDate, dayStats.get(dateKey), isCellToday)}+ accessibilityState={{ selected: isSelected, disabled: isFuture }}+ android_ripple={+ isFuture+ ? undefined+ : { color: colors.text + STATE_LAYER_ALPHA, borderless: true, radius: size.touch / 2 }+ }+ style={styles.dayCell}+ onPress={() => selectDay(day)}+ disabled={isFuture}+ >+ <View+ testID={`day-disc-${day}`}style={[- styles.dayText,- { color: isFuture ? colors.textDisabled : isSelected ? colors.textOnPrimary : colors.text },- isCellToday && !isSelected && { color: colors.primary, ...fonts.bold }+ styles.dayDisc,+ isSelected && { backgroundColor: colors.primary },+ isCellToday && !isSelected && { borderColor: colors.primary }]}>- {cell.day}- </Text>- {hasNote && (- <View style={[styles.noteDot, { backgroundColor: colors.primary, borderColor: colors.card }]} />- )}- </View>- {dist != null && dist > 0 ? (- <Text- style={[styles.dayDist, { color: isSelected ? colors.primary : colors.textLight }]}- numberOfLines={1}- >- {formatDistance(dist)}- </Text>- ) : hasData ? (- <View- style={[styles.dataDot, { backgroundColor: isSelected ? colors.primary : colors.textLight }]}- />- ) : null}- </Pressable>- )- })}- </View>- </View>+ <Text style={[styles.dayText, numeralWeight, { color: numeralColor }]}>{day}</Text>+ {hasData && (+ <View+ testID={`day-dot-${day}`}+ style={[+ styles.dataDot,+ { backgroundColor: isSelected ? colors.textOnPrimary : colors.primary }+ ]}+ />+ )}+ </View>+ </Pressable>+ )+ })}+ </View>+ ))}+ </>)}</View>)}const styles = StyleSheet.create({- container: {- paddingHorizontal: 12,- paddingVertical: 10,- borderBottomWidth: StyleSheet.hairlineWidth- },- row: {+ monthRow: {flexDirection: "row",alignItems: "center",- justifyContent: "space-between"+ justifyContent: "space-between",+ marginBottom: space.sm},- navBtn: {- padding: 8+ monthNavSpacer: {+ width: size.iconButton},- dateContainer: {- alignItems: "center",- flex: 1+ monthLabel: {+ fontSize: fontSizes.label,+ ...fonts.semiBold},- dateLabelRow: {+ monthLabelBtn: {flexDirection: "row",alignItems: "center",- gap: 6- },- calendarIcon: {- marginTop: 1- },- dateText: {- fontSize: 15,- ...fonts.bold- },- todayBadge: {- paddingHorizontal: 6,- paddingVertical: 2,- borderRadius: 6- },- todayBadgeText: {- fontSize: 10,- ...fonts.bold+ justifyContent: "center",+ minHeight: size.touch,+ gap: space.sm,+ paddingHorizontal: space.sm},- countText: {- fontSize: 12,- ...fonts.regular,- marginTop: 2+ pane: {+ height: YEAR_ROW_HEIGHT * YEAR_PANE_ROWS},- todayBtn: {- alignSelf: "center",- marginTop: 8,- paddingHorizontal: 16,- paddingVertical: 6,- borderRadius: 14- },- todayText: {- fontSize: 12,- ...fonts.semiBold+ paneGrid: {+ flexDirection: "row",+ flexWrap: "wrap"},- calendarContainer: {- marginTop: 12+ paneCell: {+ width: "33.33%",+ height: YEAR_ROW_HEIGHT,+ padding: space.xs},- monthRow: {- flexDirection: "row",+ paneCellBtn: {+ overflow: "hidden",+ flex: 1,alignItems: "center",- justifyContent: "space-between",- marginBottom: 8- },- monthNav: {- padding: 8+ justifyContent: "center",+ borderRadius: radius.sm,+ borderWidth: 1,+ borderColor: "transparent"},- monthLabel: {- fontSize: 14,- ...fonts.semiBold+ paneCellText: {+ fontSize: fontSizes.body,+ ...fonts.medium},- weekdayRow: {- flexDirection: "row",- marginBottom: 4+ weekRow: {+ flexDirection: "row"},weekdayText: {flex: 1,textAlign: "center",- fontSize: 11,+ fontSize: fontSizes.small,+ lineHeight: lineHeights.small,...fonts.semiBold},- daysGrid: {- flexDirection: "row",- flexWrap: "wrap"- },dayCell: {- width: "14.28%",- paddingVertical: 4,+ flex: 1,+ minHeight: size.touch,alignItems: "center",justifyContent: "center"},- dayCircle: {- width: 32,- height: 32,- borderRadius: 16,+ dayDisc: {+ width: size.iconColumn,+ height: size.iconColumn,+ borderRadius: radius.pill,+ borderWidth: 1,+ borderColor: "transparent",alignItems: "center",justifyContent: "center"},dayText: {- fontSize: 13,- ...fonts.regular- },- dayDist: {- fontSize: 9,- ...fonts.medium,- marginTop: 1+ fontSize: fontSizes.description},dataDot: {- width: 4,- height: 4,- borderRadius: 2,- marginTop: 2- },- noteDot: {- position: "absolute",- top: 1,- right: 1,- width: 7,- height: 7,- borderRadius: 3.5,- borderWidth: 1+ width: space.xs,+ height: space.xs,+ borderRadius: radius.pill,+ marginTop: space.xxs}})diff --git a/apps/mobile/src/components/features/inspector/DayHeader.tsx b/apps/mobile/src/components/features/inspector/DayHeader.tsxnew file mode 100644index 00000000..cf642680--- /dev/null+++ b/apps/mobile/src/components/features/inspector/DayHeader.tsx@@ -0,0 +1,94 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import React from "react"+import { formatDistance } from "../../../utils/geo"+import { StepperHeader } from "../../ui/StepperHeader"++export type DayStats = {+ points: number+ trips: number+ distanceMeters: number+}++type DayHeaderProps = {+ date: Date+ stats: DayStats | null+ loading: boolean+ onPrevious: () => void+ onNext: () => void+ onOpenPicker: () => void+ nextDisabled: boolean+}++function startOfDay(date: Date): number {+ return new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime()+}++function daysBefore(date: Date, now: Date): number {+ return Math.round((startOfDay(now) - startOfDay(date)) / 86_400_000)+}++function withYear(date: Date, now: Date): { year?: "numeric" } {+ return date.getFullYear() === now.getFullYear() ? {} : { year: "numeric" }+}++export function isRelativeDay(date: Date, now: Date = new Date()): boolean {+ const days = daysBefore(date, now)+ return days === 0 || days === 1+}++export function dayTitle(date: Date, now: Date = new Date()): string {+ const days = daysBefore(date, now)+ if (days === 0) return "Today"+ if (days === 1) return "Yesterday"+ return date.toLocaleDateString(undefined, {+ weekday: "short",+ month: "short",+ day: "numeric",+ ...withYear(date, now)+ })+}++export function dayLongDate(date: Date, now: Date = new Date()): string {+ return date.toLocaleDateString(undefined, { weekday: "long", month: "long", day: "numeric", ...withYear(date, now) })+}++function count(n: number, noun: string): string {+ return `${n} ${noun}${n === 1 ? "" : "s"}`+}++export function dayLedger(stats: DayStats | null, loading: boolean): string {+ if (loading) return "Loading"+ if (!stats || stats.points === 0) return "No locations recorded"+ if (stats.trips === 0) return `${count(stats.points, "point")} · no trips`+ return `${count(stats.trips, "trip")} · ${formatDistance(stats.distanceMeters)} · ${count(stats.points, "point")}`+}++export function dayCaption(date: Date, stats: DayStats | null, loading: boolean, now: Date = new Date()): string {+ const ledger = dayLedger(stats, loading)+ if (!isRelativeDay(date, now)) return ledger+ return `${date.toLocaleDateString(undefined, { month: "short", day: "numeric" })} · ${ledger}`+}++export function DayHeader({ date, stats, loading, onPrevious, onNext, onOpenPicker, nextDisabled }: DayHeaderProps) {+ const now = new Date()++ return (+ <StepperHeader+ title={dayTitle(date, now)}+ caption={dayCaption(date, stats, loading, now)}+ onPrevious={onPrevious}+ onNext={onNext}+ previousLabel="Previous day"+ nextLabel="Next day"+ nextDisabled={nextDisabled}+ onPress={onOpenPicker}+ accessibilityLabel={`Change day, ${dayLongDate(date, now)}, ${dayLedger(stats, loading)}`}+ accessibilityHint="Opens the calendar"+ testID="day"+ />+ )+}diff --git a/apps/mobile/src/components/features/inspector/DayPickerModal.tsx b/apps/mobile/src/components/features/inspector/DayPickerModal.tsxnew file mode 100644index 00000000..5bde3410--- /dev/null+++ b/apps/mobile/src/components/features/inspector/DayPickerModal.tsx@@ -0,0 +1,62 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import React, { useCallback } from "react"+import { DailyStat } from "../../../types/global"+import { useTheme } from "../../../hooks/useTheme"+import { DialogShell } from "../../ui/DialogShell"+import { Button } from "../../ui/Button"+import { CalendarPicker } from "./CalendarPicker"++interface DayPickerModalProps {+ visible: boolean+ date: Date+ onSelect: (date: Date) => void+ onRequestClose: () => void+ daysWithData: Set<string>+ dayStats: ReadonlyMap<string, DailyStat>+ onMonthChange: (year: number, month: number) => void+ onPrefetchMonth?: (year: number, month: number) => void+}++export function DayPickerModal({+ visible,+ date,+ onSelect,+ onRequestClose,+ daysWithData,+ dayStats,+ onMonthChange,+ onPrefetchMonth+}: DayPickerModalProps) {+ const { colors } = useTheme()++ const handleSelect = useCallback(+ (selected: Date) => {+ onSelect(selected)+ onRequestClose()+ },+ [onSelect, onRequestClose]+ )++ return (+ <DialogShell+ visible={visible}+ onRequestClose={onRequestClose}+ gutter="picker"+ footer={<Button variant="ghost" title="Close" onPress={onRequestClose} testID="day-picker-close-btn" />}+ >+ <CalendarPicker+ date={date}+ onSelectDay={handleSelect}+ colors={colors}+ daysWithData={daysWithData}+ dayStats={dayStats}+ onMonthChange={onMonthChange}+ onPrefetchMonth={onPrefetchMonth}+ />+ </DialogShell>+ )+}diff --git a/apps/mobile/src/components/features/inspector/InspectorDock.tsx b/apps/mobile/src/components/features/inspector/InspectorDock.tsxnew file mode 100644index 00000000..2bf1a7cb--- /dev/null+++ b/apps/mobile/src/components/features/inspector/InspectorDock.tsx@@ -0,0 +1,213 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import React from "react"+import { LayoutChangeEvent, Pressable, ScrollView, StyleSheet, Text, View } from "react-native"+import { Check, MapPin, MapPinOff, Route, type LucideIcon } from "lucide-react-native"+import { radius } from "@colota/shared"+import { useTheme } from "../../../hooks/useTheme"+import { HIT_SLOP_MD, size, space, STATE_LAYER_ALPHA } from "../../../constants"+import { fonts, fontSizes } from "../../../styles/typography"+import { formatDistance, formatTime } from "../../../utils/geo"+import type { Trip } from "../../../types/global"+import { Divider } from "../../ui/Divider"+import { ListItem } from "../../ui/ListItem"+import { MapDock } from "../../ui/MapDock"+import { StateLine } from "../../ui/StateLine"+import { PointCard, type PointCardProps } from "./PointCard"+import { TripRow, TripSwatch } from "./TripRow"++export type DockEmptyAction = {+ icon: LucideIcon+ label: string+ sub: string+ onPress: () => void+}++export type DockContent =+ | { kind: "legend"; trips: Trip[]; focusedTripIndex: number | null; onFocusTrip: (index: number | null) => void }+ | { kind: "points"; count: number; startTime: number; endTime: number }+ | ({ kind: "point" } & PointCardProps)+ | { kind: "empty"; title: string; hint: string; action?: DockEmptyAction }++type InspectorDockProps = {+ content: DockContent+ left: number+ right: number+ maxHeight: number+ onLayout?: (event: LayoutChangeEvent) => void+}++type TripChipProps = {+ trip: Trip+ selected: boolean+ onPress: () => void+}++function TripChip({ trip, selected, onPress }: TripChipProps) {+ const { colors } = useTheme()+ const content = selected ? colors.onPrimaryContainer : colors.text+ const start = formatTime(trip.startTime)++ return (+ <Pressable+ testID={`dock-trip-${trip.index}`}+ accessibilityRole="button"+ accessibilityLabel={`Trip ${trip.index}, starts ${start}`}+ accessibilityState={{ selected }}+ android_ripple={{ color: colors.text + STATE_LAYER_ALPHA }}+ hitSlop={HIT_SLOP_MD}+ onPress={onPress}+ style={[styles.chip, { backgroundColor: selected ? colors.primaryContainer : colors.well }]}+ >+ {selected ? <Check size={size.icon.sm} color={content} strokeWidth={2} /> : <TripSwatch index={trip.index} />}+ <Text style={[styles.chipLabel, selected && styles.chipLabelSelected, { color: content }]}>{start}</Text>+ </Pressable>+ )+}++function Legend({ trips, focusedTripIndex, onFocusTrip }: Extract<DockContent, { kind: "legend" }>) {+ const { colors } = useTheme()+ const focused = trips.find((trip) => trip.index === focusedTripIndex) ?? null+ const first = trips[0]+ const last = trips[trips.length - 1]+ const distance = trips.reduce((sum, trip) => sum + trip.distance, 0)++ return (+ <>+ {focused ? (+ <TripRow+ trip={focused}+ index={focused.index}+ selected+ selecting+ onPress={() => onFocusTrip(null)}+ onLongPress={() => {}}+ testID="dock-focused-trip"+ />+ ) : (+ <StateLine+ icon={Route}+ iconColor={colors.textSecondary}+ label={`${trips.length} ${trips.length === 1 ? "trip" : "trips"}`}+ caption={`${formatTime(first.startTime)} - ${formatTime(last.endTime)} · ${formatDistance(distance)}`}+ testID="dock-legend"+ />+ )}+ <Divider tight />+ <ScrollView+ horizontal+ showsHorizontalScrollIndicator={false}+ style={styles.strip}+ contentContainerStyle={styles.stripContent}+ testID="dock-trip-strip"+ >+ {trips.map((trip) => (+ <TripChip+ key={trip.index}+ trip={trip}+ selected={trip.index === focusedTripIndex}+ onPress={() => onFocusTrip(trip.index === focusedTripIndex ? null : trip.index)}+ />+ ))}+ </ScrollView>+ </>+ )+}++function DockBody({ content }: { content: DockContent }) {+ const { colors } = useTheme()++ switch (content.kind) {+ case "legend":+ return <Legend {...content} />+ case "points": {+ const { count, startTime, endTime } = content+ const points = `${count} ${count === 1 ? "point" : "points"}`+ return (+ <StateLine+ icon={MapPin}+ iconColor={colors.textSecondary}+ label="No trips"+ caption={`${points} · ${formatTime(startTime)} - ${formatTime(endTime)}`}+ testID="dock-points"+ />+ )+ }+ case "point":+ return <PointCard {...content} />+ case "empty": {+ const { title, hint, action } = content+ return (+ <>+ <StateLine+ icon={MapPinOff}+ iconColor={colors.textSecondary}+ label={title}+ caption={hint}+ testID="dock-empty"+ />+ {action && (+ <>+ <Divider tight inset />+ <ListItem+ icon={action.icon}+ label={action.label}+ sub={action.sub}+ onPress={action.onPress}+ testID="dock-empty-action"+ />+ </>+ )}+ </>+ )+ }+ }+}++export function InspectorDock({ content, left, right, maxHeight, onLayout }: InspectorDockProps) {+ return (+ <View style={[styles.dock, { left, right }]} onLayout={onLayout} testID="inspector-dock">+ <MapDock maxHeight={maxHeight}>+ <DockBody content={content} />+ </MapDock>+ </View>+ )+}++const styles = StyleSheet.create({+ dock: {+ position: "absolute",+ bottom: space.lg+ },+ // The strip scrolls edge to edge inside the card, so it cancels the card's inset the way a row does.+ strip: {+ marginHorizontal: -space.lg+ },+ stripContent: {+ flexDirection: "row",+ gap: space.sm,+ paddingHorizontal: space.lg,+ paddingVertical: space.sm+ },+ chip: {+ overflow: "hidden",+ flexDirection: "row",+ alignItems: "center",+ gap: space.xs,+ minHeight: size.chip,+ borderRadius: radius.sm,+ paddingVertical: space.sm,+ paddingHorizontal: space.md+ },+ chipLabel: {+ fontSize: fontSizes.caption,+ ...fonts.medium,+ fontVariant: ["tabular-nums"]+ },+ chipLabelSelected: {+ ...fonts.semiBold+ }+})diff --git a/apps/mobile/src/components/features/inspector/LocationTable.tsx b/apps/mobile/src/components/features/inspector/LocationTable.tsxindex f44c84b8..568029bf 100644--- a/apps/mobile/src/components/features/inspector/LocationTable.tsx+++ b/apps/mobile/src/components/features/inspector/LocationTable.tsx@@ -3,97 +3,189 @@* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.*/-import React, { useCallback, useMemo } from "react"-import { View, Text, FlatList, ScrollView, StyleSheet } from "react-native"-import { fonts } from "../../../styles/typography"+import React, { useCallback, useMemo, useRef } from "react"+import {+ View,+ Text,+ FlatList,+ ScrollView,+ Pressable,+ StyleSheet,+ NativeScrollEvent,+ NativeSyntheticEvent+} from "react-native"+import { BatteryCharging, BatteryFull } from "lucide-react-native"+import { fontSizes, fonts, lineHeights, type } from "../../../styles/typography"import { LocationCoords, ThemeColors } from "../../../types/global"-import { formatTime, getSpeedUnit } from "../../../utils/geo"+import { formatTime, getSpeedUnit, getTimeFormat } from "../../../utils/geo"+import { size, space, STATE_LAYER_ALPHA } from "../../../constants"+import { Divider } from "../../ui/Divider"interface Props {locations: LocationCoords[]colors: ThemeColors+ hasEndpoint: boolean+ selectedPointId?: number+ onSelectPoint: (id: number) => void}interface TableRow extends LocationCoords {delta: number | null}-const ROW_HEIGHT = 36-const TABLE_WIDTH = 870+const COLUMN_WIDTHS = {+ delta: 56,+ lat: 88,+ lon: 88,+ acc: 56,+ speed: 72,+ alt: 56,+ bear: 56,+ batt: 80,+ sync: 72,+ note: 176+}++// "10:17:10 PM" is three characters wider than "22:17:10".+const TIME_WIDTH = { "24h": 88, "12h": 112 } as const+const ROW_LENGTH = size.touch + StyleSheet.hairlineWidth+const BATTERY_CHARGING = 2+const BATTERY_FULL = 3function val(v?: number | null, decimals = 0): string {if (v == null) return "-"return decimals > 0 ? v.toFixed(decimals) : String(Math.round(v))}-// Mirrors BatteryStatus.kt.-const BATTERY_STATUS: Record<number, string> = {- 0: "Unknown",- 1: "Discharging",- 2: "Charging",- 3: "Full"+function timeOf(item: TableRow): string {+ return item.timestamp ? formatTime(item.timestamp, true) : "-"+}++type RowProps = {+ item: TableRow+ colors: ThemeColors+ selected: boolean+ onSelectPoint: (id: number) => void}-const LocationRow = React.memo(+const TimeCell = React.memo(({ item, colors, selected, onSelectPoint }: RowProps) => (+ <Pressable+ style={[styles.row, selected && { backgroundColor: colors.primaryContainer }]}+ android_ripple={{ color: colors.text + STATE_LAYER_ALPHA }}+ accessibilityRole="button"+ accessibilityLabel={`${timeOf(item)}, show on map`}+ accessibilityState={{ selected }}+ onPress={() => item.id != null && onSelectPoint(item.id)}+ >+ <Text+ style={[+ styles.mono,+ { width: TIME_WIDTH[getTimeFormat()], color: colors.text },+ selected && [styles.selectedTime, { color: colors.onPrimaryContainer }]+ ]}+ numberOfLines={1}+ >+ {timeOf(item)}+ </Text>+ </Pressable>+))++const DataRow = React.memo(({item,+ colors,+ selected,+ onSelectPoint,speedUnit,- colors- }: {- item: TableRow- speedUnit: { factor: number; unit: string }- colors: ThemeColors- }) => (- <View style={[styles.row, { borderBottomColor: colors.border }]}>- <Text style={[styles.cell, styles.cellTime, { color: colors.text }]} numberOfLines={1}>- {item.timestamp ? formatTime(item.timestamp, true) : "-"}- </Text>- <Text style={[styles.cell, styles.cellNum, { color: colors.textSecondary }]} numberOfLines={1}>- {item.delta != null ? `+${item.delta}` : ""}- </Text>- <Text style={[styles.cell, styles.cellCoord, { color: colors.text }]} numberOfLines={1}>- {val(item.latitude, 5)}- </Text>- <Text style={[styles.cell, styles.cellCoord, { color: colors.text }]} numberOfLines={1}>- {val(item.longitude, 5)}- </Text>- <Text style={[styles.cell, styles.cellNum, { color: colors.text }]} numberOfLines={1}>- {val(item.accuracy)}- </Text>- <Text style={[styles.cell, styles.cellNum, { color: colors.text }]} numberOfLines={1}>- {item.speed != null ? (item.speed * speedUnit.factor).toFixed(1) : "-"}- </Text>- <Text style={[styles.cell, styles.cellNum, { color: colors.text }]} numberOfLines={1}>- {val(item.altitude)}- </Text>- <Text style={[styles.cell, styles.cellNum, { color: colors.text }]} numberOfLines={1}>- {item.bearing != null ? val(item.bearing, 1) : "-"}- </Text>- <Text style={[styles.cell, styles.cellNum, { color: colors.text }]} numberOfLines={1}>- {item.battery != null ? `${item.battery}%` : "-"}- </Text>- <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>- )+ hasEndpoint+ }: RowProps & { speedUnit: { factor: number; unit: string }; hasEndpoint: boolean }) => {+ const BatteryGlyph =+ item.battery_status === BATTERY_CHARGING+ ? BatteryCharging+ : item.battery_status === BATTERY_FULL+ ? BatteryFull+ : null+ const batteryWord =+ item.battery_status === BATTERY_CHARGING ? "charging" : item.battery_status === BATTERY_FULL ? "full" : null+ const battery = item.battery != null ? `${item.battery}%` : "-"+ const syncWord = item.sent ? "Sent" : "Queued"+ const facts = [+ timeOf(item),+ item.delta != null ? `${item.delta} seconds after the previous point` : null,+ `${val(item.latitude, 5)}, ${val(item.longitude, 5)}`,+ `accuracy ${val(item.accuracy)} m`,+ item.speed != null ? `speed ${(item.speed * speedUnit.factor).toFixed(1)} ${speedUnit.unit}` : null,+ item.altitude != null ? `altitude ${val(item.altitude)} m` : null,+ item.bearing != null ? `bearing ${val(item.bearing)}` : null,+ item.battery != null ? `battery ${battery}${batteryWord ? ` ${batteryWord}` : ""}` : null,+ hasEndpoint ? syncWord : null,+ item.note ? `note ${item.note}` : null,+ "show on map"+ ].filter(Boolean)+ const content = selected ? colors.onPrimaryContainer : colors.text+ const mono = [styles.mono, styles.numeric, { color: content }]+ return (+ <Pressable+ style={[styles.row, selected && { backgroundColor: colors.primaryContainer }]}+ android_ripple={{ color: colors.text + STATE_LAYER_ALPHA }}+ accessibilityRole="button"+ accessibilityLabel={facts.join(", ")}+ accessibilityState={{ selected }}+ onPress={() => item.id != null && onSelectPoint(item.id)}+ >+ <Text style={[mono, { width: COLUMN_WIDTHS.delta }]} numberOfLines={1}>+ {item.delta != null ? `+${item.delta}` : ""}+ </Text>+ <Text style={[mono, { width: COLUMN_WIDTHS.lat }]} numberOfLines={1}>+ {val(item.latitude, 5)}+ </Text>+ <Text style={[mono, { width: COLUMN_WIDTHS.lon }]} numberOfLines={1}>+ {val(item.longitude, 5)}+ </Text>+ <Text style={[mono, { width: COLUMN_WIDTHS.acc }]} numberOfLines={1}>+ {val(item.accuracy)}+ </Text>+ <Text style={[mono, { width: COLUMN_WIDTHS.speed }]} numberOfLines={1}>+ {item.speed != null ? (item.speed * speedUnit.factor).toFixed(1) : "-"}+ </Text>+ <Text style={[mono, { width: COLUMN_WIDTHS.alt }]} numberOfLines={1}>+ {val(item.altitude)}+ </Text>+ <Text style={[mono, { width: COLUMN_WIDTHS.bear }]} numberOfLines={1}>+ {val(item.bearing)}+ </Text>+ <View+ style={[styles.batteryCell, { width: COLUMN_WIDTHS.batt }]}+ accessibilityRole="text"+ accessibilityLabel={batteryWord ? `${battery} ${batteryWord}` : battery}+ >+ <Text style={[styles.mono, { color: content }]} numberOfLines={1}>+ {battery}+ </Text>+ {BatteryGlyph && <BatteryGlyph size={size.icon.sm} color={colors.textSecondary} />}+ </View>+ {hasEndpoint && (+ <Text style={[styles.caption, { width: COLUMN_WIDTHS.sync, color: content }]} numberOfLines={1}>+ {syncWord}+ </Text>+ )}+ <Text style={[styles.caption, { width: COLUMN_WIDTHS.note, color: content }]} numberOfLines={1}>+ {item.note ?? ""}+ </Text>+ </Pressable>+ )+ })-const keyExtractor = (_: TableRow, index: number) => String(index)-const getItemLayout = (_: any, index: number) => ({- length: ROW_HEIGHT,- offset: ROW_HEIGHT * index,- index-})+const Separator = () => <Divider tight />+const keyExtractor = (item: TableRow, index: number) => String(item.id ?? index)+const getItemLayout = (_: unknown, index: number) => ({ length: ROW_LENGTH, offset: ROW_LENGTH * index, index })-export function LocationTable({ locations, colors }: Props) {- const speedUnit = useMemo(() => getSpeedUnit(), [])+export function LocationTable({ locations, colors, hasEndpoint, selectedPointId, onSelectPoint }: Props) {+ const speedUnit = getSpeedUnit()+ const timeListRef = useRef<FlatList<TableRow>>(null)const data = useMemo<TableRow[]>(() => {- // Compute deltas in chronological order, then reverse for newest-first displayconst rows = locations.map((loc, i) => ({...loc,delta:@@ -104,112 +196,172 @@ export function LocationTable({ locations, colors }: Props) {return rows.reverse()}, [locations])- const renderItem = useCallback(- ({ item }: { item: TableRow }) => <LocationRow item={item} speedUnit={speedUnit} colors={colors} />,- [colors, speedUnit]+ // The time pane only follows: a second scroller echoing every frame cancels the fling of the first.+ const onDataScroll = useCallback((e: NativeSyntheticEvent<NativeScrollEvent>) => {+ timeListRef.current?.scrollToOffset({ offset: e.nativeEvent.contentOffset.y, animated: false })+ }, [])++ const renderTime = useCallback(+ ({ item }: { item: TableRow }) => (+ <TimeCell item={item} colors={colors} selected={item.id === selectedPointId} onSelectPoint={onSelectPoint} />+ ),+ [colors, selectedPointId, onSelectPoint]+ )+ const renderData = useCallback(+ ({ item }: { item: TableRow }) => (+ <DataRow+ item={item}+ colors={colors}+ selected={item.id === selectedPointId}+ onSelectPoint={onSelectPoint}+ speedUnit={speedUnit}+ hasEndpoint={hasEndpoint}+ />+ ),+ [colors, selectedPointId, onSelectPoint, speedUnit, hasEndpoint])- if (locations.length === 0) {- return (- <View style={styles.empty}>- <Text style={[styles.emptyText, { color: colors.textSecondary }]}>No data for this day</Text>- </View>- )- }+ const header = [styles.headerCell, { color: colors.textSecondary }]+ const numericHeader = [header, styles.numeric]+ const dataWidth =+ COLUMN_WIDTHS.delta ++ COLUMN_WIDTHS.lat ++ COLUMN_WIDTHS.lon ++ COLUMN_WIDTHS.acc ++ COLUMN_WIDTHS.speed ++ COLUMN_WIDTHS.alt ++ COLUMN_WIDTHS.bear ++ COLUMN_WIDTHS.batt ++ (hasEndpoint ? COLUMN_WIDTHS.sync : 0) ++ COLUMN_WIDTHS.notereturn (- <ScrollView horizontal style={styles.container} contentContainerStyle={styles.scrollContent}>- <View style={styles.tableWrapper}>- {/* Header */}- <View- style={[styles.row, styles.header, { borderBottomColor: colors.border, backgroundColor: colors.surface }]}- >- <Text style={[styles.cell, styles.cellTime, styles.headerText, { color: colors.textSecondary }]}>Time</Text>- <Text style={[styles.cell, styles.cellNum, styles.headerText, { color: colors.textSecondary }]}>Δs</Text>- <Text style={[styles.cell, styles.cellCoord, styles.headerText, { color: colors.textSecondary }]}>Lat</Text>- <Text style={[styles.cell, styles.cellCoord, styles.headerText, { color: colors.textSecondary }]}>Lon</Text>- <Text style={[styles.cell, styles.cellNum, styles.headerText, { color: colors.textSecondary }]}>Acc</Text>- <Text style={[styles.cell, styles.cellNum, styles.headerText, { color: colors.textSecondary }]}>- {speedUnit.unit}- </Text>- <Text style={[styles.cell, styles.cellNum, styles.headerText, { color: colors.textSecondary }]}>Alt</Text>- <Text style={[styles.cell, styles.cellNum, styles.headerText, { color: colors.textSecondary }]}>Bear</Text>- <Text style={[styles.cell, styles.cellNum, styles.headerText, { color: colors.textSecondary }]}>Batt</Text>- <Text style={[styles.cell, styles.cellStatus, styles.headerText, { color: colors.textSecondary }]}>- Charge+ <View style={[styles.container, { backgroundColor: colors.background }]}>+ <View+ style={{ width: TIME_WIDTH[getTimeFormat()] }}+ importantForAccessibility="no-hide-descendants"+ testID="table-time-pane"+ >+ <View style={styles.headerRow}>+ <Text style={[header, { width: TIME_WIDTH[getTimeFormat()] }]} numberOfLines={2}>+ Time</Text>- <Text style={[styles.cell, styles.cellNote, styles.headerText, { color: colors.textSecondary }]}>Note</Text></View>-+ <Divider tight /><FlatList+ ref={timeListRef}+ testID="table-time-list"data={data}- renderItem={renderItem}+ renderItem={renderTime}keyExtractor={keyExtractor}getItemLayout={getItemLayout}- extraData={locations}+ ItemSeparatorComponent={Separator}+ scrollEnabled={false}+ showsVerticalScrollIndicator={false}initialNumToRender={30}maxToRenderPerBatch={20}windowSize={11}/></View>- </ScrollView>+ <ScrollView horizontal style={styles.container} testID="table-data-pane">+ <View style={{ width: dataWidth }}>+ <View style={styles.headerRow}>+ <Text style={[numericHeader, { width: COLUMN_WIDTHS.delta }]} numberOfLines={2}>+ Δs+ </Text>+ <Text style={[numericHeader, { width: COLUMN_WIDTHS.lat }]} numberOfLines={2}>+ Lat+ </Text>+ <Text style={[numericHeader, { width: COLUMN_WIDTHS.lon }]} numberOfLines={2}>+ Lon+ </Text>+ <Text style={[numericHeader, { width: COLUMN_WIDTHS.acc }]} numberOfLines={2}>+ Acc m+ </Text>+ <Text style={[numericHeader, { width: COLUMN_WIDTHS.speed }]} numberOfLines={2}>+ {`Speed ${speedUnit.unit}`}+ </Text>+ <Text style={[numericHeader, { width: COLUMN_WIDTHS.alt }]} numberOfLines={2}>+ Alt m+ </Text>+ <Text style={[numericHeader, { width: COLUMN_WIDTHS.bear }]} numberOfLines={2}>+ Bear+ </Text>+ <Text style={[numericHeader, { width: COLUMN_WIDTHS.batt }]} numberOfLines={2}>+ Batt %+ </Text>+ {hasEndpoint && (+ <Text style={[header, { width: COLUMN_WIDTHS.sync }]} numberOfLines={2}>+ Sync+ </Text>+ )}+ <Text style={[header, { width: COLUMN_WIDTHS.note }]} numberOfLines={2}>+ Note+ </Text>+ </View>+ <Divider tight />+ <FlatList+ testID="table-data-list"+ data={data}+ renderItem={renderData}+ keyExtractor={keyExtractor}+ getItemLayout={getItemLayout}+ ItemSeparatorComponent={Separator}+ onScroll={onDataScroll}+ scrollEventThrottle={16}+ initialNumToRender={30}+ maxToRenderPerBatch={20}+ windowSize={11}+ />+ </View>+ </ScrollView>+ </View>)}const styles = StyleSheet.create({container: {- flex: 1- },- scrollContent: {- flexGrow: 1- },- empty: {flex: 1,- alignItems: "center",- justifyContent: "center",- padding: 32- },- emptyText: {- fontSize: 14,- ...fonts.regular+ flexDirection: "row"},- header: {- borderBottomWidth: 2+ headerRow: {+ flexDirection: "row",+ alignItems: "center",+ height: size.touch},- headerText: {- fontSize: 11,- ...fonts.bold,- textTransform: "uppercase"+ headerCell: {+ fontSize: fontSizes.caption,+ lineHeight: lineHeights.caption,+ ...fonts.semiBold,+ paddingHorizontal: space.md},row: {flexDirection: "row",- height: ROW_HEIGHT,alignItems: "center",- paddingHorizontal: 8,- borderBottomWidth: StyleSheet.hairlineWidth- },- cell: {- fontSize: 12,- ...fonts.regular,- paddingHorizontal: 2- },- cellTime: {- width: 80+ height: size.touch},- cellCoord: {- width: 90+ mono: {+ ...type.mono,+ paddingHorizontal: space.md},- cellNum: {- width: 50+ numeric: {+ textAlign: "right"},- cellStatus: {- width: 90+ // The platform monospace has no weight token, and its fake bold keeps the advances, so no jitter.+ selectedTime: {+ fontWeight: "bold"},- cellNote: {- width: 140+ caption: {+ fontSize: fontSizes.caption,+ lineHeight: lineHeights.caption,+ ...fonts.regular,+ paddingHorizontal: space.md},- tableWrapper: {- width: TABLE_WIDTH,- flex: 1+ batteryCell: {+ flexDirection: "row",+ alignItems: "center",+ justifyContent: "flex-end",+ gap: space.xs,+ paddingEnd: space.md}})diff --git a/apps/mobile/src/components/features/inspector/PointCard.tsx b/apps/mobile/src/components/features/inspector/PointCard.tsxnew file mode 100644index 00000000..69477cc8--- /dev/null+++ b/apps/mobile/src/components/features/inspector/PointCard.tsx@@ -0,0 +1,128 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import React from "react"+import { StyleSheet, Text, View } from "react-native"+import { Clock, CloudUpload, Crosshair, Gauge, Mountain, NotebookPen, Split, Trash2, X } from "lucide-react-native"+import { useTheme } from "../../../hooks/useTheme"+import { showPrompt } from "../../../services/modalService"+import { fontSizes, fonts } from "../../../styles/typography"+import { size, space } from "../../../constants"+import { formatSpeed, formatTime } from "../../../utils/geo"+import type { LocationCoords } from "../../../types/global"+import { Divider } from "../../ui/Divider"+import { IconButton } from "../../ui/IconButton"+import { ListItem } from "../../ui/ListItem"+import { StatRow } from "../../ui/StatRow"++export type PointCardProps = {+ point: LocationCoords+ /** The note as the screen resolves it from noteOverrides; point.note is not read. */+ note: string | undefined+ hasEndpoint: boolean+ /** Absent where a trip is not edited, so the card offers no Split there. */+ onSplit?: () => void+ onDelete?: () => void+ onClose: () => void+ onSaveNote: (note: string | null) => void+}++export function PointCard({ point, note, hasEndpoint, onSplit, onDelete, onClose, onSaveNote }: PointCardProps) {+ const { colors } = useTheme()++ const editNote = async () => {+ const next = await showPrompt({+ title: "Note",+ placeholder: "Add a note",+ initialValue: note ?? "",+ multiline: true,+ cancelText: "Close"+ })+ if (next !== null) onSaveNote(next ? next : null)+ }++ return (+ <View testID="point-card">+ <View style={styles.header}>+ <View style={styles.glyph}>+ <Clock size={size.icon.md} color={colors.textSecondary} />+ </View>+ <Text style={[styles.time, { color: colors.text }]} numberOfLines={1} testID="point-time">+ {formatTime(point.timestamp ?? 0, true)}+ </Text>+ {onSplit && (+ <IconButton icon={Split} accessibilityLabel="Start a new trip here" onPress={onSplit} testID="point-split" />+ )}+ {onDelete && (+ <IconButton+ icon={Trash2}+ tone="danger"+ accessibilityLabel="Delete point"+ onPress={onDelete}+ testID="point-delete"+ />+ )}+ <IconButton icon={X} accessibilityLabel="Close" onPress={onClose} testID="point-close" />+ </View>+ {point.speed !== undefined && (+ <>+ <Divider tight inset />+ <StatRow icon={Gauge} label="Speed" value={formatSpeed(point.speed)} testID="point-speed" />+ </>+ )}+ {point.accuracy !== undefined && (+ <>+ <Divider tight inset />+ <StatRow+ icon={Crosshair}+ label="Accuracy"+ value={`±${Math.round(point.accuracy)} m`}+ testID="point-accuracy"+ />+ </>+ )}+ {point.altitude !== undefined && (+ <>+ <Divider tight inset />+ <StatRow icon={Mountain} label="Altitude" value={`${Math.round(point.altitude)} m`} testID="point-altitude" />+ </>+ )}+ {hasEndpoint && (+ <>+ <Divider tight inset />+ <StatRow icon={CloudUpload} label="Sync" value={point.sent ? "Sent" : "Queued"} testID="point-sync" />+ </>+ )}+ <Divider tight inset />+ <ListItem+ icon={NotebookPen}+ label="Note"+ sub={note ? note : "Add a note"}+ onPress={editNote}+ testID="point-note"+ />+ </View>+ )+}++const styles = StyleSheet.create({+ header: {+ flexDirection: "row",+ alignItems: "center",+ minHeight: size.row,+ paddingVertical: space.sm,+ gap: space.lg+ },+ glyph: {+ width: size.icon.md,+ alignItems: "center"+ },+ time: {+ flex: 1,+ fontSize: fontSizes.label,+ ...fonts.semiBold,+ fontVariant: ["tabular-nums"]+ }+})diff --git a/apps/mobile/src/components/features/inspector/TrackMap.tsx b/apps/mobile/src/components/features/inspector/TrackMap.tsxindex 15518d8f..c86550b3 100644--- a/apps/mobile/src/components/features/inspector/TrackMap.tsx+++ b/apps/mobile/src/components/features/inspector/TrackMap.tsx@@ -4,24 +4,37 @@*/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 { View, StyleSheet } from "react-native"+import { GeoJSONSource, Layer, type PressEventWithFeatures, type ViewPadding } from "@maplibre/maplibre-react-native"import type { NativeSyntheticEvent } from "react-native"-import { MapPinOff, X, Check, Trash2, Split } from "lucide-react-native"+import { LocateFixed } from "lucide-react-native"import { ThemeColors, Trip } from "../../../types/global"import { getTripColor } from "../../../utils/trips"-import { fonts } from "../../../styles/typography"-import { MapCenterButton } from "../map/MapCenterButton"+import { MapActionButton } from "../map/MapActionButton"import { ColotaMapView, ColotaMapRef } from "../map/ColotaMapView"import {+ buildTripTerminalsGeoJSON,buildTrackSegmentsGeoJSON,buildTrackPointsGeoJSON,computeTrackBounds,+ TRACK_CASING_STYLE,TRACK_LINE_STYLE,type TrackLocation} from "../map/mapUtils"-import { getSpeedUnit } from "../../../utils/geo"-import { DEFAULT_MAP_ZOOM, HIT_SLOP_MD, MAP_ANIMATION_DURATION_MS } from "../../../constants"+import { DEFAULT_MAP_ZOOM, MAP_ANIMATION_DURATION_MS, WORLD_MAP_ZOOM, size, space } from "../../../constants"++const FOCUSED_FILTER: ["==", ["get", "focused"], true] = ["==", ["get", "focused"], true]+const START_FILTER: ["==", ["get", "kind"], "start"] = ["==", ["get", "kind"], "start"]+// A source press bubbles to the map press, and the point source can report after the line source.+const FEATURE_PRESS_WINDOW_MS = 200+const LINE_PRESS_DEFER_MS = 80+const END_FILTER: ["==", ["get", "kind"], "end"] = ["==", ["get", "kind"], "end"]+export const POINT_HITBOX: ViewPadding = {+ top: size.touch / 2,+ right: size.touch / 2,+ bottom: size.touch / 2,+ left: size.touch / 2+}const HAS_NOTE = ["!=", ["get", "note"], ""]const trackPointStyle: any = {@@ -32,6 +45,8 @@ const trackPointStyle: any = {circleStrokeWidth: ["case", HAS_NOTE, 2, 1.5]}+type Bounds = NonNullable<ReturnType<typeof computeTrackBounds>>+interface Props {locations: TrackLocation[]colors: ThemeColors@@ -40,12 +55,15 @@ interface Props {fitVersion?: 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. */- onPointDelete?: (id: number) => void- /** When provided, the point popup gains a "start a new trip here" action. */- onPointSplit?: (id: number) => void+ selectedPointId?: number | null+ onSelectPoint: (id: number | null) => void+ /** A `Trip.index`, the number the trip rows and `getTripColor` use. */+ focusedTripIndex?: number | null+ onFocusTrip: (index: number | null) => void+ cameraPadding: ViewPadding+ controlsBottom: number+ controlsEnd: number+ onMapReady?: () => void}export function TrackMap({@@ -55,76 +73,94 @@ export function TrackMap({trackColor,fitVersion,noteOverrides,- onPointNoteChange,- onPointDelete,- onPointSplit+ selectedPointId,+ onSelectPoint,+ focusedTripIndex,+ onFocusTrip,+ cameraPadding,+ controlsBottom,+ controlsEnd,+ onMapReady}: Props) {const mapRef = useRef<ColotaMapRef>(null)const [isCentered, setIsCentered] = useState(true)- const [selectedPoint, setSelectedPoint] = useState<{- latitude: number- longitude: number- color: string- } | null>(null)- const [popup, setPopup] = useState<{- coordinate: [number, number]- speed: number- timestamp: number- accuracy: number- altitude: number- color: string- id: number- note: string- } | null>(null)- const [noteDraft, setNoteDraft] = useState("")const [mapReady, setMapReady] = useState(false)- // Fit map to track bounds when fitVersion changes (date change, trip select)- const bounds = useMemo(() => computeTrackBounds(locations), [locations])+ const focusedTrip = useMemo(+ () => (focusedTripIndex == null ? undefined : trips?.find((trip) => trip.index === focusedTripIndex)),+ [trips, focusedTripIndex]+ )+ const dayBounds = useMemo(() => computeTrackBounds(locations), [locations])+ const fitTarget = useMemo(+ () =>+ focusedTrip+ ? computeTrackBounds(+ locations.slice(focusedTrip.startIndex, focusedTrip.startIndex + focusedTrip.locationCount)+ )+ : dayBounds,+ [focusedTrip, locations, dayBounds]+ )const fittedVersionRef = useRef(-1)// Zero-extent bounds would make fitBounds zoom past the deepest tile levelconst fitCamera = useCallback(- (camera: NonNullable<ColotaMapRef["camera"]>) => {- if (!bounds) return+ (camera: NonNullable<ColotaMapRef["camera"]>, bounds: Bounds) => {if (bounds.sw[0] === bounds.ne[0] && bounds.sw[1] === bounds.ne[1]) {- camera.setStop({ center: bounds.sw, zoom: DEFAULT_MAP_ZOOM, duration: MAP_ANIMATION_DURATION_MS })+ camera.setStop({+ center: bounds.sw,+ zoom: DEFAULT_MAP_ZOOM,+ padding: cameraPadding,+ duration: MAP_ANIMATION_DURATION_MS+ })} else {camera.fitBounds([bounds.sw[0], bounds.sw[1], bounds.ne[0], bounds.ne[1]], {- padding: { top: 60, right: 60, bottom: 60, left: 60 },+ padding: cameraPadding,duration: MAP_ANIMATION_DURATION_MS})}},- [bounds]+ [cameraPadding]+ )++ const selectedIndex = selectedPointId == null ? -1 : locations.findIndex((l) => l.id === selectedPointId)+ const mountTargetRef = useRef<[number, number] | null>(+ selectedIndex >= 0 ? [locations[selectedIndex].longitude, locations[selectedIndex].latitude] : null)useEffect(() => {- if (!bounds || !mapReady || !mapRef.current?.camera) return+ if (!fitTarget || !mapReady || !mapRef.current?.camera) returnif (fitVersion === fittedVersionRef.current) return// Defer to next frame so the map's GL context is fully ready after onDidFinishLoadingMaprequestAnimationFrame(() => {const camera = mapRef.current?.cameraif (!camera) returnfittedVersionRef.current = fitVersion ?? 0- fitCamera(camera)+ const target = mountTargetRef.current+ if (target) {+ mountTargetRef.current = null+ camera.easeTo({+ center: target,+ zoom: DEFAULT_MAP_ZOOM,+ padding: cameraPadding,+ duration: MAP_ANIMATION_DURATION_MS+ })+ return+ }+ fitCamera(camera, fitTarget)})- }, [bounds, mapReady, fitVersion, fitCamera])+ }, [fitTarget, mapReady, fitVersion, fitCamera, cameraPadding])- const handleMapReady = useCallback(() => setMapReady(true), [])+ const handleMapReady = useCallback(() => {+ setMapReady(true)+ onMapReady?.()+ }, [onMapReady])- // Clear popup and highlight when the locations change (new day / different trip)- useEffect(() => {- setPopup(null)- setSelectedPoint(null)- }, [locations])-- const handleFitTrack = useCallback(() => {- if (bounds && mapRef.current?.camera) {- fitCamera(mapRef.current.camera)+ const handleFitDay = useCallback(() => {+ if (dayBounds && mapRef.current?.camera) {+ fitCamera(mapRef.current.camera, dayBounds)setIsCentered(true)}- }, [bounds, fitCamera])+ }, [dayBounds, fitCamera])const handleRegionChange = useCallback((payload: { isUserInteraction: boolean }) => {if (payload.isUserInteraction) {@@ -154,16 +190,25 @@ export function TrackMap({return indices}, [tripIdByPoint])- // Per-location colorsconst locationColors = useMemo(() => {if (!tripIdByPoint || !trips) return locations.map(() => trackColor)return Array.from(tripIdByPoint, (tripId) => (tripId < 0 ? trackColor : getTripColor(trips[tripId].index)))}, [tripIdByPoint, trips, locations, trackColor])- // GeoJSON data+ const locationTrips = useMemo(() => {+ if (!tripIdByPoint || !trips) return undefined+ return Array.from(tripIdByPoint, (tripId) => (tripId < 0 ? -1 : trips[tripId].index))+ }, [tripIdByPoint, trips])+const segmentsGeoJSON = useMemo(- () => buildTrackSegmentsGeoJSON(locations, colors, { skipIndices, locationColors }),- [locations, colors, skipIndices, locationColors]+ () =>+ buildTrackSegmentsGeoJSON(locations, colors, {+ skipIndices,+ locationColors,+ locationTrips,+ focusedTrip: focusedTripIndex+ }),+ [locations, colors, skipIndices, locationColors, locationTrips, focusedTripIndex])const pointsGeoJSON = useMemo(() => {const locs =@@ -173,10 +218,54 @@ export function TrackMap({return buildTrackPointsGeoJSON(locs, colors, locationColors)}, [locations, colors, locationColors, noteOverrides])- // Highlight GeoJSON for selected point+ const hasFocus = focusedTripIndex != null+ const lineStyles = useMemo(() => {+ const lineOpacity = ["case", ["any", !hasFocus, ["get", "focused"]], 1, 0.4]+ return {+ casing: { ...TRACK_CASING_STYLE, lineColor: colors.card, lineOpacity },+ line: { ...TRACK_LINE_STYLE, lineWidth: ["case", ["get", "focused"], 5, 3], lineOpacity },+ // Drawn again in their own layers above the rest, so the focused trip is never under a later one.+ casingFocused: { ...TRACK_CASING_STYLE, lineColor: colors.card, lineWidth: 7 },+ lineFocused: { ...TRACK_LINE_STYLE, lineWidth: 5 }+ }+ }, [hasFocus, colors.card])++ const terminalsGeoJSON = useMemo(() => {+ const terminalTrips = trips+ ? trips.map((t) => ({+ index: t.index,+ color: getTripColor(t.index),+ locations: locations.slice(t.startIndex, t.startIndex + t.locationCount)+ }))+ : [{ index: 0, color: trackColor, locations }]+ return buildTripTerminalsGeoJSON(terminalTrips, focusedTripIndex)+ }, [trips, trackColor, locations, focusedTripIndex])+ const terminalStyles = useMemo(() => {+ const opacity = ["case", ["any", !hasFocus, ["get", "focused"]], 1, 0.4] as any+ return {+ start: {+ circleRadius: 6,+ circleColor: ["get", "color"] as any,+ circleStrokeColor: colors.card,+ circleStrokeWidth: 2,+ circleOpacity: opacity,+ circleStrokeOpacity: opacity+ },+ end: {+ circleRadius: 5,+ circleColor: colors.card,+ circleStrokeColor: ["get", "color"] as any,+ circleStrokeWidth: 3,+ circleOpacity: opacity,+ circleStrokeOpacity: opacity+ }+ }+ }, [hasFocus, colors.card])+const highlightGeoJSON = useMemo(() => {- const coord = selectedPoint ? [selectedPoint.longitude, selectedPoint.latitude] : null- const color = selectedPoint?.color ?? trackColor+ const selected = selectedIndex >= 0 ? locations[selectedIndex] : null+ const coord = selected ? [selected.longitude, selected.latitude] : null+ const color = selectedIndex >= 0 ? locationColors[selectedIndex] : trackColorreturn {type: "FeatureCollection" as const,features: [@@ -187,362 +276,121 @@ export function TrackMap({}]}- }, [selectedPoint, trackColor])+ }, [selectedIndex, locations, locationColors, trackColor])const highlightStyle = useMemo(() => ({circleRadius: 8,circleColor: ["get", "color"] as any,circleOpacity: ["get", "visible"] as any,- circleStrokeColor: colors.cardElevated,+ circleStrokeColor: colors.card,circleStrokeWidth: ["*", 2.5, ["get", "visible"]] as any}),- [colors.cardElevated]+ [colors.card])- const { factor: speedFactor, unit: speedUnit } = getSpeedUnit()-+ const lastFeaturePressRef = useRef(0)const lastPointPressRef = useRef(0)+ const linePressTimer = useRef<ReturnType<typeof setTimeout> | null>(null)+ useEffect(() => () => clearTimeout(linePressTimer.current ?? undefined), [])+const handlePointPress = useCallback((event: NativeSyntheticEvent<PressEventWithFeatures>) => {- const feature = event.nativeEvent.features[0]- if (!feature?.properties || !feature?.geometry) return+ const hits = event.nativeEvent.features+ // Where two trips share a road, the point of the trip drawn on top is the one the finger meant.+ const focusedColor = focusedTripIndex != null ? getTripColor(focusedTripIndex) : null+ const hit = (focusedColor && hits.find((f) => f.properties?.color === focusedColor)) || hits[0]+ const id = hit?.properties?.id+ if (typeof id !== "number" || id < 0) return+ lastFeaturePressRef.current = Date.now()lastPointPressRef.current = Date.now()- const geom = feature.geometry as GeoJSON.Point- const coord = geom.coordinates as [number, number]- const color = feature.properties.color ?? trackColor- const id = (feature.properties.id as number | undefined) ?? -1- const note = 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,- id,- note- })+ if (linePressTimer.current) {+ clearTimeout(linePressTimer.current)+ linePressTimer.current = null+ }+ onSelectPoint(id)},- [trackColor]+ [onSelectPoint, focusedTripIndex])- const handleSaveNote = useCallback(() => {- if (!popup || popup.id < 0 || !onPointNoteChange) return- const saved = noteDraft.trim()- onPointNoteChange(popup.id, saved || null)- setPopup((p) => (p ? { ...p, note: saved } : p))- setNoteDraft(saved)- }, [popup, noteDraft, onPointNoteChange])+ const handleLinePress = useCallback(+ (event: NativeSyntheticEvent<PressEventWithFeatures>) => {+ const tripIndex = event.nativeEvent.features[0]?.properties?.tripIndex+ if (typeof tripIndex !== "number" || tripIndex < 0) return+ lastFeaturePressRef.current = Date.now()+ if (Date.now() - lastPointPressRef.current < FEATURE_PRESS_WINDOW_MS) return+ if (linePressTimer.current) clearTimeout(linePressTimer.current)+ linePressTimer.current = setTimeout(() => {+ linePressTimer.current = null+ if (Date.now() - lastPointPressRef.current >= FEATURE_PRESS_WINDOW_MS) onFocusTrip(tripIndex)+ }, LINE_PRESS_DEFER_MS)+ },+ [onFocusTrip]+ )const handleMapPress = useCallback(() => {- if (Date.now() - lastPointPressRef.current < 200) return- setPopup(null)- setSelectedPoint(null)- }, [])+ if (Date.now() - lastFeaturePressRef.current < FEATURE_PRESS_WINDOW_MS) return+ onFocusTrip(null)+ onSelectPoint(null)+ }, [onFocusTrip, onSelectPoint])const initialCenter = useMemo(() => [locations[0]?.longitude ?? 0, locations[0]?.latitude ?? 0] as [number, number],[locations])- // Memoize the map block to prevent popup state changes from triggering re-renders- const mapView = useMemo(- () => (+ const hasPoints = locations.length > 0++ return (+ <View style={StyleSheet.absoluteFill}><ColotaMapViewref={mapRef}initialCenter={initialCenter}- initialZoom={2}+ initialZoom={WORLD_MAP_ZOOM}+ cameraPadding={cameraPadding}+ controlsBottom={controlsBottom}+ controlsEnd={controlsEnd}onPress={handleMapPress}onRegionDidChange={handleRegionChange}onMapReady={handleMapReady}>- <GeoJSONSource id="track-segments" data={segmentsGeoJSON}>- <Layer id="track-line" type="line" style={TRACK_LINE_STYLE} />+ <GeoJSONSource id="track-segments" data={segmentsGeoJSON} onPress={handleLinePress}>+ <Layer id="track-casing" type="line" style={lineStyles.casing} />+ <Layer id="track-line" type="line" style={lineStyles.line} />+ {hasFocus && (+ <>+ <Layer id="track-casing-focused" type="line" filter={FOCUSED_FILTER} style={lineStyles.casingFocused} />+ <Layer id="track-line-focused" type="line" filter={FOCUSED_FILTER} style={lineStyles.lineFocused} />+ </>+ )}</GeoJSONSource>- <GeoJSONSource- id="track-points"- data={pointsGeoJSON}- onPress={handlePointPress}- hitbox={{ top: 10, right: 10, bottom: 10, left: 10 }}- >+ <GeoJSONSource id="track-points" data={pointsGeoJSON} onPress={handlePointPress} hitbox={POINT_HITBOX}><Layer id="track-point-circles" type="circle" style={trackPointStyle} /></GeoJSONSource>+ <GeoJSONSource id="trip-terminals" data={terminalsGeoJSON}>+ <Layer id="trip-start" type="circle" filter={START_FILTER} style={terminalStyles.start} />+ <Layer id="trip-end" type="circle" filter={END_FILTER} style={terminalStyles.end} />+ </GeoJSONSource><GeoJSONSource id="highlight-point" data={highlightGeoJSON}><Layer id="highlight-circle" type="circle" style={highlightStyle} /></GeoJSONSource></ColotaMapView>- ),- [- initialCenter,- handleMapPress,- handleRegionChange,- handleMapReady,- segmentsGeoJSON,- pointsGeoJSON,- highlightGeoJSON,- handlePointPress,- highlightStyle- ]- )-- const isEmpty = locations.length === 0-- return (- <View style={styles.container}>- {mapView}-- {isEmpty && (- <View style={[styles.emptyOverlay, { backgroundColor: colors.card, borderRadius: colors.borderRadius }]}>- <View style={[styles.iconCircle, { backgroundColor: colors.border }]}>- <MapPinOff size={32} color={colors.textSecondary} />- </View>- <Text style={[styles.emptyTitle, { color: colors.text }]}>No Locations</Text>- <Text style={[styles.emptySubtext, { color: colors.textSecondary }]}>No tracked locations for this day.</Text>- </View>- )}- {!isEmpty && popup && (- <View style={[styles.popupCard, { backgroundColor: colors.card, borderColor: colors.border }]}>- <View style={styles.popupHeader}>- <Text style={[styles.popupTime, { color: colors.text }]}>- {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"- onPress={() => onPointDelete(popup.id)}- hitSlop={HIT_SLOP_MD}- style={({ pressed }) => pressed && { opacity: colors.pressedOpacity }}- accessibilityRole="button"- accessibilityLabel="Delete this point"- >- <Trash2 size={16} color={colors.error} />- </Pressable>- )}- <Pressable- onPress={() => {- setPopup(null)- setSelectedPoint(null)- }}- hitSlop={HIT_SLOP_MD}- style={({ pressed }) => pressed && { opacity: colors.pressedOpacity }}- >- <X size={16} color={colors.textSecondary} />- </Pressable>- </View>- </View>- <View style={styles.popupRow}>- <Text style={[styles.popupLabel, { color: colors.textSecondary }]}>Speed</Text>- <Text style={[styles.popupValue, { color: colors.text }]}>- {(popup.speed * speedFactor).toFixed(1)} {speedUnit}- </Text>- </View>- <View style={styles.popupRow}>- <Text style={[styles.popupLabel, { color: colors.textSecondary }]}>Accuracy</Text>- <Text style={[styles.popupValue, { color: colors.text }]}>- {"\u00B1"}- {popup.accuracy.toFixed(0)}m- </Text>- </View>- <View style={styles.popupRow}>- <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- testID="popup-note-input"- 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- testID="popup-note-save"- 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>- )}-- {!isEmpty && <MapCenterButton visible={!isCentered} onPress={handleFitTrack} />}-- {!isEmpty && trips && trips.length > 1 && (- <View style={[styles.legend, { backgroundColor: colors.card, borderColor: colors.border }]}>- {trips.map((trip) => (- <View key={trip.index} style={styles.legendItem}>- <View style={[styles.legendDot, { backgroundColor: getTripColor(trip.index) }]} />- <Text style={[styles.legendLabel, { color: colors.textSecondary }]}>Trip {trip.index}</Text>- </View>- ))}- </View>+ {hasPoints && !isCentered && (+ <MapActionButton+ onPress={handleFitDay}+ anchored={false}+ style={[styles.fitDay, { bottom: controlsBottom + size.iconColumn + space.lg, right: controlsEnd }]}+ accessibilityRole="button"+ accessibilityLabel="Fit the day"+ >+ <LocateFixed size={size.icon.md} color={colors.textLight} />+ </MapActionButton>)}</View>)}const styles = StyleSheet.create({- container: {- flex: 1,- overflow: "hidden"- },- emptyOverlay: {- position: "absolute",- top: 0,- left: 0,- right: 0,- bottom: 0,- justifyContent: "center",- alignItems: "center",- padding: 24,- zIndex: 20- },- iconCircle: {- width: 64,- height: 64,- borderRadius: 32,- justifyContent: "center",- alignItems: "center",- marginBottom: 16- },- emptyTitle: {- fontSize: 18,- ...fonts.bold,- textAlign: "center"- },- emptySubtext: {- fontSize: 14,- textAlign: "center",- marginTop: 8,- lineHeight: 20- },- popupCard: {- position: "absolute",- top: 10,- left: 10,- right: 10,- padding: 12,- borderRadius: 12,- borderWidth: 1,- elevation: 6,- shadowColor: "#000",- shadowOffset: { width: 0, height: 4 },- shadowOpacity: 0.2,- shadowRadius: 6,- zIndex: 10- },- popupHeader: {- flexDirection: "row",- justifyContent: "space-between",- alignItems: "center",- marginBottom: 4- },- popupActions: {- flexDirection: "row",- alignItems: "center",- // Both icons carry HIT_SLOP_MD, so a smaller gap overlaps delete with close- gap: 20- },- popupTime: {- fontWeight: "600",- fontSize: 13- },- popupRow: {- flexDirection: "row",- justifyContent: "space-between"- },- popupLabel: {- fontSize: 11,- textTransform: "uppercase",- fontWeight: "600"- },- popupValue: {- 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,- left: 10,- borderRadius: 12,- borderWidth: 1,- padding: 8,- gap: 4,- elevation: 4,- shadowColor: "#000",- shadowOffset: { width: 0, height: 2 },- shadowOpacity: 0.15,- shadowRadius: 4,- zIndex: 10- },- legendItem: {- flexDirection: "row",- alignItems: "center",- gap: 6- },- legendDot: {- width: 10,- height: 10,- borderRadius: 5- },- legendLabel: {- fontSize: 11,- fontWeight: "500"- }+ fitDay: { position: "absolute" }})diff --git a/apps/mobile/src/components/features/inspector/TripList.tsx b/apps/mobile/src/components/features/inspector/TripList.tsxindex c0554e03..a01e483b 100644--- a/apps/mobile/src/components/features/inspector/TripList.tsx+++ b/apps/mobile/src/components/features/inspector/TripList.tsx@@ -3,518 +3,52 @@* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.*/-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, Merge } from "lucide-react-native"+import React from "react"+import { ScrollView, StyleSheet } from "react-native"import { Card } from "../../ui/Card"-import { fonts } from "../../../styles/typography"-import { formatDistance, formatDuration, formatSpeed, formatTime } from "../../../utils/geo"-import type { Trip, ThemeColors } from "../../../types/global"-import { getTripColor, computeTripStats, type TripStats } from "../../../utils/trips"-import { EXPORT_FORMATS, EXPORT_FORMAT_KEYS, type ExportFormat } from "../../../utils/exportConverters"-import { HIT_SLOP_SM } from "../../../constants"+import { Divider } from "../../ui/Divider"+import { TripRow } from "./TripRow"+import { space } from "../../../constants"+import type { Trip } from "../../../types/global"-interface TripListProps {+type TripListProps = {trips: Trip[]- colors: ThemeColors- onTripSelect: (trip: Trip) => void- selectedTripIndex?: number | null- onExport?: (format: ExportFormat, trips: Trip[]) => void- onDelete?: (trips: Trip[]) => Promise<void>- onMerge?: (trips: Trip[]) => Promise<void>+ selected: Set<number>+ onToggle: (index: number) => void+ onEnterSelection: (index: number) => void+ onOpenTrip: (index: number) => void}-interface TripRowProps {- trip: Trip- colors: ThemeColors- stats: TripStats | undefined- selectionMode: boolean- isCabSelected: boolean- isMapSelected: boolean- onPress: (trip: Trip) => void- onLongPress: (trip: Trip) => void-}--const TripRow = React.memo(function TripRow({- trip,- colors,- stats,- selectionMode,- isCabSelected,- isMapSelected,- onPress,- onLongPress-}: TripRowProps) {- const duration = trip.endTime - trip.startTime- const tripColor = getTripColor(trip.index)- const selectedBorderColor = isCabSelected ? colors.primary : isMapSelected ? tripColor : null-- const cardStyle = [- styles.tripCard,- selectedBorderColor && [styles.tripCardSelected, { borderColor: selectedBorderColor }]- ]-- const accessibilityRole = selectionMode ? "checkbox" : "button"- const accessibilityState = selectionMode ? { checked: isCabSelected } : undefined- const accessibilityLabel = selectionMode- ? `Trip ${trip.index}, ${formatDistance(trip.distance)}, ${formatDuration(duration)}`- : `Trip ${trip.index}, ${formatDistance(trip.distance)}, ${formatDuration(duration)}, open details`-- return (- <Card- variant="interactive"- onPress={() => onPress(trip)}- onLongPress={() => onLongPress(trip)}- style={cardStyle}- accessibilityRole={accessibilityRole}- accessibilityState={accessibilityState}- accessibilityLabel={accessibilityLabel}- accessibilityHint={selectionMode ? undefined : "Long-press to select multiple trips"}- >- <View style={styles.tripHeader}>- <View style={styles.tripTitleRow}>- <View style={[styles.tripDot, { backgroundColor: tripColor }]} />- <Text style={[styles.tripTitle, { color: colors.text }]}>Trip {trip.index}</Text>- </View>- <Text style={[styles.tripTime, { color: colors.textSecondary }]}>- {formatTime(trip.startTime)} - {formatTime(trip.endTime)}- </Text>- </View>-- <View style={styles.tripStats}>- <View style={styles.stat}>- <Route size={13} color={colors.textSecondary} />- <Text style={[styles.statText, { color: colors.text }]}>{formatDistance(trip.distance)}</Text>- </View>- <View style={styles.stat}>- <Clock size={13} color={colors.textSecondary} />- <Text style={[styles.statText, { color: colors.text }]}>{formatDuration(duration)}</Text>- </View>- {stats && stats.avgSpeed > 0 && (- <View style={styles.stat}>- <Gauge size={13} color={colors.textSecondary} />- <Text style={[styles.statText, { color: colors.text }]}>{formatSpeed(stats.avgSpeed)}</Text>- </View>- )}- {stats && stats.elevationGain > 0 && (- <View style={styles.stat}>- <TrendingUp size={13} color={colors.textSecondary} />- <Text style={[styles.statText, { color: colors.text }]}>{Math.round(stats.elevationGain)}m</Text>- </View>- )}- {stats && stats.elevationLoss > 0 && (- <View style={styles.stat}>- <TrendingDown size={13} color={colors.textSecondary} />- <Text style={[styles.statText, { color: colors.text }]}>{Math.round(stats.elevationLoss)}m</Text>- </View>- )}- </View>- </Card>- )-})--export function TripList({- trips,- colors,- onTripSelect,- selectedTripIndex,- onExport,- onDelete,- onMerge-}: TripListProps) {- const [showExport, setShowExport] = useState(false)- const [selected, setSelected] = useState<Set<number>>(new Set())- const selectionMode = selected.size > 0-- useEffect(() => {- setSelected(new Set())- setShowExport(false)- }, [trips])-- useEffect(() => {- if (!selectionMode) return- const sub = BackHandler.addEventListener("hardwareBackPress", () => {- setSelected(new Set())- setShowExport(false)- return true- })- return () => sub.remove()- }, [selectionMode])-- const selectedTrips = useMemo(() => trips.filter((t) => selected.has(t.index)), [trips, selected])- const allSelected = selectionMode && selected.size === trips.length- // 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)-- const statsCache = useMemo(() => {- const map = new Map<number, TripStats>()- for (const trip of trips) {- map.set(trip.index, computeTripStats(trip.locations))- }- return map- }, [trips])-- const selectionModeRef = useRef(selectionMode)- selectionModeRef.current = selectionMode- const onTripSelectRef = useRef(onTripSelect)- onTripSelectRef.current = onTripSelect-- const handleRowPress = useCallback((trip: Trip) => {- if (selectionModeRef.current) {- setSelected((prev) => {- const next = new Set(prev)- if (next.has(trip.index)) next.delete(trip.index)- else next.add(trip.index)- return next- })- } else {- onTripSelectRef.current(trip)- }- }, [])-- const handleRowLongPress = useCallback((trip: Trip) => {- setSelected((prev) => {- const next = new Set(prev)- next.add(trip.index)- return next- })- setShowExport(false)- }, [])-- const handleSelectAllToggle = useCallback(() => {- setSelected((prev) => (prev.size === trips.length ? new Set() : new Set(trips.map((t) => t.index))))- }, [trips])-- const handleCancelSelection = useCallback(() => {- setSelected(new Set())- setShowExport(false)- }, [])-- const deletingRef = useRef(false)- const handleDeleteSelected = useCallback(async () => {- if (!onDelete || selectedTrips.length === 0 || deletingRef.current) return- deletingRef.current = true- try {- await onDelete(selectedTrips)- setSelected(new Set())- setShowExport(false)- } finally {- deletingRef.current = false- }- }, [onDelete, selectedTrips])-- const 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- trip={item}- colors={colors}- stats={statsCache.get(item.index)}- selectionMode={selectionMode}- isCabSelected={selected.has(item.index)}- isMapSelected={!selectionMode && selectedTripIndex === item.index}- onPress={handleRowPress}- onLongPress={handleRowLongPress}- />- ),- [colors, statsCache, selectionMode, selected, selectedTripIndex, handleRowPress, handleRowLongPress]- )-- if (trips.length === 0) {- return (- <View style={styles.emptyContainer}>- <Route size={40} color={colors.textDisabled} />- <Text style={[styles.emptyText, { color: colors.textSecondary }]}>No trips for this day</Text>- <Text style={[styles.emptyHint, { color: colors.textDisabled }]}>Need at least 2 points to form a trip</Text>- </View>- )- }+export function TripList({ trips, selected, onToggle, onEnterSelection, onOpenTrip }: TripListProps) {+ if (trips.length === 0) return null+ const selecting = selected.size > 0return (- <View style={styles.container}>- {selectionMode ? (- <View style={[styles.headerRow, { backgroundColor: colors.primary + "12" }]}>- <View style={styles.cabLeft}>- <Pressable- onPress={handleCancelSelection}- hitSlop={HIT_SLOP_SM}- style={({ pressed }) => [styles.cabIconBtn, pressed && { opacity: colors.pressedOpacity }]}- accessibilityRole="button"- accessibilityLabel="Cancel selection"- >- <X size={18} color={colors.text} />- </Pressable>- <Text style={[styles.cabSummary, { color: colors.text }]}>{selected.size} selected</Text>- </View>- <View style={styles.cabActions}>- <Pressable- onPress={handleSelectAllToggle}- hitSlop={HIT_SLOP_SM}- style={({ pressed }) => [styles.cabTextBtn, pressed && { opacity: colors.pressedOpacity }]}- accessibilityRole="button"- accessibilityLabel={allSelected ? "Clear selection" : "Select all trips"}- >- <Text style={[styles.cabTextBtnLabel, { color: allSelected ? colors.primary : colors.text }]}>- {allSelected ? "Clear" : "All"}- </Text>- </Pressable>- {onExport && (- <Pressable- onPress={() => setShowExport((prev) => !prev)}- hitSlop={HIT_SLOP_SM}- style={({ pressed }) => [styles.cabIconBtn, pressed && { opacity: colors.pressedOpacity }]}- accessibilityRole="button"- accessibilityLabel="Export selected trips"- accessibilityState={{ expanded: showExport }}- >- <Share size={18} color={showExport ? colors.primary : colors.text} />- </Pressable>- )}- {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}- hitSlop={HIT_SLOP_SM}- style={({ pressed }) => [styles.cabIconBtn, pressed && { opacity: colors.pressedOpacity }]}- accessibilityRole="button"- accessibilityLabel="Delete selected trips"- >- <Trash2 size={18} color={colors.error} />- </Pressable>- )}- </View>- </View>- ) : (- <View style={styles.headerRow}>- <Text style={[styles.summary, { color: colors.textSecondary }]}>- {trips.length} {trips.length === 1 ? "trip" : "trips"} · {formatDistance(totalDistance)}- </Text>- {onExport && (- <Pressable- onPress={() => setShowExport((prev) => !prev)}- style={({ pressed }) => [styles.exportAllBtn, pressed && { opacity: colors.pressedOpacity }]}- accessibilityRole="button"- accessibilityLabel="Export all trips"- accessibilityState={{ expanded: showExport }}- >- <Share size={14} color={showExport ? colors.primary : colors.textSecondary} />- <Text style={[styles.exportAllLabel, { color: showExport ? colors.primary : colors.textSecondary }]}>- Export All- </Text>- </Pressable>- )}- </View>- )}- {showExport && onExport && (- <View style={styles.exportRow}>- {EXPORT_FORMAT_KEYS.map((fmt) => (- <Pressable- key={fmt}- onPress={() => {- onExport(fmt, selectionMode ? selectedTrips : trips)- setShowExport(false)- if (selectionMode) setSelected(new Set())- }}- style={({ pressed }) => [- styles.exportChip,- { backgroundColor: colors.primary + "12", borderColor: colors.primary + "30" },- pressed && { opacity: colors.pressedOpacity }- ]}- accessibilityRole="button"- accessibilityLabel={- selectionMode- ? `Export ${selectedTrips.length} selected trips as ${EXPORT_FORMATS[fmt].label}`- : `Export all trips as ${EXPORT_FORMATS[fmt].label}`- }- >- <Text style={[styles.exportChipText, { color: colors.primary }]}>{EXPORT_FORMATS[fmt].label}</Text>- </Pressable>- ))}- </View>- )}- <FlatList- data={trips}- renderItem={renderTrip}- keyExtractor={(item) => `trip-${item.index}`}- contentContainerStyle={styles.list}- extraData={selected}- />- </View>+ <ScrollView contentContainerStyle={styles.content}>+ <Card rows>+ {trips.map((trip, i) => (+ <React.Fragment key={trip.index}>+ {i > 0 && <Divider tight inset />}+ <TripRow+ trip={trip}+ index={trip.index}+ selected={selected.has(trip.index)}+ selecting={selecting}+ onPress={() => (selecting ? onToggle(trip.index) : onOpenTrip(trip.index))}+ onLongPress={() => (selecting ? onToggle(trip.index) : onEnterSelection(trip.index))}+ testID={`trip-row-${trip.index}`}+ />+ </React.Fragment>+ ))}+ </Card>+ </ScrollView>)}const styles = StyleSheet.create({- container: {- flex: 1- },- headerRow: {- flexDirection: "row",- alignItems: "center",- justifyContent: "space-between",- paddingHorizontal: 16,- paddingTop: 10,- paddingBottom: 14,- minHeight: 54- },- cabLeft: {- flexDirection: "row",- alignItems: "center",- gap: 4,- flexShrink: 1- },- cabSummary: {- fontSize: 13,- ...fonts.semiBold- },- cabActions: {- flexDirection: "row",- alignItems: "center",- gap: 4- },- cabIconBtn: {- minWidth: 48,- minHeight: 48,- alignItems: "center",- justifyContent: "center"- },- cabTextBtn: {- minHeight: 48,- paddingHorizontal: 10,- alignItems: "center",- justifyContent: "center"- },- cabTextBtnLabel: {- fontSize: 13,- ...fonts.semiBold- },- summary: {- fontSize: 12,- ...fonts.semiBold- },- exportAllBtn: {- flexDirection: "row",- alignItems: "center",- gap: 4,- paddingHorizontal: 12,- minHeight: 48- },- exportAllLabel: {- fontSize: 11,- ...fonts.semiBold- },- exportRow: {- flexDirection: "row",- gap: 8,- paddingHorizontal: 16,- paddingTop: 10,- paddingBottom: 12- },- exportChip: {- paddingHorizontal: 10,- paddingVertical: 5,- borderRadius: 8,- borderWidth: 1- },- exportChipText: {- fontSize: 11,- ...fonts.bold- },- list: {- paddingHorizontal: 12,- paddingBottom: 16- },- tripCard: {- marginBottom: 8- },- tripCardSelected: {- borderWidth: 1.5- },- tripHeader: {- flexDirection: "row",- justifyContent: "space-between",- alignItems: "center",- marginBottom: 8- },- tripTitleRow: {- flexDirection: "row",- alignItems: "center",- gap: 8- },- tripDot: {- width: 8,- height: 8,- borderRadius: 4- },- tripTitle: {- fontSize: 15,- ...fonts.bold- },- tripTime: {- fontSize: 13,- ...fonts.regular- },- tripStats: {- flexDirection: "row",- flexWrap: "wrap",- gap: 12- },- stat: {- flexDirection: "row",- alignItems: "center",- gap: 4- },- statText: {- fontSize: 13,- ...fonts.regular- },- emptyContainer: {- flex: 1,- alignItems: "center",- justifyContent: "center",- gap: 8,- paddingTop: 60- },- emptyText: {- fontSize: 14,- ...fonts.regular- },- emptyHint: {- fontSize: 12,- ...fonts.regular+ content: {+ paddingHorizontal: space.lg,+ paddingTop: space.lg,+ paddingBottom: space.xxl}})diff --git a/apps/mobile/src/components/features/inspector/TripRow.tsx b/apps/mobile/src/components/features/inspector/TripRow.tsxnew file mode 100644index 00000000..bcc44dde--- /dev/null+++ b/apps/mobile/src/components/features/inspector/TripRow.tsx@@ -0,0 +1,128 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import React, { useMemo } from "react"+import { Pressable, StyleSheet, Text, View } from "react-native"+import { Check } from "lucide-react-native"+import { radius } from "@colota/shared"+import { useTheme } from "../../../hooks/useTheme"+import { fontSizes, fonts, lineHeights } from "../../../styles/typography"+import { size, space, STATE_LAYER_ALPHA } from "../../../constants"+import { formatDistance, formatDuration, formatSpeed, formatTime, spokenDistance } from "../../../utils/geo"+import { computeTripStats, getTripColor } from "../../../utils/trips"+import type { Trip } from "../../../types/global"++type TripRowProps = {+ trip: Trip+ index: number+ selected: boolean+ selecting: boolean+ onPress: () => void+ onLongPress: () => void+ testID?: string+}++function spokenDuration(seconds: number): string {+ const s = Math.max(0, seconds)+ const hours = Math.floor(s / 3600)+ const minutes = Math.floor((s % 3600) / 60)+ const parts: string[] = []+ if (hours > 0) parts.push(`${hours} ${hours === 1 ? "hour" : "hours"}`)+ parts.push(`${minutes} ${minutes === 1 ? "minute" : "minutes"}`)+ return parts.join(" ")+}++/** The trip's colour as an 8 dp dot, the same mark the map draws the trip in. */+export function TripSwatch({ index }: { index: number }) {+ return <View style={[styles.swatch, { backgroundColor: getTripColor(index) }]} />+}++export function TripRow({ trip, index, selected, selecting, onPress, onLongPress, testID }: TripRowProps) {+ const { colors } = useTheme()+ const duration = trip.endTime - trip.startTime+ const avgSpeed = useMemo(() => computeTripStats(trip.locations).avgSpeed, [trip.locations])+ const start = formatTime(trip.startTime)+ const end = formatTime(trip.endTime)+ const detail = [formatDistance(trip.distance), formatDuration(duration), avgSpeed > 0 ? formatSpeed(avgSpeed) : null]+ .filter(Boolean)+ .join(" · ")++ const content = selected ? colors.onPrimaryContainer : colors.text+ const subContent = selected ? colors.onPrimaryContainer : colors.textSecondary++ return (+ <Pressable+ testID={testID}+ accessibilityRole="button"+ accessibilityLabel={`Trip ${index}, ${start} to ${end}, ${spokenDistance(trip.distance)}, ${spokenDuration(duration)}`}+ accessibilityHint={selecting ? undefined : "Opens trip details"}+ accessibilityState={{ selected }}+ android_ripple={{ color: colors.text + STATE_LAYER_ALPHA }}+ onPress={onPress}+ onLongPress={onLongPress}+ style={[styles.row, selected && { backgroundColor: colors.primaryContainer }]}+ >+ <View style={styles.glyph}>+ {selected ? <Check size={size.icon.md} color={content} /> : <TripSwatch index={index} />}+ </View>+ <View style={styles.column}>+ <View style={styles.titleRow}>+ <Text style={[styles.title, { color: content }]}>Trip {index}</Text>+ <Text style={[styles.time, { color: subContent }]}>+ {start} - {end}+ </Text>+ </View>+ <Text style={[styles.detail, { color: subContent }]}>{detail}</Text>+ </View>+ </Pressable>+ )+}++const styles = StyleSheet.create({+ row: {+ flexDirection: "row",+ alignItems: "center",+ gap: space.lg,+ minHeight: size.row,+ paddingVertical: space.md,+ marginHorizontal: -space.lg,+ paddingHorizontal: space.lg+ },+ glyph: {+ width: size.icon.md,+ alignItems: "center"+ },+ swatch: {+ width: 8,+ height: 8,+ borderRadius: radius.pill+ },+ column: {+ flex: 1+ },+ titleRow: {+ flexDirection: "row",+ flexWrap: "wrap",+ alignItems: "flex-start",+ gap: space.sm+ },+ title: {+ flexGrow: 1,+ fontSize: fontSizes.label,+ ...fonts.semiBold+ },+ time: {+ fontSize: fontSizes.caption,+ lineHeight: lineHeights.caption,+ ...fonts.regular,+ fontVariant: ["tabular-nums"]+ },+ detail: {+ fontSize: fontSizes.description,+ lineHeight: lineHeights.description,+ ...fonts.regular,+ marginTop: space.xxs+ }+})diff --git a/apps/mobile/src/components/features/inspector/__tests__/CalendarPicker.test.tsx b/apps/mobile/src/components/features/inspector/__tests__/CalendarPicker.test.tsxnew file mode 100644index 00000000..2cf8646e--- /dev/null+++ b/apps/mobile/src/components/features/inspector/__tests__/CalendarPicker.test.tsx@@ -0,0 +1,272 @@+import React from "react"+import { render, fireEvent } from "@testing-library/react-native"+import { StyleSheet } from "react-native"+import { lightColors, radius } from "@colota/shared"+import { size, space } from "../../../../constants"+import type { DailyStat } from "../../../../types/global"++jest.mock("../../../../hooks/useTheme", () => ({+ useTheme: () => ({ colors: require("@colota/shared").lightColors })+}))++jest.mock("../../../../utils/geo", () => ({+ formatDistance: (m: number) => `${(m / 1000).toFixed(1)} km`,+ spokenDistance: (m: number) => `${(m / 1000).toFixed(1)} kilometres`+}))++import { CalendarPicker, dayCellLabel } from "../CalendarPicker"++// September 2026, so August is a reachable past month and October a refused future one.+const TODAY = new Date(2026, 8, 15)++function stat(day: string, overrides: Partial<DailyStat> = {}): DailyStat {+ return { day, count: 412, startTime: 0, endTime: 0, distanceMeters: 12_400, tripCount: 3, ...overrides }+}++function renderPicker(overrides: Partial<React.ComponentProps<typeof CalendarPicker>> = {}) {+ const onMonthChange = jest.fn()+ const onSelectDay = jest.fn()+ const view = render(+ <CalendarPicker+ date={new Date(2026, 8, 15)}+ onSelectDay={onSelectDay}+ colors={lightColors}+ daysWithData={new Set()}+ dayStats={new Map()}+ onMonthChange={onMonthChange}+ {...overrides}+ />+ )+ return { ...view, onMonthChange, onSelectDay }+}++function discOf(view: ReturnType<typeof renderPicker>, day: number) {+ return StyleSheet.flatten(view.getByTestId(`day-disc-${day}`).props.style)+}++function numeralOf(view: ReturnType<typeof renderPicker>, day: number) {+ return StyleSheet.flatten(view.getByText(String(day)).props.style)+}++beforeAll(() => {+ jest.useFakeTimers()+ jest.setSystemTime(TODAY)+})++afterAll(() => {+ jest.useRealTimers()+})++describe("CalendarPicker day grid", () => {+ it("opens on the day pane of the month the shown day belongs to", () => {+ const view = renderPicker({ date: new Date(2026, 7, 3) })++ expect(view.getByText("August 2026")).toBeTruthy()+ expect(view.getByTestId("prev-month-btn")).toBeTruthy()+ expect(view.getByTestId("day-31")).toBeTruthy()+ expect(view.queryByTestId("year-pane")).toBeNull()+ })++ it("hands back the tapped day so the screen can jump to it", () => {+ const view = renderPicker()++ fireEvent.press(view.getByTestId("day-3"))++ expect(view.onSelectDay).toHaveBeenCalledTimes(1)+ expect(view.onSelectDay.mock.calls[0][0].getTime()).toBe(new Date(2026, 8, 3).getTime())+ })++ it("marks today with a ring and the shown day with a fill, never with a border that comes and goes", () => {+ const view = renderPicker({ date: new Date(2026, 8, 3) })++ const today = discOf(view, 15)+ expect(today.borderWidth).toBe(1)+ expect(today.borderColor).toBe(lightColors.primary)+ expect(today.backgroundColor).toBeUndefined()+ expect(numeralOf(view, 15).color).toBe(lightColors.text)++ const selected = discOf(view, 3)+ expect(selected.borderWidth).toBe(1)+ expect(selected.borderColor).toBe("transparent")+ expect(selected.backgroundColor).toBe(lightColors.primary)+ expect(numeralOf(view, 3).color).toBe(lightColors.textOnPrimary)++ const plain = discOf(view, 7)+ expect(plain.borderWidth).toBe(1)+ expect(plain.borderColor).toBe("transparent")+ expect(plain.width).toBe(size.iconColumn)+ expect(plain.borderRadius).toBe(radius.pill)+ })++ it("shows a dot under a day that holds data and nothing under one that does not", () => {+ const view = renderPicker({ daysWithData: new Set(["2026-09-03"]) })++ const dot = StyleSheet.flatten(view.getByTestId("day-dot-3").props.style)+ expect(dot.width).toBe(space.xs)+ expect(dot.height).toBe(space.xs)+ expect(dot.borderRadius).toBe(radius.pill)+ expect(dot.backgroundColor).toBe(lightColors.primary)++ expect(view.queryByTestId("day-dot-7")).toBeNull()+ })++ it("refuses days after today", () => {+ const view = renderPicker()++ fireEvent.press(view.getByTestId("day-16"))++ expect(view.onSelectDay).not.toHaveBeenCalled()+ expect(view.getByTestId("day-16").props.accessibilityState).toMatchObject({ disabled: true })+ expect(numeralOf(view, 16).color).toBe(lightColors.textDisabled)+ })++ it("speaks the day's trips, distance and points, because the dot cannot", () => {+ const view = renderPicker({+ daysWithData: new Set(["2026-09-02", "2026-09-05"]),+ dayStats: new Map([+ ["2026-09-02", stat("2026-09-02")],+ ["2026-09-05", stat("2026-09-05", { count: 1, tripCount: 0, distanceMeters: 0 })]+ ])+ })++ expect(view.getByTestId("day-2").props.accessibilityLabel).toBe(+ "Wednesday 2 September, 3 trips, 12.4 kilometres, 412 points"+ )+ expect(view.getByTestId("day-5").props.accessibilityLabel).toBe("Saturday 5 September, no trips, 1 point")+ expect(view.getByTestId("day-7").props.accessibilityLabel).toBe("Monday 7 September, no data")+ expect(view.getByTestId("day-15").props.accessibilityLabel).toBe("Tuesday 15 September, no data, today")+ })++ it("keeps one trip singular", () => {+ expect(dayCellLabel(new Date(2026, 8, 1), stat("2026-09-01", { tripCount: 1, count: 1 }), false)).toBe(+ "Tuesday 1 September, 1 trip, 12.4 kilometres, 1 point"+ )+ })+})++describe("CalendarPicker date panes", () => {+ it("reaches any month without one chevron tap per month", () => {+ const view = renderPicker()++ expect(view.getByTestId("prev-month-btn")).toBeTruthy()+ expect(view.queryByTestId("year-pane")).toBeNull()++ fireEvent.press(view.getByTestId("calendar-pane-btn"))++ expect(view.getByTestId("year-pane")).toBeTruthy()+ // The month chevrons step the day grid, which is no longer on screen.+ expect(view.queryByTestId("prev-month-btn")).toBeNull()+ })++ it("asks the screen for the picked month so its days load", () => {+ const view = renderPicker()++ fireEvent.press(view.getByTestId("calendar-pane-btn"))+ fireEvent.press(view.getByTestId("year-2026"))+ fireEvent.press(view.getByTestId("month-1"))++ expect(view.onMonthChange).toHaveBeenCalledWith(2026, 1)+ expect(view.getByTestId("prev-month-btn")).toBeTruthy()+ })++ it("steps a month with the chevrons and warms the one beyond it", () => {+ const onPrefetchMonth = jest.fn()+ const view = renderPicker({ onPrefetchMonth })++ fireEvent.press(view.getByTestId("prev-month-btn"))++ expect(view.onMonthChange).toHaveBeenCalledWith(2026, 7)+ expect(onPrefetchMonth).toHaveBeenCalledWith(2026, 6)+ expect(view.getByText("August 2026")).toBeTruthy()+ })++ it("will not step into a month that has not happened", () => {+ const view = renderPicker()++ fireEvent.press(view.getByTestId("next-month-btn"))++ expect(view.onMonthChange).not.toHaveBeenCalled()+ expect(view.getByTestId("next-month-btn").props.accessibilityState).toMatchObject({ disabled: true })+ })++ it("crosses a year boundary, which the chevrons need twelve taps for", () => {+ const view = renderPicker()++ fireEvent.press(view.getByTestId("calendar-pane-btn"))+ fireEvent.press(view.getByTestId("year-2021"))+ fireEvent.press(view.getByTestId("month-11"))++ expect(view.onMonthChange).toHaveBeenCalledWith(2021, 11)+ })++ it("offers no year the app cannot hold data for", () => {+ const view = renderPicker()+ fireEvent.press(view.getByTestId("calendar-pane-btn"))++ expect(view.queryByTestId("year-2027")).toBeNull()+ expect(view.getByTestId("year-2000")).toBeTruthy()+ })++ it("refuses months after today, as the forward chevron already does", () => {+ const view = renderPicker()++ fireEvent.press(view.getByTestId("calendar-pane-btn"))+ fireEvent.press(view.getByTestId("year-2026"))+ fireEvent.press(view.getByTestId("month-9"))++ expect(view.onMonthChange).not.toHaveBeenCalled()+ expect(view.getByTestId("month-9").props.accessibilityState).toMatchObject({ disabled: true })+ })++ it("allows a full past year once the year moves back", () => {+ const view = renderPicker()++ fireEvent.press(view.getByTestId("calendar-pane-btn"))+ fireEvent.press(view.getByTestId("year-2025"))++ expect(view.getByTestId("month-9").props.accessibilityState).toMatchObject({ disabled: false })+ })++ it("walks back up a level rather than trapping you in a pane", () => {+ const view = renderPicker()++ fireEvent.press(view.getByTestId("calendar-pane-btn"))+ fireEvent.press(view.getByTestId("year-2025"))+ expect(view.getByTestId("month-pane")).toBeTruthy()++ fireEvent.press(view.getByTestId("calendar-pane-btn"))+ expect(view.getByTestId("year-pane")).toBeTruthy()++ fireEvent.press(view.getByTestId("calendar-pane-btn"))+ expect(view.getByTestId("prev-month-btn")).toBeTruthy()+ expect(view.onMonthChange).not.toHaveBeenCalled()+ })++ it("rings the current year the way the day grid rings today, never as primary text", () => {+ const view = renderPicker({ date: new Date(2025, 8, 3) })++ fireEvent.press(view.getByTestId("calendar-pane-btn"))++ const current = StyleSheet.flatten(view.getByTestId("year-2026").props.style)+ expect(current.borderWidth).toBe(1)+ expect(current.borderColor).toBe(lightColors.primary)+ expect(current.backgroundColor).toBeUndefined()+ expect(StyleSheet.flatten(view.getByText("2026").props.style).color).toBe(lightColors.text)++ const viewed = StyleSheet.flatten(view.getByTestId("year-2025").props.style)+ expect(viewed.borderColor).toBe("transparent")+ expect(viewed.backgroundColor).toBe(lightColors.primaryContainer)+ })++ it("marks the year and month the day grid is showing", () => {+ const view = renderPicker()++ fireEvent.press(view.getByTestId("calendar-pane-btn"))+ expect(view.getByTestId("year-2026").props.accessibilityState).toMatchObject({ checked: true })+ expect(view.getByTestId("year-2025").props.accessibilityState).toMatchObject({ checked: false })++ fireEvent.press(view.getByTestId("year-2026"))+ expect(view.getByTestId("month-8").props.accessibilityState).toMatchObject({ checked: true })+ expect(view.getByTestId("month-7").props.accessibilityState).toMatchObject({ checked: false })+ })+})diff --git a/apps/mobile/src/components/features/inspector/__tests__/DayHeader.test.tsx b/apps/mobile/src/components/features/inspector/__tests__/DayHeader.test.tsxnew file mode 100644index 00000000..cc6f2aff--- /dev/null+++ b/apps/mobile/src/components/features/inspector/__tests__/DayHeader.test.tsx@@ -0,0 +1,176 @@+import React from "react"+import { render, fireEvent } from "@testing-library/react-native"+import { StyleSheet } from "react-native"+import { lightColors } from "@colota/shared"+import { size, space, STATE_LAYER_ALPHA } from "../../../../constants"+import { DayHeader, dayCaption, dayTitle } from "../DayHeader"++jest.mock("../../../../hooks/useTheme", () => ({+ useTheme: () => ({ colors: require("@colota/shared").lightColors })+}))++jest.mock("../../../../utils/geo", () => ({+ formatDistance: (meters: number) => `${(meters / 1000).toFixed(1)} km`+}))++const now = new Date(2026, 8, 8, 14, 30)+const today = new Date(2026, 8, 8)+const yesterday = new Date(2026, 8, 7)+const thisYear = new Date(2026, 8, 3)+const lastYear = new Date(2025, 8, 3)+const withTrips = { points: 412, trips: 3, distanceMeters: 12_400 }++describe("dayTitle", () => {+ it.each([+ ["today reads Today", today, "Today"],+ ["yesterday reads Yesterday", yesterday, "Yesterday"],+ ["a day this year carries weekday and date, no year", thisYear, "Thu, Sep 3"],+ ["a day in another year appends the year", lastYear, "Wed, Sep 3, 2025"]+ ])("%s", (_, date, expected) => {+ expect(dayTitle(date, now)).toBe(expected)+ })++ it("counts calendar days, so last night is Yesterday just after midnight", () => {+ expect(dayTitle(new Date(2026, 8, 7, 23, 59), new Date(2026, 8, 8, 0, 10))).toBe("Yesterday")+ })+})++describe("dayCaption", () => {+ it.each([+ ["loading beats every count", thisYear, withTrips, true, "Loading"],+ ["no stats yet reads as an empty day", thisYear, null, false, "No locations recorded"],+ [+ "zero points reads as an empty day",+ thisYear,+ { points: 0, trips: 0, distanceMeters: 0 },+ false,+ "No locations recorded"+ ],+ [+ "points without trips name the points",+ thisYear,+ { points: 412, trips: 0, distanceMeters: 0 },+ false,+ "412 points · no trips"+ ],+ ["trips lead, then distance, then points", thisYear, withTrips, false, "3 trips · 12.4 km · 412 points"],+ [+ "one trip and one point are singular",+ thisYear,+ { points: 1, trips: 1, distanceMeters: 300 },+ false,+ "1 trip · 0.3 km · 1 point"+ ]+ ])("%s", (_, date, stats, loading, expected) => {+ expect(dayCaption(date, stats, loading, now)).toBe(expected)+ })++ it("prefixes the short date when the title is relative, so Today still says which date it is", () => {+ expect(dayCaption(today, withTrips, false, now)).toBe("Sep 8 · 3 trips · 12.4 km · 412 points")+ expect(dayCaption(yesterday, null, false, now)).toBe("Sep 7 · No locations recorded")+ expect(dayCaption(today, null, true, now)).toBe("Sep 8 · Loading")+ })+})++type Node = { props: { android_ripple?: unknown; disabled?: boolean }; parent: Node | null }++// The ripple lives on the composite Pressable, which the host view the label finds does not carry.+const pressableOf = (host: Node): Node => {+ let node: Node | null = host+ while (node && node.props.android_ripple === undefined && node.props.disabled === undefined) node = node.parent+ return node ?? host+}++const props = {+ date: thisYear,+ stats: withTrips,+ loading: false,+ onPrevious: jest.fn(),+ onNext: jest.fn(),+ onOpenPicker: jest.fn(),+ nextDisabled: false+}++describe("DayHeader", () => {+ beforeEach(() => jest.clearAllMocks())++ it("shows the day as a title over its ledger, the two lines the screen is read by", () => {+ const { getByText } = render(<DayHeader {...props} />)++ expect(getByText("Thu, Sep 3")).toBeTruthy()+ expect(getByText("3 trips · 12.4 km · 412 points")).toBeTruthy()+ })++ it("speaks the full date and the ledger on the title button, so the calendar is found by ear", () => {+ const { getByTestId } = render(<DayHeader {...props} />)++ const centre = getByTestId("day-title")+ expect(centre.props.accessibilityRole).toBe("button")+ expect(centre.props.accessibilityLabel).toBe("Change day, Thursday, September 3, 3 trips · 12.4 km · 412 points")+ expect(centre.props.accessibilityHint).toBe("Opens the calendar")+ })++ it("steps a day with each chevron and opens the picker from the title", () => {+ const { getByLabelText, getByTestId } = render(<DayHeader {...props} />)++ fireEvent.press(getByLabelText("Previous day"))+ fireEvent.press(getByLabelText("Next day"))+ fireEvent.press(getByTestId("day-title"))++ expect(props.onPrevious).toHaveBeenCalledTimes(1)+ expect(props.onNext).toHaveBeenCalledTimes(1)+ expect(props.onOpenPicker).toHaveBeenCalledTimes(1)+ })++ it("disables the next chevron on today, dims its glyph and drops the ripple, with Today as the second signal", () => {+ const { getByLabelText, getByTestId, getByText } = render(<DayHeader {...props} date={new Date()} nextDisabled />)++ const next = getByLabelText("Next day")+ fireEvent.press(next)+ expect(props.onNext).not.toHaveBeenCalled()+ expect(next.props.accessibilityState).toEqual({ disabled: true })+ expect(pressableOf(next as unknown as Node).props.android_ripple).toBeUndefined()+ expect(getByTestId("icon-ChevronRight").props.color).toBe(lightColors.textDisabled)+ expect(getByText("Today")).toBeTruthy()+ })++ it("draws the chevrons as bare glyphs in 48 dp targets with a borderless ripple, not as discs", () => {+ const { getByLabelText, getByTestId } = render(<DayHeader {...props} />)++ const previous = getByLabelText("Previous day")+ expect(StyleSheet.flatten(previous.props.style).width).toBe(size.touch)+ expect(StyleSheet.flatten(previous.props.style).minHeight).toBe(size.touch)+ expect(StyleSheet.flatten(getByTestId("day-title").props.style).minHeight).toBe(size.touch)+ expect(pressableOf(previous as unknown as Node).props.android_ripple).toEqual({+ color: lightColors.text + STATE_LAYER_ALPHA,+ borderless: true,+ radius: size.touch / 2+ })+ expect(getByTestId("icon-ChevronLeft").props.color).toBe(lightColors.text)+ expect(getByTestId("icon-ChevronLeft").props.size).toBe(size.icon.md)+ })++ it("sits at row height on the plain background, so the header draws no band over the tiles", () => {+ const { getByTestId } = render(<DayHeader {...props} />)++ const row = StyleSheet.flatten(getByTestId("day-header").props.style)+ expect(row.minHeight).toBe(size.row)+ expect(row.backgroundColor).toBe(lightColors.background)+ expect(row.paddingHorizontal).toBe(space.sm)+ expect(row.minHeight - 2 * row.paddingVertical).toBe(size.touch)+ })++ it("gives the ledger tabular figures and a second line, so stepping days never jitters and a large font never truncates it", () => {+ const { getByText } = render(<DayHeader {...props} />)++ const caption = getByText("3 trips · 12.4 km · 412 points")+ expect(StyleSheet.flatten(caption.props.style).fontVariant).toEqual(["tabular-nums"])+ expect(caption.props.numberOfLines).toBe(2)+ })++ it("reads Loading while the day is fetched, so an empty caption never flashes between days", () => {+ const { getByText } = render(<DayHeader {...props} stats={null} loading />)++ expect(getByText("Loading")).toBeTruthy()+ })+})diff --git a/apps/mobile/src/components/features/inspector/__tests__/DayPickerModal.test.tsx b/apps/mobile/src/components/features/inspector/__tests__/DayPickerModal.test.tsxnew file mode 100644index 00000000..6bef34cb--- /dev/null+++ b/apps/mobile/src/components/features/inspector/__tests__/DayPickerModal.test.tsx@@ -0,0 +1,144 @@+import React from "react"+import { render, fireEvent } from "@testing-library/react-native"+import { Modal, StyleSheet } from "react-native"+import { space } from "../../../../constants"++jest.mock("../../../../hooks/useTheme", () => ({+ useTheme: () => ({ colors: require("@colota/shared").lightColors })+}))++import { DayPickerModal } from "../DayPickerModal"++// September 2026, so the 15th is today and the 16th is a refused future day.+const TODAY = new Date(2026, 8, 15)++function renderModal(overrides: Partial<React.ComponentProps<typeof DayPickerModal>> = {}) {+ const onSelect = jest.fn()+ const onRequestClose = jest.fn()+ const view = render(+ <DayPickerModal+ visible+ date={new Date(2026, 8, 3)}+ onSelect={onSelect}+ onRequestClose={onRequestClose}+ daysWithData={new Set(["2026-09-03"])}+ dayStats={new Map()}+ onMonthChange={jest.fn()}+ {...overrides}+ />+ )+ return { ...view, onSelect, onRequestClose }+}++beforeAll(() => {+ jest.useFakeTimers()+ jest.setSystemTime(TODAY)+})++afterAll(() => {+ jest.useRealTimers()+})++describe("DayPickerModal", () => {+ it("opens on the day pane of the shown day's month with the grid gutter", () => {+ const view = renderModal()++ expect(view.getByText("September 2026")).toBeTruthy()+ expect(view.getByTestId("day-3").props.accessibilityState).toMatchObject({ selected: true })+ expect(view.queryByTestId("year-pane")).toBeNull()++ const scrim = StyleSheet.flatten(view.getByTestId("dialog-scrim").props.style)+ const card = StyleSheet.flatten(view.getByTestId("dialog-card").props.style)+ expect(scrim.paddingHorizontal).toBe(space.lg)+ expect(card.padding).toBe(space.md)+ })++ it("hands the picker the month's data and its month changes, so the dots and the prefetch survive the dialog", () => {+ const onMonthChange = jest.fn()+ const onPrefetchMonth = jest.fn()+ const view = renderModal({+ dayStats: new Map([+ [+ "2026-09-03",+ { day: "2026-09-03", count: 412, startTime: 0, endTime: 0, distanceMeters: 12_400, tripCount: 3 }+ ]+ ]),+ onMonthChange,+ onPrefetchMonth+ })++ expect(view.getByTestId("day-dot-3")).toBeTruthy()+ expect(view.getByTestId("day-3").props.accessibilityLabel).toMatch(/, 3 trips, .+, 412 points$/)++ fireEvent.press(view.getByTestId("prev-month-btn"))+ expect(onMonthChange).toHaveBeenCalledWith(2026, 7)+ expect(onPrefetchMonth).toHaveBeenCalledWith(2026, 6)+ })++ it("renders nothing while closed", () => {+ const view = renderModal({ visible: false })++ expect(view.queryByText("September 2026")).toBeNull()+ expect(view.queryByTestId("day-3")).toBeNull()+ })++ it("selects the tapped day and closes in one tap", () => {+ const view = renderModal()++ fireEvent.press(view.getByTestId("day-9"))++ expect(view.onSelect).toHaveBeenCalledTimes(1)+ expect(view.onSelect.mock.calls[0][0].getTime()).toBe(new Date(2026, 8, 9).getTime())+ expect(view.onRequestClose).toHaveBeenCalledTimes(1)+ })++ it("comes back on the day pane after a walk into the years and a close", () => {+ const view = renderModal()++ fireEvent.press(view.getByTestId("calendar-pane-btn"))+ expect(view.getByTestId("year-pane")).toBeTruthy()++ view.rerender(+ <DayPickerModal+ visible={false}+ date={new Date(2026, 8, 3)}+ onSelect={view.onSelect}+ onRequestClose={view.onRequestClose}+ daysWithData={new Set()}+ dayStats={new Map()}+ onMonthChange={jest.fn()}+ />+ )+ view.rerender(+ <DayPickerModal+ visible+ date={new Date(2026, 8, 3)}+ onSelect={view.onSelect}+ onRequestClose={view.onRequestClose}+ daysWithData={new Set()}+ dayStats={new Map()}+ onMonthChange={jest.fn()}+ />+ )++ expect(view.queryByTestId("year-pane")).toBeNull()+ expect(view.getByTestId("day-3")).toBeTruthy()+ })++ it("closes from the footer, the scrim and hardware back without picking a day", () => {+ const view = renderModal()++ fireEvent.press(view.getByRole("button", { name: "Close" }))+ fireEvent.press(view.getByTestId("dialog-scrim"))+ view.UNSAFE_getByType(Modal).props.onRequestClose()++ expect(view.onRequestClose).toHaveBeenCalledTimes(3)+ expect(view.onSelect).not.toHaveBeenCalled()+ })++ it("carries no Today button, the header action covers it", () => {+ const view = renderModal()++ expect(view.queryByText("Today")).toBeNull()+ })+})diff --git a/apps/mobile/src/components/features/inspector/__tests__/InspectorDock.test.tsx b/apps/mobile/src/components/features/inspector/__tests__/InspectorDock.test.tsxnew file mode 100644index 00000000..0347872e--- /dev/null+++ b/apps/mobile/src/components/features/inspector/__tests__/InspectorDock.test.tsx@@ -0,0 +1,184 @@+import React from "react"+import { render, fireEvent } from "@testing-library/react-native"+import { ScrollView, StyleSheet } from "react-native"+import { CirclePause } from "lucide-react-native"+import { lightColors } from "@colota/shared"+import { space } from "../../../../constants"+import type { Trip } from "../../../../types/global"+import { Card } from "../../../ui/Card"+import { Divider } from "../../../ui/Divider"+import { InspectorDock, type DockContent } from "../InspectorDock"+import { TripRow } from "../TripRow"++jest.mock("../../../../hooks/useTheme", () => ({+ useTheme: () => ({ colors: require("@colota/shared").lightColors })+}))++jest.mock("../../../../utils/geo", () => ({+ formatDistance: (m: number) => `${(m / 1000).toFixed(1)} km`,+ spokenDistance: (m: number) => `${(m / 1000).toFixed(1)} kilometres`,+ formatDuration: (s: number) => `${Math.round(s / 60)}min`,+ formatSpeed: (mps: number) => `${(mps * 3.6).toFixed(1)} km/h`,+ formatTime: (ts: number, seconds?: boolean) => {+ const h = Math.floor(ts / 3600)+ const m = Math.floor((ts % 3600) / 60)+ const pad = (n: number) => String(n).padStart(2, "0")+ return seconds ? `${pad(h)}:${pad(m)}:${pad(ts % 60)}` : `${pad(h)}:${pad(m)}`+ }+}))++function makeTrip(index: number, startHour: number): Trip {+ const start = startHour * 3600+ const end = start + 6 * 60+ return {+ index,+ locations: [+ { latitude: 0, longitude: 0, timestamp: start, speed: 5 },+ { latitude: 0.01, longitude: 0, timestamp: end, speed: 5 }+ ],+ startTime: start,+ endTime: end,+ distance: 1100,+ locationCount: 2,+ startIndex: 0+ }+}++const trips = [makeTrip(1, 8), makeTrip(2, 12), makeTrip(3, 17)]++function renderDock(content: DockContent, props: Partial<React.ComponentProps<typeof InspectorDock>> = {}) {+ return render(<InspectorDock content={content} left={16} right={16} maxHeight={400} {...props} />)+}++describe("InspectorDock", () => {+ it("summarises the day over one chip per trip, so ten trips take no more of the map than one", () => {+ const many = Array.from({ length: 10 }, (_, i) => makeTrip(i + 1, 7 + i))+ const { getByTestId, UNSAFE_queryAllByType } = renderDock({+ kind: "legend",+ trips: many,+ focusedTripIndex: null,+ onFocusTrip: jest.fn()+ })++ expect(getByTestId("dock-legend").props.accessibilityLabel).toBe("10 trips, 07:00 - 16:06 · 11.0 km")+ expect(UNSAFE_queryAllByType(TripRow)).toHaveLength(0)+ expect(getByTestId("dock-trip-strip").props.horizontal).toBe(true)+ for (let i = 1; i <= 10; i++) expect(getByTestId(`dock-trip-${i}`)).toBeTruthy()+ })++ it("focuses a trip from its chip and shows that trip's row in place of the summary until it is tapped off", () => {+ const onFocusTrip = jest.fn()+ const { getByTestId, queryByTestId, rerender } = renderDock({+ kind: "legend",+ trips,+ focusedTripIndex: null,+ onFocusTrip+ })++ fireEvent.press(getByTestId("dock-trip-2"))+ expect(onFocusTrip).toHaveBeenLastCalledWith(2)+ expect(getByTestId("dock-trip-2").props.accessibilityState.selected).toBe(false)++ rerender(+ <InspectorDock+ content={{ kind: "legend", trips, focusedTripIndex: 2, onFocusTrip }}+ left={16}+ right={16}+ maxHeight={400}+ />+ )+ expect(getByTestId("dock-trip-2").props.accessibilityState.selected).toBe(true)+ expect(getByTestId("dock-trip-1").props.accessibilityState.selected).toBe(false)+ expect(queryByTestId("dock-legend")).toBeNull()+ expect(getByTestId("dock-focused-trip").props.accessibilityState.selected).toBe(true)+ expect(getByTestId("dock-focused-trip").props.accessibilityHint).toBeUndefined()++ fireEvent.press(getByTestId("dock-trip-2"))+ expect(onFocusTrip).toHaveBeenLastCalledWith(null)+ fireEvent.press(getByTestId("dock-focused-trip"))+ expect(onFocusTrip).toHaveBeenLastCalledWith(null)+ })++ it("names a day of points that formed no trip, with their count and span", () => {+ const { getByLabelText, getByTestId } = renderDock({+ kind: "points",+ count: 42,+ startTime: 8 * 3600 + 12 * 60,+ endTime: 18 * 3600 + 40 * 60+ })++ expect(getByLabelText("No trips, 42 points · 08:12 - 18:40")).toBeTruthy()+ expect(getByTestId("icon-MapPin").props.color).toBe(lightColors.textSecondary)+ })++ it("holds the point card once a point is chosen, in place of the legend", () => {+ const onClose = jest.fn()+ const { getByTestId, queryByText, getByLabelText } = renderDock({+ kind: "point",+ point: { latitude: 0, longitude: 0, timestamp: 8 * 3600, accuracy: 8 },+ note: undefined,+ hasEndpoint: false,+ onSplit: jest.fn(),+ onDelete: jest.fn(),+ onClose,+ onSaveNote: jest.fn()+ })++ expect(getByTestId("point-card")).toBeTruthy()+ expect(queryByText("Trip 1")).toBeNull()+ fireEvent.press(getByLabelText("Close"))+ expect(onClose).toHaveBeenCalledTimes(1)+ })++ it("states an empty day over the tiles and offers its next step as a row", () => {+ const onPress = jest.fn()+ const { getByLabelText, getByTestId, UNSAFE_getAllByType } = renderDock({+ kind: "empty",+ title: "No locations today",+ hint: "Tracking is off.",+ action: { icon: CirclePause, label: "Open Dashboard", sub: "Tracking is off", onPress }+ })++ expect(getByLabelText("No locations today, Tracking is off.")).toBeTruthy()+ expect(getByTestId("icon-MapPinOff").props.color).toBe(lightColors.textSecondary)+ expect(UNSAFE_getAllByType(Divider)).toHaveLength(1)+ expect(getByTestId("icon-CirclePause")).toBeTruthy()+ fireEvent.press(getByLabelText("Open Dashboard, Tracking is off"))+ expect(onPress).toHaveBeenCalledTimes(1)+ })++ it("shows the empty line alone when the day has no next step", () => {+ const { getByLabelText, queryByTestId, UNSAFE_queryAllByType } = renderDock({+ kind: "empty",+ title: "No locations yet",+ hint: "Tracking is on. The first fix lands here."+ })++ expect(getByLabelText("No locations yet, Tracking is on. The first fix lands here.")).toBeTruthy()+ expect(queryByTestId("dock-empty-action")).toBeNull()+ expect(UNSAFE_queryAllByType(Divider)).toHaveLength(0)+ })++ it("docks over the map's bottom edge on the elevated row surface and reports its height", () => {+ const onLayout = jest.fn()+ const { getByTestId, UNSAFE_getByType } = renderDock(+ { kind: "points", count: 1, startTime: 0, endTime: 60 },+ { left: 20, right: 24, maxHeight: 320, onLayout }+ )++ const dock = StyleSheet.flatten(getByTestId("inspector-dock").props.style)+ expect(dock.position).toBe("absolute")+ expect(dock.bottom).toBe(space.lg)+ expect(dock.left).toBe(20)+ expect(dock.right).toBe(24)+ fireEvent(getByTestId("inspector-dock"), "layout", { nativeEvent: { layout: { height: 120 } } })+ expect(onLayout).toHaveBeenCalledTimes(1)++ expect(UNSAFE_getByType(Card).props.variant).toBe("elevated")+ expect(UNSAFE_getByType(Card).props.rows).toBe(true)+ const scroll = UNSAFE_getByType(ScrollView)+ expect(StyleSheet.flatten(scroll.props.style).maxHeight).toBe(320)+ expect(StyleSheet.flatten(scroll.props.style).marginHorizontal).toBe(-space.lg)+ expect(StyleSheet.flatten(scroll.props.contentContainerStyle).paddingHorizontal).toBe(space.lg)+ })+})diff --git a/apps/mobile/src/components/features/inspector/__tests__/LocationTable.test.tsx b/apps/mobile/src/components/features/inspector/__tests__/LocationTable.test.tsxindex 247b6076..2e4e8399 100644--- a/apps/mobile/src/components/features/inspector/__tests__/LocationTable.test.tsx+++ b/apps/mobile/src/components/features/inspector/__tests__/LocationTable.test.tsx@@ -1,29 +1,32 @@import React from "react"-import { render } from "@testing-library/react-native"+import { configure, render, fireEvent, within } from "@testing-library/react-native"+import { FlatList, StyleSheet } from "react-native"+import { lightColors } from "@colota/shared"import { LocationCoords } from "../../../../types/global"-// --- Mocks ----+const mockGetSpeedUnit = jest.fn(() => ({ factor: 3.6, unit: "km/h" }))+let mockTimeFormat: "24h" | "12h" = "24h"jest.mock("../../../../utils/geo", () => ({- formatTime: jest.fn((_ts: number) => "12:00:00"),- getSpeedUnit: jest.fn(() => ({ factor: 3.6, unit: "km/h" }))+ formatTime: (ts: number) => new Date(ts * 1000).toISOString().slice(11, 19),+ getSpeedUnit: () => mockGetSpeedUnit(),+ getTimeFormat: () => mockTimeFormat}))-jest.mock("../../../../styles/typography", () => ({- fonts: { regular: {}, bold: {}, semiBold: {} }+jest.mock("../../../../hooks/useTheme", () => ({+ useTheme: () => ({ colors: require("@colota/shared").lightColors })}))import { LocationTable } from "../LocationTable"-const mockColors = {- text: "#000",- textSecondary: "#6b7280",- border: "#e5e7eb",- surface: "#fff"-} as any+// The time pane is hidden from a screen reader on purpose, so the queries have to look past that.+configure({ defaultIncludeHiddenElements: true })++// The real palette: a hand-written subset reads a missing key as undefined and the style silently disappears.+const colors = lightColorsconst locations: LocationCoords[] = [{+ id: 1,latitude: 48.1,longitude: 11.5,accuracy: 10,@@ -32,9 +35,11 @@ const locations: LocationCoords[] = [speed: 5,bearing: 90,battery: 80,- battery_status: 2+ battery_status: 2,+ sent: 1},{+ id: 2,latitude: 48.2,longitude: 11.6,accuracy: 15,@@ -43,108 +48,184 @@ const locations: LocationCoords[] = [speed: 8,bearing: 180,battery: 79,- battery_status: 1+ battery_status: 1,+ sent: 0,+ note: "Coffee"},{+ id: 3,latitude: 48.3,longitude: 11.7,accuracy: 20,timestamp: 1060,- altitude: null as any,- speed: null as any,- bearing: null as any,- battery: null as any,- battery_status: null as any+ battery: 100,+ battery_status: 3,+ sent: 1}]+const rowLabel = /show on map$/++const scrollEvent = (y: number) => ({+ nativeEvent: {+ contentOffset: { x: 0, y },+ contentSize: { width: 800, height: 1000 },+ layoutMeasurement: { width: 360, height: 500 }+ }+})++function renderTable(props: Partial<React.ComponentProps<typeof LocationTable>> = {}) {+ return render(+ <LocationTable locations={locations} colors={colors} hasEndpoint={false} onSelectPoint={jest.fn()} {...props} />+ )+}+describe("LocationTable", () => {beforeEach(() => {jest.clearAllMocks()+ mockGetSpeedUnit.mockReturnValue({ factor: 3.6, unit: "km/h" })+ mockTimeFormat = "24h"})- it("shows empty state message when no locations", () => {- const { getByText } = render(<LocationTable locations={[]} colors={mockColors} />)+ it("widens the time column on a 12-hour clock so the seconds and the period both fit", () => {+ mockTimeFormat = "12h"+ const { getByTestId } = renderTable()++ expect(StyleSheet.flatten(getByTestId("table-time-pane").props.style).width).toBe(112)+ })- expect(getByText("No data for this day")).toBeTruthy()+ it("keeps the time column outside the horizontal pane so it stays in view while the data scrolls", () => {+ const { getByTestId } = renderTable()++ const timePane = within(getByTestId("table-time-pane"))+ const dataPane = within(getByTestId("table-data-pane"))+ expect(timePane.getByText("Time")).toBeTruthy()+ expect(timePane.getAllByText(/^\d\d:\d\d:\d\d$/)).toHaveLength(3)+ expect(dataPane.queryByText("Time")).toBeNull()+ for (const heading of ["Δs", "Lat", "Lon", "Acc m", "Alt m", "Bear", "Batt %", "Note"]) {+ expect(dataPane.getByText(heading)).toBeTruthy()+ }})- it("renders table header with column names", () => {- const { getByText } = render(<LocationTable locations={locations} colors={mockColors} />)-- expect(getByText("Time")).toBeTruthy()- expect(getByText("Δs")).toBeTruthy()- expect(getByText("Lat")).toBeTruthy()- expect(getByText("Lon")).toBeTruthy()- expect(getByText("Acc")).toBeTruthy()- expect(getByText("km/h")).toBeTruthy()- expect(getByText("Alt")).toBeTruthy()- expect(getByText("Bear")).toBeTruthy()- expect(getByText("Batt")).toBeTruthy()- expect(getByText("Charge")).toBeTruthy()+ it("lists the newest point first so the top row answers whether it is still recording", () => {+ const { getByTestId } = renderTable()++ const times = within(getByTestId("table-time-pane"))+ .getAllByLabelText(rowLabel)+ .map((row) => row.props.accessibilityLabel)+ expect(times).toEqual(["00:17:40, show on map", "00:17:10, show on map", "00:16:40, show on map"])++ const dataRows = within(getByTestId("table-data-pane")).getAllByLabelText(rowLabel)+ expect(dataRows).toHaveLength(3)+ expect(within(dataRows[0]).getByText("48.30000")).toBeTruthy()+ expect(within(dataRows[0]).getByText("+30")).toBeTruthy()+ expect(within(dataRows[2]).getByText("48.10000")).toBeTruthy()+ expect(within(dataRows[2]).queryByText(/^\+/)).toBeNull()})- it("renders location rows with correct values", () => {- const { getAllByText, getByText } = render(<LocationTable locations={locations} colors={mockColors} />)+ it("names the speed unit in the header so the cells stay bare numbers", () => {+ const { getByText, rerender } = renderTable()+ expect(getByText("Speed km/h")).toBeTruthy()+ expect(getByText("18.0")).toBeTruthy()- // formatTime is mocked to return "12:00:00" for all timestamps- expect(getAllByText("12:00:00").length).toBe(3)+ mockGetSpeedUnit.mockReturnValue({ factor: 2, unit: "mph" })+ rerender(<LocationTable locations={[]} colors={colors} hasEndpoint={false} onSelectPoint={jest.fn()} />)+ const fresh = renderTable()+ expect(fresh.getByText("Speed mph")).toBeTruthy()+ expect(fresh.getByText("10.0")).toBeTruthy()+ })- // Latitude values (5 decimal places)- expect(getByText("48.10000")).toBeTruthy()- expect(getByText("48.20000")).toBeTruthy()- expect(getByText("48.30000")).toBeTruthy()+ it("shows the Sync column only when a server is configured, because without one nothing is queued", () => {+ const without = renderTable({ hasEndpoint: false })+ expect(without.queryByText("Sync")).toBeNull()+ expect(without.queryByText("Sent")).toBeNull()+ expect(without.queryByText("Queued")).toBeNull()- // Longitude values (5 decimal places)- expect(getByText("11.50000")).toBeTruthy()- expect(getByText("11.60000")).toBeTruthy()- expect(getByText("11.70000")).toBeTruthy()+ const withServer = renderTable({ hasEndpoint: true })+ expect(withServer.getByText("Sync")).toBeTruthy()+ expect(withServer.getAllByText("Sent")).toHaveLength(2)+ expect(withServer.getAllByText("Queued")).toHaveLength(1)})- it("shows newest location first (reversed order)", () => {- const { getAllByText } = render(<LocationTable locations={locations} colors={mockColors} />)+ it("draws a battery glyph only while charging or full and speaks the word for a screen reader", () => {+ const { getAllByTestId, getByTestId, getByLabelText, queryByLabelText } = renderTable()- // The component reverses the array, so the newest timestamp (1060) should be first- // Verify all three timestamps were rendered- expect(getAllByText("12:00:00").length).toBe(3)+ expect(getAllByTestId("icon-BatteryCharging")).toHaveLength(1)+ expect(getAllByTestId("icon-BatteryFull")).toHaveLength(1)+ expect(getByLabelText("80% charging")).toBeTruthy()+ expect(getByLabelText("100% full")).toBeTruthy()+ expect(getByLabelText("79%")).toBeTruthy()+ expect(queryByLabelText(/discharging/i)).toBeNull()- // The first row should be the newest (index 2 from original = lat 48.3)- // and the last row should be the oldest (index 0 = lat 48.1)- // We can verify this by checking the rendered order of latitude values- const latTexts = ["48.30000", "48.20000", "48.10000"]- latTexts.forEach((lat) => {- expect(getAllByText(lat).length).toBe(1)+ const dataRows = within(getByTestId("table-data-pane")).getAllByLabelText(rowLabel)+ expect(dataRows[2].props.accessibilityLabel).toContain("battery 80% charging")+ expect(dataRows[1].props.accessibilityLabel).not.toContain("charging")+ })++ it("hands the point id to the screen from either pane so the map can open it", () => {+ const onSelectPoint = jest.fn()+ const { getByTestId } = renderTable({ onSelectPoint })++ fireEvent.press(within(getByTestId("table-time-pane")).getAllByLabelText(rowLabel)[1])+ expect(onSelectPoint).toHaveBeenCalledWith(2)++ fireEvent.press(within(getByTestId("table-data-pane")).getAllByLabelText(rowLabel)[0])+ expect(onSelectPoint).toHaveBeenCalledWith(3)+ expect(onSelectPoint).toHaveBeenCalledTimes(2)+ })++ it("fills the selected point's row in both panes and never a border", () => {+ const { getAllByLabelText } = renderTable({ selectedPointId: 2 })++ const rows = getAllByLabelText(rowLabel)+ const filled = rows.filter((r) => StyleSheet.flatten(r.props.style)?.backgroundColor === colors.primaryContainer)+ expect(filled).toHaveLength(2)+ filled.forEach((r) => {+ expect(r.props.accessibilityLabel).toMatch(/^00:17:10/)+ expect(r.props.accessibilityState).toEqual({ selected: true })+ expect(StyleSheet.flatten(r.props.style).borderWidth).toBeUndefined()})+ expect(rows.filter((r) => r.props.accessibilityState.selected)).toHaveLength(2)})- it("computes delta correctly between consecutive timestamps", () => {- const { getAllByText } = render(<LocationTable locations={locations} colors={mockColors} />)-- // Deltas computed in chronological order:- // index 0 (ts=1000): delta = null (first item)- // index 1 (ts=1030): delta = 1030 - 1000 = 30- // index 2 (ts=1060): delta = 1060 - 1030 = 30- // After reverse: [index2, index1, index0]- // Both index2 and index1 have delta = 30, index0 has delta = null- const deltaElements = getAllByText("+30")- expect(deltaElements.length).toBe(2)+ it("weights the selected time and recolours the row's text, so the tint is never the only cue", () => {+ const { getByText, getAllByText } = renderTable({ selectedPointId: 2 })++ const selectedTime = StyleSheet.flatten(getByText("00:17:10").props.style)+ expect(selectedTime.fontWeight).toBe("bold")+ expect(selectedTime.fontFamily).toBe("monospace")+ expect(selectedTime.color).toBe(colors.onPrimaryContainer)+ expect(StyleSheet.flatten(getByText("48.20000").props.style).color).toBe(colors.onPrimaryContainer)++ const otherTime = StyleSheet.flatten(getByText("00:17:40").props.style)+ expect(otherTime.fontWeight).toBeUndefined()+ expect(otherTime.color).toBe(colors.text)+ expect(getAllByText(/^\d\d:\d\d:\d\d$/)).toHaveLength(3)})- it("handles null optional fields (altitude, speed, bearing, battery)", () => {- const { getAllByText } = render(<LocationTable locations={locations} colors={mockColors} />)+ it("hides the time pane from a screen reader, since the data row already speaks the time and the action", () => {+ const { getByTestId, getAllByLabelText } = renderTable()- // The third location (index 2, but shown first after reverse) has null altitude,- // speed, bearing, battery - all rendered as "-"- // There should be dashes for: altitude, speed, bearing, battery = 4 dashes from- // the null-field row. Plus the newest row has no delta so its delta cell is empty.- const dashes = getAllByText("-")- expect(dashes.length).toBeGreaterThanOrEqual(4)+ expect(getByTestId("table-time-pane").props.importantForAccessibility).toBe("no-hide-descendants")+ expect(getByTestId("table-data-pane").props.importantForAccessibility).toBeUndefined()+ const spoken = getAllByLabelText(rowLabel, { includeHiddenElements: false })+ expect(spoken).toHaveLength(3)+ expect(spoken[0].props.accessibilityLabel).toMatch(/^00:17:40, .*show on map$/)})- it("shows battery status text (Charging, Discharging, etc.)", () => {- const { getByText } = render(<LocationTable locations={locations} colors={mockColors} />)+ it("moves the time pane with the data pane and lets it take no drags of its own, so a fling keeps its momentum", () => {+ const scrollToOffset = jest.spyOn(FlatList.prototype, "scrollToOffset").mockImplementation(() => {})+ const { getByTestId } = renderTable()++ expect(getByTestId("table-time-list").props.scrollEnabled).toBe(false)++ fireEvent.scroll(getByTestId("table-data-list"), scrollEvent(96))+ fireEvent.scroll(getByTestId("table-data-list"), scrollEvent(144))+ expect(scrollToOffset.mock.calls.map((c) => c[0])).toEqual([+ { offset: 96, animated: false },+ { offset: 144, animated: false }+ ])- expect(getByText("Charging")).toBeTruthy()- expect(getByText("Discharging")).toBeTruthy()+ scrollToOffset.mockRestore()})})diff --git a/apps/mobile/src/components/features/inspector/__tests__/PointCard.test.tsx b/apps/mobile/src/components/features/inspector/__tests__/PointCard.test.tsxnew file mode 100644index 00000000..9f2bdc45--- /dev/null+++ b/apps/mobile/src/components/features/inspector/__tests__/PointCard.test.tsx@@ -0,0 +1,159 @@+import React from "react"+import { render, fireEvent, waitFor } from "@testing-library/react-native"+import { StyleSheet } from "react-native"+import { lightColors } from "@colota/shared"+import { size, space } from "../../../../constants"+import { Divider } from "../../../ui/Divider"+import { PointCard } from "../PointCard"++const mockShowPrompt = jest.fn()+jest.mock("../../../../services/modalService", () => ({+ showPrompt: (...args: unknown[]) => mockShowPrompt(...args)+}))++jest.mock("../../../../hooks/useTheme", () => ({+ useTheme: () => ({ colors: require("@colota/shared").lightColors })+}))++jest.mock("../../../../utils/geo", () => ({+ formatSpeed: (mps: number) => `${(mps * 3.6).toFixed(1)} km/h`,+ formatTime: (ts: number, seconds?: boolean) => {+ const h = Math.floor(ts / 3600)+ const m = Math.floor((ts % 3600) / 60)+ const s = ts % 60+ const pad = (n: number) => String(n).padStart(2, "0")+ return seconds ? `${pad(h)}:${pad(m)}:${pad(s)}` : `${pad(h)}:${pad(m)}`+ }+}))++const TS = 8 * 3600 + 12 * 60 + 1+const point = {+ id: 7,+ latitude: 48.1,+ longitude: 11.5,+ timestamp: TS,+ speed: 5,+ accuracy: 8.4,+ altitude: 412.3,+ sent: 1+}++function renderCard(props: Partial<React.ComponentProps<typeof PointCard>> = {}) {+ const callbacks = { onSplit: jest.fn(), onDelete: jest.fn(), onClose: jest.fn(), onSaveNote: jest.fn() }+ const utils = render(<PointCard point={point} note={undefined} hasEndpoint {...callbacks} {...props} />)+ return { ...utils, ...callbacks }+}++describe("PointCard", () => {+ it("heads with the exact time and the three actions, so the card says which point it is and what can be done", () => {+ const { getByTestId, getByLabelText, onSplit, onDelete, onClose } = renderCard()++ const time = getByTestId("point-time")+ expect(time.props.children).toBe("08:12:01")+ expect(StyleSheet.flatten(time.props.style).fontVariant).toEqual(["tabular-nums"])+ expect(StyleSheet.flatten(time.props.style).marginStart).toBeUndefined()+ expect(StyleSheet.flatten(time.parent?.parent?.props.style).gap).toBe(space.lg)+ expect(getByTestId("icon-Clock").props.size).toBe(size.icon.md)++ fireEvent.press(getByLabelText("Start a new trip here"))+ fireEvent.press(getByLabelText("Delete point"))+ fireEvent.press(getByLabelText("Close"))+ expect(onSplit).toHaveBeenCalledTimes(1)+ expect(onDelete).toHaveBeenCalledTimes(1)+ expect(onClose).toHaveBeenCalledTimes(1)+ expect(getByTestId("icon-Trash2").props.color).toBe(lightColors.error)+ })++ it("offers no Delete on a screen that cannot remove a point, rather than a button that does nothing", () => {+ const { queryByLabelText, getByLabelText } = renderCard({ onDelete: undefined })++ expect(queryByLabelText("Delete point")).toBeNull()+ expect(getByLabelText("Start a new trip here")).toBeTruthy()+ expect(getByLabelText("Close")).toBeTruthy()+ })++ it("lists speed, accuracy, altitude and sync with a seam before each, and the note row last", () => {+ const { getByLabelText, UNSAFE_getAllByType } = renderCard()++ expect(getByLabelText("Speed, 18.0 km/h")).toBeTruthy()+ expect(getByLabelText("Accuracy, ±8 m")).toBeTruthy()+ expect(getByLabelText("Altitude, 412 m")).toBeTruthy()+ expect(getByLabelText("Sync, Sent")).toBeTruthy()+ expect(getByLabelText("Note, Add a note").props.accessibilityRole).toBe("button")+ const dividers = UNSAFE_getAllByType(Divider)+ expect(dividers).toHaveLength(5)+ for (const divider of dividers) {+ expect(divider.props.tight).toBe(true)+ expect(divider.props.inset).toBe(true)+ }+ })++ it("omits a fact the fix did not carry together with its seam, rather than printing a blank", () => {+ const { queryByLabelText, getByLabelText, UNSAFE_getAllByType } = renderCard({+ point: { ...point, speed: undefined, altitude: undefined }+ })++ expect(queryByLabelText(/^Speed/)).toBeNull()+ expect(queryByLabelText(/^Altitude/)).toBeNull()+ expect(getByLabelText("Accuracy, ±8 m")).toBeTruthy()+ expect(UNSAFE_getAllByType(Divider)).toHaveLength(3)+ })++ it("hides the sync row without an endpoint, since nothing is queued anywhere", () => {+ const { queryByLabelText } = renderCard({ hasEndpoint: false })++ expect(queryByLabelText(/^Sync/)).toBeNull()+ })++ it("reads Queued for a point the server has not received yet", () => {+ const { getByLabelText } = renderCard({ point: { ...point, sent: 0 } })++ expect(getByLabelText("Sync, Queued")).toBeTruthy()+ })++ it("shows the note under the Note row, or invites one when the point has none", () => {+ const empty = renderCard()+ expect(empty.getByText("Add a note")).toBeTruthy()+ empty.unmount()++ const noted = renderCard({ note: "Coffee stop" })+ expect(noted.getByText("Coffee stop")).toBeTruthy()+ expect(noted.queryByText("Add a note")).toBeNull()+ })++ it("edits the note through the app's prompt dialog seeded with the note, and hands the answer back", async () => {+ mockShowPrompt.mockResolvedValueOnce("Lunch")+ const { getByTestId, onSaveNote } = renderCard({ note: "Coffee stop" })++ fireEvent.press(getByTestId("point-note"))++ expect(mockShowPrompt).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Note",+ initialValue: "Coffee stop",+ multiline: true,+ placeholder: "Add a note"+ })+ )+ await waitFor(() => expect(onSaveNote).toHaveBeenCalledWith("Lunch"))+ })++ it("clears the note on an empty answer and keeps it when the prompt is dismissed", async () => {+ const first = renderCard({ note: "Coffee stop" })+ mockShowPrompt.mockResolvedValueOnce("")+ fireEvent.press(first.getByTestId("point-note"))+ await waitFor(() => expect(first.onSaveNote).toHaveBeenCalledWith(null))++ const second = renderCard({ note: "Coffee stop" })+ mockShowPrompt.mockResolvedValueOnce(null)+ fireEvent.press(second.getByTestId("point-note"))+ await new Promise<void>((r) => setTimeout(() => r(), 0))+ expect(second.onSaveNote).not.toHaveBeenCalled()+ })++ it("shows Split only where a caller offers it, since only Trip Detail edits a trip", () => {+ const { queryByTestId } = renderCard({ onSplit: undefined })++ expect(queryByTestId("point-split")).toBeNull()+ })+})diff --git a/apps/mobile/src/components/features/inspector/__tests__/TrackMap.test.tsx b/apps/mobile/src/components/features/inspector/__tests__/TrackMap.test.tsxindex 5231694c..86d6626c 100644--- a/apps/mobile/src/components/features/inspector/__tests__/TrackMap.test.tsx+++ b/apps/mobile/src/components/features/inspector/__tests__/TrackMap.test.tsx@@ -1,14 +1,20 @@import React from "react"-import { render, act, fireEvent } from "@testing-library/react-native"-import { TrackMap } from "../TrackMap"-import { DEFAULT_MAP_ZOOM } from "../../../../constants"+import { render, act, fireEvent, within } from "@testing-library/react-native"+import { TrackMap, POINT_HITBOX } from "../TrackMap"+import { DEFAULT_MAP_ZOOM, MAP_ANIMATION_DURATION_MS, size, space } from "../../../../constants"import type { Trip } from "../../../../types/global"const mockFitBounds = jest.fn()const mockSetStop = jest.fn()+const mockEaseTo = jest.fn()+const mockMapProps = jest.fn()const mockBuildSegments = jest.fn()const mockBuildPoints = jest.fn()+jest.mock("../../../../hooks/useTheme", () => ({+ useTheme: () => ({ colors: require("@colota/shared").lightColors })+}))+jest.mock("../../map/mapUtils", () => {const actual = jest.requireActual("../../map/mapUtils")return {@@ -32,9 +38,10 @@ jest.mock("../../map/ColotaMapView", () => {ColotaMapView: R.forwardRef(function MockColotaMapView(props: any, ref: any) {const onMapReady = props.onMapReadyR.useImperativeHandle(ref, () => ({- camera: { fitBounds: mockFitBounds, setStop: mockSetStop },+ camera: { fitBounds: mockFitBounds, setStop: mockSetStop, easeTo: mockEaseTo },mapView: null}))+ mockMapProps(props)R.useEffect(() => {onMapReady?.()}, [onMapReady])@@ -47,8 +54,7 @@ jest.mock("@maplibre/maplibre-react-native", () => {const R = require("react")const { View } = require("react-native")const stub = (name: string) => {- const Stub = (props: any) =>- R.createElement(View, { testID: props.id ?? name, onPress: props.onPress }, props.children)+ const Stub = (props: any) => R.createElement(View, { ...props, testID: props.id ?? name }, props.children)Stub.displayName = namereturn Stub}@@ -58,18 +64,6 @@ jest.mock("@maplibre/maplibre-react-native", () => {}})-jest.mock("../../map/MapCenterButton", () => ({- MapCenterButton: () => null-}))--jest.mock("../../../../styles/typography", () => ({- fonts: { regular: {}, bold: {}, semiBold: {} }-}))--jest.mock("../../../../utils/geo", () => ({- getSpeedUnit: () => ({ factor: 3.6, unit: "km/h" })-}))-jest.mock("../../../../utils/trips", () => ({getTripColor: (index: number) => `#trip${index}`}))@@ -80,11 +74,14 @@ const colors = {border: "#ccc",text: "#000",textSecondary: "#666",- borderRadius: 8,- pressedOpacity: 0.6+ textLight: "#999"} as any-const loc = (lat: number, lon: number) => ({+const cameraPadding = { top: 16, right: 72, bottom: 200, left: 16 }+const frame = { cameraPadding, controlsBottom: 180, controlsEnd: 16 }++const loc = (lat: number, lon: number, id?: number) => ({+ id,latitude: lat,longitude: lon,accuracy: 5,@@ -96,180 +93,424 @@ const loc = (lat: number, lon: number) => ({battery_status: 2})+const trip = (index: number, startIndex: number, locationCount: number): Trip => ({+ index,+ locations: [],+ startTime: 0,+ endTime: 0,+ distance: 1000,+ locationCount,+ startIndex+})++const twoTrips = {+ locations: [loc(52.5, 13.4), loc(52.51, 13.41), loc(52.6, 13.5), loc(52.61, 13.51)],+ trips: [trip(1, 0, 2), trip(2, 2, 2)]+}++const renderMap = (props: Partial<React.ComponentProps<typeof TrackMap>> = {}) =>+ render(+ <TrackMap+ locations={[loc(52.5, 13.4), loc(52.6, 13.5)]}+ colors={colors}+ trackColor="#000"+ onSelectPoint={jest.fn()}+ onFocusTrip={jest.fn()}+ {...frame}+ {...props}+ />+ )++const tapFeature = (source: any, properties: Record<string, unknown>) =>+ fireEvent(source, "press", {+ nativeEvent: { features: [{ properties, geometry: { type: "Point", coordinates: [13.4, 52.5] } }] }+ })++const tapMap = () => act(() => mockMapProps.mock.calls.at(-1)![0].onPress())+const panMap = () => act(() => mockMapProps.mock.calls.at(-1)![0].onRegionDidChange({ isUserInteraction: true }))++const flat = (style: unknown) => Object.assign({}, ...[style].flat(Infinity).filter(Boolean))+type Node = { type: unknown; parent: Node | null; props: { style?: unknown } }+// Run the auto-fit synchronously, otherwise it lands after the test has torn downbeforeEach(() => {jest.spyOn(globalThis, "requestAnimationFrame").mockImplementation((cb: any) => {cb(0)return 0})+ mockFitBounds.mockClear()+ mockSetStop.mockClear()+ mockEaseTo.mockClear()+ mockMapProps.mockClear()+ mockBuildSegments.mockClear()+ mockBuildPoints.mockClear()})afterEach(() => {jest.restoreAllMocks()})-describe("TrackMap auto-fit", () => {- beforeEach(() => {- mockFitBounds.mockClear()- mockSetStop.mockClear()+describe("TrackMap track drawing", () => {+ it("paints a casing under every trip line so any trip colour reads against the tiles", () => {+ const { getByTestId } = renderMap()++ const layers = within(getByTestId("track-segments"))+ .getAllByTestId(/^track-(casing|line)$/)+ .map((layer) => layer.props.testID)+ expect(layers).toEqual(["track-casing", "track-line"])+ expect(getByTestId("track-casing").props.style).toMatchObject({+ lineColor: colors.card,+ lineWidth: ["case", ["get", "focused"], 7, 5],+ lineCap: "round",+ lineJoin: "round"+ })})- it("fits bounds when switching from empty day to non-empty day", () => {- const locsA = [loc(48.1, 11.5), loc(48.2, 11.6)]- const locsB = [loc(52.5, 13.4), loc(52.6, 13.5)]+ it("widens the focused trip and dims the others, so focus never rests on colour alone", () => {+ const { getByTestId } = renderMap({ ...twoTrips, focusedTripIndex: 2 })++ const line = getByTestId("track-line").props.style+ expect(line.lineWidth).toEqual(["case", ["get", "focused"], 5, 3])+ expect(line.lineOpacity).toEqual(["case", ["any", false, ["get", "focused"]], 1, 0.4])+ expect(getByTestId("track-casing").props.style.lineOpacity).toEqual(line.lineOpacity)+ const layers = within(getByTestId("track-segments"))+ .getAllByTestId(/^track-(casing|line)(-focused)?$/)+ .map((layer) => layer.props.testID)+ expect(layers).toEqual(["track-casing", "track-line", "track-casing-focused", "track-line-focused"])+ expect(getByTestId("track-line-focused").props.filter).toEqual(["==", ["get", "focused"], true])+ expect(getByTestId("track-line-focused").props.style.lineWidth).toBe(5)+ expect(getByTestId("track-casing-focused").props.style.lineWidth).toBe(7)+ expect(getByTestId("trip-start").props.style.circleOpacity).toEqual(line.lineOpacity)+ expect(getByTestId("trip-end").props.style.circleStrokeOpacity).toEqual(line.lineOpacity)++ const features = getByTestId("track-segments").props.data.features+ expect(features.map((f: any) => [f.properties.tripIndex, f.properties.focused])).toEqual([+ [1, false],+ [2, true]+ ])+ })- const { rerender } = render(<TrackMap locations={locsA} colors={colors} trackColor="#000" fitVersion={1} />)- expect(mockFitBounds).toHaveBeenCalledTimes(1)+ it("marks every trip's start with a solid disc and its end with a ring, the mark's own two terminals", () => {+ const { getByTestId } = renderMap(twoTrips)++ const features = getByTestId("trip-terminals").props.data.features+ expect(features.map((f: any) => [f.properties.kind, f.properties.trip])).toEqual([+ ["start", 1],+ ["end", 1],+ ["start", 2],+ ["end", 2]+ ])+ expect(getByTestId("trip-start").props.filter).toEqual(["==", ["get", "kind"], "start"])+ expect(getByTestId("trip-start").props.style).toMatchObject({+ circleColor: ["get", "color"],+ circleStrokeColor: colors.card+ })+ expect(getByTestId("trip-end").props.filter).toEqual(["==", ["get", "kind"], "end"])+ expect(getByTestId("trip-end").props.style).toMatchObject({+ circleColor: colors.card,+ circleStrokeColor: ["get", "color"]+ })+ })- // Switch to empty day- act(() => {- rerender(<TrackMap locations={[]} colors={colors} trackColor="#000" fitVersion={2} />)+ it("marks the one trip of a Trip Detail map in its track colour when no trips are given", () => {+ const { getByTestId } = renderMap({ trips: undefined, trackColor: "#abc" })++ const features = getByTestId("trip-terminals").props.data.features+ expect(features.map((f: any) => [f.properties.kind, f.properties.color])).toEqual([+ ["start", "#abc"],+ ["end", "#abc"]+ ])+ })++ it("draws every trip at full strength while nothing is focused", () => {+ const { getByTestId } = renderMap(twoTrips)++ expect(getByTestId("track-line").props.style.lineOpacity).toEqual([+ "case",+ ["any", true, ["get", "focused"]],+ 1,+ 0.4+ ])+ })++ it("keeps points aligned with their trip when segmentTrips dropped a segment", () => {+ // Points 2-4 were dropped by segmentTrips+ const locations = [loc(52.5, 13.4), loc(52.51, 13.4), loc(52.6, 13.4), loc(52.6, 13.4), loc(52.6, 13.4), loc(52.7, 13.4), loc(52.71, 13.4)] // prettier-ignore+ const trips = [trip(1, 0, 2), trip(2, 5, 2)]++ renderMap({ locations, trips, trackColor: "#track", fitVersion: 1 })++ const options = mockBuildSegments.mock.calls[0][2]+ expect(options.locationColors).toEqual(["#trip1", "#trip1", "#track", "#track", "#track", "#trip2", "#trip2"])+ expect(options.locationTrips).toEqual([1, 1, -1, -1, -1, 2, 2])+ expect([...options.skipIndices].sort((a: number, b: number) => a - b)).toEqual([2, 3, 4, 5])+ })+})++describe("TrackMap point targets and selection", () => {+ it("gives every point a 48 dp touch target", () => {+ const { getByTestId } = renderMap()++ const half = size.touch / 2+ expect(POINT_HITBOX).toEqual({ top: half, right: half, bottom: half, left: half })+ expect(getByTestId("track-points").props.hitbox).toEqual(POINT_HITBOX)+ })++ it("hands a tapped point to the screen instead of opening anything itself", () => {+ const onSelectPoint = jest.fn()+ const { getByTestId, queryByTestId, queryByText } = renderMap({ onSelectPoint })++ tapFeature(getByTestId("track-points"), { id: 42, color: "#000" })++ expect(onSelectPoint).toHaveBeenCalledWith(42)+ expect(queryByTestId("popup-note-input")).toBeNull()+ expect(queryByText(/Trip 1/)).toBeNull()+ expect(queryByText("Speed")).toBeNull()+ })++ it("ignores a tap on a point with no row id, because nothing downstream can name it", () => {+ const onSelectPoint = jest.fn()+ const { getByTestId } = renderMap({ onSelectPoint })++ tapFeature(getByTestId("track-points"), { id: -1, color: "#000" })++ expect(onSelectPoint).not.toHaveBeenCalled()+ })++ it("rings the selected point on the card surface so it stands out from its neighbours", () => {+ const { getByTestId } = renderMap({+ ...twoTrips,+ locations: twoTrips.locations.map((l, i) => ({ ...l, id: i + 1 })),+ selectedPointId: 3})- expect(mockFitBounds).toHaveBeenCalledTimes(1) // no new fit on empty- // Switch to another non-empty day - the regression target+ const ring = getByTestId("highlight-point").props.data.features[0]+ expect(ring.properties).toEqual({ color: "#trip2", visible: 1 })+ expect(ring.geometry.coordinates).toEqual([13.5, 52.6])+ expect(getByTestId("highlight-circle").props.style.circleStrokeColor).toBe(colors.card)+ })+})++describe("TrackMap trip focus", () => {+ it("focuses the trip whose line was tapped, a beat later, in case the tap also hit a point", () => {+ jest.useFakeTimers()+ const onFocusTrip = jest.fn()+ const { getByTestId } = renderMap({ ...twoTrips, onFocusTrip })++ tapFeature(getByTestId("track-segments"), { tripIndex: 2, color: "#trip2", focused: false })+ expect(onFocusTrip).not.toHaveBeenCalled()act(() => {- rerender(<TrackMap locations={locsB} colors={colors} trackColor="#000" fitVersion={3} />)+ jest.advanceTimersByTime(100)})- expect(mockFitBounds).toHaveBeenCalledTimes(2)++ expect(onFocusTrip).toHaveBeenCalledWith(2)+ jest.useRealTimers()})- it("centers a single point at a fixed zoom instead of fitting bounds", () => {- render(<TrackMap locations={[loc(52.5, 13.4)]} colors={colors} trackColor="#000" fitVersion={1} />)+ it("opens the point and leaves the focus alone when one tap lands on a point and its line, in either order", () => {+ jest.useFakeTimers()+ const onFocusTrip = jest.fn()+ const onSelectPoint = jest.fn()+ const { getByTestId } = renderMap({ ...twoTrips, onFocusTrip, onSelectPoint })- // A zero-extent bounds would make fitBounds zoom to the max level, so a lone point must not fit- expect(mockFitBounds).not.toHaveBeenCalled()- expect(mockSetStop).toHaveBeenCalledWith(expect.objectContaining({ center: [13.4, 52.5], zoom: DEFAULT_MAP_ZOOM }))+ tapFeature(getByTestId("track-segments"), { tripIndex: 2 })+ tapFeature(getByTestId("track-points"), { id: 7, color: "#trip2" })+ act(() => {+ jest.advanceTimersByTime(300)+ })+ expect(onSelectPoint).toHaveBeenCalledWith(7)+ expect(onFocusTrip).not.toHaveBeenCalled()++ tapFeature(getByTestId("track-points"), { id: 8, color: "#trip2" })+ tapFeature(getByTestId("track-segments"), { tripIndex: 1 })+ act(() => {+ jest.advanceTimersByTime(300)+ })+ expect(onSelectPoint).toHaveBeenLastCalledWith(8)+ expect(onFocusTrip).not.toHaveBeenCalled()+ jest.useRealTimers()})-})-describe("TrackMap point deletion", () => {- const tapPoint = (points: any, id: number) =>- fireEvent(points, "press", {+ it("prefers the focused trip's point where two trips share a road, since that trip is drawn on top", () => {+ const onSelectPoint = jest.fn()+ const { getByTestId } = renderMap({ ...twoTrips, onSelectPoint, focusedTripIndex: 2 })++ fireEvent(getByTestId("track-points"), "press", {nativeEvent: {features: [- {- properties: { id, color: "#000", speed: 0, timestamp: 1000, accuracy: 5, altitude: 10, note: "" },- geometry: { type: "Point", coordinates: [13.4, 52.5] }- }+ { properties: { id: 1, color: "#trip1" }, geometry: { type: "Point", coordinates: [13.4, 52.5] } },+ { properties: { id: 2, color: "#trip2" }, geometry: { type: "Point", coordinates: [13.4, 52.5] } }]}})- it("reports the tapped point's id to the delete handler", () => {- const onPointDelete = jest.fn()- const { getByTestId } = render(- <TrackMap locations={[loc(52.5, 13.4)]} colors={colors} trackColor="#000" onPointDelete={onPointDelete} />- )-- tapPoint(getByTestId("track-points"), 42)- fireEvent.press(getByTestId("popup-delete-point"))+ expect(onSelectPoint).toHaveBeenCalledWith(2)+ })- expect(onPointDelete).toHaveBeenCalledWith(42)+ it("clears focus and selection on an empty tap, but not for the tap that just landed on a feature", () => {+ const onFocusTrip = jest.fn()+ const onSelectPoint = jest.fn()+ const now = jest.spyOn(Date, "now")+ const { getByTestId } = renderMap({ ...twoTrips, onFocusTrip, onSelectPoint, focusedTripIndex: 1 })++ now.mockReturnValue(1000)+ tapFeature(getByTestId("track-segments"), { tripIndex: 1 })+ now.mockReturnValue(1100)+ tapMap()+ expect(onFocusTrip).not.toHaveBeenCalledWith(null)+ expect(onSelectPoint).not.toHaveBeenCalled()++ now.mockReturnValue(1300)+ tapMap()+ expect(onFocusTrip).toHaveBeenCalledWith(null)+ expect(onSelectPoint).toHaveBeenCalledWith(null)})+})- it("offers no delete action on a read-only map", () => {- const { getByTestId, queryByTestId } = render(- <TrackMap locations={[loc(52.5, 13.4)]} colors={colors} trackColor="#000" />- )+describe("TrackMap camera", () => {+ it("frames the day inside the caller's padding, clear of the dock and the disc column", () => {+ renderMap({ fitVersion: 1 })- tapPoint(getByTestId("track-points"), 42)+ expect(mockFitBounds).toHaveBeenCalledWith([13.4, 52.5, 13.5, 52.6], {+ padding: cameraPadding,+ duration: MAP_ANIMATION_DURATION_MS+ })+ })- expect(queryByTestId("popup-delete-point")).toBeNull()+ it("frames only the focused trip when a fit is requested while one is focused", () => {+ renderMap({ ...twoTrips, focusedTripIndex: 2, fitVersion: 1 })++ expect(mockFitBounds).toHaveBeenCalledWith([13.5, 52.6, 13.51, 52.61], expect.anything())})- it("offers no delete action for a point with no row id", () => {- const { getByTestId, queryByTestId } = render(- <TrackMap locations={[loc(52.5, 13.4)]} colors={colors} trackColor="#000" onPointDelete={jest.fn()} />+ it("fits again when switching from an empty day to a day with points", () => {+ const locsA = [loc(48.1, 11.5), loc(48.2, 11.6)]+ const locsB = [loc(52.5, 13.4), loc(52.6, 13.5)]++ const { rerender } = render(+ <TrackMap+ locations={locsA}+ colors={colors}+ trackColor="#000"+ fitVersion={1}+ onSelectPoint={jest.fn()}+ onFocusTrip={jest.fn()}+ {...frame}+ />)+ expect(mockFitBounds).toHaveBeenCalledTimes(1)- tapPoint(getByTestId("track-points"), -1)+ act(() => {+ rerender(+ <TrackMap+ locations={[]}+ colors={colors}+ trackColor="#000"+ fitVersion={2}+ onSelectPoint={jest.fn()}+ onFocusTrip={jest.fn()}+ {...frame}+ />+ )+ })+ expect(mockFitBounds).toHaveBeenCalledTimes(1)- expect(queryByTestId("popup-delete-point")).toBeNull()+ act(() => {+ rerender(+ <TrackMap+ locations={locsB}+ colors={colors}+ trackColor="#000"+ fitVersion={3}+ onSelectPoint={jest.fn()}+ onFocusTrip={jest.fn()}+ {...frame}+ />+ )+ })+ expect(mockFitBounds).toHaveBeenCalledTimes(2)})- 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} />+ it("centres a lone point at a fixed zoom instead of fitting a zero-extent box", () => {+ renderMap({ locations: [loc(52.5, 13.4)], fitVersion: 1 })++ expect(mockFitBounds).not.toHaveBeenCalled()+ expect(mockSetStop).toHaveBeenCalledWith(+ expect.objectContaining({ center: [13.4, 52.5], zoom: DEFAULT_MAP_ZOOM, padding: cameraPadding }))+ })- tapPoint(getByTestId("track-points"), 42)- fireEvent.press(getByTestId("popup-split-point"))+ it("eases to the point a Data row chose once the map is ready, instead of fitting the day", () => {+ renderMap({+ locations: [loc(52.5, 13.4, 1), loc(52.6, 13.5, 2), loc(52.7, 13.6, 3)],+ selectedPointId: 2,+ fitVersion: 1+ })- expect(onPointSplit).toHaveBeenCalledWith(42)+ expect(mockEaseTo).toHaveBeenCalledWith({+ center: [13.5, 52.6],+ zoom: DEFAULT_MAP_ZOOM,+ padding: cameraPadding,+ duration: MAP_ANIMATION_DURATION_MS+ })+ expect(mockFitBounds).not.toHaveBeenCalled()})- 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)+ it("tells the screen when the map is ready", () => {+ const onMapReady = jest.fn()+ renderMap({ onMapReady })- expect(queryByTestId("popup-split-point")).toBeNull()+ expect(onMapReady).toHaveBeenCalledTimes(1)})+})- 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()} />- )+describe("TrackMap fit-the-day disc", () => {+ it("offers to refit only after the user has panned away", () => {+ const { queryByRole, getByRole } = renderMap({ fitVersion: 1 })+ expect(queryByRole("button")).toBeNull()- tapPoint(getByTestId("track-points"), -1)+ panMap()- expect(queryByTestId("popup-split-point")).toBeNull()+ const button = getByRole("button")+ expect(button.props.accessibilityLabel).toBe("Fit the day")+ fireEvent.press(button)+ expect(mockFitBounds).toHaveBeenCalledTimes(2)+ expect(queryByRole("button")).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)+ it("sits one slot above the attribution disc in the screen's disc column", () => {+ const { getByRole } = renderMap()+ panMap()- 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()+ let disc = getByRole("button").parent as Node | null+ while (disc && disc.type !== "View") disc = disc.parent+ const style = flat(disc!.props.style)+ expect(style.position).toBe("absolute")+ expect(style.bottom).toBe(frame.controlsBottom + size.iconColumn + space.lg)+ expect(style.right).toBe(frame.controlsEnd)})-})-describe("TrackMap trip coloring", () => {- beforeEach(() => mockBuildSegments.mockClear())+ it("stays away on an empty day, where there is nothing to fit", () => {+ const { queryByRole } = renderMap({ locations: [] })+ panMap()- it("keeps points aligned with their trip when segmentTrips dropped a segment", () => {- // Points 2-4 were dropped by segmentTrips- const locations = [loc(52.5, 13.4), loc(52.51, 13.4), loc(52.6, 13.4), loc(52.6, 13.4), loc(52.6, 13.4), loc(52.7, 13.4), loc(52.71, 13.4)] // prettier-ignore- const trips: Trip[] = [- { index: 1, locations: [], startTime: 0, endTime: 0, distance: 1000, locationCount: 2, startIndex: 0 },- { index: 2, locations: [], startTime: 0, endTime: 0, distance: 1000, locationCount: 2, startIndex: 5 }- ]+ expect(queryByRole("button")).toBeNull()+ })- render(<TrackMap locations={locations} colors={colors} trips={trips} trackColor="#track" fitVersion={1} />)+ it("passes the frame through to the map so its own discs share the column", () => {+ renderMap()- const options = mockBuildSegments.mock.calls[0][2]- expect(options.locationColors).toEqual(["#trip1", "#trip1", "#track", "#track", "#track", "#trip2", "#trip2"])- expect([...options.skipIndices].sort((a: number, b: number) => a - b)).toEqual([2, 3, 4, 5])+ expect(mockMapProps.mock.calls.at(-1)![0]).toMatchObject(frame)})})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()}- />- )+ renderMap({+ locations: [{ ...loc(52.5, 13.4), id: 42, note: "stored" }] as any,+ noteOverrides: { 42: "saved this session" }+ })const [locationsPassed] = mockBuildPoints.mock.calls.at(-1)!expect(locationsPassed[0].note).toBe("saved this session")@@ -277,60 +518,17 @@ describe("TrackMap note overrides", () => {/** 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()}- />- )+ renderMap({+ locations: [{ ...loc(52.5, 13.4), id: 42, note: "stored" }] as any,+ noteOverrides: { 42: undefined }+ })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()}- />- )+ renderMap({ locations: [{ ...loc(52.5, 13.4), id: 42, note: "stored" }] as any })const [locationsPassed] = mockBuildPoints.mock.calls.at(-1)!expect(locationsPassed[0].note).toBe("stored")diff --git a/apps/mobile/src/components/features/inspector/__tests__/TripList.test.tsx b/apps/mobile/src/components/features/inspector/__tests__/TripList.test.tsxindex a040ee05..333053ff 100644--- a/apps/mobile/src/components/features/inspector/__tests__/TripList.test.tsx+++ b/apps/mobile/src/components/features/inspector/__tests__/TripList.test.tsx@@ -1,12 +1,18 @@import React from "react"-import { render, fireEvent, act } from "@testing-library/react-native"+import { render, fireEvent } from "@testing-library/react-native"+import { ScrollView, StyleSheet } from "react-native"+import { space } from "../../../../constants"import type { Trip } from "../../../../types/global"-import type { ExportFormat } from "../../../../utils/exportConverters"++jest.mock("../../../../hooks/useTheme", () => ({+ useTheme: () => ({ colors: require("@colota/shared").lightColors })+}))jest.mock("../../../../utils/geo", () => ({formatDistance: (m: number) => `${(m / 1000).toFixed(1)} km`,- formatDuration: (s: number) => `${Math.round(s / 60)}m`,- formatSpeed: (s: number) => `${s} m/s`,+ spokenDistance: (m: number) => `${(m / 1000).toFixed(1)} kilometres`,+ formatDuration: (s: number) => `${Math.round(s / 60)}min`,+ formatSpeed: (mps: number) => `${(mps * 3.6).toFixed(1)} km/h`,formatTime: (_ts: number) => "12:00"}))@@ -15,75 +21,23 @@ jest.mock("../../../../utils/trips", () => ({computeTripStats: () => ({ avgSpeed: 0, elevationGain: 0, elevationLoss: 0 })}))-jest.mock("../../../../styles/typography", () => ({- fonts: { regular: {}, bold: {}, semiBold: {} }-}))--jest.mock("../../../../utils/exportConverters", () => ({- EXPORT_FORMATS: {- csv: { label: "CSV" },- geojson: { label: "GeoJSON" },- gpx: { label: "GPX" },- kml: { label: "KML" }- },- EXPORT_FORMAT_KEYS: ["csv", "geojson", "gpx", "kml"]-}))--jest.mock("../../../../hooks/useTheme", () => ({- useTheme: () => ({- colors: {- primary: "#0d9488",- text: "#000",- textSecondary: "#6b7280",- textDisabled: "#9ca3af",- border: "#e5e7eb",- card: "#fff",- cardElevated: "#f9fafb",- error: "#ef4444",- pressedOpacity: 0.7- }- })-}))-jest.mock("lucide-react-native", () => {const R = require("react")const { Text } = require("react-native")- const stub = (name: string) => (_props: any) => R.createElement(Text, null, name)- return {- Clock: stub("Clock"),- Route: stub("Route"),- Share: stub("Share"),- TrendingUp: stub("TrendingUp"),- TrendingDown: stub("TrendingDown"),- Gauge: stub("Gauge"),- Trash2: stub("Trash2"),- X: stub("X"),- Merge: stub("Merge"),- CheckSquare: stub("CheckSquare"),- Square: stub("Square")- }+ return { Check: (_props: any) => R.createElement(Text, null, "Check") }})import { TripList } from "../TripList"+import { Card } from "../../../ui/Card"+import { Divider } from "../../../ui/Divider"-const colors = {- primary: "#0d9488",- text: "#000",- textSecondary: "#6b7280",- textDisabled: "#9ca3af",- border: "#e5e7eb",- card: "#fff",- error: "#ef4444",- pressedOpacity: 0.7-} as any--function makeTrip(index: number, distance = 1000): Trip {+function makeTrip(index: number): Trip {return {index,locations: [],startTime: index * 100,endTime: index * 100 + 60,- distance,+ distance: 1000,locationCount: 5,startIndex: (index - 1) * 5}@@ -93,254 +47,71 @@ function makeTrips(n: number): Trip[] {return Array.from({ length: n }, (_, i) => makeTrip(i + 1))}-describe("TripList - CAB selection", () => {- beforeEach(() => jest.clearAllMocks())-- it("renders idle header with Export All when trips exist", () => {- const { getByLabelText, queryByLabelText } = render(- <TripList trips={makeTrips(3)} colors={colors} onTripSelect={jest.fn()} onExport={jest.fn()} />- )- expect(getByLabelText("Export all trips")).toBeTruthy()- expect(queryByLabelText("Cancel selection")).toBeNull()- })-- it("long-press on a card enters selection mode and shows CAB", () => {- const { getByLabelText, queryByLabelText } = render(- <TripList- trips={makeTrips(3)}- colors={colors}- onTripSelect={jest.fn()}- onExport={jest.fn()}- onDelete={jest.fn().mockResolvedValue(undefined)}- />- )-- fireEvent(getByLabelText(/Trip 1,/), "longPress")-- expect(getByLabelText("Cancel selection")).toBeTruthy()- expect(getByLabelText("Export selected trips")).toBeTruthy()- expect(getByLabelText("Delete selected trips")).toBeTruthy()- expect(queryByLabelText("Export all trips")).toBeNull()- })-- it("tap in selection mode toggles, does not navigate", () => {- const onTripSelect = jest.fn()- const { getByLabelText } = render(- <TripList trips={makeTrips(3)} colors={colors} onTripSelect={onTripSelect} onExport={jest.fn()} />- )-- fireEvent(getByLabelText(/Trip 1,/), "longPress")- fireEvent.press(getByLabelText(/Trip 2,/))-- expect(onTripSelect).not.toHaveBeenCalled()- })-- it("tap when idle navigates via onTripSelect", () => {- const onTripSelect = jest.fn()- const { getByLabelText } = render(- <TripList trips={makeTrips(3)} colors={colors} onTripSelect={onTripSelect} onExport={jest.fn()} />- )-- fireEvent.press(getByLabelText(/Trip 2,/))-- expect(onTripSelect).toHaveBeenCalledTimes(1)- expect(onTripSelect.mock.calls[0][0].index).toBe(2)- })-- it("Select all selects every trip, then deselect all clears", () => {- const onExport = jest.fn()- const { getByLabelText } = render(- <TripList trips={makeTrips(3)} colors={colors} onTripSelect={jest.fn()} onExport={onExport} />- )-- fireEvent(getByLabelText(/Trip 1,/), "longPress")- fireEvent.press(getByLabelText("Select all trips"))- fireEvent.press(getByLabelText("Export selected trips"))- fireEvent.press(getByLabelText(/Export 3 selected trips as GPX/))-- expect(onExport).toHaveBeenCalledTimes(1)- const [, trips] = onExport.mock.calls[0]- expect(trips.map((t: Trip) => t.index)).toEqual([1, 2, 3])- })-- it("CAB Share exports only the selected subset (non-contiguous)", () => {- const onExport = jest.fn()- const trips = makeTrips(3)- const { getByLabelText } = render(- <TripList trips={trips} colors={colors} onTripSelect={jest.fn()} onExport={onExport} />- )-- fireEvent(getByLabelText(/Trip 1,/), "longPress")- fireEvent.press(getByLabelText(/Trip 3,/))- fireEvent.press(getByLabelText("Export selected trips"))- fireEvent.press(getByLabelText(/Export 2 selected trips as GeoJSON/))-- expect(onExport).toHaveBeenCalledTimes(1)- const [fmt, exported] = onExport.mock.calls[0] as [ExportFormat, Trip[]]- expect(fmt).toBe("geojson")- expect(exported.map((t) => t.index)).toEqual([1, 3])- })-- it("CAB Trash fires onDelete with the selected subset", async () => {- const onDelete = jest.fn().mockResolvedValue(undefined)- const { getByLabelText } = render(- <TripList- trips={makeTrips(3)}- colors={colors}- onTripSelect={jest.fn()}- onExport={jest.fn()}- onDelete={onDelete}- />- )-- fireEvent(getByLabelText(/Trip 2,/), "longPress")- await act(async () => {- fireEvent.press(getByLabelText("Delete selected trips"))- })-- expect(onDelete).toHaveBeenCalledTimes(1)- expect(onDelete.mock.calls[0][0].map((t: Trip) => t.index)).toEqual([2])- })-- it("double-press Trash does not fire onDelete twice while in-flight", async () => {- let resolve!: () => void- const onDelete = jest.fn().mockImplementation(- () =>- new Promise<void>((r) => {- resolve = r- })- )- const { getByLabelText } = render(- <TripList- trips={makeTrips(3)}- colors={colors}- onTripSelect={jest.fn()}- onExport={jest.fn()}- onDelete={onDelete}- />- )-- fireEvent(getByLabelText(/Trip 1,/), "longPress")-- await act(async () => {- fireEvent.press(getByLabelText("Delete selected trips"))- fireEvent.press(getByLabelText("Delete selected trips"))- })-- expect(onDelete).toHaveBeenCalledTimes(1)-- await act(async () => {- resolve()- })- })-- it("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} />- )+function renderList(props: Partial<React.ComponentProps<typeof TripList>> = {}) {+ const handlers = { onToggle: jest.fn(), onEnterSelection: jest.fn(), onOpenTrip: jest.fn() }+ const utils = render(<TripList trips={makeTrips(3)} selected={new Set<number>()} {...handlers} {...props} />)+ return { ...utils, ...handlers }+}- fireEvent(getByLabelText(/Trip 1,/), "longPress")- fireEvent.press(getByLabelText(/Trip 3,/))+describe("TripList", () => {+ it("lists the day's trips in order inside one card, seamed by inset hairlines", () => {+ const { getAllByRole, UNSAFE_getAllByType, UNSAFE_getByType } = renderList()- const mergeBtn = getByLabelText("Merge selected trips")- expect(mergeBtn.props.accessibilityState.disabled).toBe(true)- await act(async () => {- fireEvent.press(mergeBtn)- })- expect(onMerge).not.toHaveBeenCalled()+ const rows = getAllByRole("button")+ expect(rows.map((r) => r.props.accessibilityLabel)).toEqual([+ expect.stringMatching(/^Trip 1,/),+ expect.stringMatching(/^Trip 2,/),+ expect.stringMatching(/^Trip 3,/)+ ])+ expect(UNSAFE_getByType(Card).props.rows).toBe(true)+ const dividers = UNSAFE_getAllByType(Divider)+ expect(dividers).toHaveLength(2)+ expect(dividers.every((d) => d.props.tight && d.props.inset)).toBe(true)})- 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")+ it("scrolls with the screen skeleton's insets, so the card lands where every other screen's does", () => {+ const { UNSAFE_getByType } = renderList()+ const content = StyleSheet.flatten(UNSAFE_getByType(ScrollView).props.contentContainerStyle)- expect(getByLabelText("Merge selected trips").props.accessibilityState.disabled).toBe(true)- await act(async () => {- fireEvent.press(getByLabelText("Merge selected trips"))- })- expect(onMerge).not.toHaveBeenCalled()+ expect(content).toEqual({ paddingHorizontal: space.lg, paddingTop: space.lg, paddingBottom: space.xxl })})- 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} />- )+ it("starts selecting on a long press, so a row is picked without opening it", () => {+ const { getByTestId, onEnterSelection, onToggle, onOpenTrip } = renderList()- fireEvent(getByLabelText(/Trip 1,/), "longPress")- fireEvent.press(getByLabelText(/Trip 2,/))- await act(async () => {- fireEvent.press(getByLabelText("Merge selected trips"))- })+ fireEvent(getByTestId("trip-row-2"), "longPress")- expect(getByLabelText("Cancel selection")).toBeTruthy()- await act(async () => {- fireEvent.press(getByLabelText("Merge selected trips"))- })- expect(onMerge).toHaveBeenCalledTimes(2)+ expect(onEnterSelection).toHaveBeenCalledWith(2)+ expect(onToggle).not.toHaveBeenCalled()+ expect(onOpenTrip).not.toHaveBeenCalled()})- 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()} />- )+ it("toggles a row on tap while selecting and marks the picked ones, so the tap never navigates away", () => {+ const { getByTestId, onToggle, onOpenTrip, onEnterSelection } = renderList({ selected: new Set([1]) })- fireEvent(getByLabelText(/Trip 1,/), "longPress")- expect(getByLabelText("Cancel selection")).toBeTruthy()+ fireEvent.press(getByTestId("trip-row-2"))+ fireEvent(getByTestId("trip-row-3"), "longPress")- fireEvent.press(getByLabelText("Cancel selection"))-- expect(queryByLabelText("Cancel selection")).toBeNull()- expect(getByLabelText("Export all trips")).toBeTruthy()+ expect(onToggle.mock.calls).toEqual([[2], [3]])+ expect(onOpenTrip).not.toHaveBeenCalled()+ expect(onEnterSelection).not.toHaveBeenCalled()+ expect(getByTestId("trip-row-1").props.accessibilityState.selected).toBe(true)+ expect(getByTestId("trip-row-2").props.accessibilityState.selected).toBe(false)+ expect(getByTestId("trip-row-2").props.accessibilityHint).toBeUndefined()})- it("changing the trips prop clears the selection", () => {- const { getByLabelText, queryByLabelText, rerender } = render(- <TripList trips={makeTrips(3)} colors={colors} onTripSelect={jest.fn()} onExport={jest.fn()} />- )-- fireEvent(getByLabelText(/Trip 1,/), "longPress")- expect(getByLabelText("Cancel selection")).toBeTruthy()+ it("opens a trip on tap when nothing is selected", () => {+ const { getByTestId, onOpenTrip, onToggle } = renderList()- rerender(<TripList trips={makeTrips(2)} colors={colors} onTripSelect={jest.fn()} onExport={jest.fn()} />)+ fireEvent.press(getByTestId("trip-row-2"))- expect(queryByLabelText("Cancel selection")).toBeNull()+ expect(onOpenTrip).toHaveBeenCalledWith(2)+ expect(onToggle).not.toHaveBeenCalled()})- it("idle Export All exports the full trips array", () => {- const onExport = jest.fn()- const { getByLabelText, getByText } = render(- <TripList trips={makeTrips(3)} colors={colors} onTripSelect={jest.fn()} onExport={onExport} />- )-- fireEvent.press(getByLabelText("Export all trips"))- fireEvent.press(getByText("KML"))+ it("renders nothing on an empty day, leaving the empty composition to the screen", () => {+ const { toJSON } = renderList({ trips: [] })- expect(onExport).toHaveBeenCalledTimes(1)- const [fmt, exported] = onExport.mock.calls[0] as [ExportFormat, Trip[]]- expect(fmt).toBe("kml")- expect(exported).toHaveLength(3)+ expect(toJSON()).toBeNull()})})diff --git a/apps/mobile/src/components/features/inspector/__tests__/TripRow.test.tsx b/apps/mobile/src/components/features/inspector/__tests__/TripRow.test.tsxnew file mode 100644index 00000000..c1f89101--- /dev/null+++ b/apps/mobile/src/components/features/inspector/__tests__/TripRow.test.tsx@@ -0,0 +1,153 @@+import React from "react"+import { render, fireEvent } from "@testing-library/react-native"+import { StyleSheet } from "react-native"+import { lightColors } from "@colota/shared"+import { size, space } from "../../../../constants"+import type { Trip } from "../../../../types/global"++jest.mock("../../../../hooks/useTheme", () => ({+ useTheme: () => ({ colors: require("@colota/shared").lightColors })+}))++jest.mock("../../../../utils/geo", () => ({+ formatDistance: (m: number) => `${(m / 1000).toFixed(1)} km`,+ spokenDistance: (m: number) => `${(m / 1000).toFixed(1)} kilometres`,+ formatDuration: (s: number) => `${Math.round(s / 60)}min`,+ formatSpeed: (mps: number) => `${(mps * 3.6).toFixed(1)} km/h`,+ formatTime: (ts: number) => {+ const h = Math.floor(ts / 3600)+ const m = Math.floor((ts % 3600) / 60)+ return `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}`+ }+}))++jest.mock("lucide-react-native", () => {+ const R = require("react")+ const { Text } = require("react-native")+ return { Check: (_props: any) => R.createElement(Text, null, "Check") }+})++import { TripRow } from "../TripRow"++const START = 8 * 3600 + 12 * 60+const END = START + 6 * 60++function makeTrip(): Trip {+ const speed = 17 / 3.6+ return {+ index: 2,+ locations: [+ { latitude: 0, longitude: 0, timestamp: START, speed },+ { latitude: 0.01, longitude: 0, timestamp: END, speed }+ ],+ startTime: START,+ endTime: END,+ distance: 1100,+ locationCount: 2,+ startIndex: 5+ }+}++function renderRow(props: Partial<React.ComponentProps<typeof TripRow>> = {}) {+ return render(+ <TripRow+ trip={makeTrip()}+ index={2}+ selected={false}+ selecting={false}+ onPress={jest.fn()}+ onLongPress={jest.fn()}+ testID="trip-row"+ {...props}+ />+ )+}++describe("TripRow", () => {+ it("names the trip and sums it up in one line, so a row reads as a legend entry and a list item", () => {+ const { getByText } = renderRow()++ expect(getByText("Trip 2")).toBeTruthy()+ expect(getByText("1.1 km · 6min · 17.0 km/h")).toBeTruthy()+ })++ it("speaks the whole row with units a screen reader can say, and offers the details it opens", () => {+ const { getByTestId } = renderRow()+ const row = getByTestId("trip-row")++ expect(row.props.accessibilityRole).toBe("button")+ expect(row.props.accessibilityLabel).toBe("Trip 2, 08:12 to 08:18, 1.1 kilometres, 6 minutes")+ expect(row.props.accessibilityHint).toBe("Opens trip details")+ })++ it("puts the time range in the trailing slot with tabular figures, so rows line up down the card", () => {+ const { getByText } = renderRow()+ const time = getByText("08:12 - 08:18")++ expect(StyleSheet.flatten(time.props.style).fontVariant).toEqual(["tabular-nums"])+ expect(StyleSheet.flatten(time.props.style).color).toBe(lightColors.textSecondary)+ })++ it("leads with the trip's map colour, so the row doubles as the legend", () => {+ const { getByTestId, queryByText, UNSAFE_getAllByType } = renderRow()+ const { View } = require("react-native")++ expect(queryByText("Check")).toBeNull()+ const swatch = UNSAFE_getAllByType(View).find((v: any) => StyleSheet.flatten(v.props.style)?.width === 8)+ expect(StyleSheet.flatten(swatch?.props.style).backgroundColor).toBe(+ require("../../../../utils/trips").getTripColor(2)+ )+ expect(getByTestId("trip-row").props.accessibilityState.selected).toBe(false)+ })++ it("marks a selected trip with a fill and a check, never a border that comes and goes", () => {+ const { getByTestId, getByText } = renderRow({ selected: true })+ const row = getByTestId("trip-row")++ expect(StyleSheet.flatten(row.props.style).backgroundColor).toBe(lightColors.primaryContainer)+ expect(getByText("Check")).toBeTruthy()+ expect(StyleSheet.flatten(getByText("Trip 2").props.style).color).toBe(lightColors.onPrimaryContainer)+ expect(StyleSheet.flatten(getByText("08:12 - 08:18").props.style).color).toBe(lightColors.onPrimaryContainer)+ expect(row.props.accessibilityState.selected).toBe(true)+ })++ it("fires a tap and a long press separately, so the list can open a trip or start selecting", () => {+ const onPress = jest.fn()+ const onLongPress = jest.fn()+ const { getByTestId } = renderRow({ onPress, onLongPress })++ fireEvent.press(getByTestId("trip-row"))+ expect(onPress).toHaveBeenCalledTimes(1)+ expect(onLongPress).not.toHaveBeenCalled()++ fireEvent(getByTestId("trip-row"), "longPress")+ expect(onLongPress).toHaveBeenCalledTimes(1)+ })++ it("drops the details hint while selecting, because a tap then toggles the row instead", () => {+ const { getByTestId } = renderRow({ selecting: true })++ expect(getByTestId("trip-row").props.accessibilityHint).toBeUndefined()+ })++ it("wraps the time under the title at a large font scale rather than clipping either", () => {+ const { getByText, UNSAFE_getAllByType } = renderRow()+ const { View } = require("react-native")++ expect(getByText("Trip 2").props.numberOfLines).toBeUndefined()+ expect(getByText("1.1 km · 6min · 17.0 km/h").props.numberOfLines).toBeUndefined()+ const titleRow = UNSAFE_getAllByType(View).find((v: any) => StyleSheet.flatten(v.props.style)?.flexWrap === "wrap")+ expect(titleRow).toBeTruthy()+ expect(StyleSheet.flatten(getByText("Trip 2").props.style).flexShrink).toBeUndefined()+ })++ it("cancels the card's inset and reapplies it, so the ripple spans the card and text starts at 36", () => {+ const { getByTestId } = renderRow()+ const style = StyleSheet.flatten(getByTestId("trip-row").props.style)++ expect(style.marginHorizontal).toBe(-space.lg)+ expect(style.paddingHorizontal).toBe(space.lg)+ expect(style.gap).toBe(space.lg)+ expect(style.minHeight).toBe(size.row)+ })+})diff --git a/apps/mobile/src/components/index.ts b/apps/mobile/src/components/index.tsindex f5b77f80..da95fabb 100644--- a/apps/mobile/src/components/index.ts+++ b/apps/mobile/src/components/index.ts@@ -74,3 +74,8 @@ export { FormatSelector } from "./ui/FormatSelector"export { StatsCard } from "./features/settings/StatsCard"export { DashboardBanner } from "./features/dashboard/DashboardBanner"export { DashboardDock } from "./features/dashboard/DashboardDock"+export { DayHeader } from "./features/inspector/DayHeader"+export { DayPickerModal } from "./features/inspector/DayPickerModal"+export { TripRow } from "./features/inspector/TripRow"+export { InspectorDock } from "./features/inspector/InspectorDock"+export { PointCard } from "./features/inspector/PointCard"diff --git a/apps/mobile/src/screens/LocationInspectorScreen.tsx b/apps/mobile/src/screens/LocationInspectorScreen.tsxindex 0d032696..da54ac02 100644--- a/apps/mobile/src/screens/LocationInspectorScreen.tsx+++ b/apps/mobile/src/screens/LocationInspectorScreen.tsx@@ -4,49 +4,86 @@*/import React, { useState, useEffect, useRef, useCallback, useMemo, useLayoutEffect } from "react"-import { View, Text, StyleSheet, Pressable } from "react-native"+import { AccessibilityInfo, View, StyleSheet, BackHandler, useWindowDimensions } from "react-native"+import { useSafeAreaInsets } from "react-native-safe-area-context"import { useFocusEffect } from "@react-navigation/native"-import { fonts } from "../styles/typography"-import { BarChart2 } from "lucide-react-native"-import { Container } from "../components"+import {+ CalendarCheck,+ ChartNoAxesColumn,+ CirclePause,+ EllipsisVertical,+ Merge,+ RotateCcwClock,+ Route,+ Upload,+ Table,+ Trash2,+ X+} from "lucide-react-native"+import {+ Container,+ DayHeader,+ DayPickerModal,+ Divider,+ EmptyState,+ InspectorDock,+ SpinningLoader,+ TrackMap,+ HeaderAction+} from "../components"+import type { DockContent } from "../components/features/inspector/InspectorDock"+import { dayLongDate, dayTitle, type DayStats } from "../components/features/inspector/DayHeader"import { Tab } from "../components/ui/Tab"+import { TripList } from "../components/features/inspector/TripList"+import { ExportFormatDialog } from "../components/ui/ExportFormatDialog"+import { LocationTable } from "../components/features/inspector/LocationTable"import { useTheme } from "../hooks/useTheme"-import { Trip, LocationCoords, BoundaryAction, BOUNDARY_ACTION_SPLIT } from "../types/global"+import { useTimeout } from "../hooks/useTimeout"+import { useTracking } from "../contexts/TrackingProvider"+import { Trip, LocationCoords, BoundaryAction, type DailyStat } from "../types/global"import NativeLocationService from "../services/NativeLocationService"import { logger } from "../utils/logger"-import { CalendarPicker } from "../components/features/inspector/CalendarPicker"-import { TrackMap } from "../components/features/inspector/TrackMap"-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,- buildBoundaryOverrideMap,- gapsBetweenTrips,- splitBlockedReason,- SPLIT_BLOCKED_NOT_A_TRIP-} from "../utils/trips"+import { formatTime, startOfDaySec, endOfDaySec } from "../utils/geo"+import { segmentTrips, getTripColor, buildBoundaryOverrideMap, gapsBetweenTrips } from "../utils/trips"import { EXPORT_FORMATS, type ExportFormat } from "../utils/exportConverters"-import { showAlert, showConfirm } from "../services/modalService"+import {+ EMPTY_MONTH,+ dateFromKey,+ dayKey,+ emptyDayVariant,+ exportMessage,+ findLastDayWithData,+ isAdjacentSelection,+ lastDaySub,+ monthKey,+ type LastDay,+ type MonthData+} from "../utils/inspectorDay"+import { showAlert, showChoice, showConfirm } from "../services/modalService"import type { RootScreenProps } from "../types/navigation"+import { LOADING_INDICATOR_DELAY_MS, size, space } from "../constants"type TabType = "map" | "trips" | "data"+// setOptions cannot unset a key, so leaving selection writes the SCREEN_CONFIG title back.+const SCREEN_TITLE = "Location history"+const NO_SELECTION = new Set<number>()++type ExportRequest = { title: string; message: string; resolve: (format: ExportFormat | null) => void }+export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Location History">) {const { colors } = useTheme()+ const { settings, tracking } = useTracking()+ const insets = useSafeAreaInsets()+ const { height: windowHeight } = useWindowDimensions()const [activeTab, setActiveTab] = useState<TabType>(route?.params?.initialTab ?? "map")- // Map tab state - accept initialDate from Summary screen navigationconst [mapDate, setMapDate] = useState(() => {const initialDate = route?.params?.initialDatereturn 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- // close its popup). Applied wherever a location's note is shown: the table, the map and the- // trip handed to Trip Detail.+ // Note edits stay out of trackLocations so a save does not hand the map a new array.const [noteOverrides, setNoteOverrides] = useState<Record<number, string | undefined>>({})const withNotes = useCallback((locs: LocationCoords[]) =>@@ -57,151 +94,177 @@ export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Lo)const [boundaryOverrides, setBoundaryOverrides] = useState<Map<string, BoundaryAction>>(() => new Map())- const [selectedTrip, setSelectedTrip] = useState<Trip | null>(null)const [fitVersion, setFitVersion] = useState(0)+ const [loading, setLoading] = useState(true)+ const [showSpinner, setShowSpinner] = useState(false)+ const [lastDay, setLastDay] = useState<LastDay | null>(null)+ const [pickerOpen, setPickerOpen] = useState(false)+ const [selectedPointId, setSelectedPointId] = useState<number | null>(null)+ const [focusedTripIndex, setFocusedTripIndex] = useState<number | null>(null)+ const [selected, setSelected] = useState(NO_SELECTION)+ const [dockHeight, setDockHeight] = useState(0)++ const [daysWithData, setDaysWithData] = useState(() => new Set<string>())+ const [monthStats, setMonthStats] = useState<ReadonlyMap<string, DailyStat>>(EMPTY_MONTH.stats)+ const monthCache = useRef<Map<string, MonthData>>(new Map())- // 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 dataconst trips = useMemo(() => segmentTrips(trackLocations, undefined, boundaryOverrides),[trackLocations, boundaryOverrides])-- // Sum of per-trip distances (excludes gap jumps between trips)- const dailyDistance = useMemo(() => {- if (trips.length === 0) return undefined- const meters = trips.reduce((sum, t) => sum + t.distance, 0)- return meters > 0 ? formatDistance(meters) : undefined- }, [trips])+ const dayDistanceMeters = useMemo(() => trips.reduce((sum, t) => sum + t.distance, 0), [trips])+ const dayStats: DayStats | null =+ trackLocations.length === 0+ ? null+ : { points: trackLocations.length, trips: trips.length, distanceMeters: dayDistanceMeters }+ const isToday = dayKey(mapDate) === dayKey(new Date())+ const hasEndpoint = settings.endpoint.trim().length > 0+ const selecting = selected.size > 0const fetchTrackIdRef = useRef(0)const deletingPointRef = useRef(false)+ const editingTripsRef = useRef(false)+ const wasSelectingRef = useRef(false)- // Summary navigation button- const headerRight = useCallback(- () => (- <Pressable- onPress={() => navigation.navigate("Location Summary")}- style={({ pressed }) => [styles.headerBtn, pressed && { opacity: colors.pressedOpacity }]}- >- <BarChart2 size={20} color={colors.text} />- </Pressable>- ),- [navigation, colors]- )-- useLayoutEffect(() => {- navigation.setOptions({ headerRight })- }, [navigation, headerRight])+ const { set: startSpinnerTimer, clear: clearSpinnerTimer } = useTimeout()+ useEffect(() => {+ if (!loading) {+ clearSpinnerTimer()+ setShowSpinner(false)+ return+ }+ startSpinnerTimer(() => setShowSpinner(true), LOADING_INDICATOR_DELAY_MS)+ }, [loading, startSpinnerTimer, clearSpinnerTimer])- /** Fetch days-with-data and daily distances for a month into cache. */- const prefetchMonth = useCallback(async (year: number, month: number): Promise<Set<string>> => {- const key = `${year}-${pad2(month + 1)}`- if (daysCache.current.has(key)) return daysCache.current.get(key)!+ const prefetchMonth = useCallback(async (year: number, month: number): Promise<MonthData> => {+ const key = monthKey(year, month)+ const cached = monthCache.current.get(key)+ if (cached) return cachedtry {const start = new Date(year, month, 1)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, noteDays] = await Promise.all([+ const [days, stats] = await Promise.all([NativeLocationService.getDaysWithData(startTs, endTs),- NativeLocationService.getDailyStats(startTs, endTs),- NativeLocationService.getDaysWithNotes(startTs, endTs)+ NativeLocationService.getDailyStats(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)- }- distanceCache.current.set(key, distances)- return daySet+ const data: MonthData = { days: new Set(days), stats: new Map(stats.map((s) => [s.day, s] as const)) }+ monthCache.current.set(key, data)+ return data} catch (err) {logger.error("[LocationHistory] Failed to fetch days with data:", err)- return new Set()+ return EMPTY_MONTH}}, [])- /** Fetch and display days with data for a given month */const fetchDaysWithData = useCallback(async (year: number, month: number) => {- const daySet = await prefetchMonth(year, month)- setDaysWithData(daySet)- setDaysWithNotes(notesCache.current.get(`${year}-${pad2(month + 1)}`) ?? new Set())+ const data = await prefetchMonth(year, month)+ setDaysWithData(new Set(data.days))+ setMonthStats(data.stats)},[prefetchMonth])- // Fetch days for current month on mount and when date changes monthuseEffect(() => {fetchDaysWithData(mapDate.getFullYear(), mapDate.getMonth())}, [mapDate, fetchDaysWithData])- /** Fetch track data for the selected day */const fetchTrackData = useCallback(async () => {const id = ++fetchTrackIdRef.current+ setLoading(true)try {- const startTimestamp = startOfDaySec(mapDate)- const endTimestamp = endOfDaySec(mapDate)-const [result, overrides] = await Promise.all([- NativeLocationService.getLocationsByDateRange(startTimestamp, endTimestamp),+ NativeLocationService.getLocationsByDateRange(startOfDaySec(mapDate), endOfDaySec(mapDate)),NativeLocationService.getBoundaryOverrides()])- if (id === fetchTrackIdRef.current) {- setTrackLocations(result || [])- setBoundaryOverrides(buildBoundaryOverrideMap(overrides))- setNoteOverrides({})- setSelectedTrip(null)- setFitVersion((v) => v + 1)- }+ const locations: LocationCoords[] = result || []+ const last = locations.length === 0 ? await findLastDayWithData(mapDate, prefetchMonth) : null+ if (id !== fetchTrackIdRef.current) return+ setTrackLocations(locations)+ setBoundaryOverrides(buildBoundaryOverrideMap(overrides))+ setNoteOverrides({})+ setLastDay(last)+ setSelectedPointId(null)+ setFocusedTripIndex(null)+ setFitVersion((v) => v + 1)+ setLoading(false)} catch (err) {logger.error("[LocationHistory] Track fetch error:", err)- if (id === fetchTrackIdRef.current) {- setTrackLocations([])- setBoundaryOverrides(new Map())- setNoteOverrides({})- setSelectedTrip(null)- setFitVersion((v) => v + 1)- }+ if (id !== fetchTrackIdRef.current) return+ setTrackLocations([])+ setBoundaryOverrides(new Map())+ setNoteOverrides({})+ setLastDay(null)+ setSelectedPointId(null)+ setFocusedTripIndex(null)+ setFitVersion((v) => v + 1)+ setLoading(false)+ showAlert("Load Failed", "Unable to load this day. Please try again.", "error")}- }, [mapDate])+ }, [mapDate, prefetchMonth])- /** Fetch track data when map date changes */useEffect(() => {fetchTrackData()}, [fetchTrackData])- /** Refresh on focus so trip deletions in TripDetail are reflected */+ const invalidateMonth = useCallback(() => {+ monthCache.current.delete(monthKey(mapDate.getFullYear(), mapDate.getMonth()))+ }, [mapDate])+useFocusEffect(useCallback(() => {- const key = `${mapDate.getFullYear()}-${pad2(mapDate.getMonth() + 1)}`- daysCache.current.delete(key)- notesCache.current.delete(key)- distanceCache.current.delete(key)+ invalidateMonth()fetchTrackData()fetchDaysWithData(mapDate.getFullYear(), mapDate.getMonth())- }, [fetchTrackData, fetchDaysWithData, mapDate])+ }, [invalidateMonth, fetchTrackData, fetchDaysWithData, mapDate])+ )++ const refreshAfterEdit = useCallback(async () => {+ invalidateMonth()+ await fetchTrackData()+ await fetchDaysWithData(mapDate.getFullYear(), mapDate.getMonth())+ }, [invalidateMonth, mapDate, fetchTrackData, fetchDaysWithData])++ const exitSelection = useCallback(() => setSelected(NO_SELECTION), [])++ const changeDay = useCallback(+ (date: Date) => {+ setMapDate(date)+ setFocusedTripIndex(null)+ setSelectedPointId(null)+ exitSelection()+ },+ [exitSelection]+ )++ const stepDay = useCallback(+ (delta: number) => changeDay(new Date(mapDate.getFullYear(), mapDate.getMonth(), mapDate.getDate() + delta)),+ [mapDate, changeDay]+ )++ const goToToday = useCallback(() => changeDay(new Date()), [changeDay])++ const changeTab = useCallback(+ (tab: TabType) => {+ setActiveTab(tab)+ exitSelection()+ },+ [exitSelection])- /** 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) => {+ const openTrip = useCallback(+ (index: number) => {+ const trip = trips.find((t) => t.index === index)+ if (!trip) returnconst withSessionNotes = (t: Trip) => ({ ...t, locations: withNotes(t.locations) })navigation.navigate("Trip Detail", { trip: withSessionNotes(trip), trips: trips.map(withSessionNotes) })},[navigation, trips, withNotes])- /** Export trips (all or single) */const exportTrips = useCallback(async (format: ExportFormat, tripsToExport: Trip[]) => {if (tripsToExport.length === 0) return@@ -231,25 +294,50 @@ export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Lo[mapDate])- const handleShowFullDay = useCallback(() => {- setSelectedTrip(null)- setFitVersion((v) => v + 1)- }, [])-- const refreshAfterEdit = useCallback(async () => {- 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())- }, [mapDate, fetchTrackData, fetchDaysWithData])+ const [exportRequest, setExportRequest] = useState<ExportRequest | null>(null)+ const chooseExportFormat = useCallback(+ (title: string, message: string) =>+ new Promise<ExportFormat | null>((resolve) => setExportRequest({ title, message, resolve })),+ []+ )+ const settleExport = useCallback(+ (format: ExportFormat | null) => {+ exportRequest?.resolve(format)+ setExportRequest(null)+ },+ [exportRequest]+ )- 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 handleExportDay = useCallback(async () => {+ const format = await chooseExportFormat(+ "Export day",+ exportMessage(dayTitle(mapDate), trips.length, dayDistanceMeters)+ )+ if (format) await exportTrips(format, trips)+ }, [mapDate, trips, dayDistanceMeters, exportTrips, chooseExportFormat])++ const selectedTrips = useMemo(() => trips.filter((t) => selected.has(t.index)), [trips, selected])+ const canMerge = isAdjacentSelection(selected)++ const handleExportSelected = useCallback(async () => {+ if (selectedTrips.length === 0) return+ const distance = selectedTrips.reduce((sum, t) => sum + t.distance, 0)+ const format = await chooseExportFormat(+ selectedTrips.length === 1 ? `Export Trip ${selectedTrips[0].index}` : `Export ${selectedTrips.length} trips`,+ exportMessage(dayTitle(mapDate), selectedTrips.length, distance)+ )+ if (format) await exportTrips(format, selectedTrips)+ }, [selectedTrips, mapDate, exportTrips, chooseExportFormat])++ const handleMergeSelected = useCallback(async () => {+ if (editingTripsRef.current) return+ editingTripsRef.current = true+ try {+ if (!canMerge) {+ showAlert("Merge trips", "Select two or more trips that follow each other.", "info")+ return+ }+ const sorted = [...selectedTrips].sort((a, b) => a.index - b.index)const first = sorted[0].indexconst last = sorted[sorted.length - 1].indexconst confirmed = await showConfirm({@@ -265,23 +353,27 @@ export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Lo.flatMap((trip, i) => gapsBetweenTrips(trackLocations, sorted[i], trip, boundaryOverrides))try {await NativeLocationService.addBoundaryOverrides(overrides)+ exitSelection()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]- )+ } finally {+ editingTripsRef.current = false+ }+ }, [canMerge, selectedTrips, trackLocations, boundaryOverrides, exitSelection, refreshAfterEdit])- const handleDeleteTrips = useCallback(- async (toDelete: Trip[]) => {- if (toDelete.length === 0) return- const totalPoints = toDelete.reduce((n, t) => n + t.locationCount, 0)+ const handleDeleteSelected = useCallback(async () => {+ if (selectedTrips.length === 0 || editingTripsRef.current) return+ editingTripsRef.current = true+ try {+ const totalPoints = selectedTrips.reduce((n, t) => n + t.locationCount, 0)const confirmed = await showConfirm({- title: toDelete.length === 1 ? `Delete Trip ${toDelete[0].index}?` : `Delete ${toDelete.length} trips?`,+ title:+ selectedTrips.length === 1+ ? `Delete Trip ${selectedTrips[0].index}?`+ : `Delete ${selectedTrips.length} trips?`,message: `Removes ${totalPoints} location point${totalPoints === 1 ? "" : "s"} from this device only. Already-synced points remain on your server. Unsent points will not be uploaded.`,@@ -291,65 +383,141 @@ export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Loif (!confirmed) returntry {await NativeLocationService.deleteLocationsInRanges(- toDelete.map((t) => ({ start: t.startTime, end: t.endTime }))+ selectedTrips.map((t) => ({ start: t.startTime, end: t.endTime })))+ exitSelection()await refreshAfterEdit()} catch (error) {logger.error("[LocationHistory] Trip delete failed:", error)showAlert("Delete Failed", "Unable to delete selection. Please try again.", "error")}- },- [refreshAfterEdit]+ } finally {+ editingTripsRef.current = false+ }+ }, [selectedTrips, exitSelection, refreshAfterEdit])++ const handleMoreSelection = useCallback(async () => {+ const choice = await showChoice({+ title: "Selection",+ message: `${selected.size} of ${trips.length} trips selected`,+ variant: "info",+ buttons: [{ text: "Select all" }, { text: "Clear selection" }, { text: "Cancel", style: "secondary" }]+ })+ if (choice === 0) setSelected(new Set(trips.map((t) => t.index)))+ else if (choice === 1) exitSelection()+ }, [selected.size, trips, exitSelection])++ const toggleTrip = useCallback((index: number) => {+ setSelected((prev) => {+ const next = new Set(prev)+ if (next.has(index)) next.delete(index)+ else next.add(index)+ return next+ })+ }, [])++ const enterSelection = useCallback((index: number) => setSelected(new Set([index])), [])++ // The title carries the count, and a title change is silent for a screen reader.+ useEffect(() => {+ if (selecting) AccessibilityInfo.announceForAccessibility(`${selected.size} selected`)+ else if (wasSelectingRef.current) AccessibilityInfo.announceForAccessibility("Selection cleared")+ wasSelectingRef.current = selecting+ }, [selecting, selected.size])++ useEffect(() => {+ if (!selecting) return+ const subscription = BackHandler.addEventListener("hardwareBackPress", () => {+ exitSelection()+ return true+ })+ return () => subscription.remove()+ }, [selecting, exitSelection])++ const renderExitSelection = useCallback(+ () => <HeaderAction icon={X} label="Exit selection" onPress={exitSelection} testID="exit-selection-btn" />,+ [exitSelection])- 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 renderSelectionActions = useCallback(+ () => (+ <View style={styles.headerRow}>+ <HeaderAction+ icon={Upload}+ label="Export selected trips"+ onPress={handleExportSelected}+ testID="export-selected-btn"+ />+ {selected.size > 1 && (+ <HeaderAction+ icon={Merge}+ label="Merge trips"+ hint={canMerge ? undefined : "Select two or more trips that follow each other"}+ color={canMerge ? colors.text : colors.textDisabled}+ onPress={handleMergeSelected}+ testID="merge-btn"+ />+ )}+ <HeaderAction+ icon={Trash2}+ label="Delete trips"+ color={colors.error}+ onPress={handleDeleteSelected}+ testID="delete-trips-btn"+ />+ <HeaderAction icon={EllipsisVertical} label="More" onPress={handleMoreSelection} testID="more-btn" />+ </View>+ ),+ [+ colors,+ canMerge,+ selected.size,+ handleExportSelected,+ handleMergeSelected,+ handleDeleteSelected,+ handleMoreSelection+ ])+ const renderDayActions = useCallback(+ () => (+ <View style={styles.headerRow}>+ {!isToday && <HeaderAction icon={CalendarCheck} label="Go to today" onPress={goToToday} testID="today-btn" />}+ {trips.length > 0 && (+ <HeaderAction icon={Upload} label="Export day" onPress={handleExportDay} testID="export-day-btn" />+ )}+ <HeaderAction+ icon={ChartNoAxesColumn}+ label="Location summary"+ onPress={() => navigation.navigate("Location Summary")}+ testID="summary-btn"+ />+ </View>+ ),+ [isToday, trips.length, goToToday, handleExportDay, navigation]+ )++ useLayoutEffect(() => {+ if (selecting) {+ navigation.setOptions({+ headerLeft: renderExitSelection,+ headerTitle: `${selected.size} selected`,+ headerStyle: { backgroundColor: colors.card },+ headerRight: renderSelectionActions+ })+ return+ }+ navigation.setOptions({+ headerLeft: undefined,+ headerTitle: SCREEN_TITLE,+ headerStyle: undefined,+ headerRight: renderDayActions+ })+ }, [navigation, colors, selecting, selected.size, renderExitSelection, renderSelectionActions, renderDayActions])+const handlePointDelete = useCallback(async (id: number) => {if (deletingPointRef.current) return- // The confirm covers the popup, so name the point in itconst point = trackLocations.find((l) => l.id === id)const at = point?.timestamp ? formatTime(point.timestamp, true) : nullconst confirmed = await showConfirm({@@ -374,146 +542,221 @@ export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Lo[trackLocations, refreshAfterEdit])- 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")- }+ 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 focusTripFromDock = useCallback((index: number | null) => {+ setFocusedTripIndex(index)+ setFitVersion((v) => v + 1)+ }, [])++ const selectPointFromTable = useCallback(+ (id: number) => {+ setSelectedPointId(id)+ changeTab("map")},- [mapDate, fetchDaysWithData]+ [changeTab])- const mapLocations = selectedTrip ? (selectedTrip.locations as LocationCoords[]) : trackLocations-- // 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(- () => (- <CalendarPicker+ const edgeStart = space.lg + insets.left+ const edgeEnd = space.lg + insets.right+ const controlsBottom = space.lg + dockHeight + space.sm+ const cameraPadding = useMemo(+ () => ({+ top: space.lg,+ bottom: dockHeight + space.lg + space.lg,+ left: edgeStart,+ right: edgeEnd + size.iconColumn + space.lg+ }),+ [dockHeight, edgeStart, edgeEnd]+ )++ const empty = emptyDayVariant({ isToday, tracking, longDate: dayLongDate(mapDate), hasLastDay: lastDay !== null })+ const dockEmptyAction =+ empty.action === "lastDay" && lastDay+ ? {+ icon: RotateCcwClock,+ label: "Last day with data",+ sub: lastDaySub(lastDay),+ onPress: () => changeDay(dateFromKey(lastDay.day))+ }+ : empty.action === "dashboard"+ ? {+ icon: CirclePause,+ label: "Open Dashboard",+ sub: "Tracking is off",+ onPress: () => navigation.navigate("Dashboard")+ }+ : undefined+ const emptyAction = dockEmptyAction && { label: dockEmptyAction.label, onPress: dockEmptyAction.onPress }++ const selectedPoint = selectedPointId == null ? undefined : trackLocations.find((l) => l.id === selectedPointId)+ let dockContent: DockContent+ if (selectedPoint && selectedPointId != null) {+ const id = selectedPointId+ dockContent = {+ kind: "point",+ point: selectedPoint,+ note: id in noteOverrides ? noteOverrides[id] : selectedPoint.note,+ hasEndpoint,+ onDelete: () => handlePointDelete(id),+ onClose: () => setSelectedPointId(null),+ onSaveNote: (note) => handlePointNoteChange(id, note)+ }+ } else if (trackLocations.length === 0) {+ dockContent = { kind: "empty", title: empty.title, hint: empty.hint, action: dockEmptyAction }+ } else if (trips.length === 0) {+ dockContent = {+ kind: "points",+ count: trackLocations.length,+ startTime: trackLocations[0].timestamp ?? 0,+ endTime: trackLocations[trackLocations.length - 1].timestamp ?? 0+ }+ } else {+ dockContent = { kind: "legend", trips, focusedTripIndex, onFocusTrip: focusTripFromDock }+ }++ const spinner = showSpinner ? (+ <View style={styles.spinner} pointerEvents="none" testID="day-loading">+ <SpinningLoader size={size.icon.lg} color={colors.primary} />+ </View>+ ) : null++ return (+ <Container>+ <DayHeader+ date={mapDate}+ stats={dayStats}+ loading={loading}+ onPrevious={() => stepDay(-1)}+ onNext={() => stepDay(1)}+ onOpenPicker={() => setPickerOpen(true)}+ nextDisabled={isToday}+ />+ <DayPickerModal+ visible={pickerOpen}date={mapDate}- onDateChange={setMapDate}- locationCount={trackLocations.length}- distance={dailyDistance}- colors={colors}+ onSelect={changeDay}+ onRequestClose={() => setPickerOpen(false)}daysWithData={daysWithData}- daysWithNotes={daysWithNotes}- dayDistances={distanceCache.current.get(`${mapDate.getFullYear()}-${pad2(mapDate.getMonth() + 1)}`)}+ dayStats={monthStats}onMonthChange={fetchDaysWithData}onPrefetchMonth={prefetchMonth}/>- ),- [- mapDate,- trackLocations.length,- dailyDistance,- colors,- daysWithData,- daysWithNotes,- fetchDaysWithData,- prefetchMonth- ]- )- return (- <Container>- {/* Tab Bar */}- <View style={styles.tabBar}>- <Tab label="Map" active={activeTab === "map"} onPress={() => setActiveTab("map")} colors={colors} />- <Tab label="Trips" active={activeTab === "trips"} onPress={() => setActiveTab("trips")} colors={colors} />- <Tab label="Data" active={activeTab === "data"} onPress={() => setActiveTab("data")} colors={colors} />+ <View style={[styles.tabBar, { backgroundColor: colors.background }]}>+ <Tab label="Map" active={activeTab === "map"} onPress={() => changeTab("map")} colors={colors} />+ <Tab label="Trips" active={activeTab === "trips"} onPress={() => changeTab("trips")} colors={colors} />+ <Tab label="Data" active={activeTab === "data"} onPress={() => changeTab("data")} colors={colors} /></View>-- {activeTab === "map" && (- <View style={styles.mapContainer}>- {calendarPicker}- <TrackMap- locations={mapLocations}- colors={colors}- noteOverrides={noteOverrides}- trips={selectedTrip ? undefined : trips}- trackColor={colors.primary}- fitVersion={fitVersion}- onPointNoteChange={handlePointNoteChange}- onPointDelete={handlePointDelete}- onPointSplit={handlePointSplit}- />- {selectedTrip && (- <Pressable- onPress={handleShowFullDay}- style={({ pressed }) => [- styles.floatingPill,- { backgroundColor: colors.primary, borderRadius: colors.borderRadius },- pressed && { opacity: colors.pressedOpacity }- ]}- >- <Text style={[styles.floatingPillText, { color: colors.textOnPrimary }]}>- Trip {selectedTrip.index} · Show full day- </Text>- </Pressable>- )}- </View>- )}-- {activeTab === "trips" && (- <View style={styles.mapContainer}>- {calendarPicker}- <TripList- trips={trips}- colors={colors}- onTripSelect={handleTripSelect}- selectedTripIndex={selectedTrip?.index ?? null}- onExport={exportTrips}- onDelete={handleDeleteTrips}- onMerge={handleMergeTrips}- />- </View>- )}-- {activeTab === "data" && (- <View style={styles.mapContainer}>- {calendarPicker}- <LocationTable locations={tableLocations} colors={colors} />- </View>- )}+ <Divider tight />++ <View style={styles.content}>+ {activeTab === "map" && (+ <>+ <TrackMap+ locations={trackLocations}+ colors={colors}+ noteOverrides={noteOverrides}+ trips={trips}+ trackColor={colors.primary}+ fitVersion={fitVersion}+ selectedPointId={selectedPointId}+ onSelectPoint={setSelectedPointId}+ focusedTripIndex={focusedTripIndex}+ onFocusTrip={setFocusedTripIndex}+ cameraPadding={cameraPadding}+ controlsBottom={controlsBottom}+ controlsEnd={edgeEnd}+ />+ {loading ? (+ spinner+ ) : (+ <InspectorDock+ content={dockContent}+ left={edgeStart}+ right={edgeEnd}+ maxHeight={windowHeight / 2}+ onLayout={(e) => setDockHeight(e.nativeEvent.layout.height)}+ />+ )}+ </>+ )}++ {activeTab === "trips" &&+ (loading ? (+ spinner+ ) : trackLocations.length === 0 ? (+ <EmptyState icon={Route} title={empty.title} hint={empty.hint} action={emptyAction} />+ ) : trips.length === 0 ? (+ <EmptyState+ icon={Route}+ title="No trips"+ hint={`${trackLocations.length} points were recorded but none spread more than 100 m`}+ action={{ label: "Show points", onPress: () => changeTab("data") }}+ />+ ) : (+ <TripList+ trips={trips}+ selected={selected}+ onToggle={toggleTrip}+ onEnterSelection={enterSelection}+ onOpenTrip={openTrip}+ />+ ))}++ {activeTab === "data" &&+ (loading ? (+ spinner+ ) : trackLocations.length === 0 ? (+ <EmptyState icon={Table} title={empty.title} hint={empty.hint} action={emptyAction} />+ ) : (+ <LocationTable+ locations={tableLocations}+ colors={colors}+ hasEndpoint={hasEndpoint}+ selectedPointId={selectedPointId ?? undefined}+ onSelectPoint={selectPointFromTable}+ />+ ))}+ </View>+ <ExportFormatDialog+ visible={exportRequest !== null}+ title={exportRequest?.title ?? ""}+ message={exportRequest?.message ?? ""}+ onSelect={settleExport}+ onRequestClose={() => settleExport(null)}+ /></Container>)}const styles = StyleSheet.create({- headerBtn: {- padding: 8+ headerRow: {+ flexDirection: "row"+ },+ tabBar: {+ flexDirection: "row"},- mapContainer: {+ content: {flex: 1},- floatingPill: {+ spinner: {position: "absolute",- bottom: 16,- alignSelf: "center",- paddingHorizontal: 24,- paddingVertical: 12,- elevation: 4,- shadowColor: "#000",- shadowOffset: { width: 0, height: 2 },- shadowOpacity: 0.25,- shadowRadius: 4- },- floatingPillText: {- fontSize: 16,- ...fonts.semiBold- },- tabBar: {- flexDirection: "row",- marginBottom: 12+ top: 0,+ bottom: 0,+ left: 0,+ right: 0,+ alignItems: "center",+ justifyContent: "center"}})diff --git a/apps/mobile/src/screens/LocationSummaryScreen.tsx b/apps/mobile/src/screens/LocationSummaryScreen.tsxindex 15f60fb9..8a14ef67 100644--- a/apps/mobile/src/screens/LocationSummaryScreen.tsx+++ b/apps/mobile/src/screens/LocationSummaryScreen.tsx@@ -3,333 +3,162 @@* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.*/-import React, { useState, useEffect, useMemo, useCallback, useRef } from "react"-import {- View,- Text,- FlatList,- StyleSheet,- ActivityIndicator,- Pressable,- Animated,- RefreshControl,- StyleProp,- TextStyle-} from "react-native"-import { Route, Calendar, MapPin, TrendingUp, ChevronRight } from "lucide-react-native"-import { Container, Card } from "../components"-import { ChipGroup } from "../components/ui/ChipGroup"+import React, { useState, useCallback, useEffect, useRef } from "react"+import { View, ScrollView, StyleSheet, ActivityIndicator } from "react-native"+import { useFocusEffect } from "@react-navigation/native"+import { Route, Calendar, CalendarX, MapPin, TrendingUp } from "lucide-react-native"+import { Card, Container, Divider, EmptyState, ListItem, StatRow, StepperHeader } from "../components"+import { Tab } from "../components/ui/Tab"import { useTheme } from "../hooks/useTheme"import { DailyStat } from "../types/global"import NativeLocationService from "../services/NativeLocationService"-import { formatDistance, formatDuration, startOfDaySec } from "../utils/geo"-import { fonts } from "../styles/typography"+import { formatDistance, formatDuration } from "../utils/geo"import { logger } from "../utils/logger"+import { space } from "../constants"+import { dateOfDayKey, daysInRange, periodRange, periodTotals, rangeBounds, type Period } from "../utils/summaryPeriod"-type Period = "week" | "month" | "30days"--const PERIOD_OPTIONS = [- { value: "week" as const, label: "This Week" },- { value: "month" as const, label: "This Month" },- { value: "30days" as const, label: "Last 30 Days" }+// A year or all time would walk every row in the database; they return with a native daily rollup.+const PERIODS: Array<{ value: Period; label: string }> = [+ { value: "week", label: "Week" },+ { value: "month", label: "Month" }]-const COUNT_UP_DURATION = 600 // ms--function getDateRange(period: Period): { start: number; end: number } {- const now = new Date()- const endTs = Math.floor(now.getTime() / 1000)- let startDate: Date- if (period === "week") {- startDate = new Date(now)- const dayOfWeek = startDate.getDay()- const diff = dayOfWeek === 0 ? 6 : dayOfWeek - 1- startDate.setDate(startDate.getDate() - diff)- } else if (period === "month") {- startDate = new Date(now.getFullYear(), now.getMonth(), 1)- } else {- startDate = new Date(now)- startDate.setDate(startDate.getDate() - 29)- }-- return { start: startOfDaySec(startDate), end: endTs }+function count(n: number, noun: string): string {+ return `${n} ${noun}${n === 1 ? "" : "s"}`}-/** Animated number that counts up from 0 to target */-function AnimatedNumber({- value,- format,- style-}: {- value: number- format: (n: number) => string- style: StyleProp<TextStyle>-}) {- const animRef = useRef(new Animated.Value(0)).current- const [display, setDisplay] = useState(format(0))- const mountedRef = useRef(true)-- useEffect(() => {- mountedRef.current = true- return () => {- mountedRef.current = false- }- }, [])-- useEffect(() => {- animRef.setValue(0)- const listener = animRef.addListener(({ value: v }) => {- if (mountedRef.current) setDisplay(format(Math.round(v)))- })- Animated.timing(animRef, { toValue: value, duration: COUNT_UP_DURATION, useNativeDriver: false }).start()- return () => {- animRef.stopAnimation()- animRef.removeListener(listener)- }- }, [value]) // eslint-disable-line react-hooks/exhaustive-deps-- return <Text style={style}>{display}</Text>+function dayLabel(day: string): string {+ return dateOfDayKey(day).toLocaleDateString(undefined, { weekday: "short", month: "short", day: "numeric" })}export function LocationSummaryScreen({ navigation }: { navigation: any }) {const { colors } = useTheme()const [period, setPeriod] = useState<Period>("week")- const [dailyStats, setDailyStats] = useState<DailyStat[]>([])- const [loading, setLoading] = useState(true)- const [refreshing, setRefreshing] = useState(false)+ const [offset, setOffset] = useState(0)+ // One read per shown period: the native daily stats walk every row in their window, so all+ // history is read only when All asks for it.+ const [cache, setCache] = useState<Record<string, DailyStat[]>>({})+ const [focusCount, setFocusCount] = useState(0)+ const requestRef = useRef(0)++ useFocusEffect(+ useCallback(() => {+ setCache({})+ setFocusCount((n) => n + 1)+ }, [])+ )- const fetchStats = useCallback(async () => {- setLoading(true)- try {- const { start, end } = getDateRange(period)- const stats = await NativeLocationService.getDailyStats(start, end)- setDailyStats(stats)- } catch (err) {- logger.error("[LocationSummary] Failed to fetch stats:", err)- setDailyStats([])- } finally {- setLoading(false)- setRefreshing(false)- }- }, [period])+ const now = new Date()+ const key = `${period}:${offset}`+ const stats = cache[key] ?? null+ const range = periodRange(period, offset, now)useEffect(() => {- fetchStats()- }, [fetchStats])-- // Pull-to-refresh- const handleRefresh = useCallback(() => {- setRefreshing(true)- fetchStats()- }, [fetchStats])-- const summary = useMemo(() => {- const totalDistance = dailyStats.reduce((sum, d) => sum + d.distanceMeters, 0)- const totalTrips = dailyStats.reduce((sum, d) => sum + d.tripCount, 0)- const activeDays = dailyStats.length- const avgDistance = activeDays > 0 ? totalDistance / activeDays : 0-- return { totalDistance, totalTrips, activeDays, avgDistance }- }, [dailyStats])-- const formatDayLabel = useCallback((dayStr: string) => {- const [year, month, day] = dayStr.split("-").map(Number)- const date = new Date(year, month - 1, day)- return date.toLocaleDateString(undefined, { weekday: "short", month: "short", day: "numeric" })+ if (focusCount === 0 || cache[key]) return+ const request = ++requestRef.current+ const { start, end } = rangeBounds(range, new Date())+ NativeLocationService.getDailyStats(start, end)+ .then((rows) => {+ if (request === requestRef.current) setCache((c) => ({ ...c, [key]: rows }))+ })+ .catch((err) => {+ logger.error("[LocationSummary] Failed to fetch stats:", err)+ if (request === requestRef.current) setCache((c) => ({ ...c, [key]: [] }))+ })+ // The range follows the key, and focusCount forces a fresh read after the cache is cleared.+ }, [key, focusCount]) // eslint-disable-line react-hooks/exhaustive-deps++ const days = daysInRange(stats ?? [], range)+ const totals = periodTotals(days)++ const choosePeriod = useCallback((next: Period) => {+ setPeriod(next)+ setOffset(0)}, [])- // Tap daily stat → navigate to Inspector for that day- const handleDayPress = useCallback(- (dayStr: string) => {- const [year, month, day] = dayStr.split("-").map(Number)- const date = new Date(year, month - 1, day)- navigation.navigate("Location History", { initialDate: date.getTime(), initialTab: "trips" })- },+ const openDay = useCallback(+ (day: string) =>+ navigation.navigate("Location History", { initialDate: dateOfDayKey(day).getTime(), initialTab: "trips" }),[navigation])- const renderDailyStat = useCallback(- ({ item }: { item: DailyStat }) => (- <Pressable- onPress={() => handleDayPress(item.day)}- style={({ pressed }) => pressed && { opacity: colors.pressedOpacity }}- >- <Card style={styles.dayCard}>- <View style={styles.dayHeader}>- <Text style={[styles.dayLabel, { color: colors.text }]}>{formatDayLabel(item.day)}</Text>- <View style={styles.dayHeaderRight}>- <Text style={[styles.dayDistance, { color: colors.primary }]}>{formatDistance(item.distanceMeters)}</Text>- <ChevronRight size={14} color={colors.textDisabled} />- </View>- </View>- <View style={styles.dayStats}>- <Text style={[styles.dayStat, { color: colors.textSecondary }]}>- {item.tripCount} {item.tripCount === 1 ? "trip" : "trips"}- </Text>- <Text style={[styles.dayStat, { color: colors.textSecondary }]}>{item.count} points</Text>- <Text style={[styles.dayStat, { color: colors.textSecondary }]}>- {formatDuration(item.endTime - item.startTime)}- </Text>- </View>- </Card>- </Pressable>- ),- [colors, formatDayLabel, handleDayPress]- )-- const summaryHeader = useMemo(- () => (- <View style={styles.summaryGrid}>- <Card style={styles.summaryCard}>- <Route size={16} color={colors.primary} />- <AnimatedNumber- value={summary.totalDistance}- format={(n) => formatDistance(n)}- style={[styles.summaryValue, { color: colors.text }]}- />- <Text style={[styles.summaryLabel, { color: colors.textSecondary }]}>Distance</Text>- </Card>-- <Card style={styles.summaryCard}>- <MapPin size={16} color={colors.primary} />- <AnimatedNumber- value={summary.totalTrips}- format={(n) => String(n)}- style={[styles.summaryValue, { color: colors.text }]}- />- <Text style={[styles.summaryLabel, { color: colors.textSecondary }]}>Trips</Text>- </Card>-- <Card style={styles.summaryCard}>- <Calendar size={16} color={colors.primary} />- <AnimatedNumber- value={summary.activeDays}- format={(n) => String(n)}- style={[styles.summaryValue, { color: colors.text }]}- />- <Text style={[styles.summaryLabel, { color: colors.textSecondary }]}>Active Days</Text>- </Card>-- <Card style={styles.summaryCard}>- <TrendingUp size={16} color={colors.primary} />- <AnimatedNumber- value={summary.avgDistance}- format={(n) => formatDistance(n)}- style={[styles.summaryValue, { color: colors.text }]}- />- <Text style={[styles.summaryLabel, { color: colors.textSecondary }]}>Avg / Day</Text>- </Card>- </View>- ),- [summary, colors]- )-return (<Container>- <View style={styles.header}>- <ChipGroup options={PERIOD_OPTIONS} selected={period} onSelect={setPeriod} colors={colors} />+ <StepperHeader+ title={range.title}+ caption={range.caption}+ onPrevious={() => setOffset((o) => o + 1)}+ onNext={() => setOffset((o) => Math.max(0, o - 1))}+ previousLabel={`Previous ${period}`}+ nextLabel={`Next ${period}`}+ nextDisabled={offset === 0}+ testID="period"+ />+ <View style={styles.tabs} accessibilityRole="tablist">+ {PERIODS.map((p) => (+ <Tab+ key={p.value}+ label={p.label}+ active={period === p.value}+ onPress={() => choosePeriod(p.value)}+ colors={colors}+ />+ ))}</View>-- {loading && !refreshing ? (- <View style={styles.loadingContainer}>+ <Divider tight />+ {stats === null ? (+ <View style={styles.loading}><ActivityIndicator size="large" color={colors.primary} /></View>+ ) : days.length === 0 ? (+ <EmptyState icon={CalendarX} title="Nothing recorded" hint={range.caption} />) : (- <FlatList- data={dailyStats}- renderItem={renderDailyStat}- keyExtractor={(item) => item.day}- contentContainerStyle={styles.listContent}- refreshControl={- <RefreshControl- refreshing={refreshing}- onRefresh={handleRefresh}- tintColor={colors.primary}- colors={[colors.primary]}- />- }- ListHeaderComponent={summaryHeader}- ListEmptyComponent={- <View style={styles.empty}>- <Text style={[styles.emptyText, { color: colors.textSecondary }]}>No data for this period</Text>- </View>+ <ScrollView contentContainerStyle={styles.content}>+ <Card rows testID="period-ledger">+ <StatRow icon={Route} label="Distance" value={formatDistance(totals.distanceMeters)} />+ <Divider tight inset />+ <StatRow icon={MapPin} label="Trips" value={String(totals.trips)} />+ <Divider tight inset />+ <StatRow icon={Calendar} label="Active days" value={String(totals.activeDays)} />+ <Divider tight inset />+ <StatRow icon={TrendingUp} label="Avg / day" value={formatDistance(totals.avgPerDay)} />+ </Card>+ {+ <Card rows testID="period-days">+ {days.map((day, i) => (+ <React.Fragment key={day.day}>+ {i > 0 && <Divider tight inset />}+ <ListItem+ icon={Calendar}+ label={dayLabel(day.day)}+ sub={`${formatDistance(day.distanceMeters)} · ${count(day.tripCount, "trip")} · ${count(day.count, "point")} · ${formatDuration(day.endTime - day.startTime)}`}+ onPress={() => openDay(day.day)}+ accessibilityHint="Opens the day in Location History"+ testID={`day-${day.day}`}+ />+ </React.Fragment>+ ))}+ </Card>}- />+ </ScrollView>)}</Container>)}const styles = StyleSheet.create({- header: {- paddingHorizontal: 16,- paddingTop: 12,- paddingBottom: 8,- marginBottom: 8+ tabs: {+ flexDirection: "row"},- loadingContainer: {+ loading: {flex: 1,alignItems: "center",justifyContent: "center"},- listContent: {- paddingHorizontal: 12,- paddingBottom: 20- },- summaryGrid: {- flexDirection: "row",- flexWrap: "wrap",- gap: 10,- marginBottom: 16- },- summaryCard: {- flexBasis: "45%",- flexGrow: 1,- flexShrink: 0,- alignItems: "center",- padding: 12,- gap: 2- },- summaryValue: {- fontSize: 18,- ...fonts.bold- },- summaryLabel: {- fontSize: 10,- ...fonts.semiBold,- textTransform: "uppercase"- },- dayCard: {- marginBottom: 8,- padding: 12- },- dayHeader: {- flexDirection: "row",- justifyContent: "space-between",- alignItems: "center",- marginBottom: 4- },- dayHeaderRight: {- flexDirection: "row",- alignItems: "center",- gap: 4- },- dayLabel: {- fontSize: 14,- ...fonts.bold- },- dayDistance: {- fontSize: 14,- ...fonts.bold- },- dayStats: {- flexDirection: "row",- gap: 16- },- dayStat: {- fontSize: 12,- ...fonts.regular- },- empty: { alignItems: "center", paddingVertical: 40 },- emptyText: { fontSize: 15, ...fonts.semiBold }+ content: {+ paddingHorizontal: space.lg,+ paddingTop: space.lg,+ paddingBottom: space.xxl,+ gap: space.lg+ }})diff --git a/apps/mobile/src/screens/TripDetailScreen.tsx b/apps/mobile/src/screens/TripDetailScreen.tsxindex fea3da00..be7f30d5 100644--- a/apps/mobile/src/screens/TripDetailScreen.tsx+++ b/apps/mobile/src/screens/TripDetailScreen.tsx@@ -4,35 +4,34 @@*/import React, { useMemo, useState, useCallback, useLayoutEffect, useEffect, useRef } from "react"-import { View, Text, StyleSheet, ScrollView, Pressable } from "react-native"-import {- Route,- Clock,- Gauge,- TrendingUp,- TrendingDown,- MapPin,- Share,- Trash2,- ChevronLeft,- ChevronRight,- type LucideIcon-} from "lucide-react-native"+import { View, Text, StyleSheet, ScrollView, useWindowDimensions } from "react-native"+import { useSafeAreaInsets } from "react-native-safe-area-context"+import { Upload, Trash2, Route, Clock, Gauge, MapPin, TrendingUp, TrendingDown } from "lucide-react-native"import { useTheme } from "../hooks/useTheme"-import { fonts } from "../styles/typography"+import { fontSizes, fonts } from "../styles/typography"+// Deep paths on purpose: the components barrel re-exports DashboardMap, which reaches+// TrackingProvider and builds a NativeEventEmitter at module scope. This screen needs none of it.import { Card } from "../components/ui/Card"import { Container } from "../components/ui/Container"+import { SectionTitle } from "../components/ui/SectionTitle"+import { Divider } from "../components/ui/Divider"+import { StatRow } from "../components/ui/StatRow"+import { StepperHeader } from "../components/ui/StepperHeader"+import { HeaderAction } from "../components/ui/HeaderAction"import { TrackMap } from "../components/features/inspector/TrackMap"+import { TripSwatch } from "../components/features/inspector/TripRow"+import { ExportFormatDialog } from "../components/ui/ExportFormatDialog"+import { InspectorDock } from "../components/features/inspector/InspectorDock"import { InteractiveLineChart } from "../components/features/inspector/InteractiveLineChart"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 { EXPORT_FORMATS, type ExportFormat } from "../utils/exportConverters"+import { size, space } from "../constants"import { showAlert, showConfirm } from "../services/modalService"import { logger } from "../utils/logger"import NativeLocationService from "../services/NativeLocationService"import { BOUNDARY_ACTION_SPLIT } from "../types/global"-import type { Trip, ThemeColors, BoundaryAction } from "../types/global"+import type { Trip, BoundaryAction } from "../types/global"import type { RootScreenProps } from "../types/navigation"const MAX_BARS = 120@@ -52,8 +51,15 @@ function downsample(values: number[], maxBars: number): number[] {return result}+const MAP_VIEWPORT_SHARE = 0.5+// The point card may cover this much of the map; a band of tiles always stays above it.+const DOCK_MAP_SHARE = 0.6+export function TripDetailScreen({ route, navigation }: RootScreenProps<"Trip Detail">) {const { colors } = useTheme()+ const insets = useSafeAreaInsets()+ const { height: viewportHeight } = useWindowDimensions()+ const mapHeight = Math.round(viewportHeight * MAP_VIEWPORT_SHARE)const trip: Trip = route.params.tripconst trips: Trip[] = route.params.tripsconst tripColor = getTripColor(trip.index)@@ -61,12 +67,15 @@ export function TripDetailScreen({ route, navigation }: RootScreenProps<"Trip De// 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 [selectedPointId, setSelectedPointId] = useState<number | null>(null)+ const [dockHeight, setDockHeight] = useState(0)+ const [hasEndpoint, setHasEndpoint] = useState(false)const stats = useMemo(() => computeTripStats(trip.locations), [trip])const duration = trip.endTime - trip.startTimeconst displayName = `Trip ${trip.index}`- const [showExport, setShowExport] = useState(false)+ const [exportOpen, setExportOpen] = useState(false)const [chartActiveIndex, setChartActiveIndex] = useState<number | null>(null)// Without these, a boundary the user merged reads as a plain gap and refuses to splitconst [boundaryOverrides, setBoundaryOverrides] = useState<Map<string, BoundaryAction>>(() => new Map())@@ -89,6 +98,18 @@ export function TripDetailScreen({ route, navigation }: RootScreenProps<"Trip De}}, [])+ useEffect(() => {+ let active = true+ NativeLocationService.getSetting("endpoint")+ .then((endpoint) => {+ if (active) setHasEndpoint((endpoint ?? "").trim().length > 0)+ })+ .catch((error) => logger.error("[TripDetail] Endpoint read failed:", error))+ return () => {+ active = false+ }+ }, [])+const currentIdx = trips.findIndex((t) => t.index === trip.index)const prevTrip = currentIdx > 0 ? trips[currentIdx - 1] : nullconst nextTrip = currentIdx >= 0 && currentIdx < trips.length - 1 ? trips[currentIdx + 1] : null@@ -96,7 +117,8 @@ export function TripDetailScreen({ route, navigation }: RootScreenProps<"Trip De// Reset transient UI state when switching to a different trip.useEffect(() => {setChartActiveIndex(null)- setShowExport(false)+ setExportOpen(false)+ setSelectedPointId(null)}, [trip.index])const goToTrip = useCallback(@@ -179,7 +201,6 @@ export function TripDetailScreen({ route, navigation }: RootScreenProps<"Trip DeEXPORT_FORMATS[format].mimeType,`Colota ${displayName} - ${dateStr}`)- setShowExport(false)} catch (error) {logger.error("[TripDetail] Export failed:", error)showAlert("Export Failed", "Unable to export. Please try again.", "error")@@ -211,16 +232,19 @@ export function TripDetailScreen({ route, navigation }: RootScreenProps<"Trip Deconst headerRight = useCallback(() => (- <Pressable- onPress={handleDelete}- disabled={deleting}- hitSlop={8}- style={({ pressed }) => [styles.headerBtn, (pressed || deleting) && { opacity: colors.pressedOpacity }]}- >- <Trash2 size={20} color={colors.error} />- </Pressable>+ <View style={styles.headerActions}>+ <HeaderAction icon={Upload} label="Export trip" onPress={() => setExportOpen(true)} testID="export-trip-btn" />+ <HeaderAction+ icon={Trash2}+ label="Delete trip"+ color={colors.error}+ disabled={deleting}+ onPress={handleDelete}+ testID="delete-trip-btn"+ />+ </View>),- [handleDelete, deleting, colors.error, colors.pressedOpacity]+ [handleDelete, deleting, colors.error])useLayoutEffect(() => {@@ -248,92 +272,114 @@ export function TripDetailScreen({ route, navigation }: RootScreenProps<"Trip De)const elevationRange = maxElevation - minElevation+ const selectedPoint = selectedPointId == null ? undefined : trip.locations.find((l) => l.id === selectedPointId)+ const dockInset = selectedPoint ? dockHeight : 0+ const edgeStart = space.lg + insets.left+ const edgeEnd = space.lg + insets.right+ const controlsBottom = space.lg + dockInset + space.sm+ const cameraPadding = useMemo(+ () => ({+ top: space.lg,+ bottom: dockInset + space.lg + space.lg,+ left: edgeStart,+ right: edgeEnd + size.iconColumn + space.lg+ }),+ [dockInset, edgeStart, edgeEnd]+ )+return (<Container>- <View style={styles.mapContainer}>+ <StepperHeader+ title={displayName}+ caption={`${formatDate(trip.startTime)} · ${formatTime(trip.startTime, true)} - ${formatTime(trip.endTime, true)}`}+ leading={<TripSwatch index={trip.index} />}+ onPrevious={() => goToTrip(prevTrip)}+ onNext={() => goToTrip(nextTrip)}+ previousLabel="Previous trip"+ nextLabel="Next trip"+ previousDisabled={!prevTrip}+ nextDisabled={!nextTrip}+ testID="trip"+ />+ <View style={{ height: mapHeight }}><TrackMaplocations={trip.locations}colors={colors}trackColor={tripColor}fitVersion={trip.index}noteOverrides={noteOverrides}- onPointNoteChange={handlePointNoteChange}- onPointSplit={handlePointSplit}+ selectedPointId={selectedPointId}+ onSelectPoint={setSelectedPointId}+ onFocusTrip={() => {}}+ cameraPadding={cameraPadding}+ controlsBottom={controlsBottom}+ controlsEnd={edgeEnd}/>+ {selectedPoint && selectedPointId != null && (+ <InspectorDock+ content={{+ kind: "point",+ point: selectedPoint,+ note: selectedPointId in noteOverrides ? noteOverrides[selectedPointId] : selectedPoint.note,+ hasEndpoint,+ onSplit: () => handlePointSplit(selectedPointId),+ onClose: () => setSelectedPointId(null),+ onSaveNote: (note) => handlePointNoteChange(selectedPointId, note)+ }}+ left={edgeStart}+ right={edgeEnd}+ maxHeight={mapHeight * DOCK_MAP_SHARE}+ onLayout={(e) => setDockHeight(e.nativeEvent.layout.height)}+ />+ )}</View><ScrollView contentContainerStyle={styles.content}>- {/* Header */}<View style={styles.section}>- <View style={styles.headerTitleRow}>- <Pressable- onPress={() => goToTrip(prevTrip)}- disabled={!prevTrip}- hitSlop={HIT_SLOP_LG}- style={({ pressed }) => [styles.navBtn, pressed && { opacity: colors.pressedOpacity }]}- >- <ChevronLeft size={24} color={prevTrip ? colors.primary : colors.textDisabled} />- </Pressable>- <View style={styles.headerTitleCenter}>- <View style={styles.headerTitleLine}>- <View style={[styles.dot, { backgroundColor: tripColor }]} />- <Text style={[styles.title, { color: colors.text }]}>{displayName}</Text>- </View>- <Text style={[styles.subtitle, { color: colors.textSecondary }]}>- {formatDate(trip.startTime)} · {formatTime(trip.startTime, true)} - {formatTime(trip.endTime, true)}- </Text>- </View>- <Pressable- onPress={() => goToTrip(nextTrip)}- disabled={!nextTrip}- hitSlop={HIT_SLOP_LG}- style={({ pressed }) => [styles.navBtn, pressed && { opacity: colors.pressedOpacity }]}- >- <ChevronRight size={24} color={nextTrip ? colors.primary : colors.textDisabled} />- </Pressable>- </View>- </View>-- {/* Stats grid */}- <View style={[styles.statsGrid, styles.section]}>- <StatCard icon={Route} label="Distance" value={formatDistance(trip.distance)} colors={colors} />- <StatCard icon={Clock} label="Duration" value={formatDuration(duration)} colors={colors} />- <StatCard icon={Gauge} label="Avg Speed" value={formatSpeed(stats.avgSpeed)} colors={colors} />- <StatCard icon={MapPin} label="Points" value={String(trip.locationCount)} colors={colors} />- {stats.elevationGain > 0 && (- <StatCard- icon={TrendingUp}- label="Elev. Gain"- value={`${Math.round(stats.elevationGain)}m`}- colors={colors}- />- )}- {stats.elevationLoss > 0 && (- <StatCard- icon={TrendingDown}- label="Elev. Loss"- value={`${Math.round(stats.elevationLoss)}m`}- colors={colors}- />- )}+ <Card rows>+ <StatRow icon={Route} label="Distance" value={formatDistance(trip.distance)} />+ <Divider tight inset />+ <StatRow icon={Clock} label="Duration" value={formatDuration(duration)} />+ <Divider tight inset />+ <StatRow icon={Gauge} label="Avg speed" value={formatSpeed(stats.avgSpeed)} />+ <Divider tight inset />+ <StatRow icon={MapPin} label="Points" value={String(trip.locationCount)} />+ {stats.elevationGain > 0 && (+ <>+ <Divider tight inset />+ <StatRow icon={TrendingUp} label="Elev. gain" value={`${Math.round(stats.elevationGain)}m`} />+ </>+ )}+ {stats.elevationLoss > 0 && (+ <>+ <Divider tight inset />+ <StatRow icon={TrendingDown} label="Elev. loss" value={`${Math.round(stats.elevationLoss)}m`} />+ </>+ )}+ </Card></View>{/* Speed profile */}{speedProfile.length > 2 && (<View style={styles.section}>+ <View style={styles.chartTitleRow}>+ <SectionTitle>Speed</SectionTitle>+ <Text style={[styles.chartRange, { color: colors.textSecondary }]}>max {formatSpeed(maxSpeed)}</Text>+ </View><Card style={styles.chartCard}>- <View style={styles.chartTitleRow}>- <Text style={[styles.chartTitle, { color: colors.text }]}>Speed</Text>- <Text style={[styles.chartRange, { color: colors.textSecondary }]}>max {formatSpeed(maxSpeed)}</Text>+ <View+ accessibilityRole="image"+ accessibilityLabel={`Speed over the trip, average ${formatSpeed(stats.avgSpeed)}, maximum ${formatSpeed(maxSpeed)}`}+ >+ <InteractiveLineChart+ data={speedProfile}+ color={colors.primary}+ textColor={colors.text}+ backgroundColor={colors.card}+ formatValue={(v) => formatSpeed(v).replace(/\.\d+/, "")}+ activeIndex={chartActiveIndex}+ onActiveIndexChange={setChartActiveIndex}+ /></View>- <InteractiveLineChart- data={speedProfile}- color={colors.info}- textColor={colors.text}- backgroundColor={colors.card}- formatValue={(v) => formatSpeed(v).replace(/\.\d+/, "")}- activeIndex={chartActiveIndex}- onActiveIndexChange={setChartActiveIndex}- /><View style={styles.chartLabels}>{[0, 0.25, 0.5, 0.75, 1].map((frac) => (<Text key={frac} style={[styles.chartLabel, { color: colors.textSecondary }]}>@@ -348,13 +394,13 @@ export function TripDetailScreen({ route, navigation }: RootScreenProps<"Trip De{/* Elevation profile */}{elevationProfile.length > 2 && elevationRange > 0 && (<View style={styles.section}>+ <View style={styles.chartTitleRow}>+ <SectionTitle>Elevation</SectionTitle>+ <Text style={[styles.chartRange, { color: colors.textSecondary }]}>+ {Math.round(minElevation)}m - {Math.round(maxElevation)}m+ </Text>+ </View><Card style={styles.chartCard}>- <View style={styles.chartTitleRow}>- <Text style={[styles.chartTitle, { color: colors.text }]}>Elevation</Text>- <Text style={[styles.chartRange, { color: colors.textSecondary }]}>- {Math.round(minElevation)}m - {Math.round(maxElevation)}m- </Text>- </View><InteractiveLineChartdata={elevationProfile}color={colors.primary}@@ -374,184 +420,54 @@ export function TripDetailScreen({ route, navigation }: RootScreenProps<"Trip De</Card></View>)}-- {/* Export */}- <View style={styles.section}>- <Pressable- onPress={() => setShowExport((prev) => !prev)}- style={({ pressed }) => [- styles.exportBtn,- { backgroundColor: colors.primary, borderRadius: colors.borderRadius },- pressed && { opacity: 0.8 }- ]}- >- <Share size={16} color={colors.textOnPrimary} />- <Text style={[styles.exportBtnText, { color: colors.textOnPrimary }]}>Export Trip</Text>- </Pressable>-- {showExport && (- <View style={styles.exportRow}>- {EXPORT_FORMAT_KEYS.map((fmt) => (- <Pressable- key={fmt}- onPress={() => handleExport(fmt)}- style={({ pressed }) => [- styles.exportChip,- { backgroundColor: colors.primary + "12", borderColor: colors.primary + "30" },- pressed && { opacity: colors.pressedOpacity }- ]}- >- <Text style={[styles.exportChipText, { color: colors.primary }]}>{EXPORT_FORMATS[fmt].label}</Text>- </Pressable>- ))}- </View>- )}- </View></ScrollView>+ <ExportFormatDialog+ visible={exportOpen}+ title={`Export ${displayName}`}+ message={`${formatDate(trip.startTime)} · ${formatDistance(trip.distance)} · ${formatDuration(duration)}`}+ onSelect={(format) => {+ setExportOpen(false)+ handleExport(format)+ }}+ onRequestClose={() => setExportOpen(false)}+ /></Container>)}-function StatCard({- icon: Icon,- label,- value,- colors-}: {- icon: LucideIcon- label: string- value: string- colors: ThemeColors-}) {- return (- <Card style={styles.statCard}>- <Icon size={16} color={colors.primary} />- <Text style={[styles.statValue, { color: colors.text }]}>{value}</Text>- <Text style={[styles.statLabel, { color: colors.textSecondary }]}>{label}</Text>- </Card>- )-}-const styles = StyleSheet.create({content: {- paddingBottom: 32+ paddingBottom: space.xxl},section: {- paddingHorizontal: 16,- marginTop: 12- },- mapContainer: {- height: 480- },- headerTitleRow: {- flexDirection: "row",- alignItems: "center",- justifyContent: "space-between"- },- headerTitleCenter: {- flex: 1,- alignItems: "center",- gap: 4- },- headerTitleLine: {- flexDirection: "row",- alignItems: "center",- gap: 10- },- navBtn: {- padding: 4- },- dot: {- width: 12,- height: 12,- borderRadius: 6- },- title: {- fontSize: 20,- ...fonts.bold- },- subtitle: {- fontSize: 13,- ...fonts.regular,- textAlign: "center"- },- statsGrid: {- flexDirection: "row",- flexWrap: "wrap",- gap: 8- },- statCard: {- alignItems: "center",- gap: 4,- paddingVertical: 12,- paddingHorizontal: 8,- minWidth: "30%",- flex: 1- },- statValue: {- fontSize: 16,- ...fonts.bold- },- statLabel: {- fontSize: 11,- ...fonts.regular,- textTransform: "uppercase"+ paddingHorizontal: space.lg,+ marginTop: space.md},+chartCard: {- padding: 12+ padding: space.md},chartTitleRow: {flexDirection: "row",justifyContent: "space-between",alignItems: "center",- marginBottom: 8- },- chartTitle: {- fontSize: 14,- ...fonts.semiBold+ marginBottom: space.sm},chartRange: {- fontSize: 11,+ fontSize: fontSizes.small,...fonts.regular},chartLabels: {flexDirection: "row",justifyContent: "space-between",- marginTop: 4,- paddingLeft: 40+ marginTop: space.xs,+ paddingStart: size.iconColumn},chartLabel: {- fontSize: 10,+ fontSize: fontSizes.micro,...fonts.regular},- exportBtn: {- flexDirection: "row",- alignItems: "center",- justifyContent: "center",- gap: 8,- paddingVertical: 14- },- exportBtnText: {- fontSize: 15,- ...fonts.semiBold- },- exportRow: {- flexDirection: "row",- justifyContent: "center",- gap: 8,- marginTop: 12- },- exportChip: {- paddingHorizontal: 14,- paddingVertical: 8,- borderRadius: 8,- borderWidth: 1- },- exportChipText: {- fontSize: 12,- ...fonts.bold- },- headerBtn: {- padding: 8+ headerActions: {+ flexDirection: "row"}})diff --git a/apps/mobile/src/screens/__tests__/LocationHistoryScreen.test.tsx b/apps/mobile/src/screens/__tests__/LocationHistoryScreen.test.tsxdeleted file mode 100644index c6fdedfa..00000000--- a/apps/mobile/src/screens/__tests__/LocationHistoryScreen.test.tsx+++ /dev/null@@ -1,492 +0,0 @@-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", () => ({- __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"),- shareFile: jest.fn(),- deleteLocationsInRange: jest.fn().mockResolvedValue(0),- deleteLocationsByIds: jest.fn().mockResolvedValue(0),- getBoundaryOverrides: jest.fn().mockResolvedValue([]),- addBoundaryOverrides: jest.fn().mockResolvedValue(undefined),- updateLocationNote: 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"),- 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"),- formatTime: jest.fn().mockReturnValue("12:00"),- startOfDaySec: jest.fn().mockReturnValue(0),- endOfDaySec: jest.fn().mockReturnValue(86399)-}))--jest.mock("../../utils/exportConverters", () => ({- EXPORT_FORMATS: {}-}))--jest.mock("../../services/modalService", () => ({- showAlert: jest.fn(),- showConfirm: jest.fn().mockResolvedValue(false)-}))--jest.mock("../../hooks/useTheme", () => ({- useTheme: () => ({- colors: {- primary: "#0d9488",- primaryDark: "#115E59",- border: "#e5e7eb",- text: "#000",- textSecondary: "#6b7280",- textLight: "#9ca3af",- background: "#fff",- success: "#22c55e",- error: "#ef4444",- card: "#fff",- surface: "#fff",- backgroundElevated: "#f9fafb",- textOnPrimary: "#fff",- 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 {- BarChart2: stub("BarChart2")- }-})--jest.mock("../../components", () => {- const R = require("react")- const { View } = require("react-native")- return {- Container: ({ children }: any) => R.createElement(View, null, children)- }-})--jest.mock("../../components/features/inspector/CalendarPicker", () => {- const R = require("react")- const { View } = require("react-native")- return {- CalendarPicker: (_props: any) => R.createElement(View, { testID: "CalendarPicker" })- }-})--jest.mock("../../components/features/inspector/TrackMap", () => {- const R = require("react")- const { View, Pressable, Text } = require("react-native")- return {- 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",- 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, 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" },- 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- )- }-})--jest.mock("../../components/features/inspector/LocationTable", () => {- const R = require("react")- const { View } = require("react-native")- return {- LocationTable: (_props: any) => R.createElement(View, { testID: "LocationTable" })- }-})--jest.mock("../../styles/typography", () => ({- ...jest.requireActual("../../styles/typography"),- fonts: { regular: {}, bold: {}, semiBold: {} }-}))--jest.mock("../../utils/logger", () => ({- logger: { error: jest.fn(), info: jest.fn(), debug: jest.fn() }-}))--jest.mock("@react-navigation/native", () => ({- useFocusEffect: jest.fn()-}))--import { LocationHistoryScreen } from "../LocationInspectorScreen"-import NativeLocationService from "../../services/NativeLocationService"-import { showConfirm, showAlert } from "../../services/modalService"-import { gapsBetweenTrips, segmentTrips } from "../../utils/trips"-import { BOUNDARY_ACTION_SPLIT } from "../../types/global"--const createProps = () =>- ({- navigation: {- navigate: jest.fn(),- setOptions: jest.fn()- },- route: {- params: {}- }- }) 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()- })-- it("renders all three tabs (Map, Trips, Data)", () => {- const props = createProps()- const { getByText } = render(<LocationHistoryScreen {...props} />)-- expect(getByText("Map")).toBeTruthy()- expect(getByText("Trips")).toBeTruthy()- expect(getByText("Data")).toBeTruthy()- })-- it("Map tab is active by default", () => {- const props = createProps()- const { getByTestId, queryByTestId } = render(<LocationHistoryScreen {...props} />)-- // Map tab shows TrackMap- expect(getByTestId("TrackMap")).toBeTruthy()- // Trips and Data content should not be visible- expect(queryByTestId("TripList")).toBeNull()- expect(queryByTestId("LocationTable")).toBeNull()- })-- it("deletes nothing when the point delete confirm is dismissed", async () => {- const props = createProps()- const { getByTestId } = render(<LocationHistoryScreen {...props} />)-- fireEvent.press(getByTestId("trigger-point-delete"))-- await waitFor(() => expect(showConfirm).toHaveBeenCalled())- 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} />)-- fireEvent.press(getByText("Trips"))-- expect(getByTestId("TripList")).toBeTruthy()- expect(queryByTestId("TrackMap")).toBeNull()- expect(queryByTestId("LocationTable")).toBeNull()- })-- it("switches to Data tab on press", () => {- const props = createProps()- const { getByText, getByTestId, queryByTestId } = render(<LocationHistoryScreen {...props} />)-- fireEvent.press(getByText("Data"))-- expect(getByTestId("LocationTable")).toBeTruthy()- expect(queryByTestId("TrackMap")).toBeNull()- expect(queryByTestId("TripList")).toBeNull()- })-- it("renders CalendarPicker in each tab", () => {- const props = createProps()- const { getByText, getByTestId } = render(<LocationHistoryScreen {...props} />)-- // Map tab (default) - should have CalendarPicker- expect(getByTestId("CalendarPicker")).toBeTruthy()-- // Switch to Trips tab- fireEvent.press(getByText("Trips"))- expect(getByTestId("CalendarPicker")).toBeTruthy()-- // Switch to Data tab- fireEvent.press(getByText("Data"))- expect(getByTestId("CalendarPicker")).toBeTruthy()- })-- it("shows LocationTable in Data tab", () => {- const props = createProps()- const { getByText, getByTestId } = render(<LocationHistoryScreen {...props} />)-- // Initially not visible- expect(() => getByTestId("LocationTable")).toThrow()-- // Switch to Data tab- fireEvent.press(getByText("Data"))-- 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__/LocationInspectorScreen.test.tsx b/apps/mobile/src/screens/__tests__/LocationInspectorScreen.test.tsxnew file mode 100644index 00000000..7160611d--- /dev/null+++ b/apps/mobile/src/screens/__tests__/LocationInspectorScreen.test.tsx@@ -0,0 +1,988 @@+import React from "react"+import { AccessibilityInfo, BackHandler } from "react-native"+import { render, fireEvent, waitFor, act } from "@testing-library/react-native"+import { DEFAULT_SETTINGS, type Settings } from "../../types/global"+import { dayKey } from "../../utils/inspectorDay"++// Every locations array the map is handed, so a test can assert the identity survives a save+const mockMapLocationsSeen: any[] = []+let mockSettings: Settings = { ...DEFAULT_SETTINGS, endpoint: "" }+let mockTracking = false++jest.mock("../../services/NativeLocationService", () => ({+ __esModule: true,+ default: {+ getSetting: jest.fn((key: string) => Promise.resolve(key === "unitSystem" ? "metric" : "24h")),+ getDaysWithData: jest.fn().mockResolvedValue([]),+ getDailyStats: jest.fn().mockResolvedValue([]),+ getLocationsByDateRange: jest.fn().mockResolvedValue([]),+ getBoundaryOverrides: jest.fn().mockResolvedValue([]),+ addBoundaryOverrides: jest.fn().mockResolvedValue(undefined),+ deleteLocationsInRanges: jest.fn().mockResolvedValue(0),+ deleteLocationsByIds: jest.fn().mockResolvedValue(0),+ updateLocationNote: jest.fn().mockResolvedValue(undefined),+ exportTripsToFile: jest.fn().mockResolvedValue("/tmp/export"),+ shareFile: jest.fn().mockResolvedValue(true)+ }+}))++// boundarySplits stays real - the split guard's correctness is what the split tests check+jest.mock("../../utils/trips", () => ({+ ...jest.requireActual("../../utils/trips"),+ segmentTrips: jest.fn().mockReturnValue([]),+ getTripColor: jest.fn().mockReturnValue("#3B82F6"),+ buildBoundaryOverrideMap: jest.fn().mockReturnValue(new Map()),+ gapsBetweenTrips: jest.fn().mockReturnValue([])+}))++jest.mock("../../services/modalService", () => ({+ showAlert: jest.fn(),+ showConfirm: jest.fn().mockResolvedValue(false),+ showChoice: jest.fn().mockResolvedValue(-1)+}))++jest.mock("../../hooks/useTheme", () => ({+ useTheme: () => ({ colors: require("@colota/shared").lightColors, isDark: false })+}))++jest.mock("react-native-safe-area-context", () => ({+ useSafeAreaInsets: () => ({ top: 24, bottom: 0, left: 0, right: 0 })+}))++jest.mock("@react-navigation/native", () => ({+ useFocusEffect: jest.fn()+}))++jest.mock("../../contexts/TrackingProvider", () => ({+ useTracking: () => ({ settings: mockSettings, tracking: mockTracking })+}))++jest.mock("../../utils/logger", () => ({+ logger: { error: jest.fn(), info: jest.fn(), debug: jest.fn() }+}))++jest.mock("../../components/ui/ExportFormatDialog", () => {+ const R = require("react")+ const { View } = require("react-native")+ return {+ ExportFormatDialog: (props: any) =>+ props.visible ? R.createElement(View, { testID: "ExportFormatDialog", ...props }) : null+ }+})++jest.mock("../../components", () => {+ const R = require("react")+ const { View, Text, Pressable } = require("react-native")+ const { dayKey: key } = require("../../utils/inspectorDay")+ return {+ Container: ({ children }: any) => R.createElement(View, null, children),+ HeaderAction: ({ label, hint, disabled, onPress, testID }: any) =>+ R.createElement(Pressable, {+ testID,+ onPress,+ disabled,+ accessibilityRole: "button",+ accessibilityLabel: label,+ accessibilityHint: hint,+ accessibilityState: { disabled: !!disabled }+ }),+ Divider: () => R.createElement(View, { testID: "divider" }),+ SpinningLoader: () => R.createElement(View, { testID: "spinner" }),+ EmptyState: ({ title, hint, action }: any) =>+ R.createElement(+ View,+ { testID: "EmptyState" },+ R.createElement(Text, null, title),+ hint ? R.createElement(Text, null, hint) : null,+ action+ ? R.createElement(+ Pressable,+ { accessibilityRole: "button", accessibilityLabel: action.label, onPress: action.onPress },+ R.createElement(Text, null, action.label)+ )+ : null+ ),+ DayHeader: (props: any) =>+ R.createElement(+ View,+ { testID: "DayHeader" },+ R.createElement(Text, { testID: "day-header-date" }, key(props.date)),+ R.createElement(Text, { testID: "day-header-ledger" }, props.loading ? "Loading" : JSON.stringify(props.stats)),+ R.createElement(Pressable, { testID: "day-previous", onPress: props.onPrevious }),+ R.createElement(Pressable, { testID: "day-title", onPress: props.onOpenPicker }),+ R.createElement(Pressable, {+ testID: "day-next",+ onPress: props.onNext,+ disabled: props.nextDisabled,+ accessibilityState: { disabled: props.nextDisabled }+ })+ ),+ DayPickerModal: (props: any) =>+ props.visible+ ? R.createElement(+ View,+ { testID: "DayPickerModal" },+ R.createElement(Pressable, {+ testID: "picker-select",+ onPress: () => {+ props.onSelect(new Date(2026, 0, 15))+ props.onRequestClose()+ }+ })+ )+ : null,+ InspectorDock: ({ content }: any) => {+ const children = [R.createElement(Text, { key: "kind", testID: "dock-kind" }, content.kind)]+ if (content.kind === "legend") {+ children.push(R.createElement(Text, { key: "f", testID: "dock-focused" }, String(content.focusedTripIndex)))+ content.trips.forEach((t: any) =>+ children.push(+ R.createElement(Pressable, {+ key: t.index,+ testID: `dock-trip-${t.index}`,+ onPress: () => content.onFocusTrip(content.focusedTripIndex === t.index ? null : t.index)+ })+ )+ )+ }+ if (content.kind === "points") children.push(R.createElement(Text, { key: "c" }, `${content.count} points`))+ if (content.kind === "point") {+ children.push(+ R.createElement(Text, { key: "id", testID: "point-id" }, String(content.point.id)),+ R.createElement(Text, { key: "n", testID: "point-note" }, content.note ?? ""),+ R.createElement(Text, { key: "e", testID: "point-endpoint" }, String(content.hasEndpoint)),+ content.onSplit && R.createElement(Pressable, { key: "s", testID: "point-split", onPress: content.onSplit }),+ R.createElement(Pressable, { key: "d", testID: "point-delete", onPress: content.onDelete }),+ R.createElement(Pressable, { key: "x", testID: "point-close", onPress: content.onClose }),+ R.createElement(Pressable, {+ key: "w",+ testID: "point-save-note",+ onPress: () => content.onSaveNote("lunch")+ })+ )+ }+ if (content.kind === "empty") {+ children.push(+ R.createElement(Text, { key: "t" }, content.title),+ R.createElement(Text, { key: "h" }, content.hint),+ content.action+ ? R.createElement(+ Pressable,+ { key: "a", testID: "dock-empty-action", onPress: content.action.onPress },+ R.createElement(Text, null, content.action.label),+ R.createElement(Text, null, content.action.sub)+ )+ : null+ )+ }+ return R.createElement(View, { testID: "InspectorDock" }, children)+ },+ 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 ?? {})),+ R.createElement(Text, { key: "s", testID: "TrackMap-selected" }, String(props.selectedPointId)),+ R.createElement(Text, { key: "f", testID: "TrackMap-focused" }, String(props.focusedTripIndex)),+ R.createElement(Pressable, {+ key: "p",+ testID: "map-select-point",+ onPress: () => props.onSelectPoint(props.locations?.[2]?.id ?? 7)+ }),+ R.createElement(Pressable, {+ key: "p0",+ testID: "map-select-first-point",+ onPress: () => props.onSelectPoint(props.locations?.[0]?.id ?? 7)+ }),+ R.createElement(Pressable, { key: "l", testID: "map-focus-line", onPress: () => props.onFocusTrip(2) })+ )+ }+ }+})++jest.mock("../../components/features/inspector/TripList", () => {+ const R = require("react")+ const { View, Pressable } = require("react-native")+ return {+ TripList: ({ trips, selected, onToggle, onEnterSelection, onOpenTrip }: any) =>+ R.createElement(+ View,+ { testID: "TripList" },+ trips.map((t: any) =>+ R.createElement(Pressable, {+ key: t.index,+ testID: `trip-row-${t.index}`,+ accessibilityState: { selected: selected.has(t.index) },+ onPress: () => (selected.size > 0 ? onToggle(t.index) : onOpenTrip(t.index)),+ onLongPress: () => (selected.size > 0 ? onToggle(t.index) : onEnterSelection(t.index))+ })+ )+ )+ }+})++jest.mock("../../components/features/inspector/LocationTable", () => {+ const R = require("react")+ const { View, Text, Pressable } = require("react-native")+ return {+ LocationTable: ({ locations, hasEndpoint, selectedPointId, onSelectPoint }: any) =>+ R.createElement(+ View,+ { testID: "LocationTable" },+ R.createElement(Text, { key: "e", testID: "table-endpoint" }, String(hasEndpoint)),+ R.createElement(Text, { key: "s", testID: "table-selected" }, String(selectedPointId)),+ locations.map((l: any) =>+ R.createElement(Pressable, { key: l.id, testID: `table-row-${l.id}`, onPress: () => onSelectPoint(l.id) })+ )+ )+ }+})++import { LocationHistoryScreen } from "../LocationInspectorScreen"+import NativeLocationService from "../../services/NativeLocationService"+import { showAlert, showChoice, showConfirm } from "../../services/modalService"+import { gapsBetweenTrips, segmentTrips } from "../../utils/trips"+import { lightColors } from "@colota/shared"+import { loadDisplayPreferences } from "../../utils/geo"++beforeAll(() => loadDisplayPreferences())++const TODAY = new Date()+const daysAgo = (n: number) => new Date(TODAY.getFullYear(), TODAY.getMonth(), TODAY.getDate() - n)++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 }+]++// Five points 100s apart: one trip, with index 2 the only point a split can apply to+const DAY_TRIP = {+ index: 1,+ locations: DAY_POINTS,+ startTime: 1000,+ endTime: 1400,+ distance: 500,+ locationCount: 5,+ startIndex: 0+}++const TRIP_1 = {+ index: 1,+ locations: DAY_POINTS.slice(0, 2),+ startTime: 1000,+ endTime: 1100,+ distance: 500,+ locationCount: 2,+ startIndex: 0+}+const TRIP_2 = {+ index: 2,+ locations: DAY_POINTS.slice(2, 4),+ startTime: 1200,+ endTime: 1300,+ distance: 700,+ locationCount: 2,+ startIndex: 2+}+const TRIP_3 = {+ index: 3,+ locations: DAY_POINTS.slice(4),+ startTime: 1400,+ endTime: 1400,+ distance: 300,+ locationCount: 1,+ startIndex: 4+}++const createProps = (params: Record<string, unknown> = {}) =>+ ({+ navigation: { navigate: jest.fn(), setOptions: jest.fn() },+ route: { params }+ }) as any++const lastOptions = (props: any) => props.navigation.setOptions.mock.calls.at(-1)[0]+const headerRight = (props: any) => render(lastOptions(props).headerRight())+const headerLeft = (props: any) => render(lastOptions(props).headerLeft())++const settled = (getByTestId: (id: string) => any) =>+ waitFor(() => expect(getByTestId("day-header-ledger").props.children).not.toBe("Loading"))++const withDay = (points = DAY_POINTS, trips: any[] = [TRIP_1, TRIP_2, TRIP_3]) => {+ ;(NativeLocationService.getLocationsByDateRange as jest.Mock).mockResolvedValue(points)+ ;(segmentTrips as jest.Mock).mockReturnValue(trips)+}++beforeEach(() => {+ jest.clearAllMocks()+ mockMapLocationsSeen.length = 0+ mockSettings = { ...DEFAULT_SETTINGS, endpoint: "" }+ mockTracking = false+ ;(NativeLocationService.getLocationsByDateRange as jest.Mock).mockResolvedValue([])+ ;(NativeLocationService.getDaysWithData as jest.Mock).mockResolvedValue([])+ ;(NativeLocationService.getDailyStats as jest.Mock).mockResolvedValue([])+ ;(segmentTrips as jest.Mock).mockReturnValue([])+ ;(showConfirm as jest.Mock).mockResolvedValue(false)+ ;(showChoice as jest.Mock).mockResolvedValue(-1)+})++describe("day navigation", () => {+ it("opens on the day the Summary screen asked for, in the lens it named", async () => {+ withDay()+ const target = daysAgo(3)+ const props = createProps({ initialDate: target.getTime(), initialTab: "trips" })+ const { getByTestId } = render(<LocationHistoryScreen {...props} />)+ await settled(getByTestId)++ expect(getByTestId("day-header-date").props.children).toBe(dayKey(target))+ expect(getByTestId("TripList")).toBeTruthy()+ })++ it("opens on today with the next chevron disabled and the summary as the only header action", async () => {+ const props = createProps()+ const { getByTestId } = render(<LocationHistoryScreen {...props} />)+ await settled(getByTestId)++ expect(getByTestId("day-header-date").props.children).toBe(dayKey(TODAY))+ expect(getByTestId("day-next").props.accessibilityState.disabled).toBe(true)+ const header = headerRight(props)+ expect(header.getByLabelText("Location summary")).toBeTruthy()+ expect(header.queryByLabelText("Go to today")).toBeNull()+ expect(header.queryByLabelText("Export day")).toBeNull()+ })++ it("steps back a day and offers the way back to today", async () => {+ const props = createProps()+ const { getByTestId } = render(<LocationHistoryScreen {...props} />)+ await settled(getByTestId)++ fireEvent.press(getByTestId("day-previous"))+ await settled(getByTestId)+ expect(getByTestId("day-header-date").props.children).toBe(dayKey(daysAgo(1)))+ expect(getByTestId("day-next").props.accessibilityState.disabled).toBe(false)++ fireEvent.press(headerRight(props).getByLabelText("Go to today"))+ await settled(getByTestId)+ expect(getByTestId("day-header-date").props.children).toBe(dayKey(TODAY))+ })++ it("opens the calendar from the title and jumps to the picked day", async () => {+ const props = createProps()+ const { getByTestId, queryByTestId } = render(<LocationHistoryScreen {...props} />)+ await settled(getByTestId)+ expect(queryByTestId("DayPickerModal")).toBeNull()++ fireEvent.press(getByTestId("day-title"))+ fireEvent.press(getByTestId("picker-select"))+ await settled(getByTestId)++ expect(queryByTestId("DayPickerModal")).toBeNull()+ expect(getByTestId("day-header-date").props.children).toBe("2026-01-15")+ })++ it("hands the header the day's ledger once the fetch lands", async () => {+ withDay()+ const { getByTestId } = render(<LocationHistoryScreen {...createProps()} />)+ await settled(getByTestId)++ expect(JSON.parse(getByTestId("day-header-ledger").props.children)).toEqual({+ points: 5,+ trips: 3,+ distanceMeters: 1500+ })+ })+})++describe("lenses", () => {+ it("shows exactly one lens and switches by tap", async () => {+ withDay()+ const { getByText, getByTestId, queryByTestId } = render(<LocationHistoryScreen {...createProps()} />)+ await settled(getByTestId)+ expect(getByTestId("TrackMap")).toBeTruthy()+ expect(queryByTestId("TripList")).toBeNull()++ fireEvent.press(getByText("Trips"))+ expect(getByTestId("TripList")).toBeTruthy()+ expect(queryByTestId("TrackMap")).toBeNull()++ fireEvent.press(getByText("Data"))+ expect(getByTestId("LocationTable")).toBeTruthy()+ expect(queryByTestId("TripList")).toBeNull()+ })++ it("tells the table whether a sync endpoint is configured", async () => {+ withDay()+ mockSettings = { ...DEFAULT_SETTINGS, endpoint: "https://example.org/api" }+ const { getByText, getByTestId } = render(<LocationHistoryScreen {...createProps()} />)+ await settled(getByTestId)++ fireEvent.press(getByText("Data"))+ expect(getByTestId("table-endpoint").props.children).toBe("true")+ })++ it("a Data row tap opens that point on the map", async () => {+ withDay()+ const { getByText, getByTestId } = render(<LocationHistoryScreen {...createProps()} />)+ await settled(getByTestId)++ fireEvent.press(getByText("Data"))+ fireEvent.press(getByTestId("table-row-3"))++ expect(getByTestId("TrackMap-selected").props.children).toBe("3")+ expect(getByTestId("dock-kind").props.children).toBe("point")+ expect(getByTestId("point-id").props.children).toBe("3")+ })++ it("the dock lists the trips as the legend and a row tap focuses one", async () => {+ withDay()+ const { getByTestId } = render(<LocationHistoryScreen {...createProps()} />)+ await settled(getByTestId)+ expect(getByTestId("dock-kind").props.children).toBe("legend")++ fireEvent.press(getByTestId("dock-trip-2"))+ expect(getByTestId("TrackMap-focused").props.children).toBe("2")+ expect(getByTestId("dock-focused").props.children).toBe("2")++ fireEvent.press(getByTestId("dock-trip-2"))+ expect(getByTestId("TrackMap-focused").props.children).toBe("null")+ })++ it("a day with points but no trips shows the points line on the map and the Show points route in Trips", async () => {+ withDay(DAY_POINTS, [])+ const { getByText, getByTestId } = render(<LocationHistoryScreen {...createProps()} />)+ await settled(getByTestId)+ expect(getByTestId("dock-kind").props.children).toBe("points")+ expect(getByText("5 points")).toBeTruthy()++ fireEvent.press(getByText("Trips"))+ expect(getByText("No trips")).toBeTruthy()+ fireEvent.press(getByText("Show points"))+ expect(getByTestId("LocationTable")).toBeTruthy()+ })++ it("changing day drops the selected point and the focused trip", async () => {+ withDay()+ const { getByTestId } = render(<LocationHistoryScreen {...createProps()} />)+ await settled(getByTestId)+ fireEvent.press(getByTestId("dock-trip-2"))+ expect(getByTestId("TrackMap-focused").props.children).toBe("2")+ fireEvent.press(getByTestId("map-select-point"))+ expect(getByTestId("dock-kind").props.children).toBe("point")++ fireEvent.press(getByTestId("day-previous"))+ expect(getByTestId("TrackMap-selected").props.children).toBe("null")+ expect(getByTestId("TrackMap-focused").props.children).toBe("null")+ await settled(getByTestId)+ })+})++describe("export", () => {+ it("offers Export day only with trips and runs the chosen format through the day naming", async () => {+ withDay()+ const props = createProps()+ const { getByTestId, queryByTestId } = render(<LocationHistoryScreen {...props} />)+ await settled(getByTestId)+ expect(queryByTestId("ExportFormatDialog")).toBeNull()++ fireEvent.press(headerRight(props).getByLabelText("Export day"))++ const dialog = getByTestId("ExportFormatDialog")+ expect(dialog.props.title).toBe("Export day")+ expect(dialog.props.message).toMatch(/3 trips/)+ await act(async () => dialog.props.onSelect("gpx"))++ await waitFor(() => expect(NativeLocationService.shareFile).toHaveBeenCalled())+ expect(NativeLocationService.exportTripsToFile).toHaveBeenCalledWith(+ [+ expect.objectContaining({ index: 1 }),+ expect.objectContaining({ index: 2 }),+ expect.objectContaining({ index: 3 })+ ],+ "gpx",+ expect.stringMatching(/^colota_trips_\d{4}-\d{2}-\d{2}\.gpx$/)+ )+ expect(queryByTestId("ExportFormatDialog")).toBeNull()+ })++ it("exports nothing when the chooser is dismissed", async () => {+ withDay()+ const props = createProps()+ const { getByTestId, queryByTestId } = render(<LocationHistoryScreen {...props} />)+ await settled(getByTestId)++ fireEvent.press(headerRight(props).getByLabelText("Export day"))+ await act(async () => getByTestId("ExportFormatDialog").props.onRequestClose())++ expect(queryByTestId("ExportFormatDialog")).toBeNull()+ expect(NativeLocationService.exportTripsToFile).not.toHaveBeenCalled()+ })+})++describe("selection", () => {+ const selectTrips = async (props: any, indices: number[]) => {+ const screen = render(<LocationHistoryScreen {...props} />)+ await settled(screen.getByTestId)+ fireEvent.press(screen.getByText("Trips"))+ fireEvent(screen.getByTestId(`trip-row-${indices[0]}`), "longPress")+ indices.slice(1).forEach((i) => fireEvent.press(screen.getByTestId(`trip-row-${i}`)))+ return screen+ }++ it("the header becomes the contextual bar while trips are selected and the X leaves it", async () => {+ withDay()+ const props = createProps()+ const screen = await selectTrips(props, [1, 2])++ expect(lastOptions(props).headerTitle).toBe("2 selected")+ expect(lastOptions(props).headerStyle).toEqual({ backgroundColor: lightColors.card })+ expect(screen.getByTestId("trip-row-2").props.accessibilityState.selected).toBe(true)+ const bar = headerRight(props)+ expect(bar.getByLabelText("Export selected trips")).toBeTruthy()+ expect(bar.getByLabelText("Merge trips")).toBeTruthy()+ expect(bar.getByLabelText("Delete trips")).toBeTruthy()+ expect(bar.getByLabelText("More")).toBeTruthy()++ fireEvent.press(headerLeft(props).getByLabelText("Exit selection"))++ expect(lastOptions(props).headerTitle).toBe("Location history")+ expect(lastOptions(props).headerLeft).toBeUndefined()+ expect(lastOptions(props).headerStyle).toBeUndefined()+ expect(screen.getByTestId("trip-row-2").props.accessibilityState.selected).toBe(false)+ })++ it("tapping the last selected row off exits selection", async () => {+ withDay()+ const props = createProps()+ const screen = await selectTrips(props, [1])++ fireEvent.press(screen.getByTestId("trip-row-1"))+ expect(lastOptions(props).headerTitle).toBe("Location history")+ })++ it("hardware back leaves selection instead of the screen", async () => {+ withDay()+ const handlers: Array<() => boolean> = []+ const remove = jest.fn()+ const spy = jest.spyOn(BackHandler, "addEventListener").mockImplementation((_event, handler) => {+ handlers.push(handler as () => boolean)+ return { remove }+ })+ const props = createProps()+ await selectTrips(props, [1])+ expect(handlers).toHaveLength(1)++ let handled = false+ act(() => {+ handled = handlers[0]()+ })++ expect(handled).toBe(true)+ expect(lastOptions(props).headerTitle).toBe("Location history")+ expect(remove).toHaveBeenCalled()+ spy.mockRestore()+ })++ it("switching lens or day exits selection", async () => {+ withDay()+ const props = createProps()+ const screen = await selectTrips(props, [1])+ expect(lastOptions(props).headerTitle).toBe("1 selected")++ fireEvent.press(screen.getByText("Map"))+ expect(lastOptions(props).headerTitle).toBe("Location history")++ fireEvent.press(screen.getByText("Trips"))+ fireEvent(screen.getByTestId("trip-row-1"), "longPress")+ expect(lastOptions(props).headerTitle).toBe("1 selected")+ fireEvent.press(screen.getByTestId("day-previous"))+ expect(lastOptions(props).headerTitle).toBe("Location history")+ await settled(screen.getByTestId)+ })++ it("Merge explains itself when the selected trips do not follow each other", async () => {+ withDay()+ const props = createProps()+ await selectTrips(props, [1, 3])++ const merge = headerRight(props).getByLabelText("Merge trips")+ expect(merge.props.accessibilityHint).toBe("Select two or more trips that follow each other")+ fireEvent.press(merge)++ await waitFor(() =>+ expect(showAlert).toHaveBeenCalledWith("Merge trips", "Select two or more trips that follow each other.", "info")+ )+ expect(showConfirm).not.toHaveBeenCalled()+ })++ it("offers no Merge while one trip is selected, since there is nothing to merge it with", async () => {+ withDay()+ const props = createProps()+ await selectTrips(props, [2])++ const bar = headerRight(props)+ expect(bar.queryByLabelText("Merge trips")).toBeNull()+ expect(bar.getByLabelText("Delete trips")).toBeTruthy()+ })++ it("Merge on consecutive trips confirms, suppresses the gaps and leaves selection", async () => {+ withDay()+ const gaps = [{ before_timestamp: 1100, after_timestamp: 1200, action: 0 }]+ ;(gapsBetweenTrips as jest.Mock).mockReturnValueOnce(gaps)+ ;(showConfirm as jest.Mock).mockResolvedValueOnce(true)+ const props = createProps()+ await selectTrips(props, [1, 2])++ const merge = headerRight(props).getByLabelText("Merge trips")+ expect(merge.props.accessibilityHint).toBeUndefined()+ fireEvent.press(merge)++ await waitFor(() => expect(NativeLocationService.addBoundaryOverrides).toHaveBeenCalledWith(gaps))+ await waitFor(() => expect(lastOptions(props).headerTitle).toBe("Location history"))+ })++ it("keeps the selection when a merge fails, so the user can retry", async () => {+ withDay()+ ;(showConfirm as jest.Mock).mockResolvedValueOnce(true)+ ;(NativeLocationService.addBoundaryOverrides as jest.Mock).mockRejectedValueOnce(new Error("db"))+ const props = createProps()+ await selectTrips(props, [1, 2])++ fireEvent.press(headerRight(props).getByLabelText("Merge trips"))++ await waitFor(() => expect(showAlert).toHaveBeenCalledWith("Merge Failed", expect.any(String), "error"))+ expect(lastOptions(props).headerTitle).toBe("2 selected")+ })++ it("merges nothing when the merge confirm is dismissed", async () => {+ withDay()+ const props = createProps()+ await selectTrips(props, [1, 2])++ fireEvent.press(headerRight(props).getByLabelText("Merge trips"))++ await waitFor(() => expect(showConfirm).toHaveBeenCalled())+ expect(NativeLocationService.addBoundaryOverrides).not.toHaveBeenCalled()+ expect(lastOptions(props).headerTitle).toBe("2 selected")+ })++ it("Delete trips removes the selected ranges after a destructive confirm", async () => {+ withDay()+ ;(showConfirm as jest.Mock).mockResolvedValueOnce(true)+ const props = createProps()+ await selectTrips(props, [2, 3])++ fireEvent.press(headerRight(props).getByLabelText("Delete trips"))++ await waitFor(() =>+ expect(NativeLocationService.deleteLocationsInRanges).toHaveBeenCalledWith([+ { start: 1200, end: 1300 },+ { start: 1400, end: 1400 }+ ])+ )+ expect(showConfirm).toHaveBeenCalledWith(expect.objectContaining({ destructive: true, confirmText: "Delete" }))+ await waitFor(() => expect(lastOptions(props).headerTitle).toBe("Location history"))+ })++ it("keeps the selection when a delete fails, so the user can retry", async () => {+ withDay()+ ;(showConfirm as jest.Mock).mockResolvedValueOnce(true)+ ;(NativeLocationService.deleteLocationsInRanges as jest.Mock).mockRejectedValueOnce(new Error("db"))+ const props = createProps()+ await selectTrips(props, [2, 3])++ fireEvent.press(headerRight(props).getByLabelText("Delete trips"))++ await waitFor(() => expect(showAlert).toHaveBeenCalledWith("Delete Failed", expect.any(String), "error"))+ expect(lastOptions(props).headerTitle).toBe("2 selected")+ })++ it("ignores a second tap on Delete, or a tap on Merge, while the confirm is up", async () => {+ withDay()+ let resolveConfirm: (confirmed: boolean) => void = () => {}+ ;(showConfirm as jest.Mock).mockReturnValueOnce(new Promise<boolean>((resolve) => (resolveConfirm = resolve)))+ const props = createProps()+ await selectTrips(props, [2, 3])+ const bar = headerRight(props)++ fireEvent.press(bar.getByLabelText("Delete trips"))+ fireEvent.press(bar.getByLabelText("Delete trips"))+ fireEvent.press(bar.getByLabelText("Merge trips"))+ await waitFor(() => expect(showConfirm).toHaveBeenCalledTimes(1))+ await act(async () => resolveConfirm(false))++ expect(showConfirm).toHaveBeenCalledTimes(1)+ expect(NativeLocationService.deleteLocationsInRanges).not.toHaveBeenCalled()+ expect(lastOptions(props).headerTitle).toBe("2 selected")+ })++ it("announces the count as the selection grows and its end, because the title change is silent", async () => {+ withDay()+ const announce = jest.spyOn(AccessibilityInfo, "announceForAccessibility").mockImplementation(() => {})+ const props = createProps()+ await selectTrips(props, [1, 2])+ expect(announce.mock.calls.map((c) => c[0])).toEqual(["1 selected", "2 selected"])++ fireEvent.press(headerLeft(props).getByLabelText("Exit selection"))++ expect(announce).toHaveBeenLastCalledWith("Selection cleared")+ expect(announce).toHaveBeenCalledTimes(3)+ announce.mockRestore()+ })++ it("More offers Select all and Clear selection", async () => {+ withDay()+ ;(showChoice as jest.Mock).mockResolvedValueOnce(0)+ const props = createProps()+ await selectTrips(props, [1])++ fireEvent.press(headerRight(props).getByLabelText("More"))+ await waitFor(() => expect(lastOptions(props).headerTitle).toBe("3 selected"))+ expect(showChoice).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Selection",+ message: "1 of 3 trips selected",+ buttons: [{ text: "Select all" }, { text: "Clear selection" }, { text: "Cancel", style: "secondary" }]+ })+ )+ ;(showChoice as jest.Mock).mockResolvedValueOnce(1)+ fireEvent.press(headerRight(props).getByLabelText("More"))+ await waitFor(() => expect(lastOptions(props).headerTitle).toBe("Location history"))+ })++ it("Export selected trips keeps the single-trip file name", async () => {+ withDay()+ const props = createProps()+ const view = await selectTrips(props, [2])++ fireEvent.press(headerRight(props).getByLabelText("Export selected trips"))+ await act(async () => view.getByTestId("ExportFormatDialog").props.onSelect("geojson"))++ await waitFor(() =>+ expect(NativeLocationService.exportTripsToFile).toHaveBeenCalledWith(+ [expect.objectContaining({ index: 2 })],+ "geojson",+ expect.stringMatching(/^colota_trip2_\d{4}-\d{2}-\d{2}\.geojson$/)+ )+ )+ })++ it("a row tap outside selection opens Trip Detail with the day's trips", async () => {+ withDay()+ const props = createProps()+ const { getByText, getByTestId } = render(<LocationHistoryScreen {...props} />)+ await settled(getByTestId)++ fireEvent.press(getByText("Trips"))+ fireEvent.press(getByTestId("trip-row-2"))++ expect(props.navigation.navigate).toHaveBeenCalledWith(+ "Trip Detail",+ expect.objectContaining({ trip: expect.objectContaining({ index: 2 }), trips: expect.any(Array) })+ )+ })+})++describe("empty day", () => {+ it("a past day with nothing recorded points at the last day with data", async () => {+ const shown = daysAgo(3)+ const last = daysAgo(5)+ ;(NativeLocationService.getDaysWithData as jest.Mock).mockResolvedValue([dayKey(last)])+ ;(NativeLocationService.getDailyStats as jest.Mock).mockResolvedValue([+ { day: dayKey(last), count: 40, startTime: 0, endTime: 0, distanceMeters: 12_400, tripCount: 3 }+ ])+ const props = createProps({ initialDate: shown.getTime() })+ const { getByTestId, getByText, queryByTestId } = render(<LocationHistoryScreen {...props} />)+ await settled(getByTestId)++ expect(getByTestId("dock-kind").props.children).toBe("empty")+ expect(getByText("Nothing recorded")).toBeTruthy()+ expect(getByText("Last day with data")).toBeTruthy()+ expect(getByText(/3 trips · 12.4 km$/)).toBeTruthy()+ expect(queryByTestId("spinner")).toBeNull()++ fireEvent.press(getByTestId("dock-empty-action"))+ await settled(getByTestId)+ expect(getByTestId("day-header-date").props.children).toBe(dayKey(last))+ })++ it("today with tracking on waits for the first fix and offers no action", async () => {+ mockTracking = true+ const { getByTestId, getByText, queryByTestId } = render(<LocationHistoryScreen {...createProps()} />)+ await settled(getByTestId)++ expect(getByText("No locations yet")).toBeTruthy()+ expect(getByText("Tracking is on. The first fix lands here.")).toBeTruthy()+ expect(queryByTestId("dock-empty-action")).toBeNull()+ })++ it("today with tracking off and data on other days opens the Dashboard", async () => {+ ;(NativeLocationService.getDaysWithData as jest.Mock).mockResolvedValue([dayKey(daysAgo(2))])+ const props = createProps()+ const { getByTestId, getByText } = render(<LocationHistoryScreen {...props} />)+ await settled(getByTestId)++ expect(getByText("No locations today")).toBeTruthy()+ fireEvent.press(getByTestId("dock-empty-action"))+ expect(props.navigation.navigate).toHaveBeenCalledWith("Dashboard")+ })++ it("a fresh install reads as such in every lens", async () => {+ const props = createProps()+ const { getByTestId, getByText, getAllByText, getByLabelText } = render(<LocationHistoryScreen {...props} />)+ await settled(getByTestId)++ expect(getByText("Nothing recorded yet")).toBeTruthy()+ fireEvent.press(getByText("Trips"))+ expect(getByTestId("EmptyState")).toBeTruthy()+ expect(getAllByText("Nothing recorded yet")).toHaveLength(1)+ fireEvent.press(getByLabelText("Open Dashboard"))+ expect(props.navigation.navigate).toHaveBeenCalledWith("Dashboard")++ fireEvent.press(getByText("Data"))+ expect(getByTestId("EmptyState")).toBeTruthy()+ expect(getByText("Start tracking on the Dashboard and today's track appears here.")).toBeTruthy()+ })++ it("hides the Share action on a day without trips", async () => {+ const props = createProps()+ const { getByTestId } = render(<LocationHistoryScreen {...props} />)+ await settled(getByTestId)++ expect(headerRight(props).queryByLabelText("Export day")).toBeNull()+ })+})++describe("loading", () => {+ afterEach(() => jest.useRealTimers())++ it("shows the spinner only once a fetch outlasts the delay, never the empty composition", async () => {+ jest.useFakeTimers()+ ;(NativeLocationService.getLocationsByDateRange as jest.Mock).mockReturnValue(new Promise(() => {}))+ const { getByTestId, queryByTestId, queryByText } = render(<LocationHistoryScreen {...createProps()} />)+ await act(async () => {})++ expect(getByTestId("day-header-ledger").props.children).toBe("Loading")+ expect(queryByTestId("spinner")).toBeNull()+ expect(queryByTestId("InspectorDock")).toBeNull()++ act(() => {+ jest.advanceTimersByTime(200)+ })++ expect(getByTestId("spinner")).toBeTruthy()+ expect(queryByTestId("InspectorDock")).toBeNull()+ expect(queryByText("Nothing recorded yet")).toBeNull()+ })++ it("clears the day and reports a failed fetch, so nothing acts on another day's data under the new date", async () => {+ withDay()+ const { getByTestId, queryByTestId } = render(<LocationHistoryScreen {...createProps()} />)+ await settled(getByTestId)+ ;(NativeLocationService.getLocationsByDateRange as jest.Mock).mockRejectedValueOnce(new Error("db"))++ fireEvent.press(getByTestId("day-previous"))++ await waitFor(() => expect(showAlert).toHaveBeenCalledWith("Load Failed", expect.any(String), "error"))+ expect(getByTestId("day-header-date").props.children).toBe(dayKey(daysAgo(1)))+ expect(getByTestId("dock-kind").props.children).toBe("empty")+ expect(queryByTestId("spinner")).toBeNull()+ })+})++describe("point card", () => {+ it("offers no Split from the map, because a trip is edited on Trip Detail", async () => {+ withDay(DAY_POINTS, [DAY_TRIP])+ const { getByTestId, queryByTestId } = render(<LocationHistoryScreen {...createProps()} />)+ await settled(getByTestId)++ fireEvent.press(getByTestId("map-select-point"))++ expect(queryByTestId("point-split")).toBeNull()+ })++ it("deletes the point after confirming and the dock returns to the legend", async () => {+ withDay()+ ;(showConfirm as jest.Mock).mockResolvedValueOnce(true)+ const { getByTestId } = render(<LocationHistoryScreen {...createProps()} />)+ await settled(getByTestId)++ fireEvent.press(getByTestId("map-select-point"))+ fireEvent.press(getByTestId("point-delete"))++ await waitFor(() => expect(NativeLocationService.deleteLocationsByIds).toHaveBeenCalledWith([3]))+ await waitFor(() => expect(getByTestId("dock-kind").props.children).toBe("legend"))+ })++ it("deletes nothing when the confirm is dismissed and keeps the card open", async () => {+ withDay()+ const { getByTestId } = render(<LocationHistoryScreen {...createProps()} />)+ await settled(getByTestId)++ fireEvent.press(getByTestId("map-select-point"))+ fireEvent.press(getByTestId("point-delete"))++ await waitFor(() => expect(showConfirm).toHaveBeenCalled())+ expect(NativeLocationService.deleteLocationsByIds).not.toHaveBeenCalled()+ expect(getByTestId("dock-kind").props.children).toBe("point")+ })++ it("closing the card returns the dock to the legend", async () => {+ withDay()+ const { getByTestId } = render(<LocationHistoryScreen {...createProps()} />)+ await settled(getByTestId)++ fireEvent.press(getByTestId("map-select-point"))+ fireEvent.press(getByTestId("point-close"))++ expect(getByTestId("dock-kind").props.children).toBe("legend")+ expect(getByTestId("TrackMap-selected").props.children).toBe("null")+ })+})++describe("notes saved on the map", () => {+ it("shows the saved note in the card and hands it to the map without a new locations array", async () => {+ withDay()+ const { getByTestId } = render(<LocationHistoryScreen {...createProps()} />)+ await settled(getByTestId)+ fireEvent.press(getByTestId("map-select-point"))+ const before = mockMapLocationsSeen[mockMapLocationsSeen.length - 1]++ fireEvent.press(getByTestId("point-save-note"))++ await waitFor(() => expect(NativeLocationService.updateLocationNote).toHaveBeenCalledWith(3, "lunch"))+ await waitFor(() => expect(getByTestId("TrackMap-overrides").props.children).toContain("lunch"))+ expect(getByTestId("point-note").props.children).toBe("lunch")+ expect(getByTestId("dock-kind").props.children).toBe("point")+ expect(mockMapLocationsSeen[mockMapLocationsSeen.length - 1]).toBe(before)+ })++ it("hands Trip Detail the notes saved this session", async () => {+ withDay(DAY_POINTS, [DAY_TRIP])+ const props = createProps()+ const { getByTestId, getByText } = render(<LocationHistoryScreen {...props} />)+ await settled(getByTestId)++ fireEvent.press(getByTestId("map-select-point"))+ fireEvent.press(getByTestId("point-save-note"))+ await waitFor(() => expect(getByTestId("TrackMap-overrides").props.children).toContain("lunch"))+ fireEvent.press(getByText("Trips"))+ fireEvent.press(getByTestId("trip-row-1"))++ expect(props.navigation.navigate).toHaveBeenCalledWith(+ "Trip Detail",+ expect.objectContaining({+ trip: expect.objectContaining({+ locations: expect.arrayContaining([expect.objectContaining({ id: 3, note: "lunch" })])+ }),+ trips: expect.arrayContaining([+ expect.objectContaining({+ locations: expect.arrayContaining([expect.objectContaining({ id: 3, note: "lunch" })])+ })+ ])+ })+ )+ })+})diff --git a/apps/mobile/src/screens/__tests__/LocationSummaryScreen.test.tsx b/apps/mobile/src/screens/__tests__/LocationSummaryScreen.test.tsxnew file mode 100644index 00000000..4ebe0afc--- /dev/null+++ b/apps/mobile/src/screens/__tests__/LocationSummaryScreen.test.tsx@@ -0,0 +1,191 @@+import React from "react"+import { render, waitFor, fireEvent } from "@testing-library/react-native"++const mockGetDailyStats = jest.fn()+jest.mock("../../services/NativeLocationService", () => ({+ __esModule: true,+ default: {+ getDailyStats: (...args: any[]) => mockGetDailyStats(...args)+ }+}))++jest.mock("../../hooks/useTheme", () => ({+ useTheme: () => ({ colors: require("@colota/shared").lightColors })+}))++jest.mock("@react-navigation/native", () => ({+ useFocusEffect: (cb: () => (() => void) | void) => {+ const R = require("react")+ R.useEffect(() => {+ const cleanup = cb()+ return typeof cleanup === "function" ? cleanup : undefined+ }, [cb])+ }+}))++jest.mock("../../components", () => {+ const R = require("react")+ const { View, Text, Pressable } = require("react-native")+ return {+ Container: ({ children }: any) => R.createElement(View, null, children),+ Card: ({ children, testID }: any) => R.createElement(View, { testID }, children),+ Divider: () => null,+ EmptyState: ({ title, hint, action }: any) =>+ R.createElement(+ View,+ { testID: "EmptyState" },+ R.createElement(Text, null, title),+ R.createElement(Text, null, hint),+ action &&+ R.createElement(+ Pressable,+ { accessibilityRole: "button", onPress: action.onPress },+ R.createElement(Text, null, action.label)+ )+ ),+ ListItem: ({ label, sub, onPress, testID }: any) =>+ R.createElement(+ Pressable,+ { accessibilityRole: "button", onPress, testID },+ R.createElement(Text, null, label),+ R.createElement(Text, null, sub)+ ),+ StatRow: ({ label, value }: any) =>+ R.createElement(View, null, R.createElement(Text, null, label), R.createElement(Text, null, value)),+ StepperHeader: (props: any) =>+ R.createElement(+ View,+ { testID: "StepperHeader", ...props },+ R.createElement(Text, null, props.title),+ R.createElement(Text, null, props.caption),+ R.createElement(Pressable, {+ accessibilityRole: "button",+ accessibilityLabel: props.previousLabel,+ accessibilityState: { disabled: !!props.previousDisabled },+ disabled: props.previousDisabled,+ onPress: props.onPrevious+ }),+ R.createElement(Pressable, {+ accessibilityRole: "button",+ accessibilityLabel: props.nextLabel,+ accessibilityState: { disabled: !!props.nextDisabled },+ disabled: props.nextDisabled,+ onPress: props.onNext+ })+ )+ }+})++// Pinned to metric so the ledger is tested for its sums, not for the unit system of the machine.+jest.mock("../../utils/geo", () => ({+ ...jest.requireActual("../../utils/geo"),+ formatDistance: (m: number) => `${(m / 1000).toFixed(1)} km`+}))++jest.mock("../../utils/logger", () => ({+ logger: { debug: jest.fn(), error: jest.fn(), warn: jest.fn(), info: jest.fn() }+}))++import { LocationSummaryScreen } from "../LocationSummaryScreen"++const day = (d: string, distanceMeters: number, tripCount: number) => ({+ day: d,+ count: 412,+ distanceMeters,+ tripCount,+ startTime: 0,+ endTime: 37_200+})++describe("LocationSummaryScreen", () => {+ const now = new Date(2026, 8, 9, 15, 0)+ const nowSec = Math.floor(now.getTime() / 1000)+ const navigate = jest.fn()+ const sec = (y: number, m: number, d: number) => Math.floor(new Date(y, m, d).getTime() / 1000)++ beforeEach(() => {+ jest.clearAllMocks()+ jest.useFakeTimers({ now, advanceTimers: true })+ mockGetDailyStats.mockImplementation(async (start: number) => {+ if (start === sec(2026, 8, 7)) return [day("2026-09-08", 8200, 3), day("2026-09-07", 4000, 1)]+ if (start === sec(2026, 7, 24)) return [day("2026-08-26", 12_400, 2)]+ if (start === sec(2026, 8, 1)) return [day("2026-09-08", 8200, 3), day("2026-09-07", 4000, 1)]+ return []+ })+ })++ afterEach(() => {+ jest.useRealTimers()+ })++ function renderScreen() {+ return render(<LocationSummaryScreen navigation={{ navigate } as any} />)+ }++ it("reads only this week on focus and shows it as a ledger over its days", async () => {+ const { getByText, getByTestId, queryByText } = renderScreen()++ await waitFor(() => expect(getByTestId("period-ledger")).toBeTruthy())+ expect(mockGetDailyStats).toHaveBeenCalledTimes(1)+ expect(mockGetDailyStats).toHaveBeenCalledWith(sec(2026, 8, 7), nowSec)+ expect(getByText("This week")).toBeTruthy()+ expect(getByText("12.2 km")).toBeTruthy()+ expect(getByText("Active days")).toBeTruthy()+ expect(getByText("2")).toBeTruthy()+ expect(getByText(/8\.2 km · 3 trips · 412 points/)).toBeTruthy()+ expect(queryByText(/12\.4 km · 2 trips/)).toBeNull()+ })++ it("opens a day in Location History on its trips", async () => {+ const { getByTestId } = renderScreen()+ await waitFor(() => expect(getByTestId("day-2026-09-08")).toBeTruthy())++ fireEvent.press(getByTestId("day-2026-09-08"))++ expect(navigate).toHaveBeenCalledWith("Location History", {+ initialDate: new Date(2026, 8, 8).getTime(),+ initialTab: "trips"+ })+ })++ it("reads each stepped week once and forward again only as far as this week", async () => {+ const { getByLabelText, getByText, getByTestId } = renderScreen()+ await waitFor(() => expect(getByTestId("period-ledger")).toBeTruthy())+ expect(getByLabelText("Next week").props.accessibilityState.disabled).toBe(true)++ fireEvent.press(getByLabelText("Previous week"))+ await waitFor(() => expect(getByText("Nothing recorded")).toBeTruthy())+ expect(getByText("Last week")).toBeTruthy()+ expect(mockGetDailyStats).toHaveBeenLastCalledWith(sec(2026, 7, 31), sec(2026, 8, 7) - 1)+ expect(getByLabelText("Next week").props.accessibilityState.disabled).toBe(false)++ fireEvent.press(getByLabelText("Previous week"))+ await waitFor(() => expect(getByText(/12\.4 km · 2 trips/)).toBeTruthy())+ expect(getByText(/Aug 24 - Aug 30/)).toBeTruthy()++ fireEvent.press(getByLabelText("Next week"))+ fireEvent.press(getByLabelText("Next week"))+ expect(getByText("This week")).toBeTruthy()+ expect(mockGetDailyStats).toHaveBeenCalledTimes(3)+ })++ it("reads a month as one window and lists its days", async () => {+ const { getByText, getByTestId } = renderScreen()+ await waitFor(() => expect(getByTestId("period-ledger")).toBeTruthy())++ fireEvent.press(getByText("Month"))+ await waitFor(() => expect(getByText("This month")).toBeTruthy())+ await waitFor(() => expect(getByText("12.2 km")).toBeTruthy())+ expect(mockGetDailyStats).toHaveBeenLastCalledWith(sec(2026, 8, 1), nowSec)+ expect(getByTestId("period-days")).toBeTruthy()+ })++ it("shows an empty week with its range and no jump, since the next week with data is not known", async () => {+ mockGetDailyStats.mockResolvedValue([])+ const { getByText, getAllByText, queryByText } = renderScreen()++ await waitFor(() => expect(getByText("Nothing recorded")).toBeTruthy())+ expect(getAllByText("Sep 7 - Sep 13")).toHaveLength(2)+ expect(queryByText(/with data/)).toBeNull()+ })+})diff --git a/apps/mobile/src/screens/__tests__/TripDetailScreen.test.tsx b/apps/mobile/src/screens/__tests__/TripDetailScreen.test.tsxindex 61a281da..0b6a7de1 100644--- a/apps/mobile/src/screens/__tests__/TripDetailScreen.test.tsx+++ b/apps/mobile/src/screens/__tests__/TripDetailScreen.test.tsx@@ -9,6 +9,7 @@ jest.mock("../../services/NativeLocationService", () => ({getBoundaryOverrides: jest.fn().mockResolvedValue([]),deleteLocationsInRange: jest.fn().mockResolvedValue(0),updateLocationNote: jest.fn().mockResolvedValue(undefined),+ getSetting: jest.fn().mockResolvedValue(""),exportTripsToFile: jest.fn().mockResolvedValue("/tmp/export"),shareFile: jest.fn()}@@ -16,70 +17,85 @@ jest.mock("../../services/NativeLocationService", () => ({jest.mock("../../services/modalService", () => ({showAlert: jest.fn(),- showConfirm: jest.fn().mockResolvedValue(false)+ showConfirm: jest.fn().mockResolvedValue(false),+ showPrompt: jest.fn().mockResolvedValue(null)}))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+// A point tap hands the screen an id, and the screen docks the card; no real map is neededjest.mock("../../components/features/inspector/TrackMap", () => {const R = require("react")const { View, Pressable, Text } = require("react-native")+ const trigger = (props: any, testID: string, pick: (locations: any[]) => any) =>+ R.createElement(Pressable, { key: testID, testID, onPress: () => props.onSelectPoint(pick(props.locations)?.id) })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, {- 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+ R.createElement(+ Text,+ { testID: "TrackMap-frame" },+ JSON.stringify({ cameraPadding: props.cameraPadding, controlsBottom: props.controlsBottom })+ ),+ trigger(props, "select-point-first", (l) => l[0]),+ trigger(props, "select-point", (l) => l[2]),+ trigger(props, "select-point-last", (l) => l[l.length - 1]))}})+jest.mock("react-native-safe-area-context", () => ({+ useSafeAreaInsets: () => ({ top: 24, bottom: 0, left: 0, right: 0 })+}))+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/ExportFormatDialog", () => {+ const R = require("react")+ const { View } = require("react-native")+ return {+ ExportFormatDialog: (props: any) =>+ props.visible ? R.createElement(View, { testID: "ExportFormatDialog", ...props }) : null+ }+})+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/Button", () => ({+ Button: function (props: any) {+ return require("react").createElement(+ require("react-native").Pressable,+ { testID: props.testID, onPress: props.onPress, disabled: props.disabled, accessibilityRole: "button" },+ require("react").createElement(require("react-native").Text, null, props.title)+ )+ }+}))+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("../../components/ui/Divider", () => {+ const R = require("react")+ const { View } = require("react-native")+ return { Divider: (props: any) => R.createElement(View, { testID: "divider", ...props }) }+})+jest.mock("../../hooks/useTheme", () => ({useTheme: () => ({colors: {@@ -91,9 +107,7 @@ jest.mock("../../hooks/useTheme", () => ({border: "#e5e7eb",card: "#fff",background: "#fff",- error: "#ef4444",- pressedOpacity: 0.7,- borderRadius: 8+ error: "#ef4444"}})}))@@ -101,25 +115,14 @@ jest.mock("../../hooks/useTheme", () => ({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")- }+ return new Proxy({}, { get: (_target, name) => (_props: any) => R.createElement(Text, null, String(name)) })})import { TripDetailScreen } from "../TripDetailScreen"import NativeLocationService from "../../services/NativeLocationService"-import { showConfirm, showAlert } from "../../services/modalService"+import { showConfirm, showAlert, showPrompt } from "../../services/modalService"import { BOUNDARY_ACTION_SPLIT } from "../../types/global"+import { space, size } from "../../constants"function makeTrip(pointCount: number): Trip {const locations = Array.from({ length: pointCount }, (_, i) => ({@@ -156,6 +159,11 @@ describe("TripDetailScreen - split from the map", () => {return utils}+ const splitAt = (getByTestId: (id: string) => any, point: string) => {+ fireEvent.press(getByTestId(point))+ fireEvent.press(getByTestId("point-split"))+ }+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.@@ -163,7 +171,7 @@ describe("TripDetailScreen - split from the map", () => {const props = makeProps(makeTrip(4))const { getByTestId } = await renderLoaded(props)- fireEvent.press(getByTestId("trigger-point-split"))+ splitAt(getByTestId, "select-point")await waitFor(() =>expect(NativeLocationService.addBoundaryOverrides).toHaveBeenCalledWith([@@ -178,7 +186,7 @@ describe("TripDetailScreen - split from the map", () => {const props = makeProps(makeTrip(4))const { getByTestId } = await renderLoaded(props)- fireEvent.press(getByTestId("trigger-point-split"))+ splitAt(getByTestId, "select-point")await waitFor(() => expect(props.navigation.goBack).toHaveBeenCalled())})@@ -187,7 +195,7 @@ describe("TripDetailScreen - split from the map", () => {const props = makeProps(makeTrip(4))const { getByTestId } = await renderLoaded(props)- fireEvent.press(getByTestId("trigger-point-split"))+ splitAt(getByTestId, "select-point")await waitFor(() => expect(showConfirm).toHaveBeenCalled())expect(NativeLocationService.addBoundaryOverrides).not.toHaveBeenCalled()@@ -200,7 +208,7 @@ describe("TripDetailScreen - split from the map", () => {const props = makeProps(makeTrip(4))const { getByTestId } = await renderLoaded(props)- fireEvent.press(getByTestId("trigger-point-split-first"))+ splitAt(getByTestId, "select-point-first")expect(showConfirm).not.toHaveBeenCalled()expect(NativeLocationService.addBoundaryOverrides).not.toHaveBeenCalled()@@ -211,7 +219,7 @@ describe("TripDetailScreen - split from the map", () => {const props = makeProps(makeTrip(2))const { getByTestId } = await renderLoaded(props)- fireEvent.press(getByTestId("trigger-point-split"))+ splitAt(getByTestId, "select-point-last")// Says why instead of doing nothingexpect(showAlert).toHaveBeenCalledWith("Cannot Split Here", expect.any(String), "info")@@ -223,7 +231,7 @@ describe("TripDetailScreen - split from the map", () => {const props = makeProps(makeTrip(4))const { getByTestId } = await renderLoaded(props)- fireEvent.press(getByTestId("trigger-point-split-last"))+ splitAt(getByTestId, "select-point-last")expect(showConfirm).not.toHaveBeenCalled()expect(NativeLocationService.addBoundaryOverrides).not.toHaveBeenCalled()@@ -235,24 +243,138 @@ describe("TripDetailScreen - split from the map", () => {const props = makeProps(makeTrip(4))const { getByTestId } = await renderLoaded(props)- fireEvent.press(getByTestId("trigger-point-split"))+ splitAt(getByTestId, "select-point")await waitFor(() => expect(NativeLocationService.addBoundaryOverrides).toHaveBeenCalled())expect(props.navigation.goBack).not.toHaveBeenCalled()})})-describe("TripDetailScreen - notes saved on the map", () => {+describe("TripDetailScreen - point card over the map", () => {beforeEach(() => jest.clearAllMocks())+ it("docks the tapped point's card over the map and lifts the camera above it until the card closes", async () => {+ const { getByTestId, queryByTestId } = render(<TripDetailScreen {...makeProps(makeTrip(4))} />)+ await act(async () => {})+ const frame = () => JSON.parse(getByTestId("TrackMap-frame").props.children)+ const base = {+ top: space.lg,+ bottom: space.lg + space.lg,+ left: space.lg,+ right: space.lg + size.iconColumn + space.lg+ }+ expect(queryByTestId("point-card")).toBeNull()+ expect(frame()).toEqual({ cameraPadding: base, controlsBottom: space.lg + space.sm })++ fireEvent.press(getByTestId("select-point"))+ fireEvent(getByTestId("inspector-dock"), "layout", { nativeEvent: { layout: { height: 200 } } })++ expect(getByTestId("point-card")).toBeTruthy()+ expect(frame()).toEqual({+ cameraPadding: { ...base, bottom: 200 + space.lg + space.lg },+ controlsBottom: space.lg + 200 + space.sm+ })++ fireEvent.press(getByTestId("point-close"))++ expect(queryByTestId("point-card")).toBeNull()+ expect(frame()).toEqual({ cameraPadding: base, controlsBottom: space.lg + space.sm })+ })++ it("offers split and a note but no delete, since a trip's points are removed with the trip", async () => {+ const { getByTestId, queryByLabelText, getByLabelText } = render(<TripDetailScreen {...makeProps(makeTrip(4))} />)+ await act(async () => {})++ fireEvent.press(getByTestId("select-point"))++ expect(getByLabelText("Start a new trip here")).toBeTruthy()+ expect(getByLabelText("Note, Add a note")).toBeTruthy()+ expect(queryByLabelText("Delete point")).toBeNull()+ })++ it("drops the card when the chevrons swap in another trip, whose points it does not describe", async () => {+ const props = makeProps(makeTrip(4))+ const { getByTestId, queryByTestId, rerender } = render(<TripDetailScreen {...props} />)+ await act(async () => {})+ fireEvent.press(getByTestId("select-point"))+ expect(getByTestId("point-card")).toBeTruthy()++ const next = { ...makeTrip(4), index: 2 }+ rerender(<TripDetailScreen {...props} route={{ params: { trip: next, trips: [props.route.params.trip, next] } }} />)++ expect(queryByTestId("point-card")).toBeNull()+ })+/** 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))} />)+ it("hands a note saved from the card back to the map", async () => {+ const { getByTestId, getByText } = render(<TripDetailScreen {...makeProps(makeTrip(3))} />)await act(async () => {})- fireEvent.press(getByTestId("trigger-point-note"))+ fireEvent.press(getByTestId("select-point-first"))+ ;(showPrompt as jest.Mock).mockResolvedValueOnce("lunch")+ fireEvent.press(getByTestId("point-note"))await waitFor(() => expect(NativeLocationService.updateLocationNote).toHaveBeenCalledWith(1, "lunch"))await waitFor(() => expect(getByTestId("TrackMap-overrides").props.children).toContain("lunch"))+ expect(getByText("lunch")).toBeTruthy()+ })+})++describe("TripDetailScreen - figures card", () => {+ beforeEach(() => jest.clearAllMocks())++ it("starts every seam between the figure rows at the text column, so it meets the label like the dock's do", async () => {+ const { getAllByTestId } = render(<TripDetailScreen {...makeProps(makeTrip(4))} />)+ await act(async () => {})++ const seams = getAllByTestId("divider")+ expect(seams).toHaveLength(3)+ for (const seam of seams) expect(seam.props).toMatchObject({ tight: true, inset: true })+ })+})++describe("TripDetailScreen - header and stepper", () => {+ beforeEach(() => jest.clearAllMocks())++ const headerRight = (props: any) => render(props.navigation.setOptions.mock.calls.at(-1)[0].headerRight())++ it("names the trip with its swatch over its date and times, between chevrons that step the day's trips", async () => {+ const first = makeTrip(3)+ const second = { ...makeTrip(3), index: 2 }+ const props = { ...makeProps(first), route: { params: { trip: first, trips: [first, second] } } }+ const { getByTestId, getByLabelText } = render(<TripDetailScreen {...props} />)+ await act(async () => {})++ expect(getByTestId("trip-title").props.accessibilityLabel).toMatch(/^Trip 1, /)+ expect(getByLabelText("Previous trip").props.accessibilityState).toEqual({ disabled: true })+ fireEvent.press(getByLabelText("Next trip"))+ expect(props.navigation.setParams).toHaveBeenCalledWith({ trip: second })+ })++ it("exports from the app bar through the format dialog, with no button at the foot of the page", async () => {+ const props = makeProps(makeTrip(3))+ const { getByTestId, queryByTestId, queryByText } = render(<TripDetailScreen {...props} />)+ await act(async () => {})+ expect(queryByText("Export trip")).toBeNull()+ expect(queryByTestId("ExportFormatDialog")).toBeNull()++ fireEvent.press(headerRight(props).getByLabelText("Export trip"))+ const dialog = getByTestId("ExportFormatDialog")+ expect(dialog.props.title).toBe("Export Trip 1")+ await act(async () => dialog.props.onSelect("gpx"))++ await waitFor(() => expect(NativeLocationService.exportTripsToFile).toHaveBeenCalled())+ expect((NativeLocationService.exportTripsToFile as jest.Mock).mock.calls[0][1]).toBe("gpx")+ expect(queryByTestId("ExportFormatDialog")).toBeNull()+ })++ it("keeps Delete in the app bar beside Export", async () => {+ const props = makeProps(makeTrip(3))+ render(<TripDetailScreen {...props} />)+ await act(async () => {})++ const bar = headerRight(props)+ expect(bar.getByLabelText("Export trip")).toBeTruthy()+ expect(bar.getByLabelText("Delete trip")).toBeTruthy()})})diff --git a/apps/mobile/src/utils/__tests__/geo.test.ts b/apps/mobile/src/utils/__tests__/geo.test.tsindex 26cf6225..e6c255c3 100644--- a/apps/mobile/src/utils/__tests__/geo.test.ts+++ b/apps/mobile/src/utils/__tests__/geo.test.ts@@ -135,11 +135,11 @@ describe("formatDistance", () => {describe("formatDuration", () => {it("abbreviates minutes as min, because m is metres and both appear on a trip", () => {- expect(formatDuration(34 * 60)).toBe("34m")+ expect(formatDuration(34 * 60)).toBe("34min")})it("carries the hour when there is one", () => {- expect(formatDuration(3600 + 34 * 60)).toBe("1h 34m")+ expect(formatDuration(3600 + 34 * 60)).toBe("1h 34min")})})diff --git a/apps/mobile/src/utils/__tests__/inspectorDay.test.ts b/apps/mobile/src/utils/__tests__/inspectorDay.test.tsnew file mode 100644index 00000000..faa41b94--- /dev/null+++ b/apps/mobile/src/utils/__tests__/inspectorDay.test.ts@@ -0,0 +1,162 @@+import {+ dateFromKey,+ dayKey,+ emptyDayVariant,+ exportMessage,+ findLastDayWithData,+ isAdjacentSelection,+ lastDaySub,+ monthKey,+ LAST_DAY_SEARCH_MONTHS,+ type MonthData+} from "../inspectorDay"+import { loadDisplayPreferences } from "../geo"++jest.mock("../../services/NativeLocationService", () => ({+ __esModule: true,+ default: {+ getSetting: (key: string) => Promise.resolve(key === "unitSystem" ? "metric" : "24h")+ }+}))++beforeAll(() => loadDisplayPreferences())++const stat = (day: string, tripCount: number, count = 40, distanceMeters = 12_400) => ({+ day,+ count,+ startTime: 0,+ endTime: 0,+ distanceMeters,+ tripCount+})++function monthsOf(days: Record<string, ReturnType<typeof stat>>): (year: number, month: number) => Promise<MonthData> {+ return async (year, month) => {+ const prefix = monthKey(year, month)+ const inMonth = Object.keys(days).filter((d) => d.startsWith(prefix))+ return { days: new Set(inMonth), stats: new Map(inMonth.map((d) => [d, days[d]])) }+ }+}++describe("day keys", () => {+ it("round-trips a local date through its key", () => {+ const date = new Date(2026, 8, 3)+ expect(dayKey(date)).toBe("2026-09-03")+ expect(dateFromKey("2026-09-03").getTime()).toBe(date.getTime())+ expect(monthKey(2026, 0)).toBe("2026-01")+ })+})++describe("findLastDayWithData", () => {+ const NOW = new Date(2026, 8, 8)++ it("picks the nearest earlier day, skipping the month gap in between", async () => {+ const prefetch = jest.fn(monthsOf({ "2026-06-30": stat("2026-06-30", 2), "2026-06-12": stat("2026-06-12", 1) }))+ const result = await findLastDayWithData(new Date(2026, 8, 3), prefetch, NOW)+ expect(result).toEqual({ day: "2026-06-30", stat: stat("2026-06-30", 2) })+ expect(prefetch).toHaveBeenCalledTimes(4)+ })++ it("ignores days after the shown one while walking back", async () => {+ const prefetch = monthsOf({ "2026-09-05": stat("2026-09-05", 1), "2026-09-01": stat("2026-09-01", 3) })+ const result = await findLastDayWithData(new Date(2026, 8, 3), prefetch, NOW)+ expect(result?.day).toBe("2026-09-01")+ })++ it("walks forward to today when nothing earlier exists", async () => {+ const prefetch = monthsOf({ "2026-09-07": stat("2026-09-07", 1) })+ const result = await findLastDayWithData(new Date(2025, 10, 20), prefetch, NOW)+ expect(result?.day).toBe("2026-09-07")+ })++ it("never offers a future day", async () => {+ const prefetch = monthsOf({ "2026-09-20": stat("2026-09-20", 1) })+ expect(await findLastDayWithData(new Date(2026, 8, 3), prefetch, NOW)).toBeNull()+ })++ it("gives up after twelve months back and the forward walk", async () => {+ const prefetch = jest.fn(monthsOf({ "2025-06-01": stat("2025-06-01", 1) }))+ expect(await findLastDayWithData(new Date(2026, 8, 3), prefetch, NOW)).toBeNull()+ expect(prefetch).toHaveBeenCalledTimes(14)+ })++ it("caps the forward walk too, so a jump to 2000 never fetches every month since", async () => {+ const prefetch = jest.fn(monthsOf({}))+ expect(await findLastDayWithData(new Date(2020, 0, 1), prefetch, NOW)).toBeNull()+ expect(prefetch).toHaveBeenCalledTimes(2 * LAST_DAY_SEARCH_MONTHS + 2)+ })+})++describe("lastDaySub", () => {+ it("names the day with its trips and distance", () => {+ expect(lastDaySub({ day: "2026-09-02", stat: stat("2026-09-02", 3) })).toBe(+ `${dateFromKey("2026-09-02").toLocaleDateString(undefined, { weekday: "short", month: "short", day: "numeric" })} · 3 trips · 12.4 km`+ )+ })++ it("falls back to the point count when the day has no trips", () => {+ expect(lastDaySub({ day: "2026-09-02", stat: stat("2026-09-02", 0, 1) })).toMatch(/ · 1 point$/)+ })++ it("shows the date alone when the stat is missing", () => {+ expect(lastDaySub({ day: "2026-09-02", stat: undefined })).not.toContain("·")+ })+})++describe("emptyDayVariant", () => {+ it("offers the jump to the last day with data on a past day", () => {+ expect(+ emptyDayVariant({ isToday: false, tracking: true, longDate: "Wednesday, September 3", hasLastDay: true })+ ).toEqual({+ title: "Nothing recorded",+ hint: "Wednesday, September 3",+ action: "lastDay"+ })+ })++ it("offers nothing on a past day when no other day has data", () => {+ expect(+ emptyDayVariant({ isToday: false, tracking: false, longDate: "Wednesday, September 3", hasLastDay: false }).action+ ).toBeNull()+ })++ it("waits for the first fix while tracking is on today", () => {+ expect(emptyDayVariant({ isToday: true, tracking: true, longDate: "", hasLastDay: true })).toEqual({+ title: "No locations yet",+ hint: "Tracking is on. The first fix lands here.",+ action: null+ })+ })++ it("points to the Dashboard when tracking is off today", () => {+ expect(emptyDayVariant({ isToday: true, tracking: false, longDate: "", hasLastDay: true })).toEqual({+ title: "No locations today",+ hint: "Tracking is off.",+ action: "dashboard"+ })+ })++ it("reads as a first install when no day has data and tracking is off", () => {+ expect(emptyDayVariant({ isToday: true, tracking: false, longDate: "", hasLastDay: false })).toEqual({+ title: "Nothing recorded yet",+ hint: "Start tracking on the Dashboard and today's track appears here.",+ action: "dashboard"+ })+ })+})++describe("export chooser", () => {+ it("describes the export as date, trips and distance", () => {+ expect(exportMessage("Wed, Sep 3", 3, 12_400)).toBe("Wed, Sep 3 · 3 trips · 12.4 km")+ expect(exportMessage("Today", 1, 500)).toBe("Today · 1 trip · 0.5 km")+ })+})++describe("isAdjacentSelection", () => {+ it("accepts consecutive trips in any order and rejects a gap or a single trip", () => {+ expect(isAdjacentSelection([3, 1, 2])).toBe(true)+ expect(isAdjacentSelection([1, 3])).toBe(false)+ expect(isAdjacentSelection([2])).toBe(false)+ expect(isAdjacentSelection(new Set([4, 5]))).toBe(true)+ })+})diff --git a/apps/mobile/src/utils/__tests__/summaryPeriod.test.ts b/apps/mobile/src/utils/__tests__/summaryPeriod.test.tsnew file mode 100644index 00000000..d80e149a--- /dev/null+++ b/apps/mobile/src/utils/__tests__/summaryPeriod.test.ts@@ -0,0 +1,61 @@+import { daysInRange, periodRange, periodTotals, rangeBounds } from "../summaryPeriod"+import type { DailyStat } from "../../types/global"++const now = new Date(2026, 8, 9, 15, 0)+const stat = (day: string, distanceMeters = 1000, tripCount = 1): DailyStat => ({+ day,+ count: 10,+ startTime: 0,+ endTime: 3600,+ distanceMeters,+ tripCount+})++describe("periodRange", () => {+ it("names the current and last week by their place and older weeks by their dates, Monday first", () => {+ expect(periodRange("week", 0, now)).toMatchObject({+ firstDay: "2026-09-07",+ lastDay: "2026-09-13",+ title: "This week"+ })+ expect(periodRange("week", 1, now)).toMatchObject({+ firstDay: "2026-08-31",+ lastDay: "2026-09-06",+ title: "Last week"+ })+ expect(periodRange("week", 3, now).title).toMatch(/Aug 17 - Aug 23/)+ })++ it("steps months whole, so a range never straddles two of them", () => {+ expect(periodRange("month", 1, now)).toMatchObject({+ firstDay: "2026-08-01",+ lastDay: "2026-08-31",+ title: "Last month"+ })+ expect(periodRange("month", 2, now).title).toBe("July")+ })+})++describe("daysInRange and periodTotals", () => {+ it("keeps the days inside the range newest first and sums them into the ledger", () => {+ const stats = [stat("2026-09-01", 4000, 2), stat("2026-09-08", 6000, 1), stat("2026-09-20")]+ const days = daysInRange(stats, periodRange("week", 0, now))++ expect(days.map((d) => d.day)).toEqual(["2026-09-08"])+ expect(periodTotals(stats.slice(0, 2))).toEqual({ distanceMeters: 10000, trips: 3, activeDays: 2, avgPerDay: 5000 })+ expect(periodTotals([])).toEqual({ distanceMeters: 0, trips: 0, activeDays: 0, avgPerDay: 0 })+ })+})++describe("rangeBounds", () => {+ it("queries whole local days and never past now", () => {+ const week = periodRange("week", 0, now)+ const bounds = rangeBounds(week, now)++ expect(bounds.start).toBe(Math.floor(new Date(2026, 8, 7).getTime() / 1000))+ expect(bounds.end).toBe(Math.floor(now.getTime() / 1000))+ expect(rangeBounds(periodRange("month", 1, now), now).end).toBe(+ Math.floor(new Date(2026, 8, 1).getTime() / 1000) - 1+ )+ })+})diff --git a/apps/mobile/src/utils/__tests__/trips.test.ts b/apps/mobile/src/utils/__tests__/trips.test.tsindex feea186d..794b2a49 100644--- a/apps/mobile/src/utils/__tests__/trips.test.ts+++ b/apps/mobile/src/utils/__tests__/trips.test.ts@@ -439,22 +439,22 @@ describe("boundarySplits", () => {describe("formatDuration", () => {it("formats minutes only", () => {- expect(formatDuration(300)).toBe("5m")- expect(formatDuration(0)).toBe("0m")- expect(formatDuration(59)).toBe("0m")- expect(formatDuration(60)).toBe("1m")+ expect(formatDuration(300)).toBe("5min")+ expect(formatDuration(0)).toBe("0min")+ expect(formatDuration(59)).toBe("0min")+ expect(formatDuration(60)).toBe("1min")})it("formats hours and minutes", () => {- expect(formatDuration(3600)).toBe("1h 0m")- expect(formatDuration(3660)).toBe("1h 1m")- expect(formatDuration(7200)).toBe("2h 0m")- expect(formatDuration(5400)).toBe("1h 30m")+ expect(formatDuration(3600)).toBe("1h 0min")+ expect(formatDuration(3660)).toBe("1h 1min")+ expect(formatDuration(7200)).toBe("2h 0min")+ expect(formatDuration(5400)).toBe("1h 30min")})it("clamps negative values to 0", () => {- expect(formatDuration(-1)).toBe("0m")- expect(formatDuration(-3600)).toBe("0m")+ expect(formatDuration(-1)).toBe("0min")+ expect(formatDuration(-3600)).toBe("0min")})})diff --git a/apps/mobile/src/utils/geo.ts b/apps/mobile/src/utils/geo.tsindex 23db6f01..19edc0c0 100644--- a/apps/mobile/src/utils/geo.ts+++ b/apps/mobile/src/utils/geo.ts@@ -111,13 +111,13 @@ export function getSpeedUnit(): { factor: number; unit: string } {return usesMiles() ? MPH : KMH}-/** Format seconds duration as "Xh Ym" or "Ym" */+/** Format seconds duration as "Xh Ymin" or "Ymin" */export function formatDuration(seconds: number): string {const s = Math.max(0, seconds)const hours = Math.floor(s / 3600)const minutes = Math.floor((s % 3600) / 60)- if (hours > 0) return `${hours}h ${minutes}m`- return `${minutes}m`+ if (hours > 0) return `${hours}h ${minutes}min`+ return `${minutes}min`}/** Format a Unix-seconds timestamp as a localized time string. */diff --git a/apps/mobile/src/utils/inspectorDay.ts b/apps/mobile/src/utils/inspectorDay.tsnew file mode 100644index 00000000..20776281--- /dev/null+++ b/apps/mobile/src/utils/inspectorDay.ts@@ -0,0 +1,115 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import type { DailyStat } from "../types/global"+import { formatDistance } from "./geo"+import { pad2 } from "./format"++export type MonthData = {+ days: ReadonlySet<string>+ stats: ReadonlyMap<string, DailyStat>+}++export type LastDay = {+ day: string+ stat: DailyStat | undefined+}++export const EMPTY_MONTH: MonthData = { days: new Set(), stats: new Map() }++export const LAST_DAY_SEARCH_MONTHS = 12++export function monthKey(year: number, month: number): string {+ return `${year}-${pad2(month + 1)}`+}++export function dayKey(date: Date): string {+ return `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())}`+}++export function dateFromKey(key: string): Date {+ const [year, month, day] = key.split("-").map(Number)+ return new Date(year, month - 1, day)+}++export async function findLastDayWithData(+ from: Date,+ prefetch: (year: number, month: number) => Promise<MonthData>,+ now: Date = new Date()+): Promise<LastDay | null> {+ const fromKey = dayKey(from)+ const todayKey = dayKey(now)+ for (let back = 0; back <= LAST_DAY_SEARCH_MONTHS; back++) {+ const month = new Date(from.getFullYear(), from.getMonth() - back, 1)+ const data = await prefetch(month.getFullYear(), month.getMonth())+ const day = [...data.days]+ .filter((d) => d < fromKey)+ .sort()+ .pop()+ if (day) return { day, stat: data.stats.get(day) }+ }+ const monthsAhead = Math.min(+ LAST_DAY_SEARCH_MONTHS,+ (now.getFullYear() - from.getFullYear()) * 12 + now.getMonth() - from.getMonth()+ )+ for (let ahead = 0; ahead <= monthsAhead; ahead++) {+ const month = new Date(from.getFullYear(), from.getMonth() + ahead, 1)+ const data = await prefetch(month.getFullYear(), month.getMonth())+ const day = [...data.days].filter((d) => d > fromKey && d <= todayKey).sort()[0]+ if (day) return { day, stat: data.stats.get(day) }+ }+ return null+}++function count(n: number, noun: string): string {+ return `${n} ${noun}${n === 1 ? "" : "s"}`+}++export function lastDaySub({ day, stat }: LastDay): string {+ const date = dateFromKey(day).toLocaleDateString(undefined, { weekday: "short", month: "short", day: "numeric" })+ if (!stat) return date+ if (stat.tripCount === 0) return `${date} · ${count(stat.count, "point")}`+ return `${date} · ${count(stat.tripCount, "trip")} · ${formatDistance(stat.distanceMeters)}`+}++export type EmptyDayAction = "lastDay" | "dashboard"++export type EmptyDayVariant = {+ title: string+ hint: string+ action: EmptyDayAction | null+}++export function emptyDayVariant(input: {+ isToday: boolean+ tracking: boolean+ longDate: string+ hasLastDay: boolean+}): EmptyDayVariant {+ if (!input.isToday) {+ return { title: "Nothing recorded", hint: input.longDate, action: input.hasLastDay ? "lastDay" : null }+ }+ if (input.tracking) {+ return { title: "No locations yet", hint: "Tracking is on. The first fix lands here.", action: null }+ }+ if (input.hasLastDay) {+ return { title: "No locations today", hint: "Tracking is off.", action: "dashboard" }+ }+ return {+ title: "Nothing recorded yet",+ hint: "Start tracking on the Dashboard and today's track appears here.",+ action: "dashboard"+ }+}++export function exportMessage(dateLabel: string, tripCount: number, distanceMeters: number): string {+ return `${dateLabel} · ${count(tripCount, "trip")} · ${formatDistance(distanceMeters)}`+}++export function isAdjacentSelection(indices: Iterable<number>): boolean {+ const sorted = [...indices].sort((a, b) => a - b)+ if (sorted.length < 2) return false+ return sorted.every((index, i) => i === 0 || index === sorted[i - 1] + 1)+}diff --git a/apps/mobile/src/utils/summaryPeriod.ts b/apps/mobile/src/utils/summaryPeriod.tsnew file mode 100644index 00000000..6347a0d0--- /dev/null+++ b/apps/mobile/src/utils/summaryPeriod.ts@@ -0,0 +1,87 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import type { DailyStat } from "../types/global"++export type Period = "week" | "month"++export type PeriodRange = {+ /** Inclusive day keys, "YYYY-MM-DD". */+ firstDay: string+ lastDay: string+ title: string+ caption: string+}++export function dayKeyOf(date: Date): string {+ const m = String(date.getMonth() + 1).padStart(2, "0")+ const d = String(date.getDate()).padStart(2, "0")+ return `${date.getFullYear()}-${m}-${d}`+}++export function dateOfDayKey(key: string): Date {+ const [y, m, d] = key.split("-").map(Number)+ return new Date(y, m - 1, d)+}++function startOfWeek(date: Date): Date {+ const day = date.getDay()+ const back = day === 0 ? 6 : day - 1+ return new Date(date.getFullYear(), date.getMonth(), date.getDate() - back)+}++function shortDate(date: Date, withYear: boolean): string {+ return date.toLocaleDateString(undefined, { month: "short", day: "numeric", ...(withYear && { year: "numeric" }) })+}++function span(first: Date, last: Date, now: Date): string {+ const withYear = first.getFullYear() !== now.getFullYear() || last.getFullYear() !== now.getFullYear()+ return `${shortDate(first, withYear)} - ${shortDate(last, withYear)}`+}++/** The period `offset` steps before the one holding `now`. */+export function periodRange(period: Period, offset: number, now: Date): PeriodRange {+ if (period === "week") {+ const start = startOfWeek(now)+ start.setDate(start.getDate() - offset * 7)+ const end = new Date(start.getFullYear(), start.getMonth(), start.getDate() + 6)+ const title = offset === 0 ? "This week" : offset === 1 ? "Last week" : span(start, end, now)+ const caption = offset < 2 ? span(start, end, now) : `Week of ${shortDate(start, false)}`+ return { firstDay: dayKeyOf(start), lastDay: dayKeyOf(end), title, caption }+ }+ const start = new Date(now.getFullYear(), now.getMonth() - offset, 1)+ const end = new Date(start.getFullYear(), start.getMonth() + 1, 0)+ const named = start.toLocaleDateString(undefined, {+ month: "long",+ ...(start.getFullYear() !== now.getFullYear() && { year: "numeric" })+ })+ const title = offset === 0 ? "This month" : offset === 1 ? "Last month" : named+ const caption = offset < 2 ? named : span(start, end, now)+ return { firstDay: dayKeyOf(start), lastDay: dayKeyOf(end), title, caption }+}++/** The query window for a range, whole days in local time, never past now. */+export function rangeBounds(range: PeriodRange, now: Date): { start: number; end: number } {+ const first = dateOfDayKey(range.firstDay)+ const last = dateOfDayKey(range.lastDay)+ const end = Math.floor(new Date(last.getFullYear(), last.getMonth(), last.getDate() + 1).getTime() / 1000) - 1+ return {+ start: Math.floor(first.getTime() / 1000),+ end: Math.min(end, Math.floor(now.getTime() / 1000))+ }+}++export function daysInRange(stats: DailyStat[], range: PeriodRange): DailyStat[] {+ return stats.filter((s) => s.day >= range.firstDay && s.day <= range.lastDay).sort((a, b) => (a.day < b.day ? 1 : -1))+}++export type PeriodTotals = { distanceMeters: number; trips: number; activeDays: number; avgPerDay: number }++export function periodTotals(days: DailyStat[]): PeriodTotals {+ const distanceMeters = days.reduce((sum, d) => sum + d.distanceMeters, 0)+ const trips = days.reduce((sum, d) => sum + d.tripCount, 0)+ const activeDays = days.length+ return { distanceMeters, trips, activeDays, avgPerDay: activeDays > 0 ? distanceMeters / activeDays : 0 }+}