Skip to content

Colota - Android GPS Location tracker

refactor: improve code quality for location history feature

Max Dietrich0a4525797c8c
diff --git a/apps/docs/docs/development/local-setup.md b/apps/docs/docs/development/local-setup.md
index c7ef9fa7..6028c502 100644
--- a/apps/docs/docs/development/local-setup.md
+++ b/apps/docs/docs/development/local-setup.md
@@ -119,7 +119,7 @@ colota/
│ │ │ ├── gms/java/com/colota/location/ # GMS implementation
│ │ │ └── foss/java/com/colota/location/ # Native implementation
│ │ ├── src/
-│ │ │ ├── screens/ # 12 app screens
+│ │ │ ├── screens/ # 14 app screens
│ │ │ ├── components/ # UI and feature components
│ │ │ ├── hooks/ # Custom React hooks
│ │ │ ├── services/ # Native bridge services
diff --git a/apps/mobile/src/components/features/inspector/LocationTable.tsx b/apps/mobile/src/components/features/inspector/LocationTable.tsx
new file mode 100644
index 00000000..a005eef5
--- /dev/null
+++ b/apps/mobile/src/components/features/inspector/LocationTable.tsx
@@ -0,0 +1,207 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+import React, { useCallback, useMemo } from "react"
+import { View, Text, FlatList, ScrollView, StyleSheet } from "react-native"
+import { fonts } from "../../../styles/typography"
+import { LocationCoords, ThemeColors } from "../../../types/global"
+import { formatTime, getSpeedUnit } from "../../../utils/geo"
+
+interface Props {
+ locations: LocationCoords[]
+ colors: ThemeColors
+}
+
+interface TableRow extends LocationCoords {
+ delta: number | null
+}
+
+const ROW_HEIGHT = 36
+const TABLE_WIDTH = 730
+
+function val(v?: number | null, decimals = 0): string {
+ if (v == null) return "-"
+ return decimals > 0 ? v.toFixed(decimals) : String(Math.round(v))
+}
+
+const BATTERY_STATUS: Record<number, string> = {
+ 1: "Unknown",
+ 2: "Charging",
+ 3: "Discharging",
+ 4: "Not charging",
+ 5: "Full"
+}
+
+const LocationRow = React.memo(
+ ({
+ item,
+ speedUnit,
+ colors
+ }: {
+ item: TableRow
+ speedUnit: { factor: number; unit: string }
+ colors: ThemeColors
+ }) => (
+ <View style={[styles.row, { borderBottomColor: colors.border }]}>
+ <Text style={[styles.cell, styles.cellTime, { color: colors.text }]} numberOfLines={1}>
+ {item.timestamp ? formatTime(item.timestamp, true) : "-"}
+ </Text>
+ <Text style={[styles.cell, styles.cellNum, { color: colors.textSecondary }]} numberOfLines={1}>
+ {item.delta != null ? `+${item.delta}s` : ""}
+ </Text>
+ <Text style={[styles.cell, styles.cellCoord, { color: colors.text }]} numberOfLines={1}>
+ {val(item.latitude, 5)}
+ </Text>
+ <Text style={[styles.cell, styles.cellCoord, { color: colors.text }]} numberOfLines={1}>
+ {val(item.longitude, 5)}
+ </Text>
+ <Text style={[styles.cell, styles.cellNum, { color: colors.text }]} numberOfLines={1}>
+ {val(item.accuracy)}
+ </Text>
+ <Text style={[styles.cell, styles.cellNum, { color: colors.text }]} numberOfLines={1}>
+ {item.speed != null ? (item.speed * speedUnit.factor).toFixed(1) : "-"}
+ </Text>
+ <Text style={[styles.cell, styles.cellNum, { color: colors.text }]} numberOfLines={1}>
+ {val(item.altitude)}
+ </Text>
+ <Text style={[styles.cell, styles.cellNum, { color: colors.text }]} numberOfLines={1}>
+ {item.bearing != null ? val(item.bearing, 1) : "-"}
+ </Text>
+ <Text style={[styles.cell, styles.cellNum, { color: colors.text }]} numberOfLines={1}>
+ {item.battery != null ? `${item.battery}%` : "-"}
+ </Text>
+ <Text style={[styles.cell, styles.cellStatus, { color: colors.text }]} numberOfLines={1}>
+ {item.battery_status != null ? BATTERY_STATUS[item.battery_status] ?? String(item.battery_status) : "-"}
+ </Text>
+ </View>
+ )
+)
+
+const keyExtractor = (_: TableRow, index: number) => String(index)
+const getItemLayout = (_: any, index: number) => ({
+ length: ROW_HEIGHT,
+ offset: ROW_HEIGHT * index,
+ index
+})
+
+export function LocationTable({ locations, colors }: Props) {
+ const speedUnit = useMemo(() => getSpeedUnit(), [])
+
+ const data = useMemo<TableRow[]>(
+ () =>
+ locations.map((loc, i) => ({
+ ...loc,
+ delta:
+ i > 0 && loc.timestamp && locations[i - 1].timestamp
+ ? Math.round(loc.timestamp - locations[i - 1].timestamp!)
+ : null
+ })),
+ [locations]
+ )
+
+ const renderItem = useCallback(
+ ({ item }: { item: TableRow }) => <LocationRow item={item} speedUnit={speedUnit} colors={colors} />,
+ [colors, speedUnit]
+ )
+
+ if (locations.length === 0) {
+ return (
+ <View style={styles.empty}>
+ <Text style={[styles.emptyText, { color: colors.textSecondary }]}>No data for this day</Text>
+ </View>
+ )
+ }
+
+ return (
+ <ScrollView horizontal style={styles.container} contentContainerStyle={styles.scrollContent}>
+ <View style={styles.tableWrapper}>
+ {/* Header */}
+ <View
+ style={[styles.row, styles.header, { borderBottomColor: colors.border, backgroundColor: colors.surface }]}
+ >
+ <Text style={[styles.cell, styles.cellTime, styles.headerText, { color: colors.textSecondary }]}>Time</Text>
+ <Text style={[styles.cell, styles.cellNum, styles.headerText, { color: colors.textSecondary }]}>Δs</Text>
+ <Text style={[styles.cell, styles.cellCoord, styles.headerText, { color: colors.textSecondary }]}>Lat</Text>
+ <Text style={[styles.cell, styles.cellCoord, styles.headerText, { color: colors.textSecondary }]}>Lon</Text>
+ <Text style={[styles.cell, styles.cellNum, styles.headerText, { color: colors.textSecondary }]}>Acc</Text>
+ <Text style={[styles.cell, styles.cellNum, styles.headerText, { color: colors.textSecondary }]}>
+ {speedUnit.unit}
+ </Text>
+ <Text style={[styles.cell, styles.cellNum, styles.headerText, { color: colors.textSecondary }]}>Alt</Text>
+ <Text style={[styles.cell, styles.cellNum, styles.headerText, { color: colors.textSecondary }]}>Bear</Text>
+ <Text style={[styles.cell, styles.cellNum, styles.headerText, { color: colors.textSecondary }]}>Batt</Text>
+ <Text style={[styles.cell, styles.cellStatus, styles.headerText, { color: colors.textSecondary }]}>
+ Status
+ </Text>
+ </View>
+
+ <FlatList
+ data={data}
+ renderItem={renderItem}
+ keyExtractor={keyExtractor}
+ getItemLayout={getItemLayout}
+ initialNumToRender={30}
+ maxToRenderPerBatch={20}
+ windowSize={11}
+ />
+ </View>
+ </ScrollView>
+ )
+}
+
+const styles = StyleSheet.create({
+ container: {
+ flex: 1
+ },
+ scrollContent: {
+ flexGrow: 1
+ },
+ empty: {
+ flex: 1,
+ alignItems: "center",
+ justifyContent: "center",
+ padding: 32
+ },
+ emptyText: {
+ fontSize: 14,
+ ...fonts.regular
+ },
+ header: {
+ borderBottomWidth: 2
+ },
+ headerText: {
+ fontSize: 11,
+ ...fonts.bold,
+ textTransform: "uppercase"
+ },
+ row: {
+ flexDirection: "row",
+ height: ROW_HEIGHT,
+ alignItems: "center",
+ paddingHorizontal: 8,
+ borderBottomWidth: StyleSheet.hairlineWidth
+ },
+ cell: {
+ fontSize: 12,
+ ...fonts.regular,
+ paddingHorizontal: 2
+ },
+ cellTime: {
+ width: 80
+ },
+ cellCoord: {
+ width: 90
+ },
+ cellNum: {
+ width: 50
+ },
+ cellStatus: {
+ width: 90
+ },
+ tableWrapper: {
+ width: TABLE_WIDTH,
+ flex: 1
+ }
+})
diff --git a/apps/mobile/src/screens/ExportDataScreen.tsx b/apps/mobile/src/screens/ExportDataScreen.tsx
index 6d2620fe..62e85f23 100644
--- a/apps/mobile/src/screens/ExportDataScreen.tsx
+++ b/apps/mobile/src/screens/ExportDataScreen.tsx
@@ -38,10 +38,7 @@ export function ExportDataScreen() {
if (cachedData.current.length > 0) return
const data = await NativeLocationService.getExportData()
if (data && data.length > 0) {
- cachedData.current = data.map((item) => ({
- ...item,
- timestamp: item.timestamp ? item.timestamp * 1000 : Date.now()
- }))
+ cachedData.current = data
}
}, [])
diff --git a/apps/mobile/src/screens/LocationInspectorScreen.tsx b/apps/mobile/src/screens/LocationInspectorScreen.tsx
index 656ca55e..071a1fa4 100644
--- a/apps/mobile/src/screens/LocationInspectorScreen.tsx
+++ b/apps/mobile/src/screens/LocationInspectorScreen.tsx
@@ -9,12 +9,13 @@ import { fonts } from "../styles/typography"
import { BarChart2 } from "lucide-react-native"
import { Container } from "../components"
import { useTheme } from "../hooks/useTheme"
-import { Trip, LocationCoords } from "../types/global"
+import { Trip, LocationCoords, ThemeColors } from "../types/global"
import NativeLocationService from "../services/NativeLocationService"
import { logger } from "../utils/logger"
import { CalendarPicker } from "../components/features/inspector/CalendarPicker"
import { TrackMap } from "../components/features/inspector/TrackMap"
import { TripList } from "../components/features/inspector/TripList"
+import { LocationTable } from "../components/features/inspector/LocationTable"
import { formatDistance } from "../utils/geo"
import { segmentTrips } from "../utils/trips"
import { TRIP_CONVERTERS, EXPORT_FORMATS, type ExportFormat } from "../utils/exportConverters"
@@ -24,10 +25,10 @@ interface TabProps {
label: string
active: boolean
onPress: () => void
- colors: any
+ colors: ThemeColors
}
-type TabType = "map" | "trips"
+type TabType = "map" | "trips" | "data"
export function LocationHistoryScreen({ navigation, route }: { navigation: any; route: any }) {
const { colors } = useTheme()
@@ -206,9 +207,10 @@ export function LocationHistoryScreen({ navigation, route }: { navigation: any;
<View style={styles.tabBar}>
<Tab label="Map" active={activeTab === "map"} onPress={() => setActiveTab("map")} colors={colors} />
<Tab label="Trips" active={activeTab === "trips"} onPress={() => setActiveTab("trips")} colors={colors} />
+ <Tab label="Data" active={activeTab === "data"} onPress={() => setActiveTab("data")} colors={colors} />
</View>
- {activeTab === "map" ? (
+ {activeTab === "map" && (
<View style={styles.mapContainer}>
{calendarPicker}
<TrackMap
@@ -233,7 +235,9 @@ export function LocationHistoryScreen({ navigation, route }: { navigation: any;
</Pressable>
)}
</View>
- ) : (
+ )}
+
+ {activeTab === "trips" && (
<View style={styles.mapContainer}>
{calendarPicker}
<TripList
@@ -246,6 +250,13 @@ export function LocationHistoryScreen({ navigation, route }: { navigation: any;
/>
</View>
)}
+
+ {activeTab === "data" && (
+ <View style={styles.mapContainer}>
+ {calendarPicker}
+ <LocationTable locations={trackLocations} colors={colors} />
+ </View>
+ )}
</Container>
)
}
diff --git a/apps/mobile/src/screens/LocationSummaryScreen.tsx b/apps/mobile/src/screens/LocationSummaryScreen.tsx
index 8eb8fa99..ae3dec45 100644
--- a/apps/mobile/src/screens/LocationSummaryScreen.tsx
+++ b/apps/mobile/src/screens/LocationSummaryScreen.tsx
@@ -68,10 +68,20 @@ function AnimatedNumber({
}) {
const animRef = useRef(new Animated.Value(0)).current
const [display, setDisplay] = useState(format(0))
+ const mountedRef = useRef(true)
+
+ useEffect(() => {
+ mountedRef.current = true
+ return () => {
+ mountedRef.current = false
+ }
+ }, [])
useEffect(() => {
animRef.setValue(0)
- const listener = animRef.addListener(({ value: v }) => setDisplay(format(Math.round(v))))
+ const listener = animRef.addListener(({ value: v }) => {
+ if (mountedRef.current) setDisplay(format(Math.round(v)))
+ })
Animated.timing(animRef, { toValue: value, duration: COUNT_UP_DURATION, useNativeDriver: false }).start()
return () => {
animRef.stopAnimation()
diff --git a/apps/mobile/src/screens/TripDetailScreen.tsx b/apps/mobile/src/screens/TripDetailScreen.tsx
index bb92405d..aa291596 100644
--- a/apps/mobile/src/screens/TripDetailScreen.tsx
+++ b/apps/mobile/src/screens/TripDetailScreen.tsx
@@ -5,26 +5,35 @@
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 { Route, Clock, Gauge, TrendingUp, TrendingDown, MapPin, Share, type LucideIcon } 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 { formatDate, 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"
+import type { Trip, ThemeColors } from "../types/global"
-function formatDate(unixSeconds: number): string {
- return new Date(unixSeconds * 1000).toLocaleDateString(undefined, {
- weekday: "short",
- month: "short",
- day: "numeric"
- })
+const MAX_BARS = 120
+
+/** Downsample an array to at most maxBars entries by averaging buckets. */
+function downsample(values: number[], maxBars: number): number[] {
+ if (values.length <= maxBars) return values
+ const bucketSize = values.length / maxBars
+ const result: number[] = []
+ for (let i = 0; i < maxBars; i++) {
+ const start = Math.floor(i * bucketSize)
+ const end = Math.floor((i + 1) * bucketSize)
+ let sum = 0
+ for (let j = start; j < end; j++) sum += values[j]
+ result.push(sum / (end - start))
+ }
+ return result
}
export function TripDetailScreen({ route }: { navigation: any; route: any }) {
@@ -60,11 +69,13 @@ export function TripDetailScreen({ route }: { navigation: any; route: any }) {
)
const speedProfile = useMemo(() => {
- return trip.locations.filter((loc) => loc.speed != null).map((loc) => loc.speed ?? 0)
+ const raw = trip.locations.filter((loc) => loc.speed != null).map((loc) => loc.speed ?? 0)
+ return downsample(raw, MAX_BARS)
}, [trip])
const elevationProfile = useMemo(() => {
- return trip.locations.filter((loc) => loc.altitude != null).map((loc) => loc.altitude ?? 0)
+ const raw = trip.locations.filter((loc) => loc.altitude != null).map((loc) => loc.altitude ?? 0)
+ return downsample(raw, MAX_BARS)
}, [trip])
const maxSpeed = useMemo(() => speedProfile.reduce((max, v) => Math.max(max, v), 0), [speedProfile])
@@ -140,7 +151,7 @@ export function TripDetailScreen({ route }: { navigation: any; route: any }) {
return (
<View
key={i}
- style={[styles.bar, { height: `${Math.max(height, 2)}%`, backgroundColor: tripColor, flex: 1 }]}
+ style={[styles.bar, { height: `${Math.max(height, 2)}%`, backgroundColor: tripColor }]}
/>
)
})}
@@ -177,7 +188,7 @@ export function TripDetailScreen({ route }: { navigation: any; route: any }) {
key={i}
style={[
styles.bar,
- { height: `${Math.max(height, 2)}%`, backgroundColor: colors.primary + "80", flex: 1 }
+ { height: `${Math.max(height, 2)}%`, backgroundColor: colors.primary + "80" }
]}
/>
)
@@ -235,10 +246,10 @@ function StatCard({
value,
colors
}: {
- icon: React.ComponentType<any>
+ icon: LucideIcon
label: string
value: string
- colors: any
+ colors: ThemeColors
}) {
return (
<Card style={styles.statCard}>
@@ -340,7 +351,8 @@ const styles = StyleSheet.create({
gap: 1
},
bar: {
- borderRadius: 2
+ borderRadius: 2,
+ flex: 1
},
chartLabels: {
flexDirection: "row",
diff --git a/apps/mobile/src/types/global.ts b/apps/mobile/src/types/global.ts
index 982bca88..22a19ae4 100644
--- a/apps/mobile/src/types/global.ts
+++ b/apps/mobile/src/types/global.ts
@@ -26,6 +26,7 @@ export interface LocationCoords {
bearing?: number
battery?: number
battery_status?: number
+ /** Unix epoch seconds */
timestamp?: number
}
diff --git a/apps/mobile/src/utils/__tests__/exportConverters.test.ts b/apps/mobile/src/utils/__tests__/exportConverters.test.ts
index b6b2c780..02f95cc7 100644
--- a/apps/mobile/src/utils/__tests__/exportConverters.test.ts
+++ b/apps/mobile/src/utils/__tests__/exportConverters.test.ts
@@ -21,7 +21,7 @@ const sampleLocation = {
bearing: 180,
battery: 85,
battery_status: 2,
- timestamp: 1700000000000
+ timestamp: 1700000000
}
const minimalLocation = {
diff --git a/apps/mobile/src/utils/__tests__/trips.test.ts b/apps/mobile/src/utils/__tests__/trips.test.ts
index df2910d2..0f4902b4 100644
--- a/apps/mobile/src/utils/__tests__/trips.test.ts
+++ b/apps/mobile/src/utils/__tests__/trips.test.ts
@@ -1,5 +1,5 @@
import { segmentTrips, getTripColor, TRIP_COLORS, computeTripStats } from "../trips"
-import { formatDuration, formatTime } from "../geo"
+import { formatDuration, formatTime, formatDate } from "../geo"
describe("segmentTrips", () => {
it("returns empty array for empty input", () => {
@@ -221,3 +221,27 @@ describe("formatTime", () => {
expect(withSeconds.length).toBeGreaterThan(withoutSeconds.length)
})
})
+
+describe("formatDate", () => {
+ it("returns a non-empty string", () => {
+ // 2024-01-15 12:00:00 UTC
+ const ts = Math.floor(new Date("2024-01-15T12:00:00Z").getTime() / 1000)
+ const result = formatDate(ts)
+ expect(result).toBeTruthy()
+ expect(result.length).toBeGreaterThan(0)
+ })
+
+ it("includes weekday and month", () => {
+ // Force a known date: 2024-01-15 is a Monday
+ const ts = Math.floor(new Date("2024-01-15T12:00:00Z").getTime() / 1000)
+ const result = formatDate(ts)
+ // Should contain abbreviated weekday and month (locale-dependent but always present)
+ expect(result).toMatch(/\w{2,}/)
+ })
+
+ it("returns different strings for different dates", () => {
+ const ts1 = Math.floor(new Date("2024-01-15T12:00:00Z").getTime() / 1000)
+ const ts2 = Math.floor(new Date("2024-06-20T12:00:00Z").getTime() / 1000)
+ expect(formatDate(ts1)).not.toBe(formatDate(ts2))
+ })
+})
diff --git a/apps/mobile/src/utils/exportConverters.ts b/apps/mobile/src/utils/exportConverters.ts
index 3cdc1d49..6fda2d6e 100644
--- a/apps/mobile/src/utils/exportConverters.ts
+++ b/apps/mobile/src/utils/exportConverters.ts
@@ -42,18 +42,18 @@ export const getByteSize = (content: string): number => {
}
// ============================================================================
-// FLAT CONVERTERS (timestamps in milliseconds)
+// FLAT CONVERTERS (timestamps in Unix seconds)
// ============================================================================
export const convertToCSV = (data: LocationCoords[]): string => {
const headers = "id,timestamp,iso_time,latitude,longitude,accuracy,altitude,speed,battery\n"
const rows = data
.map((item, i) => {
- const timestamp = item.timestamp ?? Date.now()
- const isoTime = new Date(timestamp).toISOString()
+ const ts = item.timestamp ?? Math.floor(Date.now() / 1000)
+ const isoTime = new Date(ts * 1000).toISOString()
return [
i,
- item.timestamp,
+ ts,
isoTime,
item.latitude,
item.longitude,
@@ -69,8 +69,8 @@ export const convertToCSV = (data: LocationCoords[]): string => {
export const convertToGeoJSON = (data: LocationCoords[]): string => {
const features = data.map((item, i) => {
- const timestamp = item.timestamp ? new Date(item.timestamp) : new Date()
- const timeStr = isNaN(timestamp.getTime()) ? new Date().toISOString() : timestamp.toISOString()
+ const ts = item.timestamp ?? Math.floor(Date.now() / 1000)
+ const timeStr = new Date(ts * 1000).toISOString()
return {
type: "Feature",
@@ -100,7 +100,8 @@ export const convertToGeoJSON = (data: LocationCoords[]): string => {
}
export const convertToGPX = (data: LocationCoords[]): string => {
- let gpx = `<?xml version="1.0" encoding="UTF-8"?>
+ const parts: string[] = [
+ `<?xml version="1.0" encoding="UTF-8"?>
<gpx version="1.1" creator="Colota" xmlns="http://www.topografix.com/GPX/1/1">
<metadata>
<name>Colota Location Export</name>
@@ -109,31 +110,33 @@ export const convertToGPX = (data: LocationCoords[]): string => {
<trk>
<name>Colota Track Export</name>
<trkseg>`
+ ]
- data.forEach((item) => {
- const timestamp = item.timestamp ?? Date.now()
- const isoTime = new Date(timestamp).toISOString()
- gpx += `
+ for (const item of data) {
+ const ts = item.timestamp ?? Math.floor(Date.now() / 1000)
+ parts.push(`
<trkpt lat="${item.latitude.toFixed(6)}" lon="${item.longitude.toFixed(6)}">
<ele>${item.altitude ?? 0}</ele>
- <time>${isoTime}</time>
+ <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>`
- })
+ </trkpt>`)
+ }
- gpx += `
+ parts.push(`
</trkseg>
</trk>
-</gpx>`
- return gpx
+</gpx>`)
+ return parts.join("")
}
export const convertToKML = (data: LocationCoords[]): string => {
- let kml = `<?xml version="1.0" encoding="UTF-8"?>
+ const coords = data.map((item) => `${item.longitude},${item.latitude},${item.altitude ?? 0}`).join("\n ")
+ const parts: string[] = [
+ `<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<name>Colota Location Export</name>
@@ -150,28 +153,28 @@ export const convertToKML = (data: LocationCoords[]): string => {
<LineString>
<tessellate>1</tessellate>
<coordinates>
- ${data.map((item) => `${item.longitude},${item.latitude},${item.altitude ?? 0}`).join("\n ")}
+ ${coords}
</coordinates>
</LineString>
</Placemark>`
+ ]
- data.forEach((item) => {
- const timestamp = item.timestamp ?? Date.now()
- const isoTime = new Date(timestamp).toISOString()
- kml += `
+ for (const item of data) {
+ const ts = item.timestamp ?? Math.floor(Date.now() / 1000)
+ parts.push(`
<Placemark>
- <TimeStamp><when>${isoTime}</when></TimeStamp>
+ <TimeStamp><when>${new Date(ts * 1000).toISOString()}</when></TimeStamp>
<description>Accuracy: ${item.accuracy}m, Speed: ${item.speed ?? 0}m/s</description>
<Point>
<coordinates>${item.longitude},${item.latitude},${item.altitude ?? 0}</coordinates>
</Point>
- </Placemark>`
- })
+ </Placemark>`)
+ }
- kml += `
+ parts.push(`
</Document>
-</kml>`
- return kml
+</kml>`)
+ return parts.join("")
}
// ============================================================================
@@ -229,21 +232,23 @@ export const convertTripsToGeoJSON = (trips: Trip[]): string => {
}
export const convertTripsToGPX = (trips: Trip[]): string => {
- let gpx = `<?xml version="1.0" encoding="UTF-8"?>
+ const parts: string[] = [
+ `<?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 += `
+ parts.push(`
<trk>
<name>Trip ${trip.index}</name>
- <trkseg>`
+ <trkseg>`)
for (const item of trip.locations) {
const ts = item.timestamp ?? Math.floor(Date.now() / 1000)
- gpx += `
+ parts.push(`
<trkpt lat="${item.latitude.toFixed(6)}" lon="${item.longitude.toFixed(6)}">
<ele>${item.altitude || 0}</ele>
<time>${new Date(ts * 1000).toISOString()}</time>
@@ -252,28 +257,33 @@ export const convertTripsToGPX = (trips: Trip[]): string => {
<speed>${item.speed || 0}</speed>
<battery>${item.battery || 0}</battery>
</extensions>
- </trkpt>`
+ </trkpt>`)
}
- gpx += `
+ parts.push(`
</trkseg>
- </trk>`
+ </trk>`)
}
- gpx += `
-</gpx>`
- return gpx
+ parts.push(`
+</gpx>`)
+ return parts.join("")
}
export const convertTripsToKML = (trips: Trip[]): string => {
- let kml = `<?xml version="1.0" encoding="UTF-8"?>
+ const parts: string[] = [
+ `<?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 += `
+ const coords = trip.locations
+ .map((item) => `${item.longitude},${item.latitude},${item.altitude || 0}`)
+ .join("\n ")
+ parts.push(`
<Style id="${styleId}">
<LineStyle>
<color>${hexToKmlColor(getTripColor(trip.index))}</color>
@@ -288,33 +298,31 @@ export const convertTripsToKML = (trips: Trip[]): string => {
<LineString>
<tessellate>1</tessellate>
<coordinates>
- ${trip.locations
- .map((item) => `${item.longitude},${item.latitude},${item.altitude || 0}`)
- .join("\n ")}
+ ${coords}
</coordinates>
</LineString>
- </Placemark>`
+ </Placemark>`)
for (const item of trip.locations) {
const ts = item.timestamp ?? Math.floor(Date.now() / 1000)
- kml += `
+ parts.push(`
<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>
+ <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>`
+ </Placemark>`)
}
- kml += `
- </Folder>`
+ parts.push(`
+ </Folder>`)
}
- kml += `
+ parts.push(`
</Document>
-</kml>`
- return kml
+</kml>`)
+ return parts.join("")
}
export const TRIP_CONVERTERS: Record<ExportFormat, (trips: Trip[]) => string> = {
diff --git a/apps/mobile/src/utils/geo.ts b/apps/mobile/src/utils/geo.ts
index 50712a4a..e600ea94 100644
--- a/apps/mobile/src/utils/geo.ts
+++ b/apps/mobile/src/utils/geo.ts
@@ -74,6 +74,15 @@ export function formatTime(unixSeconds: number, showSeconds = false): string {
})
}
+/** Format a Unix-seconds timestamp as a localized date string (e.g. "Wed, Feb 27"). */
+export function formatDate(unixSeconds: number): string {
+ return new Date(unixSeconds * 1000).toLocaleDateString(undefined, {
+ weekday: "short",
+ month: "short",
+ day: "numeric"
+ })
+}
+
/** Format meters into a human-readable string using the device locale's unit. */
export function formatDistance(meters: number): string {
if (usesMiles()) {