Colota - Android GPS Location tracker
Add Location History screen with track map and day picker
Max Dietrich7c0812240a52
diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.mdindex b896c08a..fb32e30d 100644--- a/apps/docs/docs/development/architecture.md+++ b/apps/docs/docs/development/architecture.md@@ -57,7 +57,7 @@ All native code lives in `apps/mobile/android/app/src/`, organized by build flavThe primary React Native bridge module (exposed as `"LocationServiceModule"`). Handles all JS-to-native communication for:- Service control (`startService`, `stopService`)-- Database queries (`getStats`, `getTableData`, `getQueuedLocationsCount`)+- Database queries (`getStats`, `getTableData`, `getLocationsByDateRange`, `getQueuedLocationsCount`)- Geofence CRUD operations- Settings persistence- Device info, file operations, authenticationdiff --git a/apps/docs/docs/guides/troubleshooting.md b/apps/docs/docs/guides/troubleshooting.mdindex 34d00422..15623149 100644--- a/apps/docs/docs/guides/troubleshooting.md+++ b/apps/docs/docs/guides/troubleshooting.md@@ -45,7 +45,7 @@ Key log tags:| `LocationDB` | Database operations || `GeofenceHelper` | Zone detection |-You can also use the **Location Inspector** screen in the app to see sent and queued locations with their accuracy and timestamps.+You can also use the **Location History** screen in the app to see recorded locations on a track map or as a list with their accuracy and timestamps.## Database growing too largediff --git a/apps/docs/docs/introduction.md b/apps/docs/docs/introduction.mdindex c3f85b84..4bdee599 100644--- a/apps/docs/docs/introduction.md+++ b/apps/docs/docs/introduction.md@@ -30,7 +30,7 @@ Colota has nine screens, each focused on a specific task:| **API Config** | Endpoint field mapping with templates for Dawarich, OwnTracks, PhoneTrack, Reitti, Traccar, or custom backends || **Auth Settings** | Endpoint authentication (None, Basic Auth, Bearer Token) and custom HTTP headers || **Geofences** | Create, edit, and delete pause zones on an interactive map |-| **Location Inspector** | Debug view for sent and queued locations with pagination and accuracy indicators |+| **Location History** | Browse recorded locations on a track map with day picker, or as a paginated list with accuracy indicators || **Export Data** | Export tracked locations as CSV, GeoJSON, GPX, or KML || **Data Management** | Clear sent history, delete old data, vacuum the database || **About** | App version, device info, links to repository and privacy policy |diff --git a/apps/mobile/.eslintignore b/apps/mobile/.eslintignoreindex 622417cd..db4dc0bc 100644--- a/apps/mobile/.eslintignore+++ b/apps/mobile/.eslintignore@@ -1,4 +1,5 @@# .eslintignore*.min.jscoverage-**/openlayers/*.js\ No newline at end of file+**/openlayers/*.js+android/app/build\ No newline at end of filediff --git a/apps/mobile/App.tsx b/apps/mobile/App.tsxindex 3cc7cf47..7d9cc5d4 100644--- a/apps/mobile/App.tsx+++ b/apps/mobile/App.tsx@@ -18,7 +18,7 @@ import {AuthSettingsScreen,GeofenceScreen,DataManagementScreen,- LocationInspectorScreen,+ LocationHistoryScreen,ExportDataScreen,AboutScreen} from "./src/screens/"@@ -52,9 +52,9 @@ const SCREEN_CONFIG = [title: "Geofences"},{- name: "Locations Inspector",- component: LocationInspectorScreen,- title: "Locations Inspector"+ name: "Location History",+ component: LocationHistoryScreen,+ title: "Location History"},{name: "Export Data",diff --git a/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.ktindex c096684e..fc0482b6 100644--- a/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt@@ -249,6 +249,15 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :}}+ @ReactMethod+ fun getLocationsByDateRange(startTimestamp: Double, endTimestamp: Double, promise: Promise) =+ executeAsync(promise) {+ val rawData = dbHelper.getLocationsByDateRange(startTimestamp.toLong(), endTimestamp.toLong())+ Arguments.createArray().apply {+ rawData.forEach { row -> pushMap(Arguments.makeNativeMap(row)) }+ }+ }+@ReactMethodfun manualFlush(promise: Promise) {try {diff --git a/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.ktindex 0e005b2f..45961b82 100644--- a/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt@@ -292,6 +292,50 @@ class DatabaseHelper private constructor(context: Context) :return data}+ /**+ * Retrieves locations within a date range, ordered chronologically.+ * Used for rendering track polylines on the map view.+ *+ * @param startTimestamp Start of range (Unix seconds, inclusive)+ * @param endTimestamp End of range (Unix seconds, inclusive)+ * @return Locations ordered by timestamp ASC for polyline drawing+ */+ fun getLocationsByDateRange(startTimestamp: Long, endTimestamp: Long): List<Map<String, Any?>> {+ val data = mutableListOf<Map<String, Any?>>()++ try {+ readableDatabase.query(+ TABLE_LOCATIONS,+ null,+ "timestamp >= ? AND timestamp <= ?",+ arrayOf(startTimestamp.toString(), endTimestamp.toString()),+ null, null,+ "timestamp ASC"+ ).use { cursor ->+ val columnNames = cursor.columnNames++ while (cursor.moveToNext()) {+ val row = mutableMapOf<String, Any?>()+ for (column in columnNames) {+ val idx = cursor.getColumnIndex(column)+ if (idx != -1) {+ row[column] = when (cursor.getType(idx)) {+ android.database.Cursor.FIELD_TYPE_INTEGER -> cursor.getLong(idx)+ android.database.Cursor.FIELD_TYPE_FLOAT -> cursor.getDouble(idx)+ android.database.Cursor.FIELD_TYPE_STRING -> cursor.getString(idx)+ else -> null+ }+ }+ }+ data.add(row)+ }+ }+ } catch (e: Exception) {+ Log.e(TAG, "Error reading locations by date range", e)+ }++ return data+ }/*** Adds location to transmission queue.diff --git a/apps/mobile/package.json b/apps/mobile/package.jsonindex b514ac82..62104cfa 100644--- a/apps/mobile/package.json+++ b/apps/mobile/package.json@@ -3,7 +3,8 @@"private": true,"scripts": {"start": "react-native start",- "android": "react-native run-android",+ "android": "react-native run-android --mode gmsDebug --appIdSuffix \"\"",+ "android:foss": "react-native run-android --mode fossDebug --appIdSuffix \"\"","android:debug": "cd android && gradlew assembleGmsDebug","android:debug:foss": "cd android && gradlew assembleFossDebug","android:release": "cd android && gradlew assembleGmsRelease",diff --git a/apps/mobile/src/components/features/dashboard/QuickAccess.tsx b/apps/mobile/src/components/features/dashboard/QuickAccess.tsxindex 8a1dc884..8ba70463 100644--- a/apps/mobile/src/components/features/dashboard/QuickAccess.tsx+++ b/apps/mobile/src/components/features/dashboard/QuickAccess.tsx@@ -37,10 +37,10 @@ export function QuickAccess({ navigation }: QuickAccessProps) {onPress: () => navigation.navigate("Geofences")},{- name: "Inspector",+ name: "History",icon: Search,color: colors.info,- onPress: () => navigation.navigate("Locations Inspector")+ onPress: () => navigation.navigate("Location History")},{name: "Export",diff --git a/apps/mobile/src/components/features/inspector/DatePicker.tsx b/apps/mobile/src/components/features/inspector/DatePicker.tsxnew file mode 100644index 00000000..b809dd30--- /dev/null+++ b/apps/mobile/src/components/features/inspector/DatePicker.tsx@@ -0,0 +1,120 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import React from "react"+import { View, Text, TouchableOpacity, StyleSheet } from "react-native"+import { ChevronLeft, ChevronRight } from "lucide-react-native"+import { ThemeColors } from "../../../types/global"+import { fonts } from "../../../styles/typography"++interface DatePickerProps {+ date: Date+ onDateChange: (date: Date) => void+ locationCount: number+ colors: ThemeColors+}++function isSameDay(a: Date, b: Date): boolean {+ return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate()+}++export function DatePicker({ date, onDateChange, locationCount, colors }: DatePickerProps) {+ const isToday = isSameDay(date, new Date())++ const goBack = () => {+ const prev = new Date(date)+ prev.setDate(prev.getDate() - 1)+ onDateChange(prev)+ }++ const goForward = () => {+ if (isToday) return+ const next = new Date(date)+ next.setDate(next.getDate() + 1)+ onDateChange(next)+ }++ const goToToday = () => {+ onDateChange(new Date())+ }++ const formatted = date.toLocaleDateString(undefined, {+ weekday: "short",+ month: "short",+ day: "numeric",+ year: "numeric"+ })++ return (+ <View style={[styles.container, { borderBottomColor: colors.border }]}>+ <View style={styles.row}>+ <TouchableOpacity onPress={goBack} style={styles.navBtn} activeOpacity={0.6}>+ <ChevronLeft size={22} color={colors.primary} />+ </TouchableOpacity>++ <TouchableOpacity onPress={goToToday} style={styles.dateContainer} activeOpacity={0.7}>+ <Text style={[styles.dateText, { color: colors.text }]}>{formatted}</Text>+ <Text style={[styles.countText, { color: colors.textSecondary }]}>+ {locationCount} {locationCount === 1 ? "location" : "locations"}+ </Text>+ </TouchableOpacity>++ <TouchableOpacity onPress={goForward} style={styles.navBtn} activeOpacity={0.6} disabled={isToday}>+ <ChevronRight size={22} color={isToday ? colors.textDisabled : colors.primary} />+ </TouchableOpacity>+ </View>++ {!isToday && (+ <TouchableOpacity+ onPress={goToToday}+ style={[styles.todayBtn, { backgroundColor: colors.primary + "15" }]}+ activeOpacity={0.7}+ >+ <Text style={[styles.todayText, { color: colors.primary }]}>Today</Text>+ </TouchableOpacity>+ )}+ </View>+ )+}++const styles = StyleSheet.create({+ container: {+ paddingHorizontal: 12,+ paddingVertical: 10,+ borderBottomWidth: StyleSheet.hairlineWidth+ },+ row: {+ flexDirection: "row",+ alignItems: "center",+ justifyContent: "space-between"+ },+ navBtn: {+ padding: 8+ },+ dateContainer: {+ alignItems: "center",+ flex: 1+ },+ dateText: {+ fontSize: 15,+ ...fonts.bold+ },+ countText: {+ fontSize: 12,+ ...fonts.regular,+ marginTop: 2+ },+ todayBtn: {+ alignSelf: "center",+ marginTop: 8,+ paddingHorizontal: 16,+ paddingVertical: 6,+ borderRadius: 14+ },+ todayText: {+ fontSize: 12,+ ...fonts.semiBold+ }+})diff --git a/apps/mobile/src/components/features/inspector/TrackMap.tsx b/apps/mobile/src/components/features/inspector/TrackMap.tsxnew file mode 100644index 00000000..b98f424e--- /dev/null+++ b/apps/mobile/src/components/features/inspector/TrackMap.tsx@@ -0,0 +1,369 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import React, { useRef, useEffect, useMemo, useState, useCallback } from "react"+import { View, StyleSheet, Text } from "react-native"+import { WebView } from "react-native-webview"+import { MapPin } from "lucide-react-native"+import { ThemeColors } from "../../../types/global"+import { fonts } from "../../../styles/typography"+import { MapCenterButton } from "../map/MapCenterButton"++interface TrackLocation {+ latitude: number+ longitude: number+ timestamp?: number+ accuracy?: number+ speed?: number+ altitude?: number+}++interface Props {+ locations: TrackLocation[]+ selectedPoint: { latitude: number; longitude: number } | null+ colors: ThemeColors+ isDark: boolean+}++export function TrackMap({ locations, selectedPoint, colors, isDark }: Props) {+ const webviewRef = useRef<WebView>(null)+ const [mapReady, setMapReady] = useState(false)+ const [isCentered, setIsCentered] = useState(true)++ // Send locations to the map when they change or map becomes ready+ useEffect(() => {+ if (webviewRef.current && mapReady && locations.length > 0) {+ webviewRef.current.postMessage(+ JSON.stringify({+ action: "update_track",+ locations: locations.map((l) => ({+ lon: l.longitude,+ lat: l.latitude+ }))+ })+ )+ }+ }, [locations, mapReady])++ // Handle zoom to selected point from table tap+ useEffect(() => {+ if (webviewRef.current && mapReady && selectedPoint) {+ webviewRef.current.postMessage(+ JSON.stringify({+ action: "zoom_to_point",+ lon: selectedPoint.longitude,+ lat: selectedPoint.latitude+ })+ )+ }+ }, [selectedPoint, mapReady])++ const handleCenterTrack = useCallback(() => {+ webviewRef.current?.postMessage(JSON.stringify({ action: "fit_track" }))+ }, [])++ const html = useMemo(() => {+ return `+<!DOCTYPE html>+<html>+ <head>+ <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">+ <link rel="stylesheet" href="openlayers/ol.css">+ <style>+ html, body, #map {+ margin: 0;+ padding: 0;+ height: 100%;+ width: 100%;+ background: ${colors.background};+ }++ .ol-zoom {+ right: auto !important;+ left: 10px;+ top: 10px;+ background: transparent !important;+ padding: 0 !important;+ z-index: 100 !important;+ }++ .ol-zoom button {+ width: 44px !important;+ height: 44px !important;+ background: ${colors.card} !important;+ color: ${colors.text} !important;+ border-radius: ${colors.borderRadius}px !important;+ margin: 8px 0 !important;+ font-size: 20px !important;+ font-weight: bold !important;+ box-shadow: 0 2px 8px rgba(0,0,0,0.15) !important;+ -webkit-tap-highlight-color: transparent !important;+ touch-action: manipulation !important;+ }++ .ol-zoom button:active {+ background: ${colors.primary} !important;+ color: white !important;+ transform: scale(0.92) !important;+ }++ .ol-zoom button:focus {+ outline: none !important;+ }++ .ol-attribution {+ background: ${isDark ? "rgba(0,0,0,0.85)" : "rgba(255,255,255,0.95)"} !important;+ padding: 4px 8px !important;+ font-size: 11px !important;+ }++ .ol-attribution ul {+ color: ${colors.textSecondary} !important;+ text-shadow: none !important;+ }++ .ol-attribution a {+ color: ${colors.primary} !important;+ text-decoration: none !important;+ }++ ${isDark ? ".ol-layer canvas { filter: brightness(0.6) contrast(1.2) saturate(0.8); }" : ""}+ </style>+ </head>+ <body>+ <div id="map"></div>+ <script src="openlayers/ol.js"></script>+ <script>+ const trackSource = new ol.source.Vector();+ const markerSource = new ol.source.Vector();+ const highlightSource = new ol.source.Vector();++ const map = new ol.Map({+ target: "map",+ layers: [+ new ol.layer.Tile({ source: new ol.source.OSM() }),+ new ol.layer.Vector({+ source: trackSource,+ style: new ol.style.Style({+ stroke: new ol.style.Stroke({+ color: "${colors.primary}",+ width: 3+ })+ })+ }),+ new ol.layer.Vector({ source: markerSource }),+ new ol.layer.Vector({ source: highlightSource })+ ],+ view: new ol.View({+ center: ol.proj.fromLonLat([0, 0]),+ zoom: 2+ })+ });++ let currentExtent = null;++ function updateTrack(locations) {+ trackSource.clear();+ markerSource.clear();++ if (!locations || locations.length === 0) return;++ // Build polyline+ const coords = locations.map(l => ol.proj.fromLonLat([l.lon, l.lat]));+ const line = new ol.geom.LineString(coords);+ trackSource.addFeature(new ol.Feature(line));++ // Start marker (green)+ const startFeature = new ol.Feature(new ol.geom.Point(coords[0]));+ startFeature.setStyle(new ol.style.Style({+ image: new ol.style.Circle({+ radius: 8,+ fill: new ol.style.Fill({ color: "#22c55e" }),+ stroke: new ol.style.Stroke({ color: "#fff", width: 2 })+ })+ }));+ markerSource.addFeature(startFeature);++ // End marker (red) — only if more than one point+ if (coords.length > 1) {+ const endFeature = new ol.Feature(new ol.geom.Point(coords[coords.length - 1]));+ endFeature.setStyle(new ol.style.Style({+ image: new ol.style.Circle({+ radius: 8,+ fill: new ol.style.Fill({ color: "#ef4444" }),+ stroke: new ol.style.Stroke({ color: "#fff", width: 2 })+ })+ }));+ markerSource.addFeature(endFeature);+ }++ // Fit map to track extent+ currentExtent = line.getExtent();+ fitTrack();+ }++ function fitTrack() {+ if (currentExtent) {+ map.getView().fit(currentExtent, {+ duration: 400,+ padding: [60, 60, 60, 60],+ maxZoom: 18+ });+ }+ }++ function zoomToPoint(lon, lat) {+ highlightSource.clear();++ const pos = ol.proj.fromLonLat([lon, lat]);++ // Add highlight marker+ const highlight = new ol.Feature(new ol.geom.Point(pos));+ highlight.setStyle(new ol.style.Style({+ image: new ol.style.Circle({+ radius: 12,+ fill: new ol.style.Fill({ color: "${colors.primary}44" }),+ stroke: new ol.style.Stroke({ color: "${colors.primary}", width: 2 })+ })+ }));+ highlightSource.addFeature(highlight);++ map.getView().animate({+ center: pos,+ zoom: 17,+ duration: 500+ });+ }++ function handleInternalMessage(e) {+ let data;+ try {+ data = JSON.parse(e.data);+ } catch(err) {+ return;+ }++ if (data.action === "update_track") {+ updateTrack(data.locations);+ }++ if (data.action === "zoom_to_point") {+ zoomToPoint(data.lon, data.lat);+ }++ if (data.action === "fit_track") {+ fitTrack();+ }+ }++ window.addEventListener("message", handleInternalMessage);+ document.addEventListener("message", handleInternalMessage);++ map.on("moveend", () => {+ window.ReactNativeWebView.postMessage(+ JSON.stringify({ type: "CENTERED", value: true })+ );+ });++ window.ReactNativeWebView.postMessage(JSON.stringify({ type: "MAP_READY" }));+ </script>+ </body>+</html>+`+ }, [colors, isDark])++ if (locations.length === 0) {+ return (+ <View style={[styles.emptyContainer, { backgroundColor: colors.card, borderRadius: colors.borderRadius }]}>+ <View style={[styles.iconCircle, { backgroundColor: colors.border }]}>+ <MapPin 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>+ )+ }++ return (+ <View style={styles.container}>+ <WebView+ ref={webviewRef}+ originWhitelist={["*"]}+ source={{+ html: html,+ baseUrl: "file:///android_asset/"+ }}+ style={styles.webview}+ scrollEnabled={false}+ startInLoadingState={false}+ onMessage={(event) => {+ try {+ const data = JSON.parse(event.nativeEvent.data)++ if (data.type === "MAP_READY") {+ setMapReady(true)++ // Send track data immediately on ready+ if (locations.length > 0) {+ webviewRef.current?.postMessage(+ JSON.stringify({+ action: "update_track",+ locations: locations.map((l) => ({+ lon: l.longitude,+ lat: l.latitude+ }))+ })+ )+ }+ }++ if (data.type === "CENTERED") {+ setIsCentered(data.value)+ }+ } catch {+ // Ignore parse errors+ }+ }}+ />++ <MapCenterButton visible={!isCentered} onPress={handleCenterTrack} />+ </View>+ )+}++const styles = StyleSheet.create({+ container: {+ flex: 1,+ overflow: "hidden"+ },+ webview: {+ flex: 1+ },+ emptyContainer: {+ flex: 1,+ justifyContent: "center",+ alignItems: "center",+ padding: 24+ },+ 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+ }+})diff --git a/apps/mobile/src/components/index.ts b/apps/mobile/src/components/index.tsindex a4376513..c8e9e34f6 100644--- a/apps/mobile/src/components/index.ts+++ b/apps/mobile/src/components/index.ts@@ -38,6 +38,12 @@ export { DatabaseStatistics } from "./features/dashboard/DatabaseStatistics"// ============================================================================export { MapCenterButton } from "./features/map/MapCenterButton"+// ============================================================================+// Feature Components - Inspector+// ============================================================================+export { DatePicker } from "./features/inspector/DatePicker"+export { TrackMap } from "./features/inspector/TrackMap"+// ============================================================================// Feature Components - Settings// ============================================================================diff --git a/apps/mobile/src/screens/LocationInspectorScreen.tsx b/apps/mobile/src/screens/LocationInspectorScreen.tsxindex 73ad6260..c335ccc0 100644--- a/apps/mobile/src/screens/LocationInspectorScreen.tsx+++ b/apps/mobile/src/screens/LocationInspectorScreen.tsx@@ -6,18 +6,19 @@import React, { useState, useEffect, useRef, useCallback, memo } from "react"import { View, Text, FlatList, StyleSheet, TouchableOpacity, Switch } from "react-native"import { fonts } from "../styles/typography"-import { AlertTriangle, ChevronLeft, ChevronRight } from "lucide-react-native"+import { ChevronLeft, ChevronRight } from "lucide-react-native"import { Container, Card } from "../components"import { useTheme } from "../hooks/useTheme"import { ThemeColors } from "../types/global"import NativeLocationService from "../services/NativeLocationService"import { STATS_REFRESH_FAST } from "../constants"import { logger } from "../utils/logger"+import { DatePicker } from "../components/features/inspector/DatePicker"+import { TrackMap } from "../components/features/inspector/TrackMap"// Typesinterface LocationData {id?: number- location_id?: numbertimestamp?: numbercreated_at?: numberlatitude: number@@ -28,13 +29,12 @@ interface LocationData {bearing?: numberbattery: numberbattery_status: number- last_error?: string}interface LocationItemProps {item: LocationDatacolors: ThemeColors- isQueue: boolean+ onTap?: (item: LocationData) => void}interface MetricProps {@@ -50,12 +50,12 @@ interface TabProps {colors: ThemeColors}-type TableType = "locations" | "queue"+type TabType = "list" | "map"/*** Memoized row component to prevent re-renders during scrolling*/-const LocationItem = memo(({ item, colors, isQueue }: LocationItemProps) => {+const LocationItem = memo(({ item, colors, onTap }: LocationItemProps) => {const getBatteryStatus = (status: number): string => {switch (status) {case 0:@@ -73,10 +73,10 @@ const LocationItem = memo(({ item, colors, isQueue }: LocationItemProps) => {const timestamp = item.timestamp || item.created_at || Date.now()- return (+ const card = (<Card style={styles.itemCard}><View style={styles.row}>- <Text style={[styles.id, { color: colors.primaryDark }]}>#{item.id || item.location_id}</Text>+ <Text style={[styles.id, { color: colors.primaryDark }]}>#{item.id}</Text><Text style={[styles.time, { color: colors.textSecondary }]}>{new Date(timestamp * 1000).toLocaleTimeString()}</Text>@@ -99,49 +99,86 @@ const LocationItem = memo(({ item, colors, isQueue }: LocationItemProps) => {<View style={styles.spacer} /><View style={styles.spacer} /></View>-- {isQueue && item.last_error && (- <View style={styles.errorRow}>- <AlertTriangle size={12} color={colors.error} />- <Text style={[styles.errorText, { color: colors.error }]}>{item.last_error}</Text>- </View>- )}</Card>)++ if (onTap) {+ return (+ <TouchableOpacity activeOpacity={0.7} onPress={() => onTap(item)}>+ {card}+ </TouchableOpacity>+ )+ }++ return card})LocationItem.displayName = "LocationItem"-export function LocationInspectorScreen() {- const { colors } = useTheme()- const [activeTable, setActiveTable] = useState<TableType>("locations")+export function LocationHistoryScreen() {+ const { colors, mode } = useTheme()+ const isDark = mode === "dark"+ const [activeTab, setActiveTab] = useState<TabType>("map")const [data, setData] = useState<LocationData[]>([])const [limit, setLimit] = useState(50)const [page, setPage] = useState(0)const [autoRefresh, setAutoRefresh] = useState(false)const refreshInterval = useRef<ReturnType<typeof setInterval> | null>(null)- /** Fetches data based on current pagination and table selection */+ // Map tab state+ const [mapDate, setMapDate] = useState(new Date())+ const [trackLocations, setTrackLocations] = useState<LocationData[]>([])+ const [selectedPoint, setSelectedPoint] = useState<{ latitude: number; longitude: number } | null>(null)++ /** Fetches data based on current pagination */const fetchData = useCallback(async () => {try {const offset = page * limit- const result = await NativeLocationService.getTableData(activeTable, limit, offset)+ const result = await NativeLocationService.getTableData("locations", limit, offset)setData(result || [])} catch (err) {- logger.error("[LocationInspector] Fetch error:", err)+ logger.error("[LocationHistory] Fetch error:", err)setData([])}- }, [activeTable, limit, page])+ }, [limit, page])++ /** Fetch track data for the selected day */+ const fetchTrackData = useCallback(async () => {+ try {+ const start = new Date(mapDate)+ start.setHours(0, 0, 0, 0)+ const end = new Date(mapDate)+ end.setHours(23, 59, 59, 999)++ const startTimestamp = Math.floor(start.getTime() / 1000)+ const endTimestamp = Math.floor(end.getTime() / 1000)- /** Fetch data when dependencies change */+ const result = await NativeLocationService.getLocationsByDateRange(startTimestamp, endTimestamp)+ setTrackLocations(result || [])+ } catch (err) {+ logger.error("[LocationHistory] Track fetch error:", err)+ setTrackLocations([])+ }+ }, [mapDate])++ /** Fetch table data when dependencies change */+ useEffect(() => {+ if (activeTab === "list") {+ fetchData()+ }+ }, [fetchData, activeTab])++ /** Fetch track data when map date changes */useEffect(() => {- fetchData()- }, [fetchData])+ if (activeTab === "map") {+ fetchTrackData()+ }+ }, [fetchTrackData, activeTab])/** Auto-refresh logic */useEffect(() => {- if (autoRefresh) {- setPage(0) // Always show newest data in live mode+ if (autoRefresh && activeTab === "list") {+ setPage(0)refreshInterval.current = setInterval(fetchData, STATS_REFRESH_FAST)} else {if (refreshInterval.current) {@@ -153,11 +190,14 @@ export function LocationInspectorScreen() {clearInterval(refreshInterval.current)}}- }, [autoRefresh, fetchData])+ }, [autoRefresh, fetchData, activeTab])- const handleTableChange = (table: TableType) => {- setActiveTable(table)- setPage(0)+ const handleTabChange = (tab: TabType) => {+ setActiveTab(tab)+ if (tab === "list") {+ setPage(0)+ setSelectedPoint(null)+ }}const handleLimitChange = (newLimit: number) => {@@ -165,111 +205,122 @@ export function LocationInspectorScreen() {setPage(0)}+ /** Tap a location row in List → switch to Map and zoom */+ const handleLocationTap = (item: LocationData) => {+ if (item.latitude && item.longitude) {+ if (item.timestamp) {+ const itemDate = new Date(item.timestamp * 1000)+ setMapDate(itemDate)+ }+ setSelectedPoint({ latitude: item.latitude, longitude: item.longitude })+ setActiveTab("map")+ }+ }+return (<Container>- {/* Header with Live Mode Toggle */}- <View style={styles.headerRow}>- <Text style={[styles.statusText, { color: autoRefresh ? colors.primary : colors.textSecondary }]}>- {autoRefresh ? "● Live Mode" : "Manual Mode"}- </Text>-- <View style={styles.controls}>- <View style={styles.toggleContainer}>- <Text style={[styles.controlLabel, { color: colors.textSecondary }]}>LIVE</Text>- <Switch- value={autoRefresh}- onValueChange={setAutoRefresh}- thumbColor={autoRefresh ? colors.primary : colors.border}- />- </View>-- <TouchableOpacity- onPress={fetchData}- disabled={autoRefresh}- style={[- styles.refreshBtn,- {- backgroundColor: colors.card,- borderColor: colors.border- },- autoRefresh && styles.refreshBtnDisabled- ]}- >- <Text style={[styles.btnText, { color: colors.primaryDark }]}>Refresh</Text>- </TouchableOpacity>- </View>+ {/* Tab Bar */}+ <View style={styles.tabBar}>+ <Tab label="Map" active={activeTab === "map"} onPress={() => handleTabChange("map")} colors={colors} />+ <Tab label="List" active={activeTab === "list"} onPress={() => handleTabChange("list")} colors={colors} /></View>- {/* Limit Selection and Pagination */}- <View style={styles.limitBar}>- <View style={styles.limitOptions}>- {[10, 50, 100].map((v) => (- <TouchableOpacity- key={v}- onPress={() => handleLimitChange(v)}- style={[- styles.limitBtn,- {- backgroundColor: limit === v ? colors.primary : colors.card,- borderColor: colors.border- }- ]}- >- <Text style={[styles.limitBtnText, { color: limit === v ? colors.textOnPrimary : colors.text }]}>- {v}- </Text>- </TouchableOpacity>- ))}+ {activeTab === "map" ? (+ <View style={styles.mapContainer}>+ <DatePicker date={mapDate} onDateChange={setMapDate} locationCount={trackLocations.length} colors={colors} />+ <TrackMap locations={trackLocations} selectedPoint={selectedPoint} colors={colors} isDark={isDark} /></View>+ ) : (+ <>+ {/* Header with Live Mode Toggle */}+ <View style={styles.headerRow}>+ <Text style={[styles.statusText, { color: autoRefresh ? colors.primary : colors.textSecondary }]}>+ {autoRefresh ? "● Live Mode" : "Manual Mode"}+ </Text>++ <View style={styles.controls}>+ <View style={styles.toggleContainer}>+ <Text style={[styles.controlLabel, { color: colors.textSecondary }]}>LIVE</Text>+ <Switch+ value={autoRefresh}+ onValueChange={setAutoRefresh}+ thumbColor={autoRefresh ? colors.primary : colors.border}+ />+ </View>- {!autoRefresh && (- <View style={styles.paginationRow}>- <TouchableOpacity- onPress={() => setPage((p) => Math.max(0, p - 1))}- disabled={page === 0}- style={styles.pageBtn}- >- <ChevronLeft size={20} color={page === 0 ? colors.textDisabled : colors.primary} />- </TouchableOpacity>- <Text style={[styles.pageIndicator, { color: colors.text }]}>{page + 1}</Text>- <TouchableOpacity- onPress={() => setPage((p) => p + 1)}- disabled={data.length < limit}- style={styles.pageBtn}- >- <ChevronRight size={20} color={data.length < limit ? colors.textDisabled : colors.primary} />- </TouchableOpacity>+ <TouchableOpacity+ onPress={fetchData}+ disabled={autoRefresh}+ style={[+ styles.refreshBtn,+ {+ backgroundColor: colors.card,+ borderColor: colors.border+ },+ autoRefresh && styles.refreshBtnDisabled+ ]}+ >+ <Text style={[styles.btnText, { color: colors.primaryDark }]}>Refresh</Text>+ </TouchableOpacity>+ </View></View>- )}- </View>- {/* Tab Bar */}- <View style={styles.tabBar}>- <Tab- label="History"- active={activeTable === "locations"}- onPress={() => handleTableChange("locations")}- colors={colors}- />- <Tab- label="Queue"- active={activeTable === "queue"}- onPress={() => handleTableChange("queue")}- colors={colors}- />- </View>+ {/* Limit Selection and Pagination */}+ <View style={styles.limitBar}>+ <View style={styles.limitOptions}>+ {[10, 50, 100].map((v) => (+ <TouchableOpacity+ key={v}+ onPress={() => handleLimitChange(v)}+ style={[+ styles.limitBtn,+ {+ backgroundColor: limit === v ? colors.primary : colors.card,+ borderColor: colors.border+ }+ ]}+ >+ <Text style={[styles.limitBtnText, { color: limit === v ? colors.textOnPrimary : colors.text }]}>+ {v}+ </Text>+ </TouchableOpacity>+ ))}+ </View>++ {!autoRefresh && (+ <View style={styles.paginationRow}>+ <TouchableOpacity+ onPress={() => setPage((p) => Math.max(0, p - 1))}+ disabled={page === 0}+ style={styles.pageBtn}+ >+ <ChevronLeft size={20} color={page === 0 ? colors.textDisabled : colors.primary} />+ </TouchableOpacity>+ <Text style={[styles.pageIndicator, { color: colors.text }]}>{page + 1}</Text>+ <TouchableOpacity+ onPress={() => setPage((p) => p + 1)}+ disabled={data.length < limit}+ style={styles.pageBtn}+ >+ <ChevronRight size={20} color={data.length < limit ? colors.textDisabled : colors.primary} />+ </TouchableOpacity>+ </View>+ )}+ </View>- {/* Location List */}- <FlatList- data={data}- contentContainerStyle={styles.listContent}- keyExtractor={(item, index) => `${activeTable}-${item.id || index}`}- ListEmptyComponent={<Text style={[styles.emptyText, { color: colors.textLight }]}>No data available</Text>}- renderItem={({ item }) => <LocationItem item={item} colors={colors} isQueue={activeTable === "queue"} />}- initialNumToRender={10}- maxToRenderPerBatch={10}- windowSize={5}- />+ {/* Location List */}+ <FlatList+ data={data}+ contentContainerStyle={styles.listContent}+ keyExtractor={(item, index) => `loc-${item.id || index}`}+ ListEmptyComponent={<Text style={[styles.emptyText, { color: colors.textLight }]}>No data available</Text>}+ renderItem={({ item }) => <LocationItem item={item} colors={colors} onTap={handleLocationTap} />}+ initialNumToRender={10}+ maxToRenderPerBatch={10}+ windowSize={5}+ />+ </>+ )}</Container>)}@@ -296,6 +347,9 @@ const Tab = ({ label, active, onPress, colors }: TabProps) => {}const styles = StyleSheet.create({+ mapContainer: {+ flex: 1+ },headerRow: {flexDirection: "row",justifyContent: "space-between",@@ -447,15 +501,5 @@ const styles = StyleSheet.create({fontSize: 14,...fonts.regular,fontStyle: "italic"- },- errorRow: {- flexDirection: "row" as const,- alignItems: "center" as const,- gap: 6,- marginTop: 8- },- errorText: {- fontSize: 11,- fontStyle: "italic"}})diff --git a/apps/mobile/src/screens/index.ts b/apps/mobile/src/screens/index.tsindex 54741d81..c7c50e7b 100644--- a/apps/mobile/src/screens/index.ts+++ b/apps/mobile/src/screens/index.ts@@ -9,6 +9,6 @@ export { DashboardScreen } from "./DashboardScreen"export { DataManagementScreen } from "./DataManagementScreen"export { ExportDataScreen } from "./ExportDataScreen"export { GeofenceScreen } from "./GeofenceScreen"-export { LocationInspectorScreen } from "./LocationInspectorScreen"+export { LocationHistoryScreen } from "./LocationInspectorScreen"export { SettingsScreen } from "./SettingsScreen"export { AboutScreen } from "./AboutScreen"diff --git a/apps/mobile/src/services/NativeLocationService.ts b/apps/mobile/src/services/NativeLocationService.tsindex fac7fc29..80bac900 100644--- a/apps/mobile/src/services/NativeLocationService.ts+++ b/apps/mobile/src/services/NativeLocationService.ts@@ -169,6 +169,21 @@ class NativeLocationService {)}+ /**+ * Fetches locations within a date range, ordered chronologically.+ * Used for track polyline rendering on the map view.+ * @param startTimestamp Start of range (Unix seconds, inclusive)+ * @param endTimestamp End of range (Unix seconds, inclusive)+ */+ static async getLocationsByDateRange(startTimestamp: number, endTimestamp: number): Promise<any[]> {+ this.ensureModule()+ return this.safeExecute(+ () => LocationServiceModule.getLocationsByDateRange(startTimestamp, endTimestamp),+ [],+ "getLocationsByDateRange failed"+ )+ }+/*** Gets the most recent location from the database*/