Skip to content

Colota - Android GPS Location tracker

feat: add location history, trips, and summary screens

Max Dietrich741477a1b271
diff --git a/README.md b/README.md
index c6f416b8..5609b434 100644
--- a/README.md
+++ b/README.md
@@ -17,6 +17,7 @@ Colota sends your location to your own server over HTTP(S). It works offline, su
- **Self-Hosted** - Send location data to your own server. Works with Dawarich, OwnTracks, PhoneTrack, Reitti, Traccar, Home Assistant, or any custom backend.
- **Privacy First** - No analytics, no telemetry, no third-party SDKs. Open source (AGPL-3.0).
- **Works Offline** - Fully functional without a server. Export as CSV, GeoJSON, GPX, or KML.
+- **Location History** - View daily summaries, trip segmentation, calendar with activity dots, and per-trip export.
- **Reliable Tracking** - Foreground service, auto-start on boot, exponential backoff retry.
- **Geofencing** - Pause zones that automatically stop recording locations.
- **Tracking Profiles** - Automatically adjust GPS interval, distance filter, and sync settings based on conditions like charging, car mode, or speed.
@@ -29,15 +30,30 @@ Colota sends your location to your own server over HTTP(S). It works offline, su
<table>
<tr>
<td><img src="screenshots/mobile/original/Dashboard.png" alt="Dashboard" width="200"/></td>
+ <td><img src="screenshots/mobile/original/LocationHistory.png" alt="Location History (Map)" width="200"/></td>
+ <td><img src="screenshots/mobile/original/TripDetails.png" alt="Trip Details" width="200"/></td>
+ <td><img src="screenshots/mobile/original/Trips.png" alt="Trips" width="200"/></td>
+ </tr>
+ <tr>
+ <td align="center">Dashboard</td>
+ <td align="center">Location History (Map)</td>
+ <td align="center">Trip Details</td>
+ <td align="center">Trips</td>
+ </tr>
+</table>
+
+<table>
+ <tr>
<td><img src="screenshots/mobile/original/Settings.png" alt="Settings" width="200"/></td>
<td><img src="screenshots/mobile/original/TrackingProfiles.png" alt="TrackingProfiles" width="200"/></td>
- <td><img src="screenshots/mobile/original/DataManagement.png" alt="Data Management" width="200"/></td>
+ <td><img src="screenshots/mobile/original/Authentication.png" alt="Authentication" width="200"/></td>
+ <td><img src="screenshots/mobile/original/DarkMode.png" alt="Dark Mode" width="200"/></td>
</tr>
<tr>
- <td align="center">Dashboard</td>
<td align="center">Settings</td>
- <td align="center">Tracking Profiles</td>
- <td align="center">Data Management</td>
+ <td align="center">TrackingProfiles</td>
+ <td align="center">Authentication</td>
+ <td align="center">Dark Mode</td>
</tr>
</table>
diff --git a/apps/docs/docs/configuration/authentication.md b/apps/docs/docs/configuration/authentication.md
index 044f84e2..1eb5abc6 100644
--- a/apps/docs/docs/configuration/authentication.md
+++ b/apps/docs/docs/configuration/authentication.md
@@ -4,8 +4,12 @@ sidebar_position: 5
# Authentication
+import ScreenshotGallery from '@site/src/components/ScreenshotGallery'
+
Colota supports multiple authentication methods, configurable in **Settings > Authentication & Headers**.
+<ScreenshotGallery screenshots={[ { src: "/img/screenshots/Authentication.png", label: "Authentication" }, ]} />
+
## Methods
| Method | Description | Header Sent |
diff --git a/apps/docs/docs/configuration/field-mapping.md b/apps/docs/docs/configuration/field-mapping.md
index 3bb3c310..7cbb8389 100644
--- a/apps/docs/docs/configuration/field-mapping.md
+++ b/apps/docs/docs/configuration/field-mapping.md
@@ -4,8 +4,12 @@ sidebar_position: 4
# Field Mapping
+import ScreenshotGallery from '@site/src/components/ScreenshotGallery'
+
Customize field names sent to your server. Field names apply to both POST (JSON body) and GET (query parameters) requests.
+<ScreenshotGallery screenshots={[ { src: "/img/screenshots/ApiFieldMapping.png", label: "Field Mapping" }, ]} />
+
## Default Fields
| Field | Description | Required |
diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.md
index f3845b84..019e4fed 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 flav
The primary React Native bridge module (exposed as `"LocationServiceModule"`). Handles all JS-to-native communication for:
- Service control (`startService`, `stopService`)
-- Database queries (`getStats`, `getTableData`, `getLocationsByDateRange`)
+- Database queries (`getStats`, `getTableData`, `getLocationsByDateRange`, `getDaysWithData`, `getDailyStats`)
- Geofence CRUD operations
- Settings persistence
- Device info, file operations, authentication
@@ -165,6 +165,25 @@ Wraps Android's `EncryptedSharedPreferences` for AES-256-GCM encrypted credentia
## React Native Layer
+### Screens
+
+| Screen | Purpose |
+| --- | --- |
+| `DashboardScreen` | Live map with tracking controls, coordinates, database stats, geofence and profile status |
+| `SettingsScreen` | GPS interval, distance filter, sync strategy, offline mode, accuracy threshold |
+| `ApiSettingsScreen` | Endpoint URL, HTTP method, field mapping with backend templates |
+| `AuthSettingsScreen` | Authentication method (None, Basic Auth, Bearer Token) and custom HTTP headers |
+| `GeofenceScreen` | Create, edit, and delete pause zones on an interactive map |
+| `TrackingProfilesScreen` | List and manage condition-based tracking profiles |
+| `ProfileEditorScreen` | Create/edit a profile's name, condition, GPS settings, priority, and deactivation delay |
+| `LocationHistoryScreen` | Calendar day picker with activity dots, map tab with trip-colored tracks, trips tab with trip cards and export |
+| `TripDetailScreen` | Full trip view with dedicated map, stats grid, speed and elevation profile charts, and per-trip export |
+| `LocationSummaryScreen` | Aggregated stats for selectable periods (week/month/30 days) with daily breakdown and tap-to-inspect navigation |
+| `ExportDataScreen` | Export all tracked locations as CSV, GeoJSON, GPX, or KML |
+| `DataManagementScreen` | Clear sent history, delete old data, vacuum database, sync controls |
+| `SetupImportScreen` | Confirmation screen for `colota://setup` deep link imports |
+| `AboutScreen` | App version, device info, links to repository and privacy policy |
+
### Services
| Service | Purpose |
@@ -182,7 +201,9 @@ The app uses [MapLibre GL Native](https://github.com/maplibre/maplibre-react-nat
| --- | --- |
| `ColotaMapView` | Shared base map component wrapping MapLibre's `MapView` with OpenFreeMap vector tiles, dark mode style transformation, custom compass, and attribution |
| `DashboardMap` | Live tracking map with user marker, accuracy circle, geofence polygons with labels, auto-center, and center button |
-| `TrackMap` | Location history map with speed-colored track segments, tappable point markers with popups, start/end markers, fit-to-track bounds, and speed legend |
+| `TrackMap` | Location history map with trip-colored track segments, tappable point markers with detail popups, fit-to-track bounds, and trip legend |
+| `CalendarPicker` | Day picker with month navigation, dot indicators for days with data, and daily distance/count display |
+| `TripList` | Segmented trip cards with distance, duration, avg speed, elevation gain/loss, and per-trip or bulk export |
| `GeofenceLayers` | Shared geofence rendering (fill polygons, stroke outlines, labels) used by DashboardMap and GeofenceScreen |
| `UserLocationOverlay` | User position dot with accuracy circle, used by DashboardMap and GeofenceScreen |
| `MapCenterButton` | Reusable button overlay to re-center the map |
@@ -204,8 +225,9 @@ Supporting utilities in `mapUtils.ts`:
| Utility | Purpose |
| --- | --- |
| `logger` | Environment-aware logging - suppresses debug/info in production via `__DEV__`, always logs warn/error |
-| `geo` | Haversine distance, speed/distance formatting with locale-aware unit selection (km/h vs mph) |
-| `exportConverters` | Converts location data to CSV, GeoJSON, GPX, and KML export formats |
+| `geo` | Haversine distance, speed/distance/duration/time formatting with locale-aware unit selection (km/h vs mph) |
+| `exportConverters` | Converts location data to CSV, GeoJSON, GPX, and KML export formats (flat and trip-aware variants) |
+| `trips` | Trip segmentation via time-gap detection (15-min threshold) with distance computation, trip stats (avg speed, elevation gain/loss), and trip color assignment |
| `queueStatus` | Maps sync queue size to color indicators for the dashboard |
| `settingsValidation` | URL validation and security checks for endpoint configuration |
diff --git a/apps/docs/docs/getting-started/quick-start.md b/apps/docs/docs/getting-started/quick-start.md
index 99d72fa2..f2cf4fa0 100644
--- a/apps/docs/docs/getting-started/quick-start.md
+++ b/apps/docs/docs/getting-started/quick-start.md
@@ -12,6 +12,10 @@ Minimal setup to start tracking:
4. Press **Start Tracking**
5. View live coordinates on the dashboard
+import ScreenshotGallery from '@site/src/components/ScreenshotGallery'
+
+<ScreenshotGallery screenshots={[ { src: "/img/screenshots/Dashboard.png", label: "Dashboard" }, ]} />
+
The app works completely offline. Server setup is optional.
## Next Steps
diff --git a/apps/docs/docs/guides/data-export.md b/apps/docs/docs/guides/data-export.md
index 936aac4b..088e26c0 100644
--- a/apps/docs/docs/guides/data-export.md
+++ b/apps/docs/docs/guides/data-export.md
@@ -17,17 +17,25 @@ Export your location history in multiple formats.
## How to Export
+### Bulk Export
+
1. Go to **Data Management**
2. Tap **Export Data**
3. Select the format
4. Share the exported file via Android's share menu
-<div className="screenshot-gallery">
- <figure>
- <img src="/img/screenshots/ExportData.png" alt="Export Data" />
- <figcaption>Export Data</figcaption>
- </figure>
-</div>
+### Trip Export
+
+1. Go to **Location History** → **Trips** tab
+2. Tap the export icon to export all trips for the selected day, or tap a trip card and export that single trip
+3. Select the format
+4. Share via Android's share menu
+
+Trip exports include a `trip` column/property so each location is tagged with its trip number.
+
+import ScreenshotGallery from '@site/src/components/ScreenshotGallery'
+
+<ScreenshotGallery screenshots={[ { src: "/img/screenshots/ExportData.png", label: "Export Data" }, ]} />
## Storage Reference
diff --git a/apps/docs/docs/guides/data-management.md b/apps/docs/docs/guides/data-management.md
index b509c426..7a3d0c7a 100644
--- a/apps/docs/docs/guides/data-management.md
+++ b/apps/docs/docs/guides/data-management.md
@@ -6,12 +6,9 @@ sidebar_position: 3
Manage your location database from the Data Management screen.
-<div className="screenshot-gallery">
- <figure>
- <img src="/img/screenshots/DataManagement.png" alt="Data Management" />
- <figcaption>Data Management</figcaption>
- </figure>
-</div>
+import ScreenshotGallery from '@site/src/components/ScreenshotGallery'
+
+<ScreenshotGallery screenshots={[ { src: "/img/screenshots/DataManagement.png", label: "Data Management" }, ]} />
## Actions
diff --git a/apps/docs/docs/guides/geofencing.md b/apps/docs/docs/guides/geofencing.md
index 54547057..52bdb077 100644
--- a/apps/docs/docs/guides/geofencing.md
+++ b/apps/docs/docs/guides/geofencing.md
@@ -19,12 +19,9 @@ Create zones where location recording stops automatically. These "pause zones" s
3. Tap the map to place the geofence
4. Enable **Pause Tracking**
-<div className="screenshot-gallery">
- <figure>
- <img src="/img/screenshots/Geofences.png" alt="Geofence setup" />
- <figcaption>Geofence setup</figcaption>
- </figure>
-</div>
+import ScreenshotGallery from '@site/src/components/ScreenshotGallery'
+
+<ScreenshotGallery screenshots={[ { src: "/img/screenshots/Geofences.png", label: "Geofence setup" }, ]} />
## How It Works
diff --git a/apps/docs/docs/guides/tracking-profiles.md b/apps/docs/docs/guides/tracking-profiles.md
index 95e837b6..a0a72dae 100644
--- a/apps/docs/docs/guides/tracking-profiles.md
+++ b/apps/docs/docs/guides/tracking-profiles.md
@@ -4,8 +4,12 @@ sidebar_position: 2
# Tracking Profiles
+import ScreenshotGallery from '@site/src/components/ScreenshotGallery'
+
Tracking profiles automatically adjust GPS interval, distance filter, and sync settings when conditions like charging, car mode, or speed thresholds are met.
+<ScreenshotGallery screenshots={[ { src: "/img/screenshots/TrackingProfiles.png", label: "Tracking Profiles" }, ]} />
+
## Use Cases
- **Charging** - Increase tracking frequency while plugged in (battery isn't a concern)
diff --git a/apps/docs/docs/introduction.md b/apps/docs/docs/introduction.md
index 6a1b1697..0bc58391 100644
--- a/apps/docs/docs/introduction.md
+++ b/apps/docs/docs/introduction.md
@@ -23,7 +23,7 @@ Colota is a self-hosted GPS tracking app for Android. It sends your location to
## App Screens
-Colota has twelve screens, each focused on a specific task:
+Colota has fourteen screens, each focused on a specific task:
| Screen | Purpose |
| --- | --- |
@@ -34,7 +34,9 @@ Colota has twelve screens, each focused on a specific task:
| **Geofences** | Create, edit, and delete pause zones on an interactive map |
| **Tracking Profiles** | Create and manage condition-based profiles that automatically adjust tracking settings |
| **Profile Editor** | Configure profile name, condition trigger, GPS interval, distance filter, sync interval, priority, and deactivation delay |
-| **Location History** | Browse recorded locations on a track map with day picker and daily distance traveled, or as a paginated list with accuracy indicators |
+| **Location History** | Browse recorded locations on a track map with calendar day picker and trip-colored segments, view segmented trips with per-trip stats |
+| **Trip Detail** | Full trip view with dedicated map, stats grid (distance, duration, avg speed, elevation), speed and elevation profile charts, and export |
+| **Location Summary** | Aggregated stats (total distance, trips, active days, avg distance) for selectable periods with daily breakdown and tap-to-inspect navigation |
| **Export Data** | Export tracked locations as CSV, GeoJSON, GPX, or KML |
| **Data Management** | Clear sent history, delete old data, vacuum the database |
| **Setup Import** | Confirmation screen for deep link configuration imports (`colota://setup`) |
@@ -42,24 +44,9 @@ Colota has twelve screens, each focused on a specific task:
## Screenshots
-<div className="screenshot-gallery">
- <figure>
- <img src="/img/screenshots/Dashboard.png" alt="Dashboard" />
- <figcaption>Dashboard</figcaption>
- </figure>
- <figure>
- <img src="/img/screenshots/Settings.png" alt="Settings" />
- <figcaption>Settings</figcaption>
- </figure>
- <figure>
- <img src="/img/screenshots/Geofences.png" alt="Geofences" />
- <figcaption>Geofences</figcaption>
- </figure>
- <figure>
- <img src="/img/screenshots/DataManagement.png" alt="Data Management" />
- <figcaption>Data Management</figcaption>
- </figure>
-</div>
+import ScreenshotGallery from '@site/src/components/ScreenshotGallery'
+
+<ScreenshotGallery screenshots={[ { src: "/img/screenshots/Dashboard.png", label: "Dashboard" }, { src: "/img/screenshots/LocationHistory.png", label: "Location History" }, { src: "/img/screenshots/TripDetails.png", label: "Trip Detail" }, { src: "/img/screenshots/Trips.png", label: "Trips" }, { src: "/img/screenshots/Settings.png", label: "Settings" }, { src: "/img/screenshots/TrackingProfiles.png", label: "Tracking Profiles" }, { src: "/img/screenshots/DataManagement.png", label: "Data Management" }, { src: "/img/screenshots/ApiFieldMapping.png", label: "API Field Mapping" }, { src: "/img/screenshots/ExportData.png", label: "Export" }, { src: "/img/screenshots/Authentication.png", label: "Authentication" }, { src: "/img/screenshots/DarkMode.png", label: "Dark Mode" }, ]} />
## Architecture
diff --git a/apps/docs/src/components/ScreenshotGallery.module.css b/apps/docs/src/components/ScreenshotGallery.module.css
new file mode 100644
index 00000000..2baac29a
--- /dev/null
+++ b/apps/docs/src/components/ScreenshotGallery.module.css
@@ -0,0 +1,114 @@
+/* Gallery grid */
+.gallery {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 1.5rem;
+ justify-content: center;
+ margin: 2rem 0;
+}
+
+.item {
+ margin: 0;
+ text-align: center;
+ max-width: 200px;
+ cursor: pointer;
+}
+
+.item img {
+ border-radius: 12px;
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
+ width: 100%;
+ transition: transform 0.2s;
+}
+
+.item img:hover {
+ transform: scale(1.03);
+}
+
+.item figcaption {
+ margin-top: 0.5rem;
+ font-size: 0.875rem;
+ color: var(--ifm-font-color-secondary);
+}
+
+/* Lightbox dialog */
+.lightbox {
+ border: none;
+ background: transparent;
+ padding: 0;
+ max-width: 100vw;
+ max-height: 100vh;
+ overflow: visible;
+}
+
+.lightbox::backdrop {
+ background: rgba(0, 0, 0, 0.85);
+}
+
+.lightboxInner {
+ display: flex;
+ align-items: center;
+ gap: 1rem;
+ position: relative;
+}
+
+.lightboxInner > img {
+ max-height: 85vh;
+ max-width: 80vw;
+ border-radius: 16px;
+}
+
+/* Nav arrows */
+.navBtn {
+ background: rgba(255, 255, 255, 0.15);
+ border: none;
+ color: white;
+ font-size: 2.5rem;
+ line-height: 1;
+ padding: 0.25rem 0.75rem;
+ border-radius: 8px;
+ cursor: pointer;
+ user-select: none;
+ transition: background 0.15s;
+}
+
+.navBtn:hover {
+ background: rgba(255, 255, 255, 0.3);
+}
+
+/* Caption + counter */
+.caption {
+ position: absolute;
+ bottom: -2.5rem;
+ left: 50%;
+ transform: translateX(-50%);
+ color: rgba(255, 255, 255, 0.9);
+ font-size: 0.9rem;
+ white-space: nowrap;
+ display: flex;
+ align-items: center;
+ gap: 0.75rem;
+}
+
+.counter {
+ font-size: 0.8rem;
+ opacity: 0.6;
+}
+
+/* Close button */
+.closeBtn {
+ position: absolute;
+ top: -2rem;
+ right: -0.5rem;
+ background: none;
+ border: none;
+ color: rgba(255, 255, 255, 0.7);
+ font-size: 1.75rem;
+ cursor: pointer;
+ line-height: 1;
+ padding: 0.25rem;
+}
+
+.closeBtn:hover {
+ color: white;
+}
diff --git a/apps/docs/src/components/ScreenshotGallery.tsx b/apps/docs/src/components/ScreenshotGallery.tsx
new file mode 100644
index 00000000..f9a5cd09
--- /dev/null
+++ b/apps/docs/src/components/ScreenshotGallery.tsx
@@ -0,0 +1,105 @@
+import { useRef, useCallback, useEffect, useState } from "react"
+import styles from "./ScreenshotGallery.module.css"
+
+interface Screenshot {
+ src: string
+ label: string
+}
+
+interface ScreenshotGalleryProps {
+ screenshots: Screenshot[]
+}
+
+export default function ScreenshotGallery({ screenshots }: ScreenshotGalleryProps) {
+ const dialogRef = useRef<HTMLDialogElement>(null)
+ const [activeIndex, setActiveIndex] = useState(-1)
+
+ const open = useCallback((index: number) => {
+ setActiveIndex(index)
+ dialogRef.current?.showModal()
+ }, [])
+
+ const close = useCallback(() => {
+ dialogRef.current?.close()
+ setActiveIndex(-1)
+ }, [])
+
+ const prev = useCallback(() => {
+ setActiveIndex((i) => (i > 0 ? i - 1 : screenshots.length - 1))
+ }, [screenshots.length])
+
+ const next = useCallback(() => {
+ setActiveIndex((i) => (i < screenshots.length - 1 ? i + 1 : 0))
+ }, [screenshots.length])
+
+ useEffect(() => {
+ const dialog = dialogRef.current
+ if (!dialog) return
+
+ function onKeyDown(e: KeyboardEvent) {
+ if (e.key === "ArrowLeft") {
+ e.preventDefault()
+ prev()
+ } else if (e.key === "ArrowRight") {
+ e.preventDefault()
+ next()
+ }
+ }
+
+ // Esc is handled natively by <dialog>, just reset state on close
+ function onClose() {
+ setActiveIndex(-1)
+ }
+
+ dialog.addEventListener("keydown", onKeyDown)
+ dialog.addEventListener("close", onClose)
+ return () => {
+ dialog.removeEventListener("keydown", onKeyDown)
+ dialog.removeEventListener("close", onClose)
+ }
+ }, [prev, next])
+
+ const active = activeIndex >= 0 ? screenshots[activeIndex] : null
+
+ return (
+ <>
+ <div className={styles.gallery}>
+ {screenshots.map(({ src, label }, i) => (
+ <figure key={label} className={styles.item} onClick={() => open(i)}>
+ <img src={src} alt={label} loading="lazy" />
+ <figcaption>{label}</figcaption>
+ </figure>
+ ))}
+ </div>
+
+ <dialog ref={dialogRef} className={styles.lightbox} onClick={close}>
+ {active && (
+ <div className={styles.lightboxInner} onClick={(e) => e.stopPropagation()}>
+ {screenshots.length > 1 && (
+ <button className={`${styles.navBtn} ${styles.navPrev}`} onClick={prev} aria-label="Previous">
+ &#8249;
+ </button>
+ )}
+ <img src={active.src} alt={active.label} />
+ {screenshots.length > 1 && (
+ <button className={`${styles.navBtn} ${styles.navNext}`} onClick={next} aria-label="Next">
+ &#8250;
+ </button>
+ )}
+ <div className={styles.caption}>
+ {active.label}
+ {screenshots.length > 1 && (
+ <span className={styles.counter}>
+ {activeIndex + 1} / {screenshots.length}
+ </span>
+ )}
+ </div>
+ <button className={styles.closeBtn} onClick={close} aria-label="Close">
+ &times;
+ </button>
+ </div>
+ )}
+ </dialog>
+ </>
+ )
+}
diff --git a/apps/docs/src/css/custom.css b/apps/docs/src/css/custom.css
index e5a77299..a0bbc416 100644
--- a/apps/docs/src/css/custom.css
+++ b/apps/docs/src/css/custom.css
@@ -49,30 +49,4 @@
font-weight: 600;
}
-/* Screenshot gallery (used on docs pages) */
-.screenshot-gallery {
- display: flex;
- flex-wrap: wrap;
- gap: 1.5rem;
- justify-content: center;
- margin: 2rem 0;
-}
-
-.screenshot-gallery figure {
- margin: 0;
- text-align: center;
- max-width: 200px;
-}
-
-.screenshot-gallery img {
- border-radius: 12px;
- box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
- width: 100%;
-}
-
-.screenshot-gallery figcaption {
- margin-top: 0.5rem;
- font-size: 0.875rem;
- color: var(--ifm-font-color-secondary);
-}
diff --git a/apps/docs/src/pages/index.module.css b/apps/docs/src/pages/index.module.css
index 496401fc..53990db9 100644
--- a/apps/docs/src/pages/index.module.css
+++ b/apps/docs/src/pages/index.module.css
@@ -14,12 +14,6 @@
flex: 1;
}
-.heroSubtitle {
- font-size: 1.25rem;
- line-height: 1.6;
- opacity: 0.9;
-}
-
.heroScreenshot {
flex: 0 0 280px;
}
@@ -30,6 +24,12 @@
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.3);
}
+.heroSubtitle {
+ font-size: 1.25rem;
+ line-height: 1.6;
+ opacity: 0.9;
+}
+
.buttons {
display: flex;
align-items: center;
@@ -91,75 +91,6 @@
margin-bottom: 2rem;
}
-.screenshotStrip {
- display: flex;
- gap: 1.25rem;
- overflow-x: auto;
- padding: 0.5rem 0 1.5rem;
- scroll-snap-type: x mandatory;
- -webkit-overflow-scrolling: touch;
-}
-
-.screenshotStrip::-webkit-scrollbar {
- height: 6px;
-}
-
-.screenshotStrip::-webkit-scrollbar-track {
- background: var(--ifm-color-emphasis-100);
- border-radius: 3px;
-}
-
-.screenshotStrip::-webkit-scrollbar-thumb {
- background: var(--ifm-color-emphasis-300);
- border-radius: 3px;
-}
-
-.screenshotItem {
- flex: 0 0 180px;
- margin: 0;
- text-align: center;
- scroll-snap-align: start;
-}
-
-.screenshotItem img {
- width: 100%;
- border-radius: 12px;
- box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
- transition: transform 0.2s;
-}
-
-.screenshotItem img:hover {
- transform: scale(1.03);
-}
-
-.screenshotItem figcaption {
- margin-top: 0.5rem;
- font-size: 0.85rem;
- color: var(--ifm-font-color-secondary);
-}
-
-/* Lightbox */
-
-.lightbox {
- border: none;
- background: transparent;
- padding: 0;
- max-width: 90vw;
- max-height: 90vh;
-}
-
-.lightbox::backdrop {
- background: rgba(0, 0, 0, 0.8);
-}
-
-.lightbox img {
- max-height: 85vh;
- border-radius: 16px;
-}
-
-.screenshotItem {
- cursor: pointer;
-}
/* Responsive */
diff --git a/apps/docs/src/pages/index.tsx b/apps/docs/src/pages/index.tsx
index 800506a7..256f03a3 100644
--- a/apps/docs/src/pages/index.tsx
+++ b/apps/docs/src/pages/index.tsx
@@ -1,8 +1,9 @@
-import { type ReactNode, useRef } from "react"
+import { type ReactNode } from "react"
import clsx from "clsx"
import Link from "@docusaurus/Link"
import Layout from "@theme/Layout"
import Heading from "@theme/Heading"
+import ScreenshotGallery from "../components/ScreenshotGallery"
import styles from "./index.module.css"
@@ -79,47 +80,28 @@ function HomepageFeatures(): ReactNode {
)
}
-function HomepageScreenshots(): ReactNode {
- const dialogRef = useRef<HTMLDialogElement>(null)
- const imgRef = useRef<HTMLImageElement>(null)
-
- const screenshots = [
- { src: "/img/screenshots/Dashboard.png", label: "Dashboard" },
- { src: "/img/screenshots/Settings.png", label: "Settings" },
- { src: "/img/screenshots/TrackingProfiles.png", label: "Tracking Profiles" },
- { src: "/img/screenshots/DataManagement.png", label: "Data Management" },
- { src: "/img/screenshots/ApiFieldMapping.png", label: "API Field Mapping" },
- { src: "/img/screenshots/ExportData.png", label: "Export" },
- { src: "/img/screenshots/Authentication.png", label: "Authentication" },
- { src: "/img/screenshots/DarkMode.png", label: "Dark Mode" }
- ]
-
- function openLightbox(src: string, alt: string) {
- if (imgRef.current) {
- imgRef.current.src = src
- imgRef.current.alt = alt
- }
- dialogRef.current?.showModal()
- }
+const homepageScreenshots = [
+ { src: "/img/screenshots/Dashboard.png", label: "Dashboard" },
+ { src: "/img/screenshots/LocationHistory.png", label: "Location History" },
+ { src: "/img/screenshots/TripDetails.png", label: "Trip Detail" },
+ { src: "/img/screenshots/Trips.png", label: "Trips" },
+ { src: "/img/screenshots/Settings.png", label: "Settings" },
+ { src: "/img/screenshots/TrackingProfiles.png", label: "Tracking Profiles" },
+ { src: "/img/screenshots/DataManagement.png", label: "Data Management" },
+ { src: "/img/screenshots/ApiFieldMapping.png", label: "API Field Mapping" },
+ { src: "/img/screenshots/Authentication.png", label: "Authentication" },
+ { src: "/img/screenshots/DarkMode.png", label: "Dark Mode" }
+]
+function HomepageScreenshots(): ReactNode {
return (
<section className={styles.screenshots}>
<div className="container">
<Heading as="h2" className={styles.sectionHeading}>
Screenshots
</Heading>
- <div className={styles.screenshotStrip}>
- {screenshots.map(({ src, label }) => (
- <figure key={label} className={styles.screenshotItem} onClick={() => openLightbox(src, label)}>
- <img src={src} alt={label} loading="lazy" />
- <figcaption>{label}</figcaption>
- </figure>
- ))}
- </div>
+ <ScreenshotGallery screenshots={homepageScreenshots} />
</div>
- <dialog ref={dialogRef} className={styles.lightbox} onClick={() => dialogRef.current?.close()}>
- <img ref={imgRef} src="" alt="" />
- </dialog>
</section>
)
}
diff --git a/apps/docs/src/theme/Root.tsx b/apps/docs/src/theme/Root.tsx
index 33e0089f..aa9900b8 100644
--- a/apps/docs/src/theme/Root.tsx
+++ b/apps/docs/src/theme/Root.tsx
@@ -1,5 +1,5 @@
/**
- * Docusaurus Root wrapper — injects CSS custom properties from @colota/shared.
+ * Docusaurus Root wrapper - injects CSS custom properties from @colota/shared.
* This makes packages/shared/src/colors.ts the single source of truth
* for both the mobile app and the docs site.
*/
diff --git a/apps/docs/static/img/screenshots/Authentication.png b/apps/docs/static/img/screenshots/Authentication.png
index 2920d010..897fcfef 100644
Binary files a/apps/docs/static/img/screenshots/Authentication.png and b/apps/docs/static/img/screenshots/Authentication.png differ
diff --git a/apps/docs/static/img/screenshots/Dashboard.png b/apps/docs/static/img/screenshots/Dashboard.png
index a57e2a67..8c92fef1 100644
Binary files a/apps/docs/static/img/screenshots/Dashboard.png and b/apps/docs/static/img/screenshots/Dashboard.png differ
diff --git a/apps/docs/static/img/screenshots/LocationHistory.png b/apps/docs/static/img/screenshots/LocationHistory.png
new file mode 100644
index 00000000..6df19af1
Binary files /dev/null and b/apps/docs/static/img/screenshots/LocationHistory.png differ
diff --git a/apps/docs/static/img/screenshots/LocationInspector.png b/apps/docs/static/img/screenshots/LocationInspector.png
deleted file mode 100644
index 78e01382..00000000
Binary files a/apps/docs/static/img/screenshots/LocationInspector.png and /dev/null differ
diff --git a/apps/docs/static/img/screenshots/Settings.png b/apps/docs/static/img/screenshots/Settings.png
index 2a88d32f..0242a610 100644
Binary files a/apps/docs/static/img/screenshots/Settings.png and b/apps/docs/static/img/screenshots/Settings.png differ
diff --git a/apps/docs/static/img/screenshots/TripDetails.png b/apps/docs/static/img/screenshots/TripDetails.png
new file mode 100644
index 00000000..ddc7241d
Binary files /dev/null and b/apps/docs/static/img/screenshots/TripDetails.png differ
diff --git a/apps/docs/static/img/screenshots/Trips.png b/apps/docs/static/img/screenshots/Trips.png
new file mode 100644
index 00000000..20f3bf37
Binary files /dev/null and b/apps/docs/static/img/screenshots/Trips.png differ
diff --git a/apps/mobile/App.tsx b/apps/mobile/App.tsx
index 9945aa88..bc797aef 100644
--- a/apps/mobile/App.tsx
+++ b/apps/mobile/App.tsx
@@ -20,11 +20,13 @@ import {
GeofenceScreen,
DataManagementScreen,
LocationHistoryScreen,
+ LocationSummaryScreen,
ExportDataScreen,
AboutScreen,
TrackingProfilesScreen,
ProfileEditorScreen,
- SetupImportScreen
+ SetupImportScreen,
+ TripDetailScreen
} from "./src/screens/"
MapLibreGL.setAccessToken(null)
@@ -62,6 +64,11 @@ const SCREEN_CONFIG = [
component: LocationHistoryScreen,
title: "Location History"
},
+ {
+ name: "Location Summary",
+ component: LocationSummaryScreen,
+ title: "Summary"
+ },
{
name: "Export Data",
component: ExportDataScreen,
@@ -91,6 +98,11 @@ const SCREEN_CONFIG = [
name: "Setup Import",
component: SetupImportScreen,
title: "Import Configuration"
+ },
+ {
+ name: "Trip Detail",
+ component: TripDetailScreen,
+ title: "Trip Detail"
}
] as const
diff --git a/apps/mobile/android/app/fastlane/metadata/android/en-US/images/phoneScreenshots/2.png b/apps/mobile/android/app/fastlane/metadata/android/en-US/images/phoneScreenshots/2.png
index 2a88d32f..6df19af1 100644
Binary files a/apps/mobile/android/app/fastlane/metadata/android/en-US/images/phoneScreenshots/2.png and b/apps/mobile/android/app/fastlane/metadata/android/en-US/images/phoneScreenshots/2.png differ
diff --git a/apps/mobile/android/app/fastlane/metadata/android/en-US/images/phoneScreenshots/3.png b/apps/mobile/android/app/fastlane/metadata/android/en-US/images/phoneScreenshots/3.png
index 2920d010..ddc7241d 100644
Binary files a/apps/mobile/android/app/fastlane/metadata/android/en-US/images/phoneScreenshots/3.png and b/apps/mobile/android/app/fastlane/metadata/android/en-US/images/phoneScreenshots/3.png differ
diff --git a/apps/mobile/android/app/fastlane/metadata/android/en-US/images/phoneScreenshots/4.png b/apps/mobile/android/app/fastlane/metadata/android/en-US/images/phoneScreenshots/4.png
index fa6f9e93..20f3bf37 100644
Binary files a/apps/mobile/android/app/fastlane/metadata/android/en-US/images/phoneScreenshots/4.png and b/apps/mobile/android/app/fastlane/metadata/android/en-US/images/phoneScreenshots/4.png differ
diff --git a/apps/mobile/android/app/fastlane/metadata/android/en-US/images/phoneScreenshots/5.png b/apps/mobile/android/app/fastlane/metadata/android/en-US/images/phoneScreenshots/5.png
index 81b58cdd..0242a610 100644
Binary files a/apps/mobile/android/app/fastlane/metadata/android/en-US/images/phoneScreenshots/5.png and b/apps/mobile/android/app/fastlane/metadata/android/en-US/images/phoneScreenshots/5.png differ
diff --git a/apps/mobile/android/app/fastlane/metadata/android/en-US/images/phoneScreenshots/6.png b/apps/mobile/android/app/fastlane/metadata/android/en-US/images/phoneScreenshots/6.png
index 6bb95f53..fa6f9e93 100644
Binary files a/apps/mobile/android/app/fastlane/metadata/android/en-US/images/phoneScreenshots/6.png and b/apps/mobile/android/app/fastlane/metadata/android/en-US/images/phoneScreenshots/6.png differ
diff --git a/apps/mobile/android/app/fastlane/metadata/android/en-US/images/phoneScreenshots/7.png b/apps/mobile/android/app/fastlane/metadata/android/en-US/images/phoneScreenshots/7.png
index 7a6a4e4e..897fcfef 100644
Binary files a/apps/mobile/android/app/fastlane/metadata/android/en-US/images/phoneScreenshots/7.png and b/apps/mobile/android/app/fastlane/metadata/android/en-US/images/phoneScreenshots/7.png differ
diff --git a/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt
index 67c3f885..c6020b95 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
@@ -321,6 +321,172 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
}
}
+ @ReactMethod
+ fun getDaysWithData(startTimestamp: Double, endTimestamp: Double, promise: Promise) =
+ executeAsync(promise) {
+ val days = dbHelper.getDaysWithData(startTimestamp.toLong(), endTimestamp.toLong())
+ Arguments.createArray().apply {
+ days.forEach { pushString(it) }
+ }
+ }
+
+ @ReactMethod
+ fun getDailyStats(startTimestamp: Double, endTimestamp: Double, promise: Promise) =
+ executeAsync(promise) {
+ val stats = dbHelper.getDailyStats(startTimestamp.toLong(), endTimestamp.toLong())
+ Arguments.createArray().apply {
+ stats.forEach { row -> pushMap(Arguments.makeNativeMap(row)) }
+ }
+ }
+
+ @ReactMethod
+ fun insertDummyData(promise: Promise) {
+ if (!BuildConfig.DEBUG) {
+ promise.reject("ERR_NOT_DEBUG", "insertDummyData is only available in debug builds")
+ return
+ }
+ executeAsync(promise) {
+ val now = System.currentTimeMillis() / 1000
+ var count = 0
+
+ // Realistic scenario: Home (Friedrichshain) → Supermarket → Gym → Home
+ // All locations follow real Berlin streets for plausible GPS tracks.
+
+ // Home: Boxhagener Platz area, Friedrichshain
+ // Supermarket: REWE on Warschauer Str (~1.2 km south)
+ // Gym: FitX Ostkreuz (~1.5 km south-east of supermarket)
+
+ // Trip 1: Home → Supermarket (driving, ~12 min)
+ val trip1 = arrayOf(
+ // lat lon alt speed acc
+ doubleArrayOf(52.51420, 13.45830, 38.0, 0.2, 4.0), // parked at home
+ doubleArrayOf(52.51390, 13.45780, 37.0, 3.5, 5.0), // pulling out
+ doubleArrayOf(52.51310, 13.45650, 36.0, 8.2, 4.0), // Grünberger Str
+ doubleArrayOf(52.51220, 13.45490, 35.0, 11.5, 3.5), // heading south
+ doubleArrayOf(52.51120, 13.45340, 35.0, 12.8, 3.0), // Revaler Str
+ doubleArrayOf(52.50980, 13.45220, 34.0, 10.1, 4.0), // turning onto Warschauer
+ doubleArrayOf(52.50870, 13.45100, 34.0, 8.7, 3.5), // Warschauer Str south
+ doubleArrayOf(52.50760, 13.44950, 33.0, 11.3, 3.0), // passing S-Bahn bridge
+ doubleArrayOf(52.50650, 13.44820, 33.0, 9.4, 4.0), // Stralauer Allee
+ doubleArrayOf(52.50560, 13.44710, 33.0, 6.2, 4.5), // slowing down
+ doubleArrayOf(52.50490, 13.44650, 32.0, 2.1, 5.0), // arriving
+ doubleArrayOf(52.50460, 13.44630, 32.0, 0.3, 4.0) // parked at supermarket
+ )
+
+ // Trip 2: Supermarket → Gym (driving, ~8 min)
+ val trip2 = arrayOf(
+ doubleArrayOf(52.50460, 13.44630, 32.0, 0.5, 4.0), // leaving supermarket
+ doubleArrayOf(52.50430, 13.44700, 32.0, 5.8, 4.5), // pulling out east
+ doubleArrayOf(52.50380, 13.44890, 33.0, 10.2, 3.5), // Stralauer Allee east
+ doubleArrayOf(52.50340, 13.45120, 33.0, 12.5, 3.0), // along the Spree
+ doubleArrayOf(52.50310, 13.45380, 34.0, 11.8, 3.5), // heading east
+ doubleArrayOf(52.50270, 13.45640, 34.0, 9.6, 4.0), // Modersohnstr area
+ doubleArrayOf(52.50230, 13.45900, 35.0, 8.3, 4.0), // near Ostkreuz
+ doubleArrayOf(52.50180, 13.46100, 35.0, 5.1, 4.5), // slowing for turn
+ doubleArrayOf(52.50150, 13.46250, 35.0, 2.4, 5.0), // arriving at gym
+ doubleArrayOf(52.50140, 13.46280, 35.0, 0.2, 4.0) // parked at gym
+ )
+
+ // Trip 3: Gym → Home (driving, ~14 min, slightly different route)
+ val trip3 = arrayOf(
+ doubleArrayOf(52.50140, 13.46280, 35.0, 0.4, 4.0), // leaving gym
+ doubleArrayOf(52.50190, 13.46180, 35.0, 4.2, 4.5), // pulling out
+ doubleArrayOf(52.50280, 13.45980, 34.0, 9.7, 3.5), // Sonntagstr north
+ doubleArrayOf(52.50390, 13.45820, 34.0, 11.4, 3.0), // heading north-west
+ doubleArrayOf(52.50510, 13.45700, 33.0, 12.1, 3.5), // Simplonstr
+ doubleArrayOf(52.50630, 13.45590, 33.0, 10.5, 4.0), // crossing rail tracks
+ doubleArrayOf(52.50740, 13.45480, 34.0, 8.9, 3.5), // Warschauer north
+ doubleArrayOf(52.50860, 13.45360, 34.0, 11.0, 3.0), // RAW-Gelände area
+ doubleArrayOf(52.50970, 13.45280, 35.0, 9.3, 4.0), // Revaler Str
+ doubleArrayOf(52.51080, 13.45370, 36.0, 10.8, 3.5), // turning onto Grünberger
+ doubleArrayOf(52.51190, 13.45490, 37.0, 8.2, 4.0), // Grünberger Str north
+ doubleArrayOf(52.51290, 13.45620, 37.0, 6.5, 4.5), // approaching home
+ doubleArrayOf(52.51370, 13.45740, 38.0, 3.1, 5.0), // slowing down
+ doubleArrayOf(52.51420, 13.45830, 38.0, 0.2, 4.0) // back home
+ )
+
+ // Generate data for the past 7 days with slight daily variation
+ for (dayOffset in 6 downTo 0) {
+ val dayMidnight = now - (now % 86400) - (dayOffset * 86400L)
+ val battery = 92 - (dayOffset * 3)
+ // Small daily jitter so tracks aren't perfectly identical
+ val jitterLat = (dayOffset * 0.00003) - 0.00009
+ val jitterLon = (dayOffset * 0.00002) - 0.00006
+
+ // Trip 1: Home → Supermarket, depart 09:30, ~30s between points
+ val t1Start = dayMidnight + 9 * 3600 + 1800
+ for ((i, wp) in trip1.withIndex()) {
+ val ts = t1Start + (i * 30L)
+ if (ts > now) break
+ dbHelper.saveLocation(
+ wp[0] + jitterLat, wp[1] + jitterLon,
+ wp[4], wp[2].toInt(), wp[3],
+ null, battery - i, 1, ts
+ )
+ count++
+ }
+
+ // Gap: 45 min at supermarket (triggers trip segmentation at 15-min threshold)
+
+ // Trip 2: Supermarket → Gym, depart 10:20, ~30s between points
+ val t2Start = dayMidnight + 10 * 3600 + 1200
+ for ((i, wp) in trip2.withIndex()) {
+ val ts = t2Start + (i * 30L)
+ if (ts > now) break
+ dbHelper.saveLocation(
+ wp[0] + jitterLat, wp[1] + jitterLon,
+ wp[4], wp[2].toInt(), wp[3],
+ null, battery - 15 - i, 2, ts
+ )
+ count++
+ }
+
+ // Gap: 1h 30min at gym
+
+ // Trip 3: Gym → Home, depart 12:00, ~30s between points
+ val t3Start = dayMidnight + 12 * 3600
+ for ((i, wp) in trip3.withIndex()) {
+ val ts = t3Start + (i * 30L)
+ if (ts > now) break
+ dbHelper.saveLocation(
+ wp[0] + jitterLat, wp[1] + jitterLon,
+ wp[4], wp[2].toInt(), wp[3],
+ null, battery - 30 - i, 1, ts
+ )
+ count++
+ }
+
+ // Skip afternoon trip on some days for variety
+ if (dayOffset % 2 == 0) continue
+
+ // Trip 4 (some days): Quick evening walk, depart 18:00
+ // Short loop around Boxhagener Platz (~10 min walk)
+ val walkTrip = arrayOf(
+ doubleArrayOf(52.51420, 13.45830, 38.0, 1.2, 6.0),
+ doubleArrayOf(52.51450, 13.45900, 38.0, 1.4, 5.5),
+ doubleArrayOf(52.51480, 13.45970, 38.0, 1.3, 5.0),
+ doubleArrayOf(52.51500, 13.46050, 38.0, 1.5, 5.5),
+ doubleArrayOf(52.51480, 13.46130, 38.0, 1.4, 6.0),
+ doubleArrayOf(52.51450, 13.46080, 38.0, 1.3, 5.5),
+ doubleArrayOf(52.51430, 13.45970, 38.0, 1.2, 5.0),
+ doubleArrayOf(52.51420, 13.45830, 38.0, 0.3, 6.0)
+ )
+ val t4Start = dayMidnight + 18 * 3600
+ for ((i, wp) in walkTrip.withIndex()) {
+ val ts = t4Start + (i * 75L)
+ if (ts > now) break
+ dbHelper.saveLocation(
+ wp[0] + jitterLat, wp[1] + jitterLon,
+ wp[4], wp[2].toInt(), wp[3],
+ null, battery - 45 - i, 1, ts
+ )
+ count++
+ }
+ }
+ count
+ }
+ }
+
@ReactMethod
fun 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.kt
index 1a305538..bd003655 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
@@ -46,6 +46,7 @@ class DatabaseHelper private constructor(context: Context) :
)
private const val TAG = "LocationDB"
+ private const val TRIP_GAP_SECONDS = 900L // 15 min, matches JS segmentTrips
@Volatile
private var INSTANCE: DatabaseHelper? = null
@@ -585,6 +586,126 @@ class DatabaseHelper private constructor(context: Context) :
}
+ /**
+ * Returns distinct dates (YYYY-MM-DD) that have location data within the range.
+ * Used by the calendar view to show activity dots.
+ */
+ fun getDaysWithData(startTimestamp: Long, endTimestamp: Long): List<String> {
+ val days = mutableListOf<String>()
+ try {
+ readableDatabase.rawQuery(
+ """
+ SELECT DISTINCT strftime('%Y-%m-%d', timestamp, 'unixepoch', 'localtime') as day
+ FROM $TABLE_LOCATIONS
+ WHERE timestamp >= ? AND timestamp <= ?
+ ORDER BY day ASC
+ """.trimIndent(),
+ arrayOf(startTimestamp.toString(), endTimestamp.toString())
+ ).use { cursor ->
+ while (cursor.moveToNext()) {
+ days.add(cursor.getString(0))
+ }
+ }
+ } catch (e: Exception) {
+ Log.e(TAG, "Error getting days with data", e)
+ }
+ return days
+ }
+
+ /**
+ * Returns per-day aggregated stats for a date range in a single query.
+ * Computes distance (haversine) and trip count (15-min gap threshold) inline
+ * to avoid nested cursors.
+ */
+ fun getDailyStats(startTimestamp: Long, endTimestamp: Long): List<Map<String, Any>> {
+ val stats = mutableListOf<Map<String, Any>>()
+ try {
+ readableDatabase.rawQuery(
+ """
+ SELECT
+ strftime('%Y-%m-%d', timestamp, 'unixepoch', 'localtime') as day,
+ latitude, longitude, timestamp
+ FROM $TABLE_LOCATIONS
+ WHERE timestamp >= ? AND timestamp <= ?
+ ORDER BY day ASC, timestamp ASC
+ """.trimIndent(),
+ arrayOf(startTimestamp.toString(), endTimestamp.toString())
+ ).use { cursor ->
+ var currentDay: String? = null
+ var count = 0
+ var startTime = 0L
+ var endTime = 0L
+ var distance = 0.0
+ var tripCount = 0
+ var segmentSize = 0
+ var prevLat = 0.0
+ var prevLon = 0.0
+ var prevTs = 0L
+
+ fun emitDay() {
+ if (currentDay != null) {
+ stats.add(mapOf(
+ "day" to currentDay!!,
+ "count" to count,
+ "startTime" to startTime,
+ "endTime" to endTime,
+ "distanceMeters" to distance,
+ "tripCount" to tripCount
+ ))
+ }
+ }
+
+ while (cursor.moveToNext()) {
+ val day = cursor.getString(0)
+ val lat = cursor.getDouble(1)
+ val lon = cursor.getDouble(2)
+ val ts = cursor.getLong(3)
+
+ if (day != currentDay) {
+ emitDay()
+ currentDay = day
+ count = 1
+ startTime = ts
+ endTime = ts
+ distance = 0.0
+ tripCount = 0
+ segmentSize = 1
+ prevLat = lat
+ prevLon = lon
+ prevTs = ts
+ } else {
+ count++
+ endTime = ts
+ if (ts - prevTs >= TRIP_GAP_SECONDS) {
+ segmentSize = 1
+ } else {
+ segmentSize++
+ if (segmentSize == 2) tripCount++
+ distance += haversineDistance(prevLat, prevLon, lat, lon)
+ }
+ }
+ prevLat = lat
+ prevLon = lon
+ prevTs = ts
+ }
+ emitDay()
+ }
+ } catch (e: Exception) {
+ Log.e(TAG, "Error getting daily stats", e)
+ }
+ return stats
+ }
+
+ internal fun haversineDistance(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double {
+ val r = 6371000.0
+ val dLat = Math.toRadians(lat2 - lat1)
+ val dLon = Math.toRadians(lon2 - lon1)
+ val a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
+ Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
+ Math.sin(dLon / 2) * Math.sin(dLon / 2)
+ return r * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
+ }
+
private fun getTodayStartTimestamp(): Long {
return Calendar.getInstance().apply {
set(Calendar.HOUR_OF_DAY, 0)
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/data/DatabaseHelperSQLiteTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/data/DatabaseHelperSQLiteTest.kt
index 78a51239..15464cb0 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/data/DatabaseHelperSQLiteTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/data/DatabaseHelperSQLiteTest.kt
@@ -678,6 +678,138 @@ class DatabaseHelperSQLiteTest {
assertEquals(52.0, data[0]["latitude"] as Double, 0.001)
}
+ // ========================================================================
+ // getDaysWithData
+ // ========================================================================
+
+ @Test
+ fun `getDaysWithData returns distinct days`() {
+ // Two locations on same day, one on a different day
+ db.saveLocation(latitude = 52.0, longitude = 13.0, timestamp = 1708344000L) // midday
+ db.saveLocation(latitude = 52.1, longitude = 13.1, timestamp = 1708344060L) // +1 min same day
+ db.saveLocation(latitude = 53.0, longitude = 14.0, timestamp = 1708430400L) // next day midday
+
+ val days = db.getDaysWithData(1708300000L, 1708500000L)
+ assertEquals(2, days.size)
+ // Ordered ASC
+ assertTrue(days[0] < days[1])
+ }
+
+ @Test
+ fun `getDaysWithData returns empty for no matches`() {
+ db.saveLocation(latitude = 52.0, longitude = 13.0, timestamp = 1708344000L)
+
+ val days = db.getDaysWithData(1700000000L, 1700100000L)
+ assertTrue(days.isEmpty())
+ }
+
+ @Test
+ fun `getDaysWithData respects range boundaries`() {
+ db.saveLocation(latitude = 52.0, longitude = 13.0, timestamp = 1000L) // outside range
+ db.saveLocation(latitude = 53.0, longitude = 14.0, timestamp = 5000L) // inside range
+ db.saveLocation(latitude = 54.0, longitude = 15.0, timestamp = 9000L) // outside range
+
+ val days = db.getDaysWithData(4000L, 6000L)
+ assertEquals(1, days.size)
+ }
+
+ // ========================================================================
+ // getDailyStats
+ // ========================================================================
+
+ @Test
+ fun `getDailyStats returns per-day aggregated stats`() {
+ // Day 1: 3 locations close together (single trip)
+ db.saveLocation(latitude = 52.0, longitude = 13.0, timestamp = 1708344000L)
+ db.saveLocation(latitude = 52.001, longitude = 13.001, timestamp = 1708344060L)
+ db.saveLocation(latitude = 52.002, longitude = 13.002, timestamp = 1708344120L)
+
+ // Day 2: 2 locations
+ db.saveLocation(latitude = 53.0, longitude = 14.0, timestamp = 1708430400L)
+ db.saveLocation(latitude = 53.001, longitude = 14.001, timestamp = 1708430460L)
+
+ val stats = db.getDailyStats(1708300000L, 1708500000L)
+ assertEquals(2, stats.size)
+
+ // Day 1 stats
+ assertEquals(3, stats[0]["count"])
+ assertTrue((stats[0]["distanceMeters"] as Double) > 0)
+ assertEquals(1, stats[0]["tripCount"]) // all within 60s, no gap
+ }
+
+ @Test
+ fun `getDailyStats counts trips based on time gaps`() {
+ // Trip 1: two locations 60s apart
+ db.saveLocation(latitude = 52.0, longitude = 13.0, timestamp = 1708344000L) // 12:00
+ db.saveLocation(latitude = 52.1, longitude = 13.1, timestamp = 1708344060L) // 12:01
+
+ // Gap of 16 minutes (> 900s threshold)
+
+ // Trip 2: two more locations
+ db.saveLocation(latitude = 53.0, longitude = 14.0, timestamp = 1708345020L) // 12:17
+ db.saveLocation(latitude = 53.1, longitude = 14.1, timestamp = 1708345080L) // 12:18
+
+ val stats = db.getDailyStats(1708300000L, 1708400000L)
+ assertEquals(1, stats.size)
+ assertEquals(4, stats[0]["count"])
+ assertEquals(2, stats[0]["tripCount"])
+ }
+
+ @Test
+ fun `getDailyStats returns empty for no data`() {
+ val stats = db.getDailyStats(1708300000L, 1708400000L)
+ assertTrue(stats.isEmpty())
+ }
+
+ @Test
+ fun `getDailyStats computes distance via haversine`() {
+ // Two points roughly 11 km apart (Berlin to Potsdam)
+ db.saveLocation(latitude = 52.52, longitude = 13.405, timestamp = 1708344000L)
+ db.saveLocation(latitude = 52.39, longitude = 13.065, timestamp = 1708344060L)
+
+ val stats = db.getDailyStats(1708300000L, 1708400000L)
+ assertEquals(1, stats.size)
+ val distance = stats[0]["distanceMeters"] as Double
+ // Distance should be roughly 25-30 km (haversine)
+ assertTrue("Distance should be > 20km, was $distance", distance > 20000)
+ assertTrue("Distance should be < 40km, was $distance", distance < 40000)
+ }
+
+ // ========================================================================
+ // haversineDistance
+ // ========================================================================
+
+ @Test
+ fun `haversineDistance Berlin to Munich is approximately 504 km`() {
+ val distance = db.haversineDistance(52.52, 13.405, 48.1351, 11.582)
+ assertTrue("Expected ~504km, got ${distance / 1000}km", distance > 500000)
+ assertTrue("Expected ~504km, got ${distance / 1000}km", distance < 510000)
+ }
+
+ @Test
+ fun `haversineDistance same point returns zero`() {
+ val distance = db.haversineDistance(52.52, 13.405, 52.52, 13.405)
+ assertEquals(0.0, distance, 0.001)
+ }
+
+ // ========================================================================
+ // deleteOlderThan
+ // ========================================================================
+
+ @Test
+ fun `deleteOlderThan removes only old locations`() {
+ val now = System.currentTimeMillis() / 1000
+ db.saveLocation(latitude = 52.0, longitude = 13.0, timestamp = now - 86400 * 10) // 10 days ago
+ db.saveLocation(latitude = 53.0, longitude = 14.0, timestamp = now) // today
+
+ val deleted = db.deleteOlderThan(7)
+ assertEquals(1, deleted)
+
+ val remaining = db.getTableData(DatabaseHelper.TABLE_LOCATIONS, 100, 0)
+ assertEquals(1, remaining.size)
+ assertEquals(53.0, remaining[0]["latitude"] as Double, 0.001)
+ }
+
// ========================================================================
// Helpers
// ========================================================================
diff --git a/apps/mobile/src/components/features/inspector/CalendarPicker.tsx b/apps/mobile/src/components/features/inspector/CalendarPicker.tsx
new file mode 100644
index 00000000..a634b57f
--- /dev/null
+++ b/apps/mobile/src/components/features/inspector/CalendarPicker.tsx
@@ -0,0 +1,386 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * 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"
+
+interface CalendarPickerProps {
+ date: Date
+ onDateChange: (date: Date) => void
+ locationCount: number
+ distance?: string
+ colors: ThemeColors
+ daysWithData: Set<string>
+ onMonthChange: (year: number, month: number) => void
+ onPrefetchMonth?: (year: number, month: number) => void
+}
+
+const WEEKDAYS = ["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"]
+
+function isSameDay(a: Date, b: Date): boolean {
+ return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate()
+}
+
+function formatDateKey(year: number, month: number, day: number): string {
+ return `${year}-${String(month + 1).padStart(2, "0")}-${String(day).padStart(2, "0")}`
+}
+
+export function CalendarPicker({
+ date,
+ onDateChange,
+ locationCount,
+ distance,
+ colors,
+ daysWithData,
+ onMonthChange,
+ onPrefetchMonth
+}: CalendarPickerProps) {
+ const [isExpanded, setIsExpanded] = useState(false)
+ const [viewYear, setViewYear] = useState(date.getFullYear())
+ const [viewMonth, setViewMonth] = useState(date.getMonth())
+
+ 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) => {
+ let newMonth = viewMonth + delta
+ let newYear = viewYear
+ if (newMonth < 0) {
+ newMonth = 11
+ newYear--
+ } else if (newMonth > 11) {
+ newMonth = 0
+ newYear++
+ }
+ setViewYear(newYear)
+ setViewMonth(newMonth)
+ onMonthChange(newYear, newMonth)
+
+ // Prefetch adjacent month (cache only, no state update)
+ if (onPrefetchMonth) {
+ const adjMonth = newMonth + delta
+ if (adjMonth < 0) {
+ onPrefetchMonth(newYear - 1, 11)
+ } else if (adjMonth > 11) {
+ onPrefetchMonth(newYear + 1, 0)
+ } else {
+ onPrefetchMonth(newYear, adjMonth)
+ }
+ }
+ },
+ [viewMonth, viewYear, onMonthChange, onPrefetchMonth]
+ )
+
+ 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)
+ },
+ [viewYear, viewMonth, onDateChange]
+ )
+
+ const calendarGrid = useMemo(() => {
+ const firstDay = new Date(viewYear, viewMonth, 1)
+ let startOffset = firstDay.getDay() - 1
+ if (startOffset < 0) startOffset = 6
+ const 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
+ }, [viewYear, viewMonth])
+
+ const monthLabel = useMemo(() => {
+ return new Date(viewYear, viewMonth, 1).toLocaleDateString(undefined, { month: "long", year: "numeric" })
+ }, [viewYear, viewMonth])
+
+ const formatted = date.toLocaleDateString(undefined, {
+ weekday: "short",
+ month: "short",
+ day: "numeric",
+ year: "numeric"
+ })
+
+ 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} style={({ pressed }) => [styles.navBtn, pressed && { opacity: 0.6 }]}>
+ <ChevronLeft size={22} color={colors.primary} />
+ </Pressable>
+
+ <Pressable
+ onPress={toggleExpanded}
+ style={({ pressed }) => [styles.dateContainer, pressed && { opacity: 0.7 }]}
+ >
+ <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>
+
+ <Pressable
+ onPress={goForward}
+ style={({ pressed }) => [styles.navBtn, pressed && { opacity: 0.6 }]}
+ disabled={isToday}
+ >
+ <ChevronRight size={22} color={isToday ? colors.textDisabled : colors.primary} />
+ </Pressable>
+ </View>
+
+ {!isToday && !isExpanded && (
+ <Pressable
+ onPress={goToToday}
+ style={({ pressed }) => [
+ styles.todayBtn,
+ { backgroundColor: colors.primary + "15" },
+ pressed && { opacity: 0.7 }
+ ]}
+ >
+ <Text style={[styles.todayText, { color: colors.primary }]}>Today</Text>
+ </Pressable>
+ )}
+
+ {/* Expanded calendar grid */}
+ {isExpanded && (
+ <View style={styles.calendarContainer}>
+ {/* Month navigation */}
+ <View style={styles.monthRow}>
+ <Pressable
+ onPress={() => navigateMonth(-1)}
+ style={({ pressed }) => [styles.monthNav, pressed && { opacity: 0.6 }]}
+ >
+ <ChevronLeft size={18} color={colors.primary} />
+ </Pressable>
+ <Text style={[styles.monthLabel, { color: colors.text }]}>{monthLabel}</Text>
+ <Pressable
+ onPress={() => navigateMonth(1)}
+ style={({ pressed }) => [styles.monthNav, pressed && { opacity: 0.6 }]}
+ disabled={isFutureMonth}
+ >
+ <ChevronRight size={18} color={isFutureMonth ? colors.textDisabled : colors.primary} />
+ </Pressable>
+ </View>
+
+ {/* Weekday headers */}
+ <View style={styles.weekdayRow}>
+ {WEEKDAYS.map((day) => (
+ <Text key={day} style={[styles.weekdayText, { color: colors.textSecondary }]}>
+ {day}
+ </Text>
+ ))}
+ </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 cellDate = new Date(viewYear, viewMonth, cell.day)
+ const isSelected = isSameDay(cellDate, date)
+ const isCellToday = isSameDay(cellDate, today)
+ const isFuture = cellDate > today
+
+ return (
+ <Pressable
+ key={cell.key}
+ style={styles.dayCell}
+ onPress={() => selectDay(cell.day!)}
+ disabled={isFuture}
+ >
+ <View style={[styles.dayCircle, isSelected && { backgroundColor: colors.primary }]}>
+ <Text
+ style={[
+ styles.dayText,
+ { color: isFuture ? colors.textDisabled : isSelected ? colors.textOnPrimary : colors.text },
+ isCellToday && !isSelected && { color: colors.primary, ...fonts.bold }
+ ]}
+ >
+ {cell.day}
+ </Text>
+ {hasData && (
+ <View
+ style={[
+ styles.dataDot,
+ { backgroundColor: isSelected ? colors.textOnPrimary : colors.primary }
+ ]}
+ />
+ )}
+ </View>
+ </Pressable>
+ )
+ })}
+ </View>
+ </View>
+ )}
+ </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
+ },
+ dateLabelRow: {
+ 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
+ },
+ countText: {
+ fontSize: 12,
+ ...fonts.regular,
+ marginTop: 2
+ },
+ todayBtn: {
+ alignSelf: "center",
+ marginTop: 8,
+ paddingHorizontal: 16,
+ paddingVertical: 6,
+ borderRadius: 14
+ },
+ todayText: {
+ fontSize: 12,
+ ...fonts.semiBold
+ },
+ calendarContainer: {
+ marginTop: 12
+ },
+ monthRow: {
+ flexDirection: "row",
+ alignItems: "center",
+ justifyContent: "space-between",
+ marginBottom: 8
+ },
+ monthNav: {
+ padding: 4
+ },
+ monthLabel: {
+ fontSize: 14,
+ ...fonts.semiBold
+ },
+ weekdayRow: {
+ flexDirection: "row",
+ marginBottom: 4
+ },
+ weekdayText: {
+ flex: 1,
+ textAlign: "center",
+ fontSize: 11,
+ ...fonts.semiBold
+ },
+ daysGrid: {
+ flexDirection: "row",
+ flexWrap: "wrap"
+ },
+ dayCell: {
+ width: "14.28%",
+ aspectRatio: 1,
+ alignItems: "center",
+ justifyContent: "center"
+ },
+ dayCircle: {
+ width: 32,
+ height: 32,
+ borderRadius: 16,
+ alignItems: "center",
+ justifyContent: "center"
+ },
+ dayText: {
+ fontSize: 13,
+ ...fonts.regular
+ },
+ dataDot: {
+ width: 4,
+ height: 4,
+ borderRadius: 2,
+ marginTop: 1
+ }
+})
diff --git a/apps/mobile/src/components/features/inspector/DatePicker.tsx b/apps/mobile/src/components/features/inspector/DatePicker.tsx
deleted file mode 100644
index 65a241cc..00000000
--- a/apps/mobile/src/components/features/inspector/DatePicker.tsx
+++ /dev/null
@@ -1,129 +0,0 @@
-/**
- * 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, Pressable, 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
- distance?: string
- 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, distance, 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}>
- <Pressable onPress={goBack} style={({ pressed }) => [styles.navBtn, pressed && { opacity: 0.6 }]}>
- <ChevronLeft size={22} color={colors.primary} />
- </Pressable>
-
- <Pressable onPress={goToToday} style={({ pressed }) => [styles.dateContainer, pressed && { opacity: 0.7 }]}>
- <Text style={[styles.dateText, { color: colors.text }]}>{formatted}</Text>
- <Text style={[styles.countText, { color: colors.textSecondary }]}>
- {locationCount} {locationCount === 1 ? "location" : "locations"}
- {distance ? ` · ${distance}` : ""}
- </Text>
- </Pressable>
-
- <Pressable
- onPress={goForward}
- style={({ pressed }) => [styles.navBtn, pressed && { opacity: 0.6 }]}
- disabled={isToday}
- >
- <ChevronRight size={22} color={isToday ? colors.textDisabled : colors.primary} />
- </Pressable>
- </View>
-
- {!isToday && (
- <Pressable
- onPress={goToToday}
- style={({ pressed }) => [
- styles.todayBtn,
- { backgroundColor: colors.primary + "15" },
- pressed && { opacity: 0.7 }
- ]}
- >
- <Text style={[styles.todayText, { color: colors.primary }]}>Today</Text>
- </Pressable>
- )}
- </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.tsx
index d59d2935..3a9c2f62 100644
--- a/apps/mobile/src/components/features/inspector/TrackMap.tsx
+++ b/apps/mobile/src/components/features/inspector/TrackMap.tsx
@@ -7,7 +7,8 @@ import React, { useRef, useEffect, useMemo, useState, useCallback } from "react"
import { View, StyleSheet, Text, Pressable } from "react-native"
import { ShapeSource, LineLayer, CircleLayer } from "@maplibre/maplibre-react-native"
import { MapPinOff, X } from "lucide-react-native"
-import { ThemeColors } from "../../../types/global"
+import { ThemeColors, Trip } from "../../../types/global"
+import { getTripColor } from "../../../utils/trips"
import { fonts } from "../../../styles/typography"
import { MapCenterButton } from "../map/MapCenterButton"
import { ColotaMapView, ColotaMapRef } from "../map/ColotaMapView"
@@ -18,8 +19,8 @@ import {
type TrackLocation
} from "../map/mapUtils"
import { getSpeedUnit } from "../../../utils/geo"
+import { MAP_ANIMATION_DURATION_MS } from "../../../constants"
-// MapLibre layer styles (extracted to satisfy no-inline-styles lint rule)
const trackLineStyle = {
lineColor: ["get", "color"] as const,
lineWidth: 3,
@@ -35,21 +36,15 @@ const trackPointStyle = {
circleStrokeWidth: 1.5
}
-const endpointStyle = {
- circleRadius: 8,
- circleColor: ["get", "color"] as const,
- circleStrokeColor: "#ffffff",
- circleStrokeWidth: 2
-}
-import { MAP_ANIMATION_DURATION_MS } from "../../../constants"
-
interface Props {
locations: TrackLocation[]
selectedPoint: { latitude: number; longitude: number } | null
colors: ThemeColors
+ trips?: Trip[]
+ fitVersion?: number
}
-export function TrackMap({ locations, selectedPoint, colors }: Props) {
+export function TrackMap({ locations, selectedPoint, colors, trips, fitVersion }: Props) {
const mapRef = useRef<ColotaMapRef>(null)
const [isCentered, setIsCentered] = useState(true)
const [popup, setPopup] = useState<{
@@ -58,20 +53,28 @@ export function TrackMap({ locations, selectedPoint, colors }: Props) {
timestamp: number
accuracy: number
altitude: number
+ color: string
} | null>(null)
const [mapReady, setMapReady] = useState(false)
- // Fit map to track bounds on first load
+ // Fit map to track bounds when fitVersion changes (date change, trip select)
const bounds = useMemo(() => computeTrackBounds(locations), [locations])
+ const fittedVersionRef = useRef(-1)
useEffect(() => {
- if (bounds && mapReady && mapRef.current?.camera) {
- mapRef.current.camera.fitBounds(bounds.ne, bounds.sw, [60, 60, 60, 60], MAP_ANIMATION_DURATION_MS)
- }
- }, [bounds, mapReady])
+ if (!bounds || !mapReady || !mapRef.current?.camera) return
+ if (fitVersion === fittedVersionRef.current) return
+ fittedVersionRef.current = fitVersion ?? 0
+ mapRef.current.camera.fitBounds(bounds.ne, bounds.sw, [60, 60, 60, 60], MAP_ANIMATION_DURATION_MS)
+ }, [bounds, mapReady, fitVersion])
const handleMapReady = useCallback(() => setMapReady(true), [])
+ // Clear popup when underlying locations change (new day / different trip)
+ useEffect(() => {
+ setPopup(null)
+ }, [locations])
+
// Zoom to selected point from table tap
useEffect(() => {
if (selectedPoint && mapRef.current?.camera) {
@@ -97,117 +100,119 @@ export function TrackMap({ locations, selectedPoint, colors }: Props) {
}
}, [])
+ // Trip boundary indices to avoid drawing lines between trips
+ const skipIndices = useMemo(() => {
+ if (!trips || trips.length <= 1) return undefined
+ const indices = new Set<number>()
+ let offset = 0
+ for (const trip of trips) {
+ if (offset > 0) indices.add(offset)
+ offset += trip.locationCount
+ }
+ return indices
+ }, [trips])
+
+ // Per-location colors
+ const locationColors = useMemo(() => {
+ if (trips) {
+ const arr: string[] = []
+ for (const trip of trips) {
+ const tripColor = getTripColor(trip.index)
+ for (let j = 0; j < trip.locationCount; j++) {
+ arr.push(tripColor)
+ }
+ }
+ // Fill remaining points with default color
+ while (arr.length < locations.length) {
+ arr.push(colors.primary)
+ }
+ return arr
+ }
+ return locations.map(() => colors.primary)
+ }, [trips, locations, colors.primary])
+
// GeoJSON data
- const segmentsGeoJSON = useMemo(() => buildTrackSegmentsGeoJSON(locations, colors), [locations, colors])
- const pointsGeoJSON = useMemo(() => buildTrackPointsGeoJSON(locations, colors), [locations, colors])
+ const segmentsGeoJSON = useMemo(
+ () => buildTrackSegmentsGeoJSON(locations, colors, skipIndices, locationColors),
+ [locations, colors, skipIndices, locationColors]
+ )
+ const pointsGeoJSON = useMemo(
+ () => buildTrackPointsGeoJSON(locations, colors, locationColors),
+ [locations, colors, locationColors]
+ )
- // Highlight point GeoJSON
+ // Highlight GeoJSON for selected point
const highlightGeoJSON = useMemo(() => {
- if (!selectedPoint) return null
+ const coord = selectedPoint ? [selectedPoint.longitude, selectedPoint.latitude] : null
return {
type: "FeatureCollection" as const,
features: [
{
type: "Feature" as const,
- properties: {},
- geometry: {
- type: "Point" as const,
- coordinates: [selectedPoint.longitude, selectedPoint.latitude]
- }
+ properties: { color: colors.primary, visible: coord ? 1 : 0 },
+ geometry: { type: "Point" as const, coordinates: coord ?? [0, 0] }
}
]
}
- }, [selectedPoint])
+ }, [selectedPoint, colors.primary])
const highlightStyle = useMemo(
() => ({
- circleRadius: 12,
- circleColor: colors.primary + "44",
- circleStrokeColor: colors.primary,
- circleStrokeWidth: 2
+ circleRadius: 8,
+ circleColor: ["get", "color"] as any,
+ circleOpacity: ["get", "visible"] as any,
+ circleStrokeColor: "#ffffff",
+ circleStrokeWidth: ["*", 2.5, ["get", "visible"]] as any
}),
- [colors.primary]
+ []
)
- // Start/end endpoint GeoJSON (single ShapeSource with data-driven color)
- const endpointsGeoJSON = useMemo(() => {
- if (locations.length === 0) return null
- const features: GeoJSON.Feature[] = [
- {
- type: "Feature",
- properties: { color: colors.success },
- geometry: { type: "Point", coordinates: [locations[0].longitude, locations[0].latitude] }
- }
- ]
- if (locations.length > 1) {
- const last = locations[locations.length - 1]
- features.push({
- type: "Feature",
- properties: { color: colors.error },
- geometry: { type: "Point", coordinates: [last.longitude, last.latitude] }
- })
- }
- return { type: "FeatureCollection" as const, features }
- }, [locations, colors])
-
- // Speed legend data
const { factor: speedFactor, unit: speedUnit } = getSpeedUnit()
- const slowLabel = `< ${Math.round(2 * speedFactor)} ${speedUnit}`
- const midLabel = `${Math.round(2 * speedFactor)}–${Math.round(8 * speedFactor)} ${speedUnit}`
- const fastLabel = `> ${Math.round(8 * speedFactor)} ${speedUnit}`
- // Handle point tap (track timestamp to distinguish from map tap)
const lastPointPressRef = useRef(0)
const handlePointPress = useCallback(
(event: { features: GeoJSON.Feature[]; coordinates: { latitude: number; longitude: number } }) => {
const feature = event.features[0]
- if (!feature?.properties) return
+ if (!feature?.properties || !feature?.geometry) return
lastPointPressRef.current = Date.now()
+ const geom = feature.geometry as GeoJSON.Point
+ const coord = geom.coordinates as [number, number]
setPopup({
- coordinate: [event.coordinates.longitude, event.coordinates.latitude],
+ coordinate: coord,
speed: feature.properties.speed,
timestamp: feature.properties.timestamp,
accuracy: feature.properties.accuracy,
- altitude: feature.properties.altitude
+ altitude: feature.properties.altitude,
+ color: feature.properties.color ?? colors.primary
})
},
- []
+ [colors.primary]
)
- // Tap on empty map area dismisses popup
const handleMapPress = useCallback(() => {
if (Date.now() - lastPointPressRef.current < 200) return
setPopup(null)
}, [])
- if (locations.length === 0) {
- return (
- <View style={[styles.emptyContainer, { 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>
- )
- }
+ const initialCenter = useMemo(
+ () => [locations[0]?.longitude ?? 0, locations[0]?.latitude ?? 0] as [number, number],
+ [locations]
+ )
- return (
- <View style={styles.container}>
+ // Memoize the map block to prevent popup state changes from triggering re-renders
+ const mapView = useMemo(
+ () => (
<ColotaMapView
ref={mapRef}
- initialCenter={locations.length > 0 ? [locations[0].longitude, locations[0].latitude] : [0, 0]}
+ initialCenter={initialCenter}
initialZoom={2}
onPress={handleMapPress}
onRegionDidChange={handleRegionChange}
onMapReady={handleMapReady}
>
- {/* Speed-colored track segments */}
<ShapeSource id="track-segments" shape={segmentsGeoJSON}>
<LineLayer id="track-line" style={trackLineStyle} />
</ShapeSource>
-
- {/* Track point dots */}
<ShapeSource
id="track-points"
shape={pointsGeoJSON}
@@ -216,28 +221,46 @@ export function TrackMap({ locations, selectedPoint, colors }: Props) {
>
<CircleLayer id="track-point-circles" style={trackPointStyle} />
</ShapeSource>
+ <ShapeSource id="highlight-point" shape={highlightGeoJSON}>
+ <CircleLayer id="highlight-circle" style={highlightStyle} />
+ </ShapeSource>
+ </ColotaMapView>
+ ),
+ [
+ initialCenter,
+ handleMapPress,
+ handleRegionChange,
+ handleMapReady,
+ segmentsGeoJSON,
+ pointsGeoJSON,
+ highlightGeoJSON,
+ handlePointPress,
+ highlightStyle
+ ]
+ )
- {/* Highlight selected point */}
- {highlightGeoJSON && (
- <ShapeSource id="highlight" shape={highlightGeoJSON}>
- <CircleLayer id="highlight-circle" style={highlightStyle} />
- </ShapeSource>
- )}
+ if (locations.length === 0) {
+ return (
+ <View style={[styles.emptyContainer, { 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>
+ )
+ }
- {/* Start/end markers via ShapeSource + CircleLayer */}
- {endpointsGeoJSON && (
- <ShapeSource id="endpoints" shape={endpointsGeoJSON}>
- <CircleLayer id="endpoint-circles" style={endpointStyle} />
- </ShapeSource>
- )}
- </ColotaMapView>
+ return (
+ <View style={styles.container}>
+ {mapView}
- {/* Popup card for tapped point (outside MapView for reliable touch on Android) */}
+ {/* Point detail popup */}
{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() : "—"}
+ {popup.timestamp ? new Date(popup.timestamp * 1000).toLocaleTimeString() : "-"}
</Text>
<Pressable
onPress={() => setPopup(null)}
@@ -269,21 +292,17 @@ export function TrackMap({ locations, selectedPoint, colors }: Props) {
<MapCenterButton visible={!isCentered} onPress={handleFitTrack} />
- {/* Speed legend */}
- <View style={[styles.speedLegend, { backgroundColor: colors.card, borderColor: colors.border }]}>
- <View style={styles.legendItem}>
- <View style={[styles.legendDot, { backgroundColor: colors.success }]} />
- <Text style={[styles.legendLabel, { color: colors.textSecondary }]}>{slowLabel}</Text>
+ {/* Trip legend */}
+ {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>
- <View style={styles.legendItem}>
- <View style={[styles.legendDot, { backgroundColor: colors.warning }]} />
- <Text style={[styles.legendLabel, { color: colors.textSecondary }]}>{midLabel}</Text>
- </View>
- <View style={styles.legendItem}>
- <View style={[styles.legendDot, { backgroundColor: colors.error }]} />
- <Text style={[styles.legendLabel, { color: colors.textSecondary }]}>{fastLabel}</Text>
- </View>
- </View>
+ )}
</View>
)
}
@@ -356,7 +375,7 @@ const styles = StyleSheet.create({
fontWeight: "500",
fontSize: 12
},
- speedLegend: {
+ legend: {
position: "absolute",
bottom: 10,
left: 10,
diff --git a/apps/mobile/src/components/features/inspector/TripList.tsx b/apps/mobile/src/components/features/inspector/TripList.tsx
new file mode 100644
index 00000000..45197f12
--- /dev/null
+++ b/apps/mobile/src/components/features/inspector/TripList.tsx
@@ -0,0 +1,302 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+import React, { useState, useCallback, useMemo } from "react"
+import { View, Text, FlatList, Pressable, StyleSheet } from "react-native"
+import { Clock, Route, Share, TrendingUp, TrendingDown, Gauge } from "lucide-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"
+
+interface TripListProps {
+ trips: Trip[]
+ colors: ThemeColors
+ onTripSelect: (trip: Trip) => void
+ selectedTripIndex?: number | null
+ onExport?: (format: ExportFormat) => void
+ onExportTrip?: (format: ExportFormat, trip: Trip) => void
+}
+
+export function TripList({ trips, colors, onTripSelect, selectedTripIndex, onExport, onExportTrip }: TripListProps) {
+ const [showExport, setShowExport] = useState(false)
+ const [exportingTripIndex, setExportingTripIndex] = useState<number | null>(null)
+ 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 renderTrip = useCallback(
+ ({ item }: { item: Trip }) => {
+ const duration = item.endTime - item.startTime
+ const tripColor = getTripColor(item.index)
+ const isSelected = selectedTripIndex === item.index
+ const showTripExport = exportingTripIndex === item.index
+ const stats = statsCache.get(item.index)
+
+ return (
+ <Card
+ variant="interactive"
+ onPress={() => onTripSelect(item)}
+ style={[
+ styles.tripCard,
+ { borderLeftColor: tripColor },
+ isSelected && [styles.tripCardSelected, { borderColor: tripColor }]
+ ]}
+ >
+ <View style={styles.tripHeader}>
+ <View style={styles.tripTitleRow}>
+ <View style={[styles.tripDot, { backgroundColor: tripColor }]} />
+ <Text style={[styles.tripTitle, { color: colors.text }]}>Trip {item.index}</Text>
+ </View>
+ <View style={styles.tripTitleRow}>
+ <Text style={[styles.tripTime, { color: colors.textSecondary }]}>
+ {formatTime(item.startTime)} - {formatTime(item.endTime)}
+ </Text>
+ {onExportTrip && (
+ <Pressable
+ onPress={() => setExportingTripIndex((prev) => (prev === item.index ? null : item.index))}
+ hitSlop={{ top: 6, right: 6, bottom: 6, left: 6 }}
+ style={({ pressed }) => pressed && { opacity: 0.6 }}
+ >
+ <Share size={14} color={showTripExport ? colors.primary : colors.textSecondary} />
+ </Pressable>
+ )}
+ </View>
+ </View>
+
+ {showTripExport && onExportTrip && (
+ <View style={styles.tripExportRow}>
+ {EXPORT_FORMAT_KEYS.map((fmt) => (
+ <Pressable
+ key={fmt}
+ onPress={() => {
+ onExportTrip(fmt, item)
+ setExportingTripIndex(null)
+ }}
+ style={({ pressed }) => [
+ styles.exportChip,
+ { backgroundColor: colors.primary + "12", borderColor: colors.primary + "30" },
+ pressed && { opacity: 0.7 }
+ ]}
+ >
+ <Text style={[styles.exportChipText, { color: colors.primary }]}>{EXPORT_FORMATS[fmt].label}</Text>
+ </Pressable>
+ ))}
+ </View>
+ )}
+
+ <View style={styles.tripStats}>
+ <View style={styles.stat}>
+ <Route size={13} color={colors.textSecondary} />
+ <Text style={[styles.statText, { color: colors.text }]}>{formatDistance(item.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>
+ )
+ },
+ [colors, onTripSelect, selectedTripIndex, onExportTrip, exportingTripIndex, statsCache]
+ )
+
+ 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>
+ )
+ }
+
+ return (
+ <View style={styles.container}>
+ <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: 0.6 }]}
+ >
+ <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)
+ setShowExport(false)
+ }}
+ style={({ pressed }) => [
+ styles.exportChip,
+ { backgroundColor: colors.primary + "12", borderColor: colors.primary + "30" },
+ pressed && { opacity: 0.7 }
+ ]}
+ >
+ <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}
+ />
+ </View>
+ )
+}
+
+const styles = StyleSheet.create({
+ container: {
+ flex: 1
+ },
+ headerRow: {
+ flexDirection: "row",
+ alignItems: "center",
+ justifyContent: "space-between",
+ paddingHorizontal: 16,
+ paddingTop: 12,
+ paddingBottom: 8
+ },
+ summary: {
+ fontSize: 12,
+ ...fonts.semiBold
+ },
+ exportAllBtn: {
+ flexDirection: "row",
+ alignItems: "center",
+ gap: 4,
+ padding: 6
+ },
+ exportAllLabel: {
+ fontSize: 11,
+ ...fonts.semiBold
+ },
+ exportRow: {
+ flexDirection: "row",
+ gap: 8,
+ paddingHorizontal: 16,
+ paddingBottom: 8
+ },
+ exportChip: {
+ paddingHorizontal: 10,
+ paddingVertical: 5,
+ borderRadius: 8,
+ borderWidth: 1
+ },
+ exportChipText: {
+ fontSize: 11,
+ ...fonts.bold
+ },
+ tripExportRow: {
+ flexDirection: "row",
+ flexWrap: "wrap",
+ gap: 6,
+ marginBottom: 8
+ },
+ list: {
+ paddingHorizontal: 12,
+ paddingBottom: 16
+ },
+ tripCard: {
+ marginBottom: 8,
+ borderLeftWidth: 3
+ },
+ 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
+ }
+})
diff --git a/apps/mobile/src/components/features/map/ColotaMapView.tsx b/apps/mobile/src/components/features/map/ColotaMapView.tsx
index 08aab368..f56cbebc 100644
--- a/apps/mobile/src/components/features/map/ColotaMapView.tsx
+++ b/apps/mobile/src/components/features/map/ColotaMapView.tsx
@@ -66,8 +66,8 @@ export const ColotaMapView = forwardRef<ColotaMapRef, Props>(function ColotaMapV
useEffect(() => {
if (isDark && !darkStyle) {
- getDarkStyle().then((style) => {
- if (style) setDarkStyle(style)
+ getDarkStyle().then((resolved) => {
+ if (resolved) setDarkStyle(resolved)
})
}
}, [isDark, darkStyle])
diff --git a/apps/mobile/src/components/features/map/__tests__/mapUtils.test.ts b/apps/mobile/src/components/features/map/__tests__/mapUtils.test.ts
index 3ca9c23b..2b07ef80 100644
--- a/apps/mobile/src/components/features/map/__tests__/mapUtils.test.ts
+++ b/apps/mobile/src/components/features/map/__tests__/mapUtils.test.ts
@@ -8,6 +8,7 @@ import {
computeTrackBounds,
darkifyStyle
} from "../mapUtils"
+import { haversine as haversineDistance } from "../../../../utils/geo"
// Only the color keys used by mapUtils functions
const colors = {
@@ -162,6 +163,27 @@ describe("buildTrackSegmentsGeoJSON", () => {
// @ts-ignore
expect(geom.coordinates[1]).toEqual([13.406, 52.53])
})
+
+ it("skips segments at skipIndices (trip boundaries)", () => {
+ const locs = [
+ { latitude: 52.52, longitude: 13.405, speed: 1 },
+ { latitude: 52.53, longitude: 13.406, speed: 1 },
+ { latitude: 52.54, longitude: 13.407, speed: 1 },
+ { latitude: 52.55, longitude: 13.408, speed: 1 }
+ ]
+ // Skip index 2 → no segment from point 1 to point 2
+ const result = buildTrackSegmentsGeoJSON(locs, colors, new Set([2]))
+ expect(result.features).toHaveLength(2) // segments 0→1 and 2→3, not 1→2
+ })
+
+ it("uses locationColors when provided", () => {
+ const locs = [
+ { latitude: 52.52, longitude: 13.405, speed: 0 },
+ { latitude: 52.53, longitude: 13.406, speed: 0 }
+ ]
+ const result = buildTrackSegmentsGeoJSON(locs, colors, undefined, ["#FF0000", "#00FF00"])
+ expect(result.features[0].properties?.color).toBe("#00FF00")
+ })
})
// ============================================================================
@@ -205,6 +227,16 @@ describe("buildTrackPointsGeoJSON", () => {
expect(props?.accuracy).toBe(0)
expect(props?.altitude).toBe(0)
})
+
+ it("uses locationColors when provided", () => {
+ const locs = [
+ { latitude: 52.52, longitude: 13.405, speed: 0 },
+ { latitude: 52.53, longitude: 13.406, speed: 10 }
+ ]
+ const result = buildTrackPointsGeoJSON(locs, colors, ["#AAAAAA", "#BBBBBB"])
+ expect(result.features[0].properties?.color).toBe("#AAAAAA")
+ expect(result.features[1].properties?.color).toBe("#BBBBBB")
+ })
})
// ============================================================================
@@ -412,17 +444,3 @@ describe("darkifyStyle", () => {
expect(result.version).toBe(8)
})
})
-
-// ============================================================================
-// Test helper
-// ============================================================================
-
-const haversineDistance = (lat1: number, lon1: number, lat2: number, lon2: number) => {
- const R = 6371000
- const dLat = ((lat2 - lat1) * Math.PI) / 180
- const dLon = ((lon2 - lon1) * Math.PI) / 180
- const a =
- Math.sin(dLat / 2) ** 2 +
- Math.cos((lat1 * Math.PI) / 180) * Math.cos((lat2 * Math.PI) / 180) * Math.sin(dLon / 2) ** 2
- return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
-}
diff --git a/apps/mobile/src/components/features/map/mapUtils.ts b/apps/mobile/src/components/features/map/mapUtils.ts
index 07cd9090..5ac23c81 100644
--- a/apps/mobile/src/components/features/map/mapUtils.ts
+++ b/apps/mobile/src/components/features/map/mapUtils.ts
@@ -83,14 +83,24 @@ export interface TrackLocation {
altitude?: number
}
-/** Build per-segment LineString features with a pre-computed `color` property */
-export function buildTrackSegmentsGeoJSON(locations: TrackLocation[], colors: ThemeColors): GeoJSON.FeatureCollection {
+/** Build per-segment LineString features with a pre-computed `color` property.
+ * Pass `skipIndices` to leave gaps between trips (indices where a new trip starts).
+ * Pass `locationColors` to override speed-based coloring with per-location colors. */
+export function buildTrackSegmentsGeoJSON(
+ locations: TrackLocation[],
+ colors: ThemeColors,
+ skipIndices?: Set<number>,
+ locationColors?: string[]
+): GeoJSON.FeatureCollection {
const features: GeoJSON.Feature[] = []
for (let i = 1; i < locations.length; i++) {
- const avgSpeed = ((locations[i - 1].speed ?? 0) + (locations[i].speed ?? 0)) / 2
+ if (skipIndices?.has(i)) continue
+ const color = locationColors
+ ? locationColors[i]
+ : getSpeedColor(((locations[i - 1].speed ?? 0) + (locations[i].speed ?? 0)) / 2, colors)
features.push({
type: "Feature",
- properties: { color: getSpeedColor(avgSpeed, colors) },
+ properties: { color },
geometry: {
type: "LineString",
coordinates: [
@@ -103,18 +113,23 @@ export function buildTrackSegmentsGeoJSON(locations: TrackLocation[], colors: Th
return { type: "FeatureCollection", features }
}
-/** Build Point features for each track location with metadata properties */
-export function buildTrackPointsGeoJSON(locations: TrackLocation[], colors: ThemeColors): GeoJSON.FeatureCollection {
+/** Build Point features for each track location with metadata properties.
+ * Pass `locationColors` to override speed-based dot coloring. */
+export function buildTrackPointsGeoJSON(
+ locations: TrackLocation[],
+ colors: ThemeColors,
+ locationColors?: string[]
+): GeoJSON.FeatureCollection {
return {
type: "FeatureCollection",
- features: locations.map((loc) => ({
+ features: locations.map((loc, i) => ({
type: "Feature" as const,
properties: {
speed: loc.speed ?? 0,
timestamp: loc.timestamp ?? 0,
accuracy: loc.accuracy ?? 0,
altitude: loc.altitude ?? 0,
- color: getSpeedColor(loc.speed ?? 0, colors)
+ color: locationColors ? locationColors[i] : getSpeedColor(loc.speed ?? 0, colors)
},
geometry: {
type: "Point" as const,
diff --git a/apps/mobile/src/components/index.ts b/apps/mobile/src/components/index.ts
index 5954bca9..ef7fac2b 100644
--- a/apps/mobile/src/components/index.ts
+++ b/apps/mobile/src/components/index.ts
@@ -45,7 +45,6 @@ export { MapCenterButton } from "./features/map/MapCenterButton"
// ============================================================================
// Feature Components - Inspector
// ============================================================================
-export { DatePicker } from "./features/inspector/DatePicker"
export { TrackMap } from "./features/inspector/TrackMap"
// ============================================================================
diff --git a/apps/mobile/src/screens/DataManagementScreen.tsx b/apps/mobile/src/screens/DataManagementScreen.tsx
index 51a800a1..c2bf0f3d 100644
--- a/apps/mobile/src/screens/DataManagementScreen.tsx
+++ b/apps/mobile/src/screens/DataManagementScreen.tsx
@@ -42,6 +42,7 @@ export function DataManagementScreen({}: ScreenProps) {
const [daysInput, setDaysInput] = useState("90")
const [isProcessing, setIsProcessing] = useState(false)
const [feedback, setFeedback] = useState<string | null>(null)
+ const [debugMode, setDebugMode] = useState(false)
const feedbackTimeout = useTimeout()
// Update stats
@@ -54,9 +55,12 @@ export function DataManagementScreen({}: ScreenProps) {
}
}, [])
- // Auto-refresh stats when screen is focused
+ // Load debug mode setting
useFocusEffect(
useCallback(() => {
+ NativeLocationService.getSetting("debug_mode_enabled", "false").then((value) => {
+ setDebugMode(value === "true")
+ })
updateStats()
const interval = setInterval(updateStats, STATS_REFRESH_FAST)
return () => clearInterval(interval)
@@ -102,7 +106,7 @@ export function DataManagementScreen({}: ScreenProps) {
receivedProgress.current = true
const processed = event.sent + event.failed
if (processed >= event.total) {
- // Sync finished
+ // Sync finished - show final result, then clean up
const msg =
event.failed > 0
? `Synced ${event.sent}/${event.total} (${event.failed} failed)`
@@ -202,6 +206,27 @@ export function DataManagementScreen({}: ScreenProps) {
)
}, [daysInput, handleDeleteAction, showFeedback])
+ const handleInsertDummyData = useCallback(async () => {
+ const confirmed = await showConfirm({
+ title: "Insert Dummy Data",
+ message: "Insert ~200 fake GPS locations across the past 7 days? This is for testing only.",
+ confirmText: "Insert"
+ })
+ if (!confirmed) return
+
+ setIsProcessing(true)
+ try {
+ const count = await NativeLocationService.insertDummyData()
+ await updateStats()
+ showFeedback(`Inserted ${count} dummy locations`)
+ } catch (err) {
+ logger.error("[DataManagementScreen] Insert dummy data failed:", err)
+ showFeedback("Failed to insert dummy data")
+ } finally {
+ setIsProcessing(false)
+ }
+ }, [updateStats, showFeedback])
+
const handleVacuum = useCallback(async () => {
setIsProcessing(true)
try {
@@ -344,6 +369,21 @@ export function DataManagementScreen({}: ScreenProps) {
</View>
</Card>
</View>
+ {/* Dev Tools */}
+ {debugMode && (
+ <View style={styles.section}>
+ <SectionTitle>DEV TOOLS</SectionTitle>
+ <Card>
+ <View style={styles.actionColumn}>
+ <Text style={[styles.actionLabel, { color: colors.text }]}>Insert Dummy Data</Text>
+ <Text style={[styles.actionHint, { color: colors.textLight }]}>
+ Generate ~200 fake GPS locations across the past 7 days for testing trips and calendar
+ </Text>
+ <Button onPress={handleInsertDummyData} disabled={isProcessing} title="Insert" variant="secondary" />
+ </View>
+ </Card>
+ </View>
+ )}
</ScrollView>
{/* Floating Feedback */}
diff --git a/apps/mobile/src/screens/LocationInspectorScreen.tsx b/apps/mobile/src/screens/LocationInspectorScreen.tsx
index 2eafd459..656ca55e 100644
--- a/apps/mobile/src/screens/LocationInspectorScreen.tsx
+++ b/apps/mobile/src/screens/LocationInspectorScreen.tsx
@@ -3,154 +3,110 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
-import React, { useState, useEffect, useRef, useCallback, useMemo, memo } from "react"
-import { View, Text, FlatList, StyleSheet, Pressable, Switch } from "react-native"
+import React, { useState, useEffect, useRef, useCallback, useMemo, useLayoutEffect } from "react"
+import { View, Text, StyleSheet, Pressable } from "react-native"
import { fonts } from "../styles/typography"
-import { ChevronLeft, ChevronRight } from "lucide-react-native"
-import { Container, Card } from "../components"
+import { BarChart2 } from "lucide-react-native"
+import { Container } from "../components"
import { useTheme } from "../hooks/useTheme"
-import { ThemeColors } from "../types/global"
+import { Trip, LocationCoords } 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 { CalendarPicker } from "../components/features/inspector/CalendarPicker"
import { TrackMap } from "../components/features/inspector/TrackMap"
-import { computeTotalDistance, formatDistance } from "../utils/geo"
-
-// Types
-interface LocationData {
- id?: number
- timestamp?: number
- created_at?: number
- latitude: number
- longitude: number
- altitude?: number
- speed?: number
- accuracy?: number
- bearing?: number
- battery: number
- battery_status: number
-}
-
-interface LocationItemProps {
- item: LocationData
- colors: ThemeColors
- onTap?: (item: LocationData) => void
-}
-
-interface MetricProps {
- label: string
- value: string
- colors: ThemeColors
-}
+import { TripList } from "../components/features/inspector/TripList"
+import { formatDistance } from "../utils/geo"
+import { segmentTrips } from "../utils/trips"
+import { TRIP_CONVERTERS, EXPORT_FORMATS, type ExportFormat } from "../utils/exportConverters"
+import { showAlert } from "../services/modalService"
interface TabProps {
label: string
active: boolean
onPress: () => void
- colors: ThemeColors
+ colors: any
}
-type TabType = "list" | "map"
+type TabType = "map" | "trips"
-/**
- * Memoized row component to prevent re-renders during scrolling
- */
-const LocationItem = memo(({ item, colors, onTap }: LocationItemProps) => {
- const getBatteryStatus = (status: number): string => {
- switch (status) {
- case 0:
- return "Unknown"
- case 1:
- return "Unplugged"
- case 2:
- return "Charging"
- case 3:
- return "Full"
- default:
- return "Unknown"
- }
- }
+export function LocationHistoryScreen({ navigation, route }: { navigation: any; route: any }) {
+ const { colors } = useTheme()
+ const [activeTab, setActiveTab] = useState<TabType>(route?.params?.initialTab ?? "map")
- const timestamp = item.timestamp || item.created_at || Date.now()
+ // Map tab state - accept initialDate from Summary screen navigation
+ const [mapDate, setMapDate] = useState(() => {
+ const initialDate = route?.params?.initialDate
+ return initialDate ? new Date(initialDate) : new Date()
+ })
+ const [trackLocations, setTrackLocations] = useState<LocationCoords[]>([])
+ const [selectedTrip, setSelectedTrip] = useState<Trip | null>(null)
+ const [fitVersion, setFitVersion] = useState(0)
- const card = (
- <Card style={styles.itemCard}>
- <View style={styles.row}>
- <Text style={[styles.id, { color: colors.primaryDark }]}>#{item.id}</Text>
- <Text style={[styles.time, { color: colors.textSecondary }]}>
- {new Date(timestamp * 1000).toLocaleTimeString()}
- </Text>
- </View>
+ // Calendar state
+ const [daysWithData, setDaysWithData] = useState<Set<string>>(new Set())
+ const daysCache = useRef<Map<string, Set<string>>>(new Map())
- <Text style={[styles.coords, { color: colors.text }]}>
- {item.latitude?.toFixed(6)}°, {item.longitude?.toFixed(6)}°
- </Text>
+ // Trip segmentation from already-fetched day data
+ const trips = useMemo(() => segmentTrips(trackLocations), [trackLocations])
- <View style={[styles.metricsGrid, { borderTopColor: colors.border }]}>
- <Metric label="Altitude" value={`${item.altitude?.toFixed(1) ?? 0}m`} colors={colors} />
- <Metric label="Speed" value={`${item.speed?.toFixed(1) ?? 0}m/s`} colors={colors} />
- <Metric label="Accuracy" value={`±${item.accuracy?.toFixed(1) ?? 0}m`} colors={colors} />
- <Metric label="Bearing" value={`${item.bearing?.toFixed(0) ?? 0}°`} colors={colors} />
- </View>
+ // 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])
- <View style={[styles.metricsGrid, styles.batteryGrid, { borderTopColor: colors.border }]}>
- <Metric label="Battery" value={`${item.battery}%`} colors={colors} />
- <Metric label="Battery Status" value={getBatteryStatus(item.battery_status)} colors={colors} />
- <View style={styles.spacer} />
- <View style={styles.spacer} />
- </View>
- </Card>
- )
+ const fetchTrackIdRef = useRef(0)
- if (onTap) {
- return (
- <Pressable style={({ pressed }) => pressed && { opacity: 0.7 }} onPress={() => onTap(item)}>
- {card}
+ // Summary navigation button
+ const headerRight = useCallback(
+ () => (
+ <Pressable
+ onPress={() => navigation.navigate("Location Summary")}
+ style={({ pressed }) => [styles.headerBtn, pressed && { opacity: 0.6 }]}
+ >
+ <BarChart2 size={20} color={colors.text} />
</Pressable>
- )
- }
-
- return card
-})
-
-LocationItem.displayName = "LocationItem"
-
-export function LocationHistoryScreen() {
- const { colors } = useTheme()
- 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)
-
- // Map tab state
- const [mapDate, setMapDate] = useState(new Date())
- const [trackLocations, setTrackLocations] = useState<LocationData[]>([])
- const [selectedPoint, setSelectedPoint] = useState<{ latitude: number; longitude: number } | null>(null)
-
- const dailyDistance = useMemo(() => {
- if (trackLocations.length < 2) return undefined
- const meters = computeTotalDistance(trackLocations)
- return formatDistance(meters)
- }, [trackLocations])
+ ),
+ [navigation, colors]
+ )
- const fetchListIdRef = useRef(0)
- const fetchTrackIdRef = useRef(0)
+ useLayoutEffect(() => {
+ navigation.setOptions({ headerRight })
+ }, [navigation, headerRight])
- /** Fetches data based on current pagination */
- const fetchData = useCallback(async () => {
- const id = ++fetchListIdRef.current
+ /** Fetch days-with-data for a month into cache; returns the Set. */
+ const prefetchMonth = useCallback(async (year: number, month: number): Promise<Set<string>> => {
+ const key = `${year}-${String(month + 1).padStart(2, "0")}`
+ if (daysCache.current.has(key)) return daysCache.current.get(key)!
try {
- const offset = page * limit
- const result = await NativeLocationService.getTableData("locations", limit, offset)
- if (id === fetchListIdRef.current) setData(result || [])
+ 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 = await NativeLocationService.getDaysWithData(startTs, endTs)
+ const daySet = new Set(days)
+ daysCache.current.set(key, daySet)
+ return daySet
} catch (err) {
- logger.error("[LocationHistory] Fetch error:", err)
- if (id === fetchListIdRef.current) setData([])
+ logger.error("[LocationHistory] Failed to fetch days with data:", err)
+ return new Set()
}
- }, [limit, page])
+ }, [])
+
+ /** 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)
+ },
+ [prefetchMonth]
+ )
+
+ // Fetch days for current month on mount and when date changes month
+ useEffect(() => {
+ fetchDaysWithData(mapDate.getFullYear(), mapDate.getMonth())
+ }, [mapDate, fetchDaysWithData])
/** Fetch track data for the selected day */
const fetchTrackData = useCallback(async () => {
@@ -165,193 +121,135 @@ export function LocationHistoryScreen() {
const endTimestamp = Math.floor(end.getTime() / 1000)
const result = await NativeLocationService.getLocationsByDateRange(startTimestamp, endTimestamp)
- if (id === fetchTrackIdRef.current) setTrackLocations(result || [])
+ if (id === fetchTrackIdRef.current) {
+ setTrackLocations(result || [])
+ setSelectedTrip(null)
+ setFitVersion((v) => v + 1)
+ }
} catch (err) {
logger.error("[LocationHistory] Track fetch error:", err)
- if (id === fetchTrackIdRef.current) setTrackLocations([])
+ if (id === fetchTrackIdRef.current) {
+ setTrackLocations([])
+ setSelectedTrip(null)
+ setFitVersion((v) => v + 1)
+ }
}
}, [mapDate])
- /** Fetch table data when dependencies change */
- useEffect(() => {
- if (activeTab === "list") {
- fetchData()
- }
- }, [fetchData, activeTab])
-
/** Fetch track data when map date changes */
useEffect(() => {
- if (activeTab === "map") {
- fetchTrackData()
- }
- }, [fetchTrackData, activeTab])
+ fetchTrackData()
+ }, [fetchTrackData])
+
+ /** Tap a trip card -> open detail screen */
+ const handleTripSelect = useCallback(
+ (trip: Trip) => {
+ navigation.navigate("Trip Detail", { trip })
+ },
+ [navigation]
+ )
- /** Auto-refresh logic */
- useEffect(() => {
- if (autoRefresh && activeTab === "list") {
- setPage(0)
- refreshInterval.current = setInterval(fetchData, STATS_REFRESH_FAST)
- } else {
- if (refreshInterval.current) {
- clearInterval(refreshInterval.current)
+ /** Export trips (all or single) */
+ const exportTrips = useCallback(
+ async (format: ExportFormat, tripsToExport: Trip[]) => {
+ if (tripsToExport.length === 0) return
+ try {
+ const content = TRIP_CONVERTERS[format](tripsToExport)
+ const dateStr = mapDate.toISOString().slice(0, 10)
+ const isSingle = tripsToExport.length === 1
+ const label = isSingle ? `Trip ${tripsToExport[0].index}` : "Trips"
+ const fileName = `colota_${isSingle ? `trip${tripsToExport[0].index}` : "trips"}_${dateStr}${
+ EXPORT_FORMATS[format].extension
+ }`
+ const filePath = await NativeLocationService.writeFile(fileName, content)
+ await NativeLocationService.shareFile(filePath, EXPORT_FORMATS[format].mimeType, `Colota ${label} - ${dateStr}`)
+ } catch (error) {
+ logger.error("[LocationHistory] Trip export failed:", error)
+ showAlert("Export Failed", "Unable to export. Please try again.", "error")
}
- }
- return () => {
- if (refreshInterval.current) {
- clearInterval(refreshInterval.current)
- }
- }
- }, [autoRefresh, fetchData, activeTab])
+ },
+ [mapDate]
+ )
- const handleTabChange = (tab: TabType) => {
- setActiveTab(tab)
- if (tab === "list") {
- setPage(0)
- setSelectedPoint(null)
- }
- }
+ const handleShowFullDay = useCallback(() => {
+ setSelectedTrip(null)
+ setFitVersion((v) => v + 1)
+ }, [])
- const handleLimitChange = (newLimit: number) => {
- setLimit(newLimit)
- setPage(0)
- }
+ const handleTripExport = useCallback((format: ExportFormat) => exportTrips(format, trips), [exportTrips, trips])
+ const handleSingleTripExport = useCallback(
+ (format: ExportFormat, trip: Trip) => exportTrips(format, [trip]),
+ [exportTrips]
+ )
- /** 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")
- }
- }
+ const mapLocations = selectedTrip ? (selectedTrip.locations as LocationCoords[]) : trackLocations
+
+ const calendarPicker = useMemo(
+ () => (
+ <CalendarPicker
+ date={mapDate}
+ onDateChange={setMapDate}
+ locationCount={trackLocations.length}
+ distance={dailyDistance}
+ colors={colors}
+ daysWithData={daysWithData}
+ onMonthChange={fetchDaysWithData}
+ onPrefetchMonth={prefetchMonth}
+ />
+ ),
+ [mapDate, trackLocations.length, dailyDistance, colors, daysWithData, fetchDaysWithData, prefetchMonth]
+ )
return (
<Container>
{/* 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} />
+ <Tab label="Map" active={activeTab === "map"} onPress={() => setActiveTab("map")} colors={colors} />
+ <Tab label="Trips" active={activeTab === "trips"} onPress={() => setActiveTab("trips")} colors={colors} />
</View>
{activeTab === "map" ? (
<View style={styles.mapContainer}>
- <DatePicker
- date={mapDate}
- onDateChange={setMapDate}
- locationCount={trackLocations.length}
- distance={dailyDistance}
+ {calendarPicker}
+ <TrackMap
+ locations={mapLocations}
+ selectedPoint={null}
colors={colors}
+ trips={selectedTrip ? undefined : trips}
+ fitVersion={fitVersion}
/>
- <TrackMap locations={trackLocations} selectedPoint={selectedPoint} colors={colors} />
+ {selectedTrip && (
+ <Pressable
+ onPress={handleShowFullDay}
+ style={({ pressed }) => [
+ styles.floatingPill,
+ { backgroundColor: colors.primary, borderRadius: colors.borderRadius },
+ pressed && { opacity: 0.7 }
+ ]}
+ >
+ <Text style={[styles.floatingPillText, { color: colors.textOnPrimary }]}>
+ Trip {selectedTrip.index} · Show full day
+ </Text>
+ </Pressable>
+ )}
</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>
-
- <Pressable
- onPress={fetchData}
- disabled={autoRefresh}
- style={({ pressed }) => [
- styles.refreshBtn,
- {
- backgroundColor: colors.card,
- borderColor: colors.border
- },
- autoRefresh && styles.refreshBtnDisabled,
- pressed && { opacity: 0.7 }
- ]}
- >
- <Text style={[styles.btnText, { color: colors.primaryDark }]}>Refresh</Text>
- </Pressable>
- </View>
- </View>
-
- {/* Limit Selection and Pagination */}
- <View style={styles.limitBar}>
- <View style={styles.limitOptions}>
- {[10, 50, 100].map((v) => (
- <Pressable
- key={v}
- onPress={() => handleLimitChange(v)}
- style={({ pressed }) => [
- styles.limitBtn,
- {
- backgroundColor: limit === v ? colors.primary : colors.card,
- borderColor: colors.border
- },
- pressed && { opacity: 0.7 }
- ]}
- >
- <Text style={[styles.limitBtnText, { color: limit === v ? colors.textOnPrimary : colors.text }]}>
- {v}
- </Text>
- </Pressable>
- ))}
- </View>
-
- {!autoRefresh && (
- <View style={styles.paginationRow}>
- <Pressable
- onPress={() => setPage((p) => Math.max(0, p - 1))}
- disabled={page === 0}
- style={({ pressed }) => [styles.pageBtn, pressed && { opacity: 0.7 }]}
- >
- <ChevronLeft size={20} color={page === 0 ? colors.textDisabled : colors.primary} />
- </Pressable>
- <Text style={[styles.pageIndicator, { color: colors.text }]}>{page + 1}</Text>
- <Pressable
- onPress={() => setPage((p) => p + 1)}
- disabled={data.length < limit}
- style={({ pressed }) => [styles.pageBtn, pressed && { opacity: 0.7 }]}
- >
- <ChevronRight size={20} color={data.length < limit ? colors.textDisabled : colors.primary} />
- </Pressable>
- </View>
- )}
- </View>
-
- {/* 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}
+ <View style={styles.mapContainer}>
+ {calendarPicker}
+ <TripList
+ trips={trips}
+ colors={colors}
+ onTripSelect={handleTripSelect}
+ selectedTripIndex={selectedTrip?.index ?? null}
+ onExport={handleTripExport}
+ onExportTrip={handleSingleTripExport}
/>
- </>
+ </View>
)}
</Container>
)
}
-// Subcomponents
-const Metric = ({ label, value, colors }: MetricProps) => (
- <View style={styles.metricItem}>
- <Text style={[styles.metricLabel, { color: colors.textSecondary }]}>{label}</Text>
- <Text style={[styles.metricValue, { color: colors.text }]}>{value}</Text>
- </View>
-)
-
const Tab = ({ label, active, onPress, colors }: TabProps) => {
const borderBottomColor = active ? colors.primary : "transparent"
const textColor = active ? colors.primary : colors.textSecondary
@@ -369,81 +267,28 @@ const Tab = ({ label, active, onPress, colors }: TabProps) => {
}
const styles = StyleSheet.create({
+ headerBtn: {
+ padding: 8
+ },
mapContainer: {
flex: 1
},
- headerRow: {
- flexDirection: "row",
- justifyContent: "space-between",
- alignItems: "center",
- paddingHorizontal: 12,
- paddingTop: 12
- },
- statusText: {
- fontSize: 11,
- ...fonts.semiBold
- },
- controls: {
- flexDirection: "row",
- alignItems: "center"
- },
- toggleContainer: {
- flexDirection: "row",
- alignItems: "center",
- marginRight: 12
- },
- controlLabel: {
- fontSize: 10,
- ...fonts.bold,
- marginRight: 6
- },
- refreshBtn: {
- paddingVertical: 6,
- paddingHorizontal: 12,
- borderRadius: 6,
- borderWidth: 1
- },
- refreshBtnDisabled: {
- opacity: 0.5
- },
- btnText: {
- fontSize: 12,
- ...fonts.bold
- },
- limitBar: {
- flexDirection: "row",
- justifyContent: "space-between",
- alignItems: "center",
- paddingHorizontal: 12,
- marginTop: 12,
- marginBottom: 12
- },
- limitOptions: {
- flexDirection: "row"
- },
- limitBtn: {
- paddingVertical: 6,
- paddingHorizontal: 12,
- borderRadius: 6,
- marginRight: 6,
- borderWidth: 1
- },
- limitBtnText: {
- fontSize: 12,
+ floatingPill: {
+ 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
},
- paginationRow: {
- flexDirection: "row",
- alignItems: "center"
- },
- pageBtn: {
- padding: 8
- },
- pageIndicator: {
- fontSize: 14,
- ...fonts.bold,
- marginHorizontal: 8
- },
tabBar: {
flexDirection: "row",
marginBottom: 12
@@ -462,66 +307,5 @@ const styles = StyleSheet.create({
},
tabTextInactive: {
...fonts.regular
- },
- listContent: {
- paddingHorizontal: 12,
- paddingBottom: 20
- },
- itemCard: {
- marginBottom: 10,
- padding: 12
- },
- row: {
- flexDirection: "row",
- justifyContent: "space-between",
- marginBottom: 6
- },
- id: {
- ...fonts.bold,
- fontSize: 12
- },
- time: {
- fontSize: 11,
- ...fonts.regular
- },
- coords: {
- fontFamily: "monospace",
- fontSize: 15,
- ...fonts.semiBold,
- marginBottom: 8
- },
- metricsGrid: {
- flexDirection: "row",
- justifyContent: "space-between",
- borderTopWidth: StyleSheet.hairlineWidth,
- paddingTop: 8,
- marginTop: 4
- },
- batteryGrid: {
- paddingTop: 6,
- marginTop: 2
- },
- metricItem: {
- flex: 1,
- alignItems: "flex-start"
- },
- metricLabel: {
- fontSize: 9,
- ...fonts.bold,
- textTransform: "uppercase"
- },
- metricValue: {
- fontSize: 12,
- marginTop: 2
- },
- spacer: {
- flex: 1
- },
- emptyText: {
- textAlign: "center",
- marginTop: 40,
- fontSize: 14,
- ...fonts.regular,
- fontStyle: "italic"
}
})
diff --git a/apps/mobile/src/screens/LocationSummaryScreen.tsx b/apps/mobile/src/screens/LocationSummaryScreen.tsx
new file mode 100644
index 00000000..8eb8fa99
--- /dev/null
+++ b/apps/mobile/src/screens/LocationSummaryScreen.tsx
@@ -0,0 +1,325 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * 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 { useTheme } from "../hooks/useTheme"
+import { DailyStat } from "../types/global"
+import NativeLocationService from "../services/NativeLocationService"
+import { formatDistance, formatDuration } from "../utils/geo"
+import { fonts } from "../styles/typography"
+import { logger } from "../utils/logger"
+
+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" }
+]
+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)
+ }
+
+ startDate.setHours(0, 0, 0, 0)
+ return { start: Math.floor(startDate.getTime() / 1000), end: endTs }
+}
+
+/** 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))
+
+ useEffect(() => {
+ animRef.setValue(0)
+ const listener = animRef.addListener(({ value: v }) => 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>
+}
+
+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 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])
+
+ 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" })
+ }, [])
+
+ // 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" })
+ },
+ [navigation]
+ )
+
+ const renderDailyStat = useCallback(
+ ({ item }: { item: DailyStat }) => (
+ <Pressable onPress={() => handleDayPress(item.day)} style={({ pressed }) => pressed && { opacity: 0.7 }}>
+ <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} />
+ </View>
+
+ {loading && !refreshing ? (
+ <View style={styles.loadingContainer}>
+ <ActivityIndicator size="large" color={colors.primary} />
+ </View>
+ ) : (
+ <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={
+ <Text style={[styles.emptyText, { color: colors.textSecondary }]}>No data for this period</Text>
+ }
+ />
+ )}
+ </Container>
+ )
+}
+
+const styles = StyleSheet.create({
+ header: {
+ paddingHorizontal: 16,
+ paddingTop: 12,
+ paddingBottom: 8,
+ marginBottom: 8
+ },
+ loadingContainer: {
+ 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
+ },
+ emptyText: {
+ textAlign: "center",
+ marginTop: 40,
+ fontSize: 14,
+ ...fonts.regular
+ }
+})
diff --git a/apps/mobile/src/screens/TripDetailScreen.tsx b/apps/mobile/src/screens/TripDetailScreen.tsx
new file mode 100644
index 00000000..bb92405d
--- /dev/null
+++ b/apps/mobile/src/screens/TripDetailScreen.tsx
@@ -0,0 +1,381 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+import React, { useMemo, useState, useCallback } from "react"
+import { View, Text, StyleSheet, ScrollView, Pressable } from "react-native"
+import { Route, Clock, Gauge, TrendingUp, TrendingDown, MapPin, Share } from "lucide-react-native"
+import { useTheme } from "../hooks/useTheme"
+import { fonts } from "../styles/typography"
+import { Card } from "../components/ui/Card"
+import { Container } from "../components/ui/Container"
+import { TrackMap } from "../components/features/inspector/TrackMap"
+import { getTripColor, computeTripStats } from "../utils/trips"
+import { formatDistance, formatDuration, formatSpeed, formatTime } from "../utils/geo"
+import { TRIP_CONVERTERS, EXPORT_FORMATS, EXPORT_FORMAT_KEYS, type ExportFormat } from "../utils/exportConverters"
+import { showAlert } from "../services/modalService"
+import { logger } from "../utils/logger"
+import NativeLocationService from "../services/NativeLocationService"
+import type { Trip } from "../types/global"
+
+function formatDate(unixSeconds: number): string {
+ return new Date(unixSeconds * 1000).toLocaleDateString(undefined, {
+ weekday: "short",
+ month: "short",
+ day: "numeric"
+ })
+}
+
+export function TripDetailScreen({ route }: { navigation: any; route: any }) {
+ const { colors } = useTheme()
+ const trip: Trip = route.params.trip
+ const tripColor = getTripColor(trip.index)
+
+ const stats = useMemo(() => computeTripStats(trip.locations), [trip])
+ const duration = trip.endTime - trip.startTime
+ const displayName = `Trip ${trip.index}`
+
+ const [showExport, setShowExport] = useState(false)
+
+ const handleExport = useCallback(
+ async (format: ExportFormat) => {
+ try {
+ const content = TRIP_CONVERTERS[format]([trip])
+ const dateStr = new Date(trip.startTime * 1000).toISOString().slice(0, 10)
+ const fileName = `colota_trip${trip.index}_${dateStr}${EXPORT_FORMATS[format].extension}`
+ const filePath = await NativeLocationService.writeFile(fileName, content)
+ await NativeLocationService.shareFile(
+ filePath,
+ EXPORT_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")
+ }
+ },
+ [trip, displayName]
+ )
+
+ const speedProfile = useMemo(() => {
+ return trip.locations.filter((loc) => loc.speed != null).map((loc) => loc.speed ?? 0)
+ }, [trip])
+
+ const elevationProfile = useMemo(() => {
+ return trip.locations.filter((loc) => loc.altitude != null).map((loc) => loc.altitude ?? 0)
+ }, [trip])
+
+ const maxSpeed = useMemo(() => speedProfile.reduce((max, v) => Math.max(max, v), 0), [speedProfile])
+ const minElevation = useMemo(
+ () => elevationProfile.reduce((min, v) => Math.min(min, v), Infinity),
+ [elevationProfile]
+ )
+ const maxElevation = useMemo(
+ () => elevationProfile.reduce((max, v) => Math.max(max, v), -Infinity),
+ [elevationProfile]
+ )
+ const elevationRange = maxElevation - minElevation
+
+ return (
+ <Container>
+ <ScrollView contentContainerStyle={styles.content}>
+ {/* Map */}
+ <View style={styles.mapContainer}>
+ <TrackMap locations={trip.locations} selectedPoint={null} colors={colors} fitVersion={1} />
+ </View>
+
+ {/* Header */}
+ <View style={styles.section}>
+ <View style={styles.headerTitleRow}>
+ <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>
+
+ {/* 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}
+ />
+ )}
+ </View>
+
+ {/* Speed profile */}
+ {speedProfile.length > 2 && (
+ <View style={styles.section}>
+ <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>
+ <View style={styles.chartBody}>
+ <View style={styles.yAxis}>
+ <Text style={[styles.yLabel, { color: colors.textSecondary }]}>{formatSpeed(maxSpeed)}</Text>
+ <Text style={[styles.yLabel, { color: colors.textSecondary }]}>0</Text>
+ </View>
+ <View style={styles.chartContainer}>
+ {speedProfile.map((speed, i) => {
+ const height = maxSpeed > 0 ? (speed / maxSpeed) * 100 : 0
+ return (
+ <View
+ key={i}
+ style={[styles.bar, { height: `${Math.max(height, 2)}%`, backgroundColor: tripColor, flex: 1 }]}
+ />
+ )
+ })}
+ </View>
+ </View>
+ <View style={styles.chartLabels}>
+ <Text style={[styles.chartLabel, { color: colors.textSecondary }]}>{formatTime(trip.startTime)}</Text>
+ <Text style={[styles.chartLabel, { color: colors.textSecondary }]}>{formatTime(trip.endTime)}</Text>
+ </View>
+ </Card>
+ </View>
+ )}
+
+ {/* Elevation profile */}
+ {elevationProfile.length > 2 && elevationRange > 0 && (
+ <View style={styles.section}>
+ <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>
+ <View style={styles.chartBody}>
+ <View style={styles.yAxis}>
+ <Text style={[styles.yLabel, { color: colors.textSecondary }]}>{Math.round(maxElevation)}m</Text>
+ <Text style={[styles.yLabel, { color: colors.textSecondary }]}>{Math.round(minElevation)}m</Text>
+ </View>
+ <View style={styles.chartContainer}>
+ {elevationProfile.map((alt, i) => {
+ const height = elevationRange > 0 ? ((alt - minElevation) / elevationRange) * 100 : 0
+ return (
+ <View
+ key={i}
+ style={[
+ styles.bar,
+ { height: `${Math.max(height, 2)}%`, backgroundColor: colors.primary + "80", flex: 1 }
+ ]}
+ />
+ )
+ })}
+ </View>
+ </View>
+ <View style={styles.chartLabels}>
+ <Text style={[styles.chartLabel, { color: colors.textSecondary }]}>{formatTime(trip.startTime)}</Text>
+ <Text style={[styles.chartLabel, { color: colors.textSecondary }]}>{formatTime(trip.endTime)}</Text>
+ </View>
+ </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: 0.7 }
+ ]}
+ >
+ <Text style={[styles.exportChipText, { color: colors.primary }]}>{EXPORT_FORMATS[fmt].label}</Text>
+ </Pressable>
+ ))}
+ </View>
+ )}
+ </View>
+ </ScrollView>
+ </Container>
+ )
+}
+
+function StatCard({
+ icon: Icon,
+ label,
+ value,
+ colors
+}: {
+ icon: React.ComponentType<any>
+ label: string
+ value: string
+ colors: any
+}) {
+ 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
+ },
+ section: {
+ paddingHorizontal: 16,
+ marginTop: 12
+ },
+ mapContainer: {
+ height: 250
+ },
+ headerTitleRow: {
+ flexDirection: "row",
+ alignItems: "center",
+ gap: 10,
+ marginBottom: 4
+ },
+ dot: {
+ width: 12,
+ height: 12,
+ borderRadius: 6
+ },
+ title: {
+ fontSize: 20,
+ ...fonts.bold
+ },
+ subtitle: {
+ fontSize: 13,
+ ...fonts.regular,
+ marginLeft: 22
+ },
+ 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"
+ },
+ chartCard: {
+ padding: 12
+ },
+ chartTitleRow: {
+ flexDirection: "row",
+ justifyContent: "space-between",
+ alignItems: "center",
+ marginBottom: 8
+ },
+ chartTitle: {
+ fontSize: 14,
+ ...fonts.semiBold
+ },
+ chartRange: {
+ fontSize: 11,
+ ...fonts.regular
+ },
+ chartBody: {
+ flexDirection: "row"
+ },
+ yAxis: {
+ justifyContent: "space-between",
+ alignItems: "flex-end",
+ marginRight: 6,
+ width: 52
+ },
+ yLabel: {
+ fontSize: 9,
+ ...fonts.regular
+ },
+ chartContainer: {
+ flexDirection: "row",
+ alignItems: "flex-end",
+ height: 80,
+ flex: 1,
+ gap: 1
+ },
+ bar: {
+ borderRadius: 2
+ },
+ chartLabels: {
+ flexDirection: "row",
+ justifyContent: "space-between",
+ marginTop: 4
+ },
+ chartLabel: {
+ fontSize: 10,
+ ...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
+ }
+})
diff --git a/apps/mobile/src/screens/index.ts b/apps/mobile/src/screens/index.ts
index c5943f26..f5b9e108 100644
--- a/apps/mobile/src/screens/index.ts
+++ b/apps/mobile/src/screens/index.ts
@@ -10,8 +10,10 @@ export { DataManagementScreen } from "./DataManagementScreen"
export { ExportDataScreen } from "./ExportDataScreen"
export { GeofenceScreen } from "./GeofenceScreen"
export { LocationHistoryScreen } from "./LocationInspectorScreen"
+export { LocationSummaryScreen } from "./LocationSummaryScreen"
export { SettingsScreen } from "./SettingsScreen"
export { TrackingProfilesScreen } from "./TrackingProfilesScreen"
export { ProfileEditorScreen } from "./ProfileEditorScreen"
export { AboutScreen } from "./AboutScreen"
export { SetupImportScreen } from "./SetupImportScreen"
+export { TripDetailScreen } from "./TripDetailScreen"
diff --git a/apps/mobile/src/services/NativeLocationService.ts b/apps/mobile/src/services/NativeLocationService.ts
index 396d1859..99aa4214 100644
--- a/apps/mobile/src/services/NativeLocationService.ts
+++ b/apps/mobile/src/services/NativeLocationService.ts
@@ -4,7 +4,15 @@
*/
import { NativeModules } from "react-native"
-import { AuthConfig, DatabaseStats, Geofence, Settings, TrackingProfile, SavedTrackingProfile } from "../types/global"
+import {
+ AuthConfig,
+ DailyStat,
+ DatabaseStats,
+ Geofence,
+ Settings,
+ TrackingProfile,
+ SavedTrackingProfile
+} from "../types/global"
import { logger } from "../utils/logger"
const { LocationServiceModule, BuildConfigModule } = NativeModules
@@ -186,6 +194,38 @@ class NativeLocationService {
return this.safeExecute(() => LocationServiceModule.getMostRecentLocation(), null, "getMostRecentLocation failed")
}
+ /**
+ * Returns date strings (YYYY-MM-DD) that have location data in the range.
+ * Used by the calendar view to show activity dots.
+ */
+ static async getDaysWithData(startTimestamp: number, endTimestamp: number): Promise<string[]> {
+ this.ensureModule()
+ return this.safeExecute(
+ () => LocationServiceModule.getDaysWithData(startTimestamp, endTimestamp),
+ [],
+ "getDaysWithData failed"
+ )
+ }
+
+ /**
+ * Returns per-day aggregated stats for a date range.
+ * Each entry: { day, count, startTime, endTime, distanceMeters, tripCount }
+ */
+ static async getDailyStats(startTimestamp: number, endTimestamp: number): Promise<DailyStat[]> {
+ this.ensureModule()
+ return this.safeExecute(
+ () => LocationServiceModule.getDailyStats(startTimestamp, endTimestamp),
+ [],
+ "getDailyStats failed"
+ )
+ }
+
+ /** DEV ONLY: Insert dummy location data for testing */
+ static async insertDummyData(): Promise<number> {
+ this.ensureModule()
+ return this.safeExecute(() => LocationServiceModule.insertDummyData(), 0, "insertDummyData failed")
+ }
+
// ============================================================================
// CLEANUP OPERATIONS
// ============================================================================
@@ -595,7 +635,7 @@ class NativeLocationService {
try {
customHeaders = JSON.parse(raw.customHeaders)
} catch {
- // Corrupted JSON — reset to empty
+ // Corrupted JSON - reset to empty
}
}
diff --git a/apps/mobile/src/types/global.ts b/apps/mobile/src/types/global.ts
index 925a26e2..982bca88 100644
--- a/apps/mobile/src/types/global.ts
+++ b/apps/mobile/src/types/global.ts
@@ -364,3 +364,25 @@ export interface DatabaseStats {
today: number
databaseSizeMB: number
}
+
+// ============================================================================
+// LOCATION HISTORY
+// ============================================================================
+
+export interface DailyStat {
+ day: string // "YYYY-MM-DD"
+ count: number
+ startTime: number // Unix seconds
+ endTime: number // Unix seconds
+ distanceMeters: number
+ tripCount: number
+}
+
+export interface Trip {
+ index: number
+ locations: LocationCoords[]
+ startTime: number // Unix seconds
+ endTime: number // Unix seconds
+ distance: number // meters
+ locationCount: number
+}
diff --git a/apps/mobile/src/utils/__tests__/exportConverters.test.ts b/apps/mobile/src/utils/__tests__/exportConverters.test.ts
index fd828b97..b6b2c780 100644
--- a/apps/mobile/src/utils/__tests__/exportConverters.test.ts
+++ b/apps/mobile/src/utils/__tests__/exportConverters.test.ts
@@ -5,11 +5,14 @@ import {
convertToGeoJSON,
convertToGPX,
convertToKML,
+ convertTripsToCSV,
+ convertTripsToGeoJSON,
+ convertTripsToGPX,
+ convertTripsToKML,
LARGE_FILE_THRESHOLD
} from "../exportConverters"
-import { LocationCoords } from "../../types/global"
-const sampleLocation: LocationCoords = {
+const sampleLocation = {
latitude: 48.137154,
longitude: 11.576124,
accuracy: 10,
@@ -21,11 +24,33 @@ const sampleLocation: LocationCoords = {
timestamp: 1700000000000
}
-const minimalLocation: LocationCoords = {
+const minimalLocation = {
latitude: 0,
longitude: 0
}
+const sampleTrips = [
+ {
+ index: 1,
+ locations: [
+ { latitude: 48.137154, longitude: 11.576124, accuracy: 10, altitude: 520, speed: 1.5, timestamp: 1700000000 },
+ { latitude: 48.138, longitude: 11.577, accuracy: 8, altitude: 525, speed: 2.0, timestamp: 1700000005 }
+ ],
+ startTime: 1700000000,
+ endTime: 1700000005,
+ distance: 120,
+ locationCount: 2
+ },
+ {
+ index: 2,
+ locations: [{ latitude: 48.14, longitude: 11.58, accuracy: 12, altitude: 530, speed: 3.0, timestamp: 1700001000 }],
+ startTime: 1700001000,
+ endTime: 1700001000,
+ distance: 0,
+ locationCount: 1
+ }
+]
+
describe("formatBytes", () => {
it("formats bytes", () => {
expect(formatBytes(0)).toBe("0 B")
@@ -203,3 +228,102 @@ describe("convertToKML", () => {
expect(kml).toContain("0,0,0") // lon,lat,alt
})
})
+
+describe("convertTripsToCSV", () => {
+ it("includes trip column in header", () => {
+ const csv = convertTripsToCSV([])
+ expect(csv).toContain("trip,id,timestamp")
+ })
+
+ it("includes trip index per row", () => {
+ const csv = convertTripsToCSV(sampleTrips)
+ const lines = csv.split("\n")
+ expect(lines[1]).toMatch(/^1,/) // trip 1
+ expect(lines[3]).toMatch(/^2,/) // trip 2
+ })
+
+ it("flattens all trip locations into rows", () => {
+ const csv = convertTripsToCSV(sampleTrips)
+ const lines = csv.split("\n")
+ expect(lines).toHaveLength(4) // header + 3 locations
+ })
+
+ it("uses Unix seconds for timestamps", () => {
+ const csv = convertTripsToCSV(sampleTrips)
+ expect(csv).toContain("1700000000")
+ })
+})
+
+describe("convertTripsToGeoJSON", () => {
+ it("returns valid FeatureCollection", () => {
+ const result = JSON.parse(convertTripsToGeoJSON(sampleTrips))
+ expect(result.type).toBe("FeatureCollection")
+ expect(result.features).toHaveLength(3)
+ })
+
+ it("includes trip index in properties", () => {
+ const result = JSON.parse(convertTripsToGeoJSON(sampleTrips))
+ expect(result.features[0].properties.trip).toBe(1)
+ expect(result.features[2].properties.trip).toBe(2)
+ })
+
+ it("uses [lon, lat] coordinate order", () => {
+ const result = JSON.parse(convertTripsToGeoJSON(sampleTrips))
+ const coords = result.features[0].geometry.coordinates
+ expect(coords[0]).toBe(11.576124)
+ expect(coords[1]).toBe(48.137154)
+ })
+})
+
+describe("convertTripsToGPX", () => {
+ it("creates separate trk elements per trip", () => {
+ const gpx = convertTripsToGPX(sampleTrips)
+ expect(gpx).toContain("<name>Trip 1</name>")
+ expect(gpx).toContain("<name>Trip 2</name>")
+ const trkCount = (gpx.match(/<trk>/g) || []).length
+ expect(trkCount).toBe(2)
+ })
+
+ it("includes trackpoints with lat/lon", () => {
+ const gpx = convertTripsToGPX(sampleTrips)
+ expect(gpx).toContain('lat="48.137154"')
+ expect(gpx).toContain('lon="11.576124"')
+ })
+
+ it("includes elevation and extensions", () => {
+ const gpx = convertTripsToGPX(sampleTrips)
+ expect(gpx).toContain("<ele>520</ele>")
+ expect(gpx).toContain("<accuracy>10</accuracy>")
+ })
+})
+
+describe("convertTripsToKML", () => {
+ it("creates separate folders per trip", () => {
+ const kml = convertTripsToKML(sampleTrips)
+ expect(kml).toContain("<name>Trip 1</name>")
+ expect(kml).toContain("<name>Trip 2</name>")
+ const folderCount = (kml.match(/<Folder>/g) || []).length
+ expect(folderCount).toBe(2)
+ })
+
+ it("uses per-trip colors", () => {
+ const kml = convertTripsToKML(sampleTrips)
+ // Trip 1: #3B82F6 -> ABGR ffF6823B
+ expect(kml).toContain("ffF6823B")
+ // Trip 2: #10B981 -> ABGR ff81B910
+ expect(kml).toContain("ff81B910")
+ })
+
+ it("includes LineString coordinates per trip", () => {
+ const kml = convertTripsToKML(sampleTrips)
+ expect(kml).toContain("11.576124,48.137154,520")
+ expect(kml).toContain("11.58,48.14,530")
+ })
+
+ it("includes Placemarks with trip labels", () => {
+ const kml = convertTripsToKML(sampleTrips)
+ expect(kml).toContain("Trip 1")
+ expect(kml).toContain("Trip 2")
+ expect(kml).toContain("<TimeStamp>")
+ })
+})
diff --git a/apps/mobile/src/utils/__tests__/trips.test.ts b/apps/mobile/src/utils/__tests__/trips.test.ts
new file mode 100644
index 00000000..df2910d2
--- /dev/null
+++ b/apps/mobile/src/utils/__tests__/trips.test.ts
@@ -0,0 +1,223 @@
+import { segmentTrips, getTripColor, TRIP_COLORS, computeTripStats } from "../trips"
+import { formatDuration, formatTime } from "../geo"
+
+describe("segmentTrips", () => {
+ it("returns empty array for empty input", () => {
+ expect(segmentTrips([])).toEqual([])
+ })
+
+ it("filters out single-point trips", () => {
+ const locations = [{ latitude: 52.52, longitude: 13.405, timestamp: 1000 }]
+ const trips = segmentTrips(locations)
+ expect(trips).toHaveLength(0)
+ })
+
+ it("returns one trip when no gaps exceed threshold", () => {
+ const locations = [
+ { latitude: 52.52, longitude: 13.405, timestamp: 1000 },
+ { latitude: 52.521, longitude: 13.405, timestamp: 1005 },
+ { latitude: 52.522, longitude: 13.405, timestamp: 1010 }
+ ]
+ const trips = segmentTrips(locations)
+ expect(trips).toHaveLength(1)
+ expect(trips[0].locationCount).toBe(3)
+ expect(trips[0].startTime).toBe(1000)
+ expect(trips[0].endTime).toBe(1010)
+ })
+
+ it("splits into two trips on a 15-minute gap", () => {
+ const locations = [
+ { latitude: 52.52, longitude: 13.405, timestamp: 1000 },
+ { latitude: 52.521, longitude: 13.405, timestamp: 1005 },
+ { latitude: 52.53, longitude: 13.405, timestamp: 1905 }, // 900s gap
+ { latitude: 52.531, longitude: 13.405, timestamp: 1910 }
+ ]
+ const trips = segmentTrips(locations)
+ expect(trips).toHaveLength(2)
+ expect(trips[0].index).toBe(1)
+ expect(trips[0].locationCount).toBe(2)
+ expect(trips[0].endTime).toBe(1005)
+ expect(trips[1].index).toBe(2)
+ expect(trips[1].locationCount).toBe(2)
+ expect(trips[1].startTime).toBe(1905)
+ })
+
+ it("splits into multiple trips with multiple gaps", () => {
+ const locations = [
+ { latitude: 52.52, longitude: 13.405, timestamp: 1000 },
+ { latitude: 52.521, longitude: 13.405, timestamp: 1005 },
+ { latitude: 52.53, longitude: 13.405, timestamp: 2000 }, // 995s gap
+ { latitude: 52.531, longitude: 13.405, timestamp: 2005 },
+ { latitude: 52.54, longitude: 13.405, timestamp: 3000 }, // 995s gap
+ { latitude: 52.541, longitude: 13.405, timestamp: 3005 }
+ ]
+ const trips = segmentTrips(locations)
+ expect(trips).toHaveLength(3)
+ expect(trips[0].index).toBe(1)
+ expect(trips[1].index).toBe(2)
+ expect(trips[2].index).toBe(3)
+ })
+
+ it("does not split when gap is just below threshold", () => {
+ const locations = [
+ { latitude: 52.52, longitude: 13.405, timestamp: 1000 },
+ { latitude: 52.521, longitude: 13.405, timestamp: 1899 } // 899s < 900s
+ ]
+ const trips = segmentTrips(locations)
+ expect(trips).toHaveLength(1)
+ })
+
+ it("splits when gap is exactly at threshold", () => {
+ const locations = [
+ { latitude: 52.52, longitude: 13.405, timestamp: 1000 },
+ { latitude: 52.521, longitude: 13.405, timestamp: 1005 },
+ { latitude: 52.53, longitude: 13.405, timestamp: 1905 }, // exactly 900s gap
+ { latitude: 52.531, longitude: 13.405, timestamp: 1910 }
+ ]
+ const trips = segmentTrips(locations)
+ expect(trips).toHaveLength(2)
+ })
+
+ it("computes distance for each trip", () => {
+ const locations = [
+ { latitude: 52.52, longitude: 13.405, timestamp: 1000 },
+ { latitude: 52.53, longitude: 13.405, timestamp: 1005 } // ~1.11 km
+ ]
+ const trips = segmentTrips(locations)
+ expect(trips[0].distance).toBeGreaterThan(1000)
+ expect(trips[0].distance).toBeLessThan(1200)
+ })
+
+ it("respects custom gap threshold", () => {
+ const locations = [
+ { latitude: 52.52, longitude: 13.405, timestamp: 1000 },
+ { latitude: 52.521, longitude: 13.405, timestamp: 1005 },
+ { latitude: 52.53, longitude: 13.405, timestamp: 1305 }, // 300s gap
+ { latitude: 52.531, longitude: 13.405, timestamp: 1310 }
+ ]
+ expect(segmentTrips(locations, 300)).toHaveLength(2)
+ expect(segmentTrips(locations, 301)).toHaveLength(1)
+ })
+})
+
+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")
+ })
+
+ 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")
+ })
+
+ it("clamps negative values to 0", () => {
+ expect(formatDuration(-1)).toBe("0m")
+ expect(formatDuration(-3600)).toBe("0m")
+ })
+})
+
+describe("getTripColor", () => {
+ it("returns first color for index 1", () => {
+ expect(getTripColor(1)).toBe(TRIP_COLORS[0])
+ })
+
+ it("cycles through colors", () => {
+ for (let i = 0; i < TRIP_COLORS.length; i++) {
+ expect(getTripColor(i + 1)).toBe(TRIP_COLORS[i])
+ }
+ })
+
+ it("wraps around when index exceeds palette length", () => {
+ expect(getTripColor(TRIP_COLORS.length + 1)).toBe(TRIP_COLORS[0])
+ expect(getTripColor(TRIP_COLORS.length + 2)).toBe(TRIP_COLORS[1])
+ })
+})
+
+describe("computeTripStats", () => {
+ it("returns zeros for empty locations", () => {
+ const stats = computeTripStats([])
+ expect(stats.avgSpeed).toBe(0)
+ expect(stats.elevationGain).toBe(0)
+ expect(stats.elevationLoss).toBe(0)
+ })
+
+ it("computes average speed from non-zero values", () => {
+ const locations = [
+ { latitude: 0, longitude: 0, speed: 2 },
+ { latitude: 0, longitude: 0, speed: 4 },
+ { latitude: 0, longitude: 0, speed: 6 }
+ ]
+ const stats = computeTripStats(locations)
+ expect(stats.avgSpeed).toBe(4) // (2+4+6)/3
+ })
+
+ it("excludes zero and null speeds from average", () => {
+ const locations = [
+ { latitude: 0, longitude: 0, speed: 0 },
+ { latitude: 0, longitude: 0, speed: undefined },
+ { latitude: 0, longitude: 0, speed: 10 }
+ ]
+ const stats = computeTripStats(locations)
+ expect(stats.avgSpeed).toBe(10) // only the 10 counts
+ })
+
+ it("computes elevation gain and loss", () => {
+ const locations = [
+ { latitude: 0, longitude: 0, altitude: 100 },
+ { latitude: 0, longitude: 0, altitude: 150 }, // +50
+ { latitude: 0, longitude: 0, altitude: 120 }, // -30
+ { latitude: 0, longitude: 0, altitude: 200 } // +80
+ ]
+ const stats = computeTripStats(locations)
+ expect(stats.elevationGain).toBe(130) // 50 + 80
+ expect(stats.elevationLoss).toBe(30)
+ })
+
+ it("ignores elevation diff when altitude is null", () => {
+ const locations = [
+ { latitude: 0, longitude: 0, altitude: 100 },
+ { latitude: 0, longitude: 0, altitude: undefined },
+ { latitude: 0, longitude: 0, altitude: 200 }
+ ]
+ const stats = computeTripStats(locations)
+ // null gap means no diff is computed for either adjacent pair
+ expect(stats.elevationGain).toBe(0)
+ expect(stats.elevationLoss).toBe(0)
+ })
+
+ it("handles flat terrain (no gain or loss)", () => {
+ const locations = [
+ { latitude: 0, longitude: 0, altitude: 500 },
+ { latitude: 0, longitude: 0, altitude: 500 },
+ { latitude: 0, longitude: 0, altitude: 500 }
+ ]
+ const stats = computeTripStats(locations)
+ expect(stats.elevationGain).toBe(0)
+ expect(stats.elevationLoss).toBe(0)
+ })
+})
+
+describe("formatTime", () => {
+ it("formats without seconds by default", () => {
+ // Use a fixed timestamp: 2024-01-15 14:30:00 UTC
+ const ts = Math.floor(new Date("2024-01-15T14:30:00Z").getTime() / 1000)
+ const result = formatTime(ts)
+ // Should not contain a third colon-separated group (seconds)
+ // The exact format depends on locale, but it should have hour and minute
+ expect(result).toBeTruthy()
+ expect(result.length).toBeGreaterThan(0)
+ })
+
+ it("includes seconds when showSeconds is true", () => {
+ const ts = Math.floor(new Date("2024-01-15T14:30:45Z").getTime() / 1000)
+ const withSeconds = formatTime(ts, true)
+ const withoutSeconds = formatTime(ts, false)
+ // The version with seconds should be longer
+ expect(withSeconds.length).toBeGreaterThan(withoutSeconds.length)
+ })
+})
diff --git a/apps/mobile/src/utils/exportConverters.ts b/apps/mobile/src/utils/exportConverters.ts
index d0286db9..3cdc1d49 100644
--- a/apps/mobile/src/utils/exportConverters.ts
+++ b/apps/mobile/src/utils/exportConverters.ts
@@ -5,10 +5,17 @@
import { type LucideIcon } from "lucide-react-native"
import { Table2, Globe, MapPin, Earth } from "lucide-react-native"
-import { LocationCoords } from "../types/global"
+import { LocationCoords, Trip } from "../types/global"
+import { getTripColor } from "./trips"
export const LARGE_FILE_THRESHOLD = 10 * 1024 * 1024 // 10 MB
+/** Convert hex RGB (#RRGGBB) to KML's ABGR format (ffBBGGRR) */
+function hexToKmlColor(hex: string): string {
+ const h = hex.replace("#", "")
+ return `ff${h.slice(4, 6)}${h.slice(2, 4)}${h.slice(0, 2)}`
+}
+
export const formatBytes = (bytes: number): string => {
if (bytes < 1024) return `${bytes} B`
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
@@ -24,7 +31,7 @@ export const getByteSize = (content: string): number => {
} else if (code <= 0x7ff) {
bytes += 2
} else if (code >= 0xd800 && code <= 0xdbff) {
- // High surrogate — pair encodes a 4-byte UTF-8 character
+ // High surrogate - pair encodes a 4-byte UTF-8 character
bytes += 4
i++ // skip the low surrogate
} else {
@@ -34,6 +41,10 @@ export const getByteSize = (content: string): number => {
return bytes
}
+// ============================================================================
+// FLAT CONVERTERS (timestamps in milliseconds)
+// ============================================================================
+
export const convertToCSV = (data: LocationCoords[]): string => {
const headers = "id,timestamp,iso_time,latitude,longitude,accuracy,altitude,speed,battery\n"
const rows = data
@@ -163,8 +174,160 @@ export const convertToKML = (data: LocationCoords[]): string => {
return kml
}
+// ============================================================================
+// TRIP-AWARE CONVERTERS (timestamps in Unix seconds)
+// ============================================================================
+
+export const convertTripsToCSV = (trips: Trip[]): string => {
+ const headers = "trip,id,timestamp,iso_time,latitude,longitude,accuracy,altitude,speed,battery\n"
+ const rows = trips
+ .flatMap((trip) =>
+ trip.locations.map((item, i) => {
+ const ts = item.timestamp ?? Math.floor(Date.now() / 1000)
+ const isoTime = new Date(ts * 1000).toISOString()
+ return [
+ trip.index,
+ i,
+ ts,
+ isoTime,
+ item.latitude,
+ item.longitude,
+ item.accuracy ?? 0,
+ item.altitude ?? 0,
+ item.speed ?? 0,
+ item.battery ?? 0
+ ].join(",")
+ })
+ )
+ .join("\n")
+ return headers + rows
+}
+
+export const convertTripsToGeoJSON = (trips: Trip[]): string => {
+ const features = trips.flatMap((trip) =>
+ trip.locations.map((item, i) => {
+ const ts = item.timestamp ?? Math.floor(Date.now() / 1000)
+ return {
+ type: "Feature",
+ geometry: {
+ type: "Point",
+ coordinates: [item.longitude || 0, item.latitude || 0]
+ },
+ properties: {
+ trip: trip.index,
+ id: i,
+ accuracy: item.accuracy,
+ altitude: item.altitude,
+ speed: item.speed,
+ battery: item.battery,
+ time: new Date(ts * 1000).toISOString()
+ }
+ }
+ })
+ )
+ return JSON.stringify({ type: "FeatureCollection", features }, null, 2)
+}
+
+export const convertTripsToGPX = (trips: Trip[]): string => {
+ let gpx = `<?xml version="1.0" encoding="UTF-8"?>
+<gpx version="1.1" creator="Colota" xmlns="http://www.topografix.com/GPX/1/1">
+ <metadata>
+ <name>Colota Trip Export</name>
+ <time>${new Date().toISOString()}</time>
+ </metadata>`
+
+ for (const trip of trips) {
+ gpx += `
+ <trk>
+ <name>Trip ${trip.index}</name>
+ <trkseg>`
+ for (const item of trip.locations) {
+ const ts = item.timestamp ?? Math.floor(Date.now() / 1000)
+ gpx += `
+ <trkpt lat="${item.latitude.toFixed(6)}" lon="${item.longitude.toFixed(6)}">
+ <ele>${item.altitude || 0}</ele>
+ <time>${new Date(ts * 1000).toISOString()}</time>
+ <extensions>
+ <accuracy>${item.accuracy || 0}</accuracy>
+ <speed>${item.speed || 0}</speed>
+ <battery>${item.battery || 0}</battery>
+ </extensions>
+ </trkpt>`
+ }
+ gpx += `
+ </trkseg>
+ </trk>`
+ }
+
+ gpx += `
+</gpx>`
+ return gpx
+}
+
+export const convertTripsToKML = (trips: Trip[]): string => {
+ let kml = `<?xml version="1.0" encoding="UTF-8"?>
+<kml xmlns="http://www.opengis.net/kml/2.2">
+ <Document>
+ <name>Colota Trip Export</name>
+ <description>Exported trips from Colota</description>`
+
+ for (const trip of trips) {
+ const styleId = `tripStyle${trip.index}`
+ kml += `
+ <Style id="${styleId}">
+ <LineStyle>
+ <color>${hexToKmlColor(getTripColor(trip.index))}</color>
+ <width>4</width>
+ </LineStyle>
+ </Style>
+ <Folder>
+ <name>Trip ${trip.index}</name>
+ <Placemark>
+ <name>Trip ${trip.index} Path</name>
+ <styleUrl>#${styleId}</styleUrl>
+ <LineString>
+ <tessellate>1</tessellate>
+ <coordinates>
+ ${trip.locations
+ .map((item) => `${item.longitude},${item.latitude},${item.altitude || 0}`)
+ .join("\n ")}
+ </coordinates>
+ </LineString>
+ </Placemark>`
+
+ for (const item of trip.locations) {
+ const ts = item.timestamp ?? Math.floor(Date.now() / 1000)
+ kml += `
+ <Placemark>
+ <TimeStamp><when>${new Date(ts * 1000).toISOString()}</when></TimeStamp>
+ <description>Trip ${trip.index} · Accuracy: ${item.accuracy ?? 0}m, Speed: ${item.speed ?? 0}m/s</description>
+ <Point>
+ <coordinates>${item.longitude},${item.latitude},${item.altitude || 0}</coordinates>
+ </Point>
+ </Placemark>`
+ }
+
+ kml += `
+ </Folder>`
+ }
+
+ kml += `
+ </Document>
+</kml>`
+ return kml
+}
+
+export const TRIP_CONVERTERS: Record<ExportFormat, (trips: Trip[]) => string> = {
+ csv: convertTripsToCSV,
+ geojson: convertTripsToGeoJSON,
+ gpx: convertTripsToGPX,
+ kml: convertTripsToKML
+}
+
export type ExportFormat = "csv" | "geojson" | "gpx" | "kml"
+export const EXPORT_FORMAT_KEYS: ExportFormat[] = ["csv", "geojson", "gpx", "kml"]
+
export interface ExportFormatConfig {
label: string
subtitle: string
diff --git a/apps/mobile/src/utils/geo.ts b/apps/mobile/src/utils/geo.ts
index 9bc275c1..50712a4a 100644
--- a/apps/mobile/src/utils/geo.ts
+++ b/apps/mobile/src/utils/geo.ts
@@ -5,8 +5,8 @@
const EARTH_RADIUS_METERS = 6371000.0
-/** Haversine formula — mirrors GeofenceHelper.kt */
-function haversine(lat1: number, lon1: number, lat2: number, lon2: number): number {
+/** Haversine formula - mirrors GeofenceHelper.kt */
+export function haversine(lat1: number, lon1: number, lat2: number, lon2: number): number {
const dLat = ((lat2 - lat1) * Math.PI) / 180
const dLon = ((lon2 - lon1) * Math.PI) / 180
const a =
@@ -55,6 +55,25 @@ export function getSpeedUnit(): { factor: number; unit: string } {
return usesMiles() ? { factor: 2.23694, unit: "mph" } : { factor: 3.6, unit: "km/h" }
}
+/** Format seconds duration as "Xh Ym" or "Ym" */
+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`
+}
+
+/** Format a Unix-seconds timestamp as a localized time string. */
+export function formatTime(unixSeconds: number, showSeconds = false): string {
+ const d = new Date(unixSeconds * 1000)
+ return d.toLocaleTimeString(undefined, {
+ hour: "2-digit",
+ minute: "2-digit",
+ ...(showSeconds && { second: "2-digit" })
+ })
+}
+
/** Format meters into a human-readable string using the device locale's unit. */
export function formatDistance(meters: number): string {
if (usesMiles()) {
diff --git a/apps/mobile/src/utils/trips.ts b/apps/mobile/src/utils/trips.ts
new file mode 100644
index 00000000..2d736432
--- /dev/null
+++ b/apps/mobile/src/utils/trips.ts
@@ -0,0 +1,96 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+import { computeTotalDistance } from "./geo"
+import type { Trip, LocationCoords } from "../types/global"
+
+export const TRIP_COLORS = ["#3B82F6", "#10B981", "#F59E0B", "#EF4444", "#8B5CF6", "#EC4899"]
+
+export function getTripColor(index: number): string {
+ return TRIP_COLORS[(index - 1) % TRIP_COLORS.length]
+}
+
+const DEFAULT_GAP_SECONDS = 900 // 15 minutes
+const MIN_TRIP_POINTS = 2
+
+/**
+ * Segments a chronologically-sorted array of locations into trips.
+ * A new trip starts when the time gap between consecutive points
+ * exceeds gapThresholdSeconds.
+ */
+export function segmentTrips(locations: LocationCoords[], gapThresholdSeconds: number = DEFAULT_GAP_SECONDS): Trip[] {
+ if (locations.length === 0) return []
+
+ const trips: Trip[] = []
+ let currentTripLocations: LocationCoords[] = [locations[0]]
+
+ for (let i = 1; i < locations.length; i++) {
+ const prevTs = locations[i - 1].timestamp ?? 0
+ const currTs = locations[i].timestamp ?? 0
+
+ if (currTs - prevTs >= gapThresholdSeconds) {
+ trips.push(buildTrip(currentTripLocations))
+ currentTripLocations = [locations[i]]
+ } else {
+ currentTripLocations.push(locations[i])
+ }
+ }
+
+ if (currentTripLocations.length > 0) {
+ trips.push(buildTrip(currentTripLocations))
+ }
+
+ // Filter out single-point "trips" (stray GPS fixes during long stops)
+ const filtered = trips.filter((t) => t.locationCount >= MIN_TRIP_POINTS)
+ // Re-index after filtering
+ return filtered.map((t, i) => ({ ...t, index: i + 1 }))
+}
+
+function buildTrip(locations: LocationCoords[]): Trip {
+ return {
+ index: 0,
+ locations,
+ startTime: locations[0].timestamp ?? 0,
+ endTime: locations[locations.length - 1].timestamp ?? 0,
+ distance: computeTotalDistance(locations),
+ locationCount: locations.length
+ }
+}
+
+export interface TripStats {
+ avgSpeed: number // m/s
+ elevationGain: number // meters
+ elevationLoss: number // meters
+}
+
+export function computeTripStats(locations: LocationCoords[]): TripStats {
+ let speedSum = 0
+ let speedCount = 0
+ let elevationGain = 0
+ let elevationLoss = 0
+
+ for (let i = 0; i < locations.length; i++) {
+ const loc = locations[i]
+ if (loc.speed != null && loc.speed > 0) {
+ speedSum += loc.speed
+ speedCount++
+ }
+ if (i > 0) {
+ const prevAlt = locations[i - 1].altitude
+ const currAlt = loc.altitude
+ if (prevAlt != null && currAlt != null) {
+ const diff = currAlt - prevAlt
+ if (diff > 0) elevationGain += diff
+ else elevationLoss += Math.abs(diff)
+ }
+ }
+ }
+
+ return {
+ avgSpeed: speedCount > 0 ? speedSum / speedCount : 0,
+ elevationGain,
+ elevationLoss
+ }
+}
diff --git a/screenshots/mobile/Samsung Galaxy S21 Ultra Screenshot 1.png b/screenshots/mobile/Samsung Galaxy S21 Ultra Screenshot 1.png
deleted file mode 100644
index cad844a2..00000000
Binary files a/screenshots/mobile/Samsung Galaxy S21 Ultra Screenshot 1.png and /dev/null differ
diff --git a/screenshots/mobile/Samsung Galaxy S21 Ultra Screenshot 2.png b/screenshots/mobile/Samsung Galaxy S21 Ultra Screenshot 2.png
deleted file mode 100644
index 628552b9..00000000
Binary files a/screenshots/mobile/Samsung Galaxy S21 Ultra Screenshot 2.png and /dev/null differ
diff --git a/screenshots/mobile/Samsung Galaxy S21 Ultra Screenshot 3.png b/screenshots/mobile/Samsung Galaxy S21 Ultra Screenshot 3.png
deleted file mode 100644
index 4e19c7ea..00000000
Binary files a/screenshots/mobile/Samsung Galaxy S21 Ultra Screenshot 3.png and /dev/null differ
diff --git a/screenshots/mobile/Samsung Galaxy S21 Ultra Screenshot 4.png b/screenshots/mobile/Samsung Galaxy S21 Ultra Screenshot 4.png
deleted file mode 100644
index 48520380..00000000
Binary files a/screenshots/mobile/Samsung Galaxy S21 Ultra Screenshot 4.png and /dev/null differ
diff --git a/screenshots/mobile/Samsung Galaxy S21 Ultra Screenshot 5.png b/screenshots/mobile/Samsung Galaxy S21 Ultra Screenshot 5.png
deleted file mode 100644
index b68cc9d0..00000000
Binary files a/screenshots/mobile/Samsung Galaxy S21 Ultra Screenshot 5.png and /dev/null differ
diff --git a/screenshots/mobile/Samsung Galaxy S21 Ultra Screenshot 6.png b/screenshots/mobile/Samsung Galaxy S21 Ultra Screenshot 6.png
deleted file mode 100644
index c1983b54..00000000
Binary files a/screenshots/mobile/Samsung Galaxy S21 Ultra Screenshot 6.png and /dev/null differ
diff --git a/screenshots/mobile/Samsung Galaxy S21 Ultra Screenshot 7.png b/screenshots/mobile/Samsung Galaxy S21 Ultra Screenshot 7.png
deleted file mode 100644
index 3879eb43..00000000
Binary files a/screenshots/mobile/Samsung Galaxy S21 Ultra Screenshot 7.png and /dev/null differ
diff --git a/screenshots/mobile/Samsung Galaxy S21 Ultra Screenshot 8.png b/screenshots/mobile/Samsung Galaxy S21 Ultra Screenshot 8.png
deleted file mode 100644
index 93cb7bd7..00000000
Binary files a/screenshots/mobile/Samsung Galaxy S21 Ultra Screenshot 8.png and /dev/null differ
diff --git a/screenshots/mobile/original/Authentication.png b/screenshots/mobile/original/Authentication.png
index 2920d010..897fcfef 100644
Binary files a/screenshots/mobile/original/Authentication.png and b/screenshots/mobile/original/Authentication.png differ
diff --git a/screenshots/mobile/original/Dashboard.png b/screenshots/mobile/original/Dashboard.png
index a57e2a67..8c92fef1 100644
Binary files a/screenshots/mobile/original/Dashboard.png and b/screenshots/mobile/original/Dashboard.png differ
diff --git a/screenshots/mobile/original/LocationHistory.png b/screenshots/mobile/original/LocationHistory.png
new file mode 100644
index 00000000..6df19af1
Binary files /dev/null and b/screenshots/mobile/original/LocationHistory.png differ
diff --git a/screenshots/mobile/original/Settings.png b/screenshots/mobile/original/Settings.png
index 2a88d32f..0242a610 100644
Binary files a/screenshots/mobile/original/Settings.png and b/screenshots/mobile/original/Settings.png differ
diff --git a/screenshots/mobile/original/TripDetails.png b/screenshots/mobile/original/TripDetails.png
new file mode 100644
index 00000000..ddc7241d
Binary files /dev/null and b/screenshots/mobile/original/TripDetails.png differ
diff --git a/screenshots/mobile/original/Trips.png b/screenshots/mobile/original/Trips.png
new file mode 100644
index 00000000..20f3bf37
Binary files /dev/null and b/screenshots/mobile/original/Trips.png differ
diff --git a/screenshots/tablet/10/Samsung Galaxy Tab S7 Screenshot 1.png b/screenshots/tablet/10/Samsung Galaxy Tab S7 Screenshot 1.png
deleted file mode 100644
index 64802260..00000000
Binary files a/screenshots/tablet/10/Samsung Galaxy Tab S7 Screenshot 1.png and /dev/null differ
diff --git a/screenshots/tablet/10/Samsung Galaxy Tab S7 Screenshot 2.png b/screenshots/tablet/10/Samsung Galaxy Tab S7 Screenshot 2.png
deleted file mode 100644
index 6681ca58..00000000
Binary files a/screenshots/tablet/10/Samsung Galaxy Tab S7 Screenshot 2.png and /dev/null differ
diff --git a/screenshots/tablet/10/Samsung Galaxy Tab S7 Screenshot 3.png b/screenshots/tablet/10/Samsung Galaxy Tab S7 Screenshot 3.png
deleted file mode 100644
index eed8d74c..00000000
Binary files a/screenshots/tablet/10/Samsung Galaxy Tab S7 Screenshot 3.png and /dev/null differ
diff --git a/screenshots/tablet/10/Samsung Galaxy Tab S7 Screenshot 4.png b/screenshots/tablet/10/Samsung Galaxy Tab S7 Screenshot 4.png
deleted file mode 100644
index 8f82e4a5..00000000
Binary files a/screenshots/tablet/10/Samsung Galaxy Tab S7 Screenshot 4.png and /dev/null differ
diff --git a/screenshots/tablet/10/Samsung Galaxy Tab S7 Screenshot 5.png b/screenshots/tablet/10/Samsung Galaxy Tab S7 Screenshot 5.png
deleted file mode 100644
index 8cea5ce7..00000000
Binary files a/screenshots/tablet/10/Samsung Galaxy Tab S7 Screenshot 5.png and /dev/null differ
diff --git a/screenshots/tablet/10/Samsung Galaxy Tab S7 Screenshot 6.png b/screenshots/tablet/10/Samsung Galaxy Tab S7 Screenshot 6.png
deleted file mode 100644
index 3c0a05ff..00000000
Binary files a/screenshots/tablet/10/Samsung Galaxy Tab S7 Screenshot 6.png and /dev/null differ
diff --git a/screenshots/tablet/10/Samsung Galaxy Tab S7 Screenshot 7.png b/screenshots/tablet/10/Samsung Galaxy Tab S7 Screenshot 7.png
deleted file mode 100644
index 0d3351e1..00000000
Binary files a/screenshots/tablet/10/Samsung Galaxy Tab S7 Screenshot 7.png and /dev/null differ
diff --git a/screenshots/tablet/10/Samsung Galaxy Tab S7 Screenshot 8.png b/screenshots/tablet/10/Samsung Galaxy Tab S7 Screenshot 8.png
deleted file mode 100644
index 38295344..00000000
Binary files a/screenshots/tablet/10/Samsung Galaxy Tab S7 Screenshot 8.png and /dev/null differ
diff --git a/screenshots/tablet/7/Apple iPad Mini Screenshot 1.png b/screenshots/tablet/7/Apple iPad Mini Screenshot 1.png
deleted file mode 100644
index b2946c98..00000000
Binary files a/screenshots/tablet/7/Apple iPad Mini Screenshot 1.png and /dev/null differ
diff --git a/screenshots/tablet/7/Apple iPad Mini Screenshot 2.png b/screenshots/tablet/7/Apple iPad Mini Screenshot 2.png
deleted file mode 100644
index b3d11df0..00000000
Binary files a/screenshots/tablet/7/Apple iPad Mini Screenshot 2.png and /dev/null differ
diff --git a/screenshots/tablet/7/Apple iPad Mini Screenshot 3.png b/screenshots/tablet/7/Apple iPad Mini Screenshot 3.png
deleted file mode 100644
index c46ef34c..00000000
Binary files a/screenshots/tablet/7/Apple iPad Mini Screenshot 3.png and /dev/null differ
diff --git a/screenshots/tablet/7/Apple iPad Mini Screenshot 4.png b/screenshots/tablet/7/Apple iPad Mini Screenshot 4.png
deleted file mode 100644
index e9792630..00000000
Binary files a/screenshots/tablet/7/Apple iPad Mini Screenshot 4.png and /dev/null differ
diff --git a/screenshots/tablet/7/Apple iPad Mini Screenshot 5.png b/screenshots/tablet/7/Apple iPad Mini Screenshot 5.png
deleted file mode 100644
index 463803f5..00000000
Binary files a/screenshots/tablet/7/Apple iPad Mini Screenshot 5.png and /dev/null differ
diff --git a/screenshots/tablet/7/Apple iPad Mini Screenshot 6.png b/screenshots/tablet/7/Apple iPad Mini Screenshot 6.png
deleted file mode 100644
index 60bda0ab..00000000
Binary files a/screenshots/tablet/7/Apple iPad Mini Screenshot 6.png and /dev/null differ
diff --git a/screenshots/tablet/7/Apple iPad Mini Screenshot 7.png b/screenshots/tablet/7/Apple iPad Mini Screenshot 7.png
deleted file mode 100644
index d9b4a865..00000000
Binary files a/screenshots/tablet/7/Apple iPad Mini Screenshot 7.png and /dev/null differ
diff --git a/screenshots/tablet/7/Apple iPad Mini Screenshot 8.png b/screenshots/tablet/7/Apple iPad Mini Screenshot 8.png
deleted file mode 100644
index baa53e13..00000000
Binary files a/screenshots/tablet/7/Apple iPad Mini Screenshot 8.png and /dev/null differ