Skip to content

Colota - Android GPS Location tracker

feat: add offline maps download and management (#227)

Max Dietrichc7419176fcc5
diff --git a/README.md b/README.md
index f27d1eae..9c2e47f1 100644
--- a/README.md
+++ b/README.md
@@ -18,6 +18,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, GeoPulse, 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.
+- **Offline Maps** - Download map areas to your device for use without an internet connection.
- **Scheduled Export** - Automatic daily, weekly or monthly exports to a local directory with file retention management.
- **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 and automatic GPS pause when stationary.
diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.md
index 3be904f6..8796f264 100644
--- a/apps/docs/docs/development/architecture.md
+++ b/apps/docs/docs/development/architecture.md
@@ -190,6 +190,7 @@ Wraps Android's `EncryptedSharedPreferences` for encrypted credential storage (A
| `LocationSummaryScreen` | Aggregated stats for selectable periods (week/month/30 days) with daily breakdown and tap-to-inspect navigation |
| `ExportDataScreen` | Export all tracked locations via native streaming converters as CSV, GeoJSON, GPX, or KML |
| `AutoExportScreen` | Configure scheduled auto-export: directory, format, frequency, export range, and file retention |
+| `OfflineMapsScreen` | Download and manage offline map areas - interactive bounding box picker, size estimate, progress tracking, and area deletion |
| `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 |
@@ -219,6 +220,17 @@ The app uses [MapLibre GL Native](https://github.com/maplibre/maplibre-react-nat
| `UserLocationOverlay` | User position dot with accuracy circle, used by DashboardMap and GeofenceScreen |
| `MapCenterButton` | Reusable button overlay to re-center the map |
+`OfflinePackManager.ts` handles the offline maps feature:
+
+| Export | Purpose |
+| --- | --- |
+| `createOfflinePack` | Creates a MapLibre offline pack for a bounding box at z8-14 |
+| `loadOfflineAreas` | Fetches all stored packs from MapLibre's `OfflineManager` and returns status info (size, complete, active) |
+| `deleteOfflineArea` | Unsubscribes, pauses, and deletes a pack; resets the tile database when the last pack is removed to reclaim OS storage |
+| `willExceedTileLimit` | Estimates whether an area would hit the 100k-tile cap before downloading |
+| `estimateSizeLabel` / `estimateSizeBytes` | Pre-download size estimates using per-zoom tile counting and per-tile byte averages |
+| `loadOfflineAreaBounds` / `saveOfflineAreaBounds` / `removeOfflineAreaBounds` | Persist area metadata (center, radius) to the native SQLite settings table |
+
Supporting utilities in `mapUtils.ts`:
| Utility | Purpose |
diff --git a/apps/docs/docs/faq.md b/apps/docs/docs/faq.md
index 3ca76857..66ca7115 100644
--- a/apps/docs/docs/faq.md
+++ b/apps/docs/docs/faq.md
@@ -32,6 +32,10 @@ To ensure modifications stay open source, especially server-side components.
3-10 meters in open sky, 10-50 meters in urban areas. The [accuracy filter](/docs/configuration/gps-settings#accuracy-filter) helps remove poor fixes.
+### Can I use maps without internet?
+
+Yes. Go to **Settings > Offline Maps** to download map areas to your device. Pan and zoom the map to frame the area you want, give it a name, and tap **Download Area**. Downloaded tiles persist across app restarts and work without any network connection. See [Offline Maps](/docs/guides/offline-maps) for details.
+
### Can I export my location history?
Yes. Tap **Export** on the Dashboard to export in CSV, GeoJSON, GPX, or KML. See [Data Export](/docs/guides/data-export) for details.
diff --git a/apps/docs/docs/guides/offline-maps.md b/apps/docs/docs/guides/offline-maps.md
new file mode 100644
index 00000000..7facd9b5
--- /dev/null
+++ b/apps/docs/docs/guides/offline-maps.md
@@ -0,0 +1,50 @@
+---
+sidebar_position: 5
+---
+
+# Offline Maps
+
+Download map areas to your device so the map works without an internet connection. Useful when tracking in areas with poor cell coverage - remote trails, backcountry routes, etc.
+
+## Downloading an Area
+
+1. Go to **Settings > Offline Maps**
+2. Pan and zoom the map to frame the area you want to download
+3. Tap the location button to center on your current position if needed
+4. Enter a **name** for the area
+5. Check the estimated size and tap **Download Area**
+
+The download runs in the background. A progress bar shows completion percentage. You can navigate away and return - the download continues.
+
+## Zoom Levels
+
+Offline packs cover zoom levels 8-14. This matches the maximum resolution served by the default tile server (maps.mxd.codes) and [OpenFreeMap](https://openfreemap.org). MapLibre uses vector overzooming to render zoom levels above 14 from z14 tiles - you get the same visual detail whether online or offline.
+
+## Tile Limit
+
+Colota caps offline packs at **100,000 tiles**. If your area would exceed this, a warning is shown before you download - the pack will still download but coverage will be incomplete at high zoom levels.
+
+To avoid hitting the cap:
+
+- Zoom out or pan to frame a smaller area
+- Download multiple smaller areas instead of one large one
+
+## Storage
+
+Downloaded areas are stored on the device by MapLibre's offline tile cache. They persist across app restarts. The **Offline Maps** screen shows the current size of each saved area.
+
+To free up space, delete areas you no longer need. When the last area is deleted, the tile database is reset and the storage is reclaimed by the OS.
+
+## Managing Areas
+
+From the **Offline Maps** screen you can:
+
+- See all downloaded areas with their size and status
+- Delete an area (removes all cached tiles for that area)
+- Start a new download
+
+## Tips
+
+- Download areas **before** you go - not when you're already out of coverage
+- For long routes, download the corridor rather than a large bounding box to stay within the tile cap
+- Offline maps only affect map rendering - GPS tracking, sync, and all other features work independently of the map tile cache
diff --git a/apps/docs/docs/guides/tile-server.md b/apps/docs/docs/guides/tile-server.md
new file mode 100644
index 00000000..82227efc
--- /dev/null
+++ b/apps/docs/docs/guides/tile-server.md
@@ -0,0 +1,59 @@
+---
+sidebar_position: 6
+---
+
+# Map Tile Server
+
+By default, Colota loads maps from [maps.mxd.codes](https://maps.mxd.codes) - a self-hosted tile server I run for this app. You can swap it out for your own if needed.
+
+## Default Server
+
+maps.mxd.codes runs [tileserver-gl](https://github.com/maptiler/tileserver-gl) on a netcup VPS. Two styles are served - bright for light mode, dark for dark mode.
+
+**Technical details**
+
+- Planet-wide `.mbtiles` sourced from [OpenFreeMap](https://openfreemap.org), downloaded and replaced weekly - OSM edits may take a few days to appear
+- Styles are served as MapLibre GL style JSON at `/styles/bright/style.json` and `/styles/dark/style.json`
+- Tile requests are rate-limited to 100 requests/second per IP (burst of 200). Normal app usage is well within this - panning and zooming typically generates 10-20 requests at a time
+- Tile responses are cached at the server, so repeat views of the same area are served instantly
+- IP addresses are not logged under normal operation. Logging may be enabled temporarily if there is a specific reason such as investigating abuse or server issues, and disabled again afterwards
+
+Free to use. Normal usage means map tiles loading as you pan and zoom within the app, and downloading offline map packs through the built-in offline maps feature. Accessing the tile server directly, bulk-downloading tiles programmatically, or scraping outside the app falls outside of this and is not permitted.
+
+If the default server is unavailable or you run into issues, you can either configure a custom tile server (see below) or open an issue on [GitHub](https://github.com/dietrichmax/colota/issues).
+
+:::tip Support the server If you find Colota useful and want to help keep the default server running, contributions are welcome - the hosting runs at 17,94€/month. [mxd.codes/support](https://mxd.codes/support)
+
+:::
+
+## Using a Custom Server
+
+:::note Offline maps Offline map packs are downloaded from whichever tile server is configured at the time. Switching to a custom server won't affect packs you've already downloaded, but new downloads will come from the new server.
+
+:::
+
+1. Open **Settings**
+2. Scroll to **Appearance** and tap **Map Tile Server**
+3. Enter your style JSON URLs for light and dark mode
+4. Leave a field empty to fall back to the default
+
+Any [MapLibre GL style](https://maplibre.org/maplibre-style-spec/) endpoint works. If you only have one style, use the same URL in both fields.
+
+:::note Attribution When using the default server, the map shows mxd.codes · OpenMapTiles · OpenStreetMap attribution. When a custom server is configured, attribution is read automatically from the style JSON served by your tile server. :::
+
+**Self-hosting options**
+
+- [tileserver-gl](https://tileserver.readthedocs.io) - serves MapLibre styles from `.mbtiles` files.
+- [PMTiles](https://docs.protomaps.com/pmtiles/) - a single static file format that can be served from any object storage (S3, Cloudflare R2, etc.) with no server process required.
+
+**Free hosted alternatives**
+
+[OpenFreeMap](https://openfreemap.org) is a good free alternative. Available styles:
+
+| Style | URL |
+| --------------- | ---------------------------------------------- |
+| Bright (light) | `https://tiles.openfreemap.org/styles/bright` |
+| Liberty (light) | `https://tiles.openfreemap.org/styles/liberty` |
+| Fiord (dark) | `https://tiles.openfreemap.org/styles/fiord` |
+
+For a light/dark pair, use `bright` or `liberty` for light mode and `fiord` for dark mode.
diff --git a/apps/docs/docs/introduction.md b/apps/docs/docs/introduction.md
index d3b45416..93a01ada 100644
--- a/apps/docs/docs/introduction.md
+++ b/apps/docs/docs/introduction.md
@@ -12,6 +12,7 @@ Colota is a self-hosted GPS tracking app for Android. It sends your location to
- **Self-Hosted** - Send location data to your own server. Works with Dawarich, GeoPulse, 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.
+- **Offline Maps** - Download map areas to your device for use without an internet connection.
- **Scheduled Export** - Automatic daily, weekly or monthly exports to a local directory with file retention management.
- **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 and automatic GPS pause when stationary.
@@ -25,7 +26,7 @@ Colota is a self-hosted GPS tracking app for Android. It sends your location to
## App Screens
-Colota has fifteen screens, each focused on a specific task:
+Colota has sixteen screens, each focused on a specific task:
| Screen | Purpose |
| --- | --- |
@@ -34,6 +35,7 @@ Colota has fifteen screens, each focused on a specific task:
| **API Config** | Endpoint field mapping with templates for Dawarich, OwnTracks, PhoneTrack, Reitti, Traccar, or custom backends |
| **Auth Settings** | Endpoint authentication (None, Basic Auth, Bearer Token) and custom HTTP headers |
| **Geofences** | Create, edit, and delete pause zones on an interactive map |
+| **Offline Maps** | Download map areas to the device for use without an internet connection |
| **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 calendar day picker and trip-colored segments, view segmented trips with per-trip stats |
diff --git a/apps/docs/sidebars.ts b/apps/docs/sidebars.ts
index eb3d62c3..cd8e4fdb 100644
--- a/apps/docs/sidebars.ts
+++ b/apps/docs/sidebars.ts
@@ -48,6 +48,8 @@ const sidebars: SidebarsConfig = {
"guides/data-management",
"guides/deep-link-setup",
"guides/battery-optimization",
+ "guides/offline-maps",
+ "guides/tile-server",
"guides/troubleshooting"
]
},
diff --git a/apps/docs/src/pages/privacy-policy.md b/apps/docs/src/pages/privacy-policy.md
index 19ed550a..a1cdb939 100644
--- a/apps/docs/src/pages/privacy-policy.md
+++ b/apps/docs/src/pages/privacy-policy.md
@@ -4,7 +4,7 @@ title: Privacy Policy
# Privacy Policy
-**Last updated: March 14, 2026**
+**Last updated: March 18, 2026**
Colota ("the App") is a self-hosted GPS tracking application for Android, developed by Max Dietrich. This privacy policy explains what data the App collects, how it is used, and your rights regarding that data.
@@ -66,9 +66,9 @@ Colota does not share your data with anyone. The only data transmission occurs t
The App is distributed via Google Play, which may collect data according to [Google's Privacy Policy](https://policies.google.com/privacy). This is outside the App's control.
-### OpenFreeMap
+### Map Tiles (maps.mxd.codes)
-The App displays maps using [OpenFreeMap](https://openfreemap.org), which serves map tiles. When the map is visible, your device makes requests to OpenFreeMap's servers to download tiles for the visible area. OpenFreeMap does not log IP addresses by default and uses no cookies or tracking. OpenFreeMap is a free, open-source service. See [OpenFreeMap's privacy policy](https://openfreemap.org/privacy/) for details.
+The App displays maps using [maps.mxd.codes](https://maps.mxd.codes), a self-hosted tile server powered by [tileserver-gl](https://github.com/maptiler/tileserver-gl) and OpenStreetMap data. When the map is visible, your device makes requests to maps.mxd.codes to download tiles for the visible area. IP addresses are not logged under normal operation. Logging may be enabled temporarily for a specific reason such as investigating abuse or server issues, and disabled again afterwards. Users can configure a custom tile server URL in Settings - see the [tile server guide](/docs/guides/tile-server) for details.
### No Other Third Parties
diff --git a/apps/mobile/App.tsx b/apps/mobile/App.tsx
index bdab5043..8331b90a 100644
--- a/apps/mobile/App.tsx
+++ b/apps/mobile/App.tsx
@@ -27,7 +27,8 @@ import {
TrackingProfilesScreen,
ProfileEditorScreen,
SetupImportScreen,
- TripDetailScreen
+ TripDetailScreen,
+ OfflineMapsScreen
} from "./src/screens/"
import NativeLocationService from "./src/services/NativeLocationService"
import { loadDisplayPreferences } from "./src/utils/geo"
@@ -118,6 +119,11 @@ const SCREEN_CONFIG = [
name: "Trip Detail",
component: TripDetailScreen,
title: "Trip Detail"
+ },
+ {
+ name: "Offline Maps",
+ component: OfflineMapsScreen,
+ title: "Offline Maps"
}
] as const
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 87995320..82105c62 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
@@ -43,6 +43,8 @@ import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
+import android.os.Environment
+import android.os.StatFs
import java.lang.ref.WeakReference
/**
@@ -833,6 +835,23 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
promise.resolve(networkManager.isNetworkAvailable())
}
+ @ReactMethod
+ fun isUnmeteredConnection(promise: Promise) {
+ promise.resolve(networkManager.isUnmeteredConnection())
+ }
+
+ @ReactMethod
+ fun getAvailableStorageMB(promise: Promise) {
+ try {
+ val stat = StatFs(Environment.getDataDirectory().path)
+ val availableBytes = stat.availableBlocksLong * stat.blockSizeLong
+ promise.resolve((availableBytes / (1024 * 1024)).toDouble())
+ } catch (e: Exception) {
+ AppLogger.e("LocationServiceModule", "getAvailableStorageMB failed", e)
+ promise.resolve(-1.0)
+ }
+ }
+
@ReactMethod
fun getMostRecentLocation(promise: Promise) = executeAsync(promise) {
dbHelper.getRawMostRecentLocation()?.let { data ->
diff --git a/apps/mobile/jest.setup.js b/apps/mobile/jest.setup.js
index 8eb8415c..d87c8adf 100644
--- a/apps/mobile/jest.setup.js
+++ b/apps/mobile/jest.setup.js
@@ -38,6 +38,14 @@ jest.mock("lucide-react-native", () => {
)
})
+// AppState mock - RN exports AppState as .default from this path
+jest.mock("react-native/Libraries/AppState/AppState", () => ({
+ __esModule: true,
+ default: {
+ addEventListener: jest.fn(() => ({ remove: jest.fn() }))
+ }
+}))
+
// Blob polyfill for getByteSize tests (RN test env doesn't have Blob)
if (typeof global.Blob === "undefined") {
global.Blob = class Blob {
diff --git a/apps/mobile/src/components/features/dashboard/DashboardMap.tsx b/apps/mobile/src/components/features/dashboard/DashboardMap.tsx
index 029bcc4f..24ac1e58 100644
--- a/apps/mobile/src/components/features/dashboard/DashboardMap.tsx
+++ b/apps/mobile/src/components/features/dashboard/DashboardMap.tsx
@@ -8,10 +8,8 @@ import { View, StyleSheet, Text, ActivityIndicator, DeviceEventEmitter, Image }
import { LocationCoords } from "../../../types/global"
import { useTheme } from "../../../hooks/useTheme"
import { fonts } from "../../../styles/typography"
-import { WifiOff } from "lucide-react-native"
import NativeLocationService from "../../../services/NativeLocationService"
-import { useFocusEffect } from "@react-navigation/native"
-import { STATS_REFRESH_IDLE, MAP_ANIMATION_DURATION_MS, MAX_MAP_ZOOM } from "../../../constants"
+import { MAP_ANIMATION_DURATION_MS, MAX_MAP_ZOOM } from "../../../constants"
import { MapCenterButton } from "../map/MapCenterButton"
import { ColotaMapView, ColotaMapRef } from "../map/ColotaMapView"
import { buildGeofencesGeoJSON } from "../map/mapUtils"
@@ -40,18 +38,6 @@ export function DashboardMap({ coords, tracking, activeZoneName, activeProfileNa
const initialCoords = useRef<LocationCoords | null>(null)
const [hasInitialCoords, setHasInitialCoords] = useState(false)
const [currentPauseZone, setCurrentPauseZone] = useState<string | null>(null)
- const [isOffline, setIsOffline] = useState(false)
-
- useFocusEffect(
- useCallback(() => {
- const check = () => {
- NativeLocationService.isNetworkAvailable().then((available) => setIsOffline(!available))
- }
- check()
- const interval = setInterval(check, STATS_REFRESH_IDLE)
- return () => clearInterval(interval)
- }, [])
- )
useEffect(() => {
if (!initialCoords.current && coords) {
@@ -176,13 +162,6 @@ export function DashboardMap({ coords, tracking, activeZoneName, activeProfileNa
{showMap && <MapCenterButton visible={!isCentered} onPress={handleCenterMe} />}
- {showMap && isOffline && (
- <View style={[styles.offlineBanner, { backgroundColor: colors.card }]}>
- <WifiOff size={14} color={colors.textSecondary} />
- <Text style={[styles.offlineText, { color: colors.textSecondary }]}>Map tiles unavailable - no internet</Text>
- </View>
- )}
-
{showMap && activeZoneName && (
<View
style={[
@@ -259,23 +238,5 @@ const styles = StyleSheet.create({
zIndex: 5
},
infoTitle: { fontSize: 16, ...fonts.bold, marginBottom: 2 },
- infoSub: { fontSize: 13 },
- offlineBanner: {
- position: "absolute",
- bottom: 90,
- left: 14,
- right: 14,
- flexDirection: "row",
- alignItems: "center",
- gap: 8,
- padding: 12,
- borderRadius: 12,
- elevation: 8,
- shadowOpacity: 0.2,
- zIndex: 5
- },
- offlineText: {
- fontSize: 13,
- ...fonts.medium
- }
+ infoSub: { fontSize: 13 }
})
diff --git a/apps/mobile/src/components/features/dashboard/__tests__/DashboardMap.test.tsx b/apps/mobile/src/components/features/dashboard/__tests__/DashboardMap.test.tsx
index e41ee2eb..222f8997 100644
--- a/apps/mobile/src/components/features/dashboard/__tests__/DashboardMap.test.tsx
+++ b/apps/mobile/src/components/features/dashboard/__tests__/DashboardMap.test.tsx
@@ -19,7 +19,8 @@ jest.mock("@maplibre/maplibre-react-native", () => {
})
jest.mock("@react-navigation/native", () => ({
- useFocusEffect: jest.fn()
+ useFocusEffect: jest.fn(),
+ useIsFocused: () => true
}))
jest.mock("../../../../hooks/useTheme", () => ({
@@ -48,7 +49,8 @@ jest.mock("../../../../services/NativeLocationService", () => ({
isNetworkAvailable: jest.fn().mockResolvedValue(true),
getGeofences: jest.fn().mockResolvedValue([]),
checkCurrentPauseZone: jest.fn().mockResolvedValue(null),
- getMostRecentLocation: jest.fn().mockResolvedValue(null)
+ getMostRecentLocation: jest.fn().mockResolvedValue(null),
+ getSetting: jest.fn().mockResolvedValue(null)
}))
jest.mock("../../../../assets/icons/icon.png", () => "mock-icon")
diff --git a/apps/mobile/src/components/features/map/ColotaMapView.tsx b/apps/mobile/src/components/features/map/ColotaMapView.tsx
index f56cbebc..58119991 100644
--- a/apps/mobile/src/components/features/map/ColotaMapView.tsx
+++ b/apps/mobile/src/components/features/map/ColotaMapView.tsx
@@ -9,33 +9,17 @@ import { MapView, Camera } from "@maplibre/maplibre-react-native"
import type { MapViewRef, CameraRef } from "@maplibre/maplibre-react-native"
import type { RegionPayload } from "@maplibre/maplibre-react-native"
import { Compass } from "lucide-react-native"
+import { useIsFocused } from "@react-navigation/native"
import { useTheme } from "../../../hooks/useTheme"
-import { DEFAULT_MAP_ZOOM } from "../../../constants"
+import { DEFAULT_MAP_ZOOM, MAP_STYLE_URL_LIGHT, MAP_STYLE_URL_DARK } from "../../../constants"
import { fonts } from "../../../styles/typography"
-import { darkifyStyle } from "./mapUtils"
-
-const OPENFREEMAP_STYLE = "https://tiles.openfreemap.org/styles/bright"
-
-/** Cached dark style object so we only fetch + transform once */
-let cachedDarkStyle: object | null = null
-let darkStyleFetchPromise: Promise<object | null> | null = null
-
-async function getDarkStyle(): Promise<object | null> {
- if (cachedDarkStyle) return cachedDarkStyle
- if (darkStyleFetchPromise) return darkStyleFetchPromise
- darkStyleFetchPromise = fetch(OPENFREEMAP_STYLE)
- .then((res) => res.json())
- .then((json) => {
- cachedDarkStyle = darkifyStyle(json)
- darkStyleFetchPromise = null
- return cachedDarkStyle
- })
- .catch(() => {
- darkStyleFetchPromise = null
- return null
- })
- return darkStyleFetchPromise
-}
+import NativeLocationService from "../../../services/NativeLocationService"
+
+const DEFAULT_ATTRIBUTION_LINKS = [
+ { url: "https://mxd.codes", label: "mxd.codes" },
+ { url: "https://openmaptiles.org/", label: "© OpenMapTiles" },
+ { url: "https://www.openstreetmap.org/copyright", label: "© OpenStreetMap contributors" }
+]
export interface ColotaMapRef {
camera: CameraRef | null
@@ -61,30 +45,43 @@ export const ColotaMapView = forwardRef<ColotaMapRef, Props>(function ColotaMapV
const { colors, mode } = useTheme()
const isDark = mode === "dark"
- const [darkStyle, setDarkStyle] = useState<object | null>(cachedDarkStyle)
+ const [mapStyleLight, setMapStyleLight] = useState(MAP_STYLE_URL_LIGHT)
+ const [mapStyleDark, setMapStyleDark] = useState(MAP_STYLE_URL_DARK)
const [heading, setHeading] = useState(0)
+ const isFocused = useIsFocused()
+
useEffect(() => {
- if (isDark && !darkStyle) {
- getDarkStyle().then((resolved) => {
- if (resolved) setDarkStyle(resolved)
+ if (!isFocused) return
+ Promise.all([
+ NativeLocationService.getSetting("mapStyleUrlLight"),
+ NativeLocationService.getSetting("mapStyleUrlDark")
+ ])
+ .then(([light, dark]) => {
+ setMapStyleLight(light || MAP_STYLE_URL_LIGHT)
+ setMapStyleDark(dark || MAP_STYLE_URL_DARK)
})
- }
- }, [isDark, darkStyle])
-
- useImperativeHandle(ref, () => ({
- get camera() {
- return cameraRef.current
- },
- get mapView() {
- return mapViewRef.current
- }
- }))
+ .catch(() => {})
+ }, [isFocused])
+
+ useImperativeHandle(
+ ref,
+ () => ({
+ get camera() {
+ return cameraRef.current
+ },
+ get mapView() {
+ return mapViewRef.current
+ }
+ }),
+ []
+ )
- const mapStyle = isDark && darkStyle ? darkStyle : OPENFREEMAP_STYLE
+ const mapStyle = isDark ? mapStyleDark : mapStyleLight
+ const isCustomStyle = mapStyleLight !== MAP_STYLE_URL_LIGHT || mapStyleDark !== MAP_STYLE_URL_DARK
const handleRegionDidChange = useCallback(
- (feature: any) => {
+ (feature: GeoJSON.Feature<GeoJSON.Point, RegionPayload>) => {
const props = feature.properties as RegionPayload & { isUserInteraction: boolean }
setHeading(props.heading ?? 0)
if (onRegionDidChange) {
@@ -104,6 +101,16 @@ export const ColotaMapView = forwardRef<ColotaMapRef, Props>(function ColotaMapV
}
}, [])
+ const handlePress = useCallback(
+ (feature: GeoJSON.Feature) => {
+ if (onPress && feature.geometry?.type === "Point") {
+ const [lon, lat] = (feature.geometry as GeoJSON.Point).coordinates
+ onPress({ latitude: lat, longitude: lon })
+ }
+ },
+ [onPress]
+ )
+
const showCompass = Math.abs(heading) > 3
return (
@@ -112,16 +119,11 @@ export const ColotaMapView = forwardRef<ColotaMapRef, Props>(function ColotaMapV
ref={mapViewRef}
style={styles.map}
mapStyle={mapStyle}
- attributionEnabled={false}
+ attributionEnabled={isCustomStyle}
logoEnabled={false}
compassEnabled={false}
onDidFinishLoadingMap={onMapReady}
- onPress={(feature) => {
- if (onPress && feature.geometry?.type === "Point") {
- const [lon, lat] = (feature.geometry as GeoJSON.Point).coordinates
- onPress({ latitude: lat, longitude: lon })
- }
- }}
+ onPress={onPress ? handlePress : undefined}
onRegionDidChange={handleRegionDidChange}
>
<Camera
@@ -151,22 +153,19 @@ export const ColotaMapView = forwardRef<ColotaMapRef, Props>(function ColotaMapV
</Pressable>
)}
- {/* Attribution */}
- <View style={[styles.attribution, { backgroundColor: colors.card + "CC" }]}>
- <Pressable
- onPress={() => Linking.openURL("https://openfreemap.org")}
- style={({ pressed }) => pressed && { opacity: 0.7 }}
- >
- <Text style={[styles.attributionText, { color: colors.link }, fonts.regular]}>OpenFreeMap</Text>
- </Pressable>
- <Text style={[styles.attributionSep, { color: colors.textLight }]}>{" | "}</Text>
- <Pressable
- onPress={() => Linking.openURL("https://www.openstreetmap.org/copyright")}
- style={({ pressed }) => pressed && { opacity: 0.7 }}
- >
- <Text style={[styles.attributionText, { color: colors.link }, fonts.regular]}>OSM</Text>
- </Pressable>
- </View>
+ {/* Attribution - custom overlay for default server, MapLibre built-in for custom styles */}
+ {!isCustomStyle && (
+ <View style={[styles.attribution, { backgroundColor: colors.card + "CC" }]}>
+ {DEFAULT_ATTRIBUTION_LINKS.map((link, i) => (
+ <React.Fragment key={link.url}>
+ {i > 0 && <Text style={[styles.attributionText, { color: colors.textLight }, fonts.regular]}> · </Text>}
+ <Pressable onPress={() => Linking.openURL(link.url)} style={({ pressed }) => pressed && { opacity: 0.7 }}>
+ <Text style={[styles.attributionText, { color: colors.link }, fonts.regular]}>{link.label}</Text>
+ </Pressable>
+ </React.Fragment>
+ ))}
+ </View>
+ )}
</View>
)
})
@@ -203,8 +202,5 @@ const styles = StyleSheet.create({
},
attributionText: {
fontSize: 10
- },
- attributionSep: {
- fontSize: 10
}
})
diff --git a/apps/mobile/src/components/features/map/OfflinePackManager.ts b/apps/mobile/src/components/features/map/OfflinePackManager.ts
new file mode 100644
index 00000000..9658aeb8
--- /dev/null
+++ b/apps/mobile/src/components/features/map/OfflinePackManager.ts
@@ -0,0 +1,217 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+import { OfflineManager } from "@maplibre/maplibre-react-native"
+import { MAP_STYLE_URL_LIGHT as MAP_STYLE_URL } from "../../../constants"
+import NativeLocationService from "../../../services/NativeLocationService"
+
+const MIN_ZOOM = 8
+const MAX_ZOOM = 14 // mxd.codes / OpenFreeMap caps vector tiles at z14
+const TILE_COUNT_LIMIT = 100_000
+
+// Per-zoom size buckets based on observed mxd.codes vector tile sizes.
+// Low-zoom tiles contain fewer features; high-zoom tiles grow significantly.
+function bytesPerTile(z: number): number {
+ if (z < 10) return 10 * 1024
+ if (z < 14) return 25 * 1024
+ return 50 * 1024
+}
+
+// state values from MapLibre's OfflinePackDownloadState
+export const DOWNLOAD_STATE = {
+ INACTIVE: 0,
+ ACTIVE: 1,
+ COMPLETE: 2,
+ FAILED: 3
+} as const
+
+export interface OfflinePackStatus {
+ state: number
+ percentage: number
+ completedResourceCount: number
+ requiredResourceCount: number
+ completedResourceSize: number
+}
+
+export interface OfflineAreaInfo {
+ name: string
+ sizeBytes: number | null
+ isComplete: boolean
+ isActive: boolean
+}
+
+function lonToTileX(lon: number, z: number): number {
+ return Math.floor(((lon + 180) / 360) * 2 ** z)
+}
+
+function latToTileY(lat: number, z: number): number {
+ const latRad = (lat * Math.PI) / 180
+ return Math.floor(((1 - Math.log(Math.tan(latRad) + 1 / Math.cos(latRad)) / Math.PI) / 2) * 2 ** z)
+}
+
+function estimateTileCount(ne: [number, number], sw: [number, number]): number {
+ const [eLon, nLat] = ne
+ const [wLon, sLat] = sw
+ let total = 0
+ for (let z = MIN_ZOOM; z <= MAX_ZOOM; z++) {
+ const xMin = lonToTileX(wLon, z)
+ const xMax = lonToTileX(eLon, z)
+ const yMin = latToTileY(nLat, z)
+ const yMax = latToTileY(sLat, z)
+ total += (xMax - xMin + 1) * (yMax - yMin + 1)
+ }
+ return total
+}
+
+/** Returns true if the area would hit the tile count cap, meaning coverage will be incomplete. */
+export function willExceedTileLimit(ne: [number, number], sw: [number, number]): boolean {
+ return estimateTileCount(ne, sw) >= TILE_COUNT_LIMIT
+}
+
+/** Returns the estimated download size in bytes, using per-zoom tile size buckets. */
+export function estimateSizeBytes(ne: [number, number], sw: [number, number]): number {
+ const [eLon, nLat] = ne
+ const [wLon, sLat] = sw
+ let remainingTiles = TILE_COUNT_LIMIT
+ let totalBytes = 0
+ for (let z = MIN_ZOOM; z <= MAX_ZOOM; z++) {
+ const tilesAtZ = Math.min(
+ (lonToTileX(eLon, z) - lonToTileX(wLon, z) + 1) * (latToTileY(sLat, z) - latToTileY(nLat, z) + 1),
+ remainingTiles
+ )
+ totalBytes += tilesAtZ * bytesPerTile(z)
+ remainingTiles -= tilesAtZ
+ if (remainingTiles <= 0) break
+ }
+ return totalBytes
+}
+
+/** Returns a human-readable estimated download size string (e.g. "~45 MB"). */
+export function estimateSizeLabel(ne: [number, number], sw: [number, number]): string {
+ const mb = estimateSizeBytes(ne, sw) / (1024 * 1024)
+ if (mb < 1) return `~${(mb * 1024).toFixed(0)} KB`
+ if (mb >= 1000) return `~${(mb / 1024).toFixed(1)} GB`
+ return `~${mb.toFixed(0)} MB`
+}
+
+export function formatBytes(bytes: number): string {
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
+}
+
+export async function createOfflinePack(
+ name: string,
+ ne: [number, number],
+ sw: [number, number],
+ onProgress: (status: OfflinePackStatus) => void,
+ onError: (err: unknown) => void
+): Promise<void> {
+ const existing = await OfflineManager.getPack(name)
+ if (existing) throw new Error(`An offline area named "${name}" already exists`)
+
+ const customStyleUrl = await NativeLocationService.getSetting("mapStyleUrlLight")
+ const styleURL = customStyleUrl || MAP_STYLE_URL
+
+ OfflineManager.setTileCountLimit(TILE_COUNT_LIMIT)
+
+ await OfflineManager.createPack(
+ { name, styleURL, minZoom: MIN_ZOOM, maxZoom: MAX_ZOOM, bounds: [ne, sw] },
+ (_pack: unknown, status: OfflinePackStatus) => onProgress(status),
+ (_pack: unknown, err: unknown) => onError(err)
+ )
+}
+
+export async function loadOfflineAreas(): Promise<OfflineAreaInfo[]> {
+ const packs = await OfflineManager.getPacks()
+
+ const namedPacks = packs.filter((p): p is typeof p & { name: string } => !!p.name)
+
+ return Promise.all(
+ namedPacks.map(async (pack) => {
+ try {
+ const status = await pack.status()
+ return {
+ name: pack.name,
+ sizeBytes: status?.completedResourceSize ?? null,
+ isComplete: status?.state === DOWNLOAD_STATE.COMPLETE,
+ isActive: status?.state === DOWNLOAD_STATE.ACTIVE
+ } satisfies OfflineAreaInfo
+ } catch {
+ return { name: pack.name, sizeBytes: null, isComplete: false, isActive: false } satisfies OfflineAreaInfo
+ }
+ })
+ )
+}
+
+/** Stops any active download for the pack and removes it and its tiles from disk. */
+export async function deleteOfflineArea(name: string): Promise<void> {
+ OfflineManager.unsubscribe(name)
+ const pack = await OfflineManager.getPack(name)
+ if (pack) {
+ try {
+ await pack.pause()
+ } catch {
+ // pack may already be inactive - proceed to delete
+ }
+ await OfflineManager.deletePack(name)
+ }
+
+ // SQLite does not shrink the database file when rows are deleted - freed pages
+ // stay allocated until the database is recreated. If this was the last pack,
+ // reset the database so the OS reclaims the storage space.
+ const remaining = await OfflineManager.getPacks()
+ if (remaining.length === 0) {
+ await OfflineManager.resetDatabase()
+ }
+}
+
+export function unsubscribeOfflinePack(name: string): void {
+ OfflineManager.unsubscribe(name)
+}
+
+// ---------------------------------------------------------------------------
+// Bounds persistence - stored as JSON in the settings table
+// ---------------------------------------------------------------------------
+
+const BOUNDS_KEY = "offline_area_bounds"
+
+export interface OfflineAreaBounds {
+ name: string
+ ne: [number, number] // [lon, lat]
+ sw: [number, number] // [lon, lat]
+ styleUrl?: string
+ downloadedAt?: number // Unix ms timestamp set when download starts
+}
+
+export async function loadOfflineAreaBounds(): Promise<OfflineAreaBounds[]> {
+ try {
+ const json = await NativeLocationService.getSetting(BOUNDS_KEY, "[]")
+ const parsed = JSON.parse(json ?? "[]") as unknown[]
+ // Filter out entries from the old schema (lat/lon/radiusMeters) that lack ne/sw
+ return parsed.filter(
+ (b): b is OfflineAreaBounds =>
+ typeof b === "object" &&
+ b !== null &&
+ "ne" in b &&
+ "sw" in b &&
+ Array.isArray((b as OfflineAreaBounds).ne) &&
+ Array.isArray((b as OfflineAreaBounds).sw)
+ )
+ } catch {
+ return []
+ }
+}
+
+export async function saveOfflineAreaBounds(entry: OfflineAreaBounds): Promise<void> {
+ const existing = await loadOfflineAreaBounds()
+ const updated = [...existing.filter((b) => b.name !== entry.name), entry]
+ await NativeLocationService.saveSetting(BOUNDS_KEY, JSON.stringify(updated))
+}
+
+export async function removeOfflineAreaBounds(name: string): Promise<void> {
+ const existing = await loadOfflineAreaBounds()
+ const updated = existing.filter((b) => b.name !== name)
+ await NativeLocationService.saveSetting(BOUNDS_KEY, JSON.stringify(updated))
+}
diff --git a/apps/mobile/src/components/features/map/__tests__/OfflinePackManager.test.ts b/apps/mobile/src/components/features/map/__tests__/OfflinePackManager.test.ts
new file mode 100644
index 00000000..65f3d13c
--- /dev/null
+++ b/apps/mobile/src/components/features/map/__tests__/OfflinePackManager.test.ts
@@ -0,0 +1,534 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+jest.mock("@maplibre/maplibre-react-native", () => ({
+ OfflineManager: {
+ createPack: jest.fn(),
+ getPacks: jest.fn(),
+ getPack: jest.fn(),
+ deletePack: jest.fn(),
+ setTileCountLimit: jest.fn(),
+ unsubscribe: jest.fn(),
+ resetDatabase: jest.fn()
+ }
+}))
+
+jest.mock("../../../../constants", () => ({
+ MAP_STYLE_URL_LIGHT: "https://tiles.example.com/style.json"
+}))
+
+jest.mock("../../../../services/NativeLocationService")
+
+import { OfflineManager } from "@maplibre/maplibre-react-native"
+import NativeLocationService from "../../../../services/NativeLocationService"
+import {
+ willExceedTileLimit,
+ estimateSizeLabel,
+ estimateSizeBytes,
+ formatBytes,
+ createOfflinePack,
+ loadOfflineAreas,
+ deleteOfflineArea,
+ loadOfflineAreaBounds,
+ saveOfflineAreaBounds,
+ removeOfflineAreaBounds,
+ unsubscribeOfflinePack,
+ DOWNLOAD_STATE
+} from "../OfflinePackManager"
+
+const mockOfflineManager = OfflineManager as jest.Mocked<typeof OfflineManager>
+const mockGetSetting = NativeLocationService.getSetting as jest.Mock
+const mockSaveSetting = NativeLocationService.saveSetting as jest.Mock
+
+// Bounding boxes [lon, lat] used across tests
+const TINY_NE: [number, number] = [0.001, 0.001] // ~100m box at equator
+const TINY_SW: [number, number] = [-0.001, -0.001]
+
+const SMALL_NE: [number, number] = [0.1, 0.1] // ~11km box at equator
+const SMALL_SW: [number, number] = [-0.1, -0.1]
+
+const LARGE_NE: [number, number] = [0.9, 0.9] // ~100km box - trail exceeds tile limit, road does not
+const LARGE_SW: [number, number] = [-0.9, -0.9]
+
+beforeEach(() => {
+ jest.clearAllMocks()
+})
+
+// ============================================================================
+// Constants / exports
+// ============================================================================
+
+describe("constants", () => {
+ it("DOWNLOAD_STATE has expected values", () => {
+ expect(DOWNLOAD_STATE.INACTIVE).toBe(0)
+ expect(DOWNLOAD_STATE.ACTIVE).toBe(1)
+ expect(DOWNLOAD_STATE.COMPLETE).toBe(2)
+ expect(DOWNLOAD_STATE.FAILED).toBe(3)
+ })
+})
+
+// ============================================================================
+// formatBytes
+// ============================================================================
+
+describe("formatBytes", () => {
+ it("formats bytes below 1MB as KB", () => {
+ expect(formatBytes(512 * 1024)).toBe("512.0 KB")
+ })
+
+ it("formats zero bytes as KB", () => {
+ expect(formatBytes(0)).toBe("0.0 KB")
+ })
+
+ it("formats 1MB as MB", () => {
+ expect(formatBytes(1024 * 1024)).toBe("1.0 MB")
+ })
+
+ it("formats 1.5MB correctly", () => {
+ expect(formatBytes(1.5 * 1024 * 1024)).toBe("1.5 MB")
+ })
+
+ it("formats large values as MB", () => {
+ expect(formatBytes(250 * 1024 * 1024)).toBe("250.0 MB")
+ })
+
+ it("threshold is exactly 1MB - values below are KB, at or above are MB", () => {
+ expect(formatBytes(1024 * 1024 - 1)).toMatch(/KB$/)
+ expect(formatBytes(1024 * 1024)).toMatch(/MB$/)
+ })
+})
+
+// ============================================================================
+// willExceedTileLimit
+// ============================================================================
+
+describe("willExceedTileLimit", () => {
+ it("returns false for a tiny area", () => {
+ expect(willExceedTileLimit(TINY_NE, TINY_SW)).toBe(false)
+ })
+
+ it("returns false for a small area", () => {
+ expect(willExceedTileLimit(SMALL_NE, SMALL_SW)).toBe(false)
+ })
+
+ it("returns false for a large (~100km) area - z8-14 stays under 100k tiles", () => {
+ expect(willExceedTileLimit(LARGE_NE, LARGE_SW)).toBe(false)
+ })
+
+ it("returns true for a world-spanning area", () => {
+ expect(willExceedTileLimit([180, 85], [-180, -85])).toBe(true)
+ })
+})
+
+// ============================================================================
+// estimateSizeBytes
+// ============================================================================
+
+describe("estimateSizeBytes", () => {
+ it("returns a positive number for any non-zero area", () => {
+ expect(estimateSizeBytes(SMALL_NE, SMALL_SW)).toBeGreaterThan(0)
+ })
+
+ it("larger area produces more bytes", () => {
+ const small = estimateSizeBytes(SMALL_NE, SMALL_SW)
+ const large = estimateSizeBytes(LARGE_NE, LARGE_SW)
+ expect(large).toBeGreaterThan(small)
+ })
+
+ it("is capped at TILE_COUNT_LIMIT tiles", () => {
+ // Max possible: all 100k tiles at the highest bucket (50 KB/tile for z >= 14)
+ const cap = 100_000 * 50 * 1024
+ expect(estimateSizeBytes([180, 85], [-180, -85])).toBeLessThanOrEqual(cap)
+ })
+
+ it("size is consistent with estimateSizeLabel units", () => {
+ const bytes = estimateSizeBytes(SMALL_NE, SMALL_SW)
+ const mb = bytes / (1024 * 1024)
+ const label = estimateSizeLabel(SMALL_NE, SMALL_SW)
+ if (mb < 1) {
+ expect(label).toMatch(/KB$/)
+ } else if (mb < 1000) {
+ expect(label).toMatch(/MB$/)
+ } else {
+ expect(label).toMatch(/GB$/)
+ }
+ })
+})
+
+// ============================================================================
+// estimateSizeLabel
+// ============================================================================
+
+describe("estimateSizeLabel", () => {
+ it("returns a string starting with ~", () => {
+ expect(estimateSizeLabel(SMALL_NE, SMALL_SW)).toMatch(/^~/)
+ })
+
+ it("returns KB for very small areas", () => {
+ expect(estimateSizeLabel(TINY_NE, TINY_SW)).toMatch(/KB$/)
+ })
+
+ it("larger area produces a larger numeric value in the label", () => {
+ const parseLabel = (s: string) => {
+ const m = s.match(/~([\d.]+)\s*(KB|MB|GB)/)
+ if (!m) return 0
+ const v = parseFloat(m[1])
+ if (m[2] === "KB") return v
+ if (m[2] === "MB") return v * 1024
+ return v * 1024 * 1024
+ }
+ expect(parseLabel(estimateSizeLabel(LARGE_NE, LARGE_SW))).toBeGreaterThan(
+ parseLabel(estimateSizeLabel(SMALL_NE, SMALL_SW))
+ )
+ })
+
+ it("label has valid format", () => {
+ expect(estimateSizeLabel(LARGE_NE, LARGE_SW)).toMatch(/^~[\d.]+ (KB|MB|GB)$/)
+ })
+
+ it("label for a capped area is bounded and does not grow with area size", () => {
+ // With per-zoom bucketing, two capped areas may produce different estimates
+ // (a vastly larger area burns the budget at cheaper low-zoom tiles).
+ // The invariant is that both are bounded, not that they're equal.
+ const wayOverNE: [number, number] = [180, 85]
+ const wayOverSW: [number, number] = [-180, -85]
+ expect(estimateSizeLabel(LARGE_NE, LARGE_SW)).toMatch(/^~[\d.]+ (KB|MB|GB)$/)
+ expect(estimateSizeLabel(wayOverNE, wayOverSW)).toMatch(/^~[\d.]+ (KB|MB|GB)$/)
+ })
+})
+
+// ============================================================================
+// createOfflinePack
+// ============================================================================
+
+describe("createOfflinePack", () => {
+ beforeEach(() => {
+ mockOfflineManager.getPack.mockResolvedValue(null as never)
+ mockGetSetting.mockResolvedValue(null)
+ })
+
+ it("throws if a pack with the same name already exists", async () => {
+ mockOfflineManager.getPack.mockResolvedValueOnce({ name: "existing" } as never)
+ await expect(createOfflinePack("existing", SMALL_NE, SMALL_SW, jest.fn(), jest.fn())).rejects.toThrow(
+ 'An offline area named "existing" already exists'
+ )
+ expect(mockOfflineManager.createPack).not.toHaveBeenCalled()
+ })
+
+ it("calls OfflineManager.setTileCountLimit before creating pack", async () => {
+ mockOfflineManager.createPack.mockResolvedValueOnce(undefined as never)
+ await createOfflinePack("test", SMALL_NE, SMALL_SW, jest.fn(), jest.fn())
+ expect(mockOfflineManager.setTileCountLimit).toHaveBeenCalledWith(100_000)
+ expect((mockOfflineManager.setTileCountLimit as jest.Mock).mock.invocationCallOrder[0]).toBeLessThan(
+ (mockOfflineManager.createPack as jest.Mock).mock.invocationCallOrder[0]
+ )
+ })
+
+ it("uses default style URL when no custom URL is configured", async () => {
+ mockOfflineManager.createPack.mockResolvedValueOnce(undefined as never)
+ await createOfflinePack("my-area", SMALL_NE, SMALL_SW, jest.fn(), jest.fn())
+ expect(mockOfflineManager.createPack).toHaveBeenCalledWith(
+ expect.objectContaining({
+ name: "my-area",
+ styleURL: "https://tiles.example.com/style.json",
+ minZoom: 8,
+ maxZoom: 14,
+ bounds: expect.any(Array)
+ }),
+ expect.any(Function),
+ expect.any(Function)
+ )
+ })
+
+ it("uses custom style URL from settings when configured", async () => {
+ mockGetSetting.mockResolvedValueOnce("https://my-server.com/style.json")
+ mockOfflineManager.createPack.mockResolvedValueOnce(undefined as never)
+ await createOfflinePack("my-area", SMALL_NE, SMALL_SW, jest.fn(), jest.fn())
+ expect(mockOfflineManager.createPack).toHaveBeenCalledWith(
+ expect.objectContaining({ styleURL: "https://my-server.com/style.json" }),
+ expect.any(Function),
+ expect.any(Function)
+ )
+ })
+
+ it("invokes onProgress callback when OfflineManager progress fires", async () => {
+ const onProgress = jest.fn()
+ mockOfflineManager.createPack.mockImplementationOnce((_opts: unknown, progressCb: Function) => {
+ progressCb(null, {
+ state: 1,
+ percentage: 50,
+ completedResourceCount: 50,
+ requiredResourceCount: 100,
+ completedResourceSize: 25600
+ })
+ return Promise.resolve()
+ })
+ await createOfflinePack("test", SMALL_NE, SMALL_SW, onProgress, jest.fn())
+ expect(onProgress).toHaveBeenCalledWith(expect.objectContaining({ state: 1, percentage: 50 }))
+ })
+
+ it("invokes onError callback when OfflineManager error fires", async () => {
+ const onError = jest.fn()
+ mockOfflineManager.createPack.mockImplementationOnce((_opts: unknown, _progressCb: Function, errorCb: Function) => {
+ errorCb(null, new Error("tile limit exceeded"))
+ return Promise.resolve()
+ })
+ await createOfflinePack("test", SMALL_NE, SMALL_SW, jest.fn(), onError)
+ expect(onError).toHaveBeenCalledWith(expect.any(Error))
+ })
+})
+
+// ============================================================================
+// loadOfflineAreas
+// ============================================================================
+
+describe("loadOfflineAreas", () => {
+ it("returns empty array when no packs exist", async () => {
+ mockOfflineManager.getPacks.mockResolvedValueOnce([] as never)
+ expect(await loadOfflineAreas()).toEqual([])
+ })
+
+ it("filters out packs without a name", async () => {
+ mockOfflineManager.getPacks.mockResolvedValueOnce([
+ { name: undefined, status: jest.fn().mockResolvedValue({ state: 2, completedResourceSize: 1024 }) },
+ { name: "valid-area", status: jest.fn().mockResolvedValue({ state: 2, completedResourceSize: 2048 }) }
+ ] as never)
+ const areas = await loadOfflineAreas()
+ expect(areas).toHaveLength(1)
+ expect(areas[0].name).toBe("valid-area")
+ })
+
+ it("maps complete pack status correctly", async () => {
+ mockOfflineManager.getPacks.mockResolvedValueOnce([
+ {
+ name: "downtown",
+ status: jest.fn().mockResolvedValue({ state: DOWNLOAD_STATE.COMPLETE, completedResourceSize: 5_000_000 })
+ }
+ ] as never)
+ expect(await loadOfflineAreas()).toEqual([
+ { name: "downtown", sizeBytes: 5_000_000, isComplete: true, isActive: false }
+ ])
+ })
+
+ it("maps active pack status correctly", async () => {
+ mockOfflineManager.getPacks.mockResolvedValueOnce([
+ {
+ name: "in-progress",
+ status: jest.fn().mockResolvedValue({ state: DOWNLOAD_STATE.ACTIVE, completedResourceSize: 1_000_000 })
+ }
+ ] as never)
+ expect(await loadOfflineAreas()).toEqual([
+ { name: "in-progress", sizeBytes: 1_000_000, isComplete: false, isActive: true }
+ ])
+ })
+
+ it("handles status() throwing - returns null sizeBytes and false flags", async () => {
+ mockOfflineManager.getPacks.mockResolvedValueOnce([
+ { name: "broken-pack", status: jest.fn().mockRejectedValue(new Error("status unavailable")) }
+ ] as never)
+ expect(await loadOfflineAreas()).toEqual([
+ { name: "broken-pack", sizeBytes: null, isComplete: false, isActive: false }
+ ])
+ })
+
+ it("handles null completedResourceSize as null sizeBytes", async () => {
+ mockOfflineManager.getPacks.mockResolvedValueOnce([
+ { name: "partial", status: jest.fn().mockResolvedValue({ state: DOWNLOAD_STATE.INACTIVE }) }
+ ] as never)
+ expect((await loadOfflineAreas())[0].sizeBytes).toBeNull()
+ })
+})
+
+// ============================================================================
+// deleteOfflineArea
+// ============================================================================
+
+describe("deleteOfflineArea", () => {
+ it("unsubscribes, pauses, and deletes pack", async () => {
+ const mockPause = jest.fn().mockResolvedValue(undefined)
+ mockOfflineManager.getPack.mockResolvedValueOnce({ pause: mockPause } as never)
+ mockOfflineManager.deletePack.mockResolvedValueOnce(undefined as never)
+ mockOfflineManager.getPacks.mockResolvedValueOnce([{ name: "other-area" }] as never)
+
+ await deleteOfflineArea("my-area")
+
+ expect(mockOfflineManager.unsubscribe).toHaveBeenCalledWith("my-area")
+ expect(mockPause).toHaveBeenCalled()
+ expect(mockOfflineManager.deletePack).toHaveBeenCalledWith("my-area")
+ expect(mockOfflineManager.resetDatabase).not.toHaveBeenCalled()
+ })
+
+ it("resets database when last pack is deleted", async () => {
+ const mockPause = jest.fn().mockResolvedValue(undefined)
+ mockOfflineManager.getPack.mockResolvedValueOnce({ pause: mockPause } as never)
+ mockOfflineManager.deletePack.mockResolvedValueOnce(undefined as never)
+ mockOfflineManager.getPacks.mockResolvedValueOnce([] as never)
+ mockOfflineManager.resetDatabase.mockResolvedValueOnce(undefined as never)
+
+ await deleteOfflineArea("last-area")
+
+ expect(mockOfflineManager.deletePack).toHaveBeenCalledWith("last-area")
+ expect(mockOfflineManager.resetDatabase).toHaveBeenCalled()
+ })
+
+ it("skips pause if pack is already inactive (pause throws) but still deletes", async () => {
+ const mockPause = jest.fn().mockRejectedValue(new Error("not active"))
+ mockOfflineManager.getPack.mockResolvedValueOnce({ pause: mockPause } as never)
+ mockOfflineManager.deletePack.mockResolvedValueOnce(undefined as never)
+ mockOfflineManager.getPacks.mockResolvedValueOnce([] as never)
+ mockOfflineManager.resetDatabase.mockResolvedValueOnce(undefined as never)
+
+ await expect(deleteOfflineArea("inactive-area")).resolves.toBeUndefined()
+ expect(mockOfflineManager.deletePack).toHaveBeenCalledWith("inactive-area")
+ })
+
+ it("skips delete if pack does not exist", async () => {
+ mockOfflineManager.getPack.mockResolvedValueOnce(null as never)
+ mockOfflineManager.getPacks.mockResolvedValueOnce([] as never)
+ mockOfflineManager.resetDatabase.mockResolvedValueOnce(undefined as never)
+
+ await deleteOfflineArea("missing-area")
+
+ expect(mockOfflineManager.deletePack).not.toHaveBeenCalled()
+ })
+})
+
+// ============================================================================
+// unsubscribeOfflinePack
+// ============================================================================
+
+describe("unsubscribeOfflinePack", () => {
+ it("calls OfflineManager.unsubscribe with the pack name", () => {
+ unsubscribeOfflinePack("some-area")
+ expect(mockOfflineManager.unsubscribe).toHaveBeenCalledWith("some-area")
+ })
+})
+
+// ============================================================================
+// loadOfflineAreaBounds
+// ============================================================================
+
+describe("loadOfflineAreaBounds", () => {
+ it("returns parsed bounds from settings", async () => {
+ const stored = [{ name: "home", ne: [13.41, 52.51], sw: [13.4, 52.5] }]
+ mockGetSetting.mockResolvedValueOnce(JSON.stringify(stored))
+ expect(await loadOfflineAreaBounds()).toEqual(stored)
+ })
+
+ it("returns empty array when setting is empty JSON array", async () => {
+ mockGetSetting.mockResolvedValueOnce("[]")
+ expect(await loadOfflineAreaBounds()).toEqual([])
+ })
+
+ it("returns empty array when setting is null", async () => {
+ mockGetSetting.mockResolvedValueOnce(null)
+ expect(await loadOfflineAreaBounds()).toEqual([])
+ })
+
+ it("returns empty array when JSON is malformed", async () => {
+ mockGetSetting.mockResolvedValueOnce("{invalid json")
+ expect(await loadOfflineAreaBounds()).toEqual([])
+ })
+
+ it("returns empty array when getSetting throws", async () => {
+ mockGetSetting.mockRejectedValueOnce(new Error("db error"))
+ expect(await loadOfflineAreaBounds()).toEqual([])
+ })
+
+ it("filters out old-schema entries with lat/lon/radiusMeters instead of ne/sw", async () => {
+ const mixed = [
+ { name: "old-entry", lat: 52.5, lon: 13.4, radiusMeters: 5000 },
+ { name: "new-entry", ne: [13.41, 52.51], sw: [13.4, 52.5] }
+ ]
+ mockGetSetting.mockResolvedValueOnce(JSON.stringify(mixed))
+ const result = await loadOfflineAreaBounds()
+ expect(result).toHaveLength(1)
+ expect(result[0].name).toBe("new-entry")
+ })
+})
+
+// ============================================================================
+// saveOfflineAreaBounds
+// ============================================================================
+
+describe("saveOfflineAreaBounds", () => {
+ it("appends a new entry when it does not exist", async () => {
+ const existing = [{ name: "park", ne: [2.31, 48.81], sw: [2.3, 48.8] }]
+ mockGetSetting.mockResolvedValueOnce(JSON.stringify(existing))
+ mockSaveSetting.mockResolvedValueOnce(undefined)
+
+ const newEntry = { name: "city", ne: [13.41, 52.51] as [number, number], sw: [13.4, 52.5] as [number, number] }
+ await saveOfflineAreaBounds(newEntry)
+
+ const saved = JSON.parse(mockSaveSetting.mock.calls[0][1])
+ expect(saved).toHaveLength(2)
+ expect(saved).toContainEqual(newEntry)
+ expect(saved).toContainEqual(existing[0])
+ })
+
+ it("replaces an existing entry with the same name", async () => {
+ const old = { name: "home", ne: [13.4, 52.5], sw: [13.39, 52.49] }
+ mockGetSetting.mockResolvedValueOnce(JSON.stringify([old]))
+ mockSaveSetting.mockResolvedValueOnce(undefined)
+
+ const updated = { name: "home", ne: [13.41, 52.51] as [number, number], sw: [13.4, 52.5] as [number, number] }
+ await saveOfflineAreaBounds(updated)
+
+ const saved = JSON.parse(mockSaveSetting.mock.calls[0][1])
+ expect(saved).toHaveLength(1)
+ expect(saved[0]).toEqual(updated)
+ })
+
+ it("saves using the correct settings key", async () => {
+ mockGetSetting.mockResolvedValueOnce("[]")
+ mockSaveSetting.mockResolvedValueOnce(undefined)
+
+ await saveOfflineAreaBounds({ name: "x", ne: [0.1, 0.1], sw: [-0.1, -0.1] })
+
+ expect(mockSaveSetting).toHaveBeenCalledWith("offline_area_bounds", expect.any(String))
+ })
+})
+
+// ============================================================================
+// removeOfflineAreaBounds
+// ============================================================================
+
+describe("removeOfflineAreaBounds", () => {
+ it("removes the named entry and saves the rest", async () => {
+ const entries = [
+ { name: "home", ne: [13.41, 52.51], sw: [13.4, 52.5] },
+ { name: "work", ne: [13.51, 52.61], sw: [13.5, 52.6] }
+ ]
+ mockGetSetting.mockResolvedValueOnce(JSON.stringify(entries))
+ mockSaveSetting.mockResolvedValueOnce(undefined)
+
+ await removeOfflineAreaBounds("home")
+
+ const saved = JSON.parse(mockSaveSetting.mock.calls[0][1])
+ expect(saved).toHaveLength(1)
+ expect(saved[0].name).toBe("work")
+ })
+
+ it("is a no-op when the name does not exist", async () => {
+ const entries = [{ name: "park", ne: [2.31, 48.81], sw: [2.3, 48.8] }]
+ mockGetSetting.mockResolvedValueOnce(JSON.stringify(entries))
+ mockSaveSetting.mockResolvedValueOnce(undefined)
+
+ await removeOfflineAreaBounds("nonexistent")
+
+ const saved = JSON.parse(mockSaveSetting.mock.calls[0][1])
+ expect(saved).toHaveLength(1)
+ })
+
+ it("saves an empty array when the only entry is removed", async () => {
+ const entries = [{ name: "solo", ne: [0.1, 0.1], sw: [-0.1, -0.1] }]
+ mockGetSetting.mockResolvedValueOnce(JSON.stringify(entries))
+ mockSaveSetting.mockResolvedValueOnce(undefined)
+
+ await removeOfflineAreaBounds("solo")
+
+ expect(JSON.parse(mockSaveSetting.mock.calls[0][1])).toEqual([])
+ })
+})
diff --git a/apps/mobile/src/components/features/settings/PresetOption.tsx b/apps/mobile/src/components/features/settings/PresetOption.tsx
index 54395d6b..9ece8fda 100644
--- a/apps/mobile/src/components/features/settings/PresetOption.tsx
+++ b/apps/mobile/src/components/features/settings/PresetOption.tsx
@@ -2,23 +2,39 @@
* 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, StyleSheet, Pressable } from "react-native"
import { Zap, Check } from "lucide-react-native"
import { SelectablePreset, TRACKING_PRESETS } from "../../../types/global"
import { fonts } from "../../../styles/typography"
import { useTheme } from "../../../hooks/useTheme"
-import { useTracking } from "../../../contexts/TrackingProvider"
import { RadioDot } from "../../ui/RadioDot"
+interface BadgeProps {
+ icon: React.ReactElement
+ label: string
+ color: string
+}
+
+function Badge({ icon, label, color }: BadgeProps) {
+ return (
+ <View style={[styles.badge, { backgroundColor: color + "20", borderColor: color + "40" }]}>
+ <View style={styles.badgeContent}>
+ {icon}
+ <Text style={[styles.badgeText, { color }]}>{label}</Text>
+ </View>
+ </View>
+ )
+}
+
interface PresetOptionProps {
preset: SelectablePreset
isSelected: boolean
+ isOfflineMode: boolean
onSelect: (preset: SelectablePreset) => void
}
-export function PresetOption({ preset, isSelected, onSelect }: PresetOptionProps) {
- const { settings } = useTracking()
- const isOfflineMode = settings.isOfflineMode
+export function PresetOption({ preset, isSelected, isOfflineMode, onSelect }: PresetOptionProps) {
const { colors } = useTheme()
const config = TRACKING_PRESETS[preset]
const showRecommendedBadge = preset === "balanced"
@@ -26,11 +42,7 @@ export function PresetOption({ preset, isSelected, onSelect }: PresetOptionProps
return (
<Pressable
- style={({ pressed }) => [
- styles.container,
- { backgroundColor: isSelected ? colors.primary + "12" : colors.background },
- pressed && { opacity: 0.7 }
- ]}
+ style={({ pressed }) => [pressed && { opacity: 0.7 }]}
onPress={() => onSelect(preset)}
accessibilityRole="radio"
accessibilityState={{ checked: isSelected }}
@@ -39,38 +51,23 @@ export function PresetOption({ preset, isSelected, onSelect }: PresetOptionProps
<View style={styles.leftContent}>
<View style={styles.textContent}>
<View style={styles.titleRow}>
- <Text style={[styles.label, { color: colors.text }]}>{config.label}</Text>
+ <Text
+ style={[
+ styles.label,
+ isSelected ? { color: colors.primaryDark, ...fonts.bold } : { color: colors.text }
+ ]}
+ >
+ {config.label}
+ </Text>
{showRecommendedBadge && (
- <View
- style={[
- styles.badge,
- {
- backgroundColor: colors.success + "20",
- borderColor: colors.success + "40"
- }
- ]}
- >
- <View style={styles.badgeContent}>
- <Check size={10} color={colors.success} />
- <Text style={[styles.badgeText, { color: colors.success }]}>Recommended</Text>
- </View>
- </View>
+ <Badge icon={<Check size={10} color={colors.success} />} label="Recommended" color={colors.success} />
)}
{showWarningBadge && (
- <View
- style={[
- styles.badge,
- {
- backgroundColor: colors.warning + "20",
- borderColor: colors.warning + "40"
- }
- ]}
- >
- <View style={styles.badgeContent}>
- <Zap size={10} color={colors.warning} />
- <Text style={[styles.badgeText, { color: colors.warning }]}>High Battery Usage</Text>
- </View>
- </View>
+ <Badge
+ icon={<Zap size={10} color={colors.warning} />}
+ label="High Battery Usage"
+ color={colors.warning}
+ />
)}
</View>
<Text style={[styles.description, { color: colors.textSecondary }]}>
@@ -86,22 +83,13 @@ export function PresetOption({ preset, isSelected, onSelect }: PresetOptionProps
}
const styles = StyleSheet.create({
- container: {
- borderRadius: 12,
- overflow: "hidden",
- marginBottom: 8
- },
content: {
flexDirection: "row",
alignItems: "center",
- padding: 16,
- paddingLeft: 20
+ padding: 12
},
leftContent: {
- flex: 1,
- flexDirection: "row",
- alignItems: "center",
- gap: 14
+ flex: 1
},
textContent: {
flex: 1
diff --git a/apps/mobile/src/components/features/settings/SyncStrategySettings.tsx b/apps/mobile/src/components/features/settings/SyncStrategySettings.tsx
index 865d32e3..46945249 100644
--- a/apps/mobile/src/components/features/settings/SyncStrategySettings.tsx
+++ b/apps/mobile/src/components/features/settings/SyncStrategySettings.tsx
@@ -5,8 +5,8 @@
import React, { useState, useCallback, useEffect } from "react"
import { Text, StyleSheet, Switch, View, Pressable } from "react-native"
-import { Lightbulb } from "lucide-react-native"
-import { Settings, TRACKING_PRESETS, SyncPreset, SelectablePreset, ThemeColors } from "../../../types/global"
+import { Lightbulb, ChevronDown, ChevronUp } from "lucide-react-native"
+import { Settings, TRACKING_PRESETS, SelectablePreset, ThemeColors } from "../../../types/global"
import { fonts, fontSizes } from "../../../styles/typography"
import { SYNC_INTERVAL_PRESETS, SYNC_INTERVAL_LABELS } from "../../../constants"
import { SectionTitle, Card, Divider, NumericInput, SettingRow } from "../../index"
@@ -84,14 +84,7 @@ export function SyncStrategySettings({
)
const handlePresetSelect = useCallback(
- (preset: SyncPreset) => {
- if (preset === "custom") {
- const next = { ...settings, syncPreset: "custom" as const }
- onSettingsChange(next)
- onImmediateSave(next)
- return
- }
-
+ (preset: SelectablePreset) => {
const config = TRACKING_PRESETS[preset]
const next: Settings = {
...settings,
@@ -128,22 +121,28 @@ export function SyncStrategySettings({
{(Object.keys(TRACKING_PRESETS) as SelectablePreset[]).map((preset, index) => (
<View key={preset}>
{index > 0 && <View style={styles.presetSpacer} />}
- <PresetOption preset={preset} isSelected={settings.syncPreset === preset} onSelect={handlePresetSelect} />
+ <PresetOption
+ preset={preset}
+ isSelected={settings.syncPreset === preset}
+ isOfflineMode={settings.isOfflineMode}
+ onSelect={handlePresetSelect}
+ />
</View>
))}
</View>
+ <Divider />
+
<Pressable
- style={({ pressed }) => [
- styles.advancedToggle,
- { borderColor: showAdvanced ? colors.primary : colors.border },
- pressed && { opacity: 0.7 }
- ]}
+ style={({ pressed }) => [styles.advancedToggle, pressed && { opacity: 0.6 }]}
onPress={() => setShowAdvanced(!showAdvanced)}
>
- <Text style={[styles.advancedText, { color: colors.primaryDark }]}>
- {showAdvanced ? "− Hide" : "+ Show"} Advanced Settings
- </Text>
+ <Text style={[styles.advancedText, { color: colors.text }]}>Advanced Settings</Text>
+ {showAdvanced ? (
+ <ChevronUp size={20} color={colors.textLight} />
+ ) : (
+ <ChevronDown size={20} color={colors.textLight} />
+ )}
</Pressable>
{showAdvanced && (
@@ -420,15 +419,13 @@ const styles = StyleSheet.create({
height: 8
},
advancedToggle: {
- paddingVertical: 14,
- paddingHorizontal: 16,
+ flexDirection: "row",
+ justifyContent: "space-between",
alignItems: "center",
- borderRadius: 12,
- borderWidth: 1.5,
- marginTop: 16
+ paddingVertical: 12
},
advancedText: {
- fontSize: 15,
+ fontSize: 16,
...fonts.semiBold
},
advancedPanel: {
diff --git a/apps/mobile/src/components/features/settings/__tests__/PresetOption.test.tsx b/apps/mobile/src/components/features/settings/__tests__/PresetOption.test.tsx
index edfd0f20..e65c89cf 100644
--- a/apps/mobile/src/components/features/settings/__tests__/PresetOption.test.tsx
+++ b/apps/mobile/src/components/features/settings/__tests__/PresetOption.test.tsx
@@ -2,14 +2,6 @@ import React from "react"
import { render, fireEvent } from "@testing-library/react-native"
import { TRACKING_PRESETS } from "../../../../types/global"
-let mockSettings = { isOfflineMode: false }
-
-jest.mock("../../../../contexts/TrackingProvider", () => ({
- useTracking: () => ({
- settings: mockSettings
- })
-}))
-
jest.mock("../../../../hooks/useTheme", () => ({
useTheme: () => ({
colors: {
@@ -49,25 +41,29 @@ describe("PresetOption", () => {
beforeEach(() => {
jest.clearAllMocks()
- mockSettings = { isOfflineMode: false }
})
it("renders preset label and description", () => {
- const { getByText } = render(<PresetOption preset="balanced" isSelected={false} onSelect={mockOnSelect} />)
+ const { getByText } = render(
+ <PresetOption preset="balanced" isSelected={false} isOfflineMode={false} onSelect={mockOnSelect} />
+ )
expect(getByText(TRACKING_PRESETS.balanced.label)).toBeTruthy()
expect(getByText(TRACKING_PRESETS.balanced.description)).toBeTruthy()
})
it("shows offline description when isOfflineMode is true", () => {
- mockSettings = { isOfflineMode: true }
- const { getByText } = render(<PresetOption preset="balanced" isSelected={false} onSelect={mockOnSelect} />)
+ const { getByText } = render(
+ <PresetOption preset="balanced" isSelected={false} isOfflineMode={true} onSelect={mockOnSelect} />
+ )
expect(getByText(TRACKING_PRESETS.balanced.description.split(" • ")[0])).toBeTruthy()
})
it("calls onSelect with preset when pressed", () => {
- const { getByRole } = render(<PresetOption preset="instant" isSelected={false} onSelect={mockOnSelect} />)
+ const { getByRole } = render(
+ <PresetOption preset="instant" isSelected={false} isOfflineMode={false} onSelect={mockOnSelect} />
+ )
fireEvent.press(getByRole("radio"))
@@ -75,25 +71,33 @@ describe("PresetOption", () => {
})
it("shows selected radio dot when isSelected", () => {
- const { getByTestId } = render(<PresetOption preset="balanced" isSelected onSelect={mockOnSelect} />)
+ const { getByTestId } = render(
+ <PresetOption preset="balanced" isSelected isOfflineMode={false} onSelect={mockOnSelect} />
+ )
expect(getByTestId("radio-selected")).toBeTruthy()
})
it("shows unselected radio dot when not selected", () => {
- const { getByTestId } = render(<PresetOption preset="balanced" isSelected={false} onSelect={mockOnSelect} />)
+ const { getByTestId } = render(
+ <PresetOption preset="balanced" isSelected={false} isOfflineMode={false} onSelect={mockOnSelect} />
+ )
expect(getByTestId("radio-unselected")).toBeTruthy()
})
it("shows Recommended badge for balanced preset", () => {
- const { getByText } = render(<PresetOption preset="balanced" isSelected={false} onSelect={mockOnSelect} />)
+ const { getByText } = render(
+ <PresetOption preset="balanced" isSelected={false} isOfflineMode={false} onSelect={mockOnSelect} />
+ )
expect(getByText("Recommended")).toBeTruthy()
})
it("shows High Battery Usage badge for instant preset", () => {
- const { getByText } = render(<PresetOption preset="instant" isSelected={false} onSelect={mockOnSelect} />)
+ const { getByText } = render(
+ <PresetOption preset="instant" isSelected={false} isOfflineMode={false} onSelect={mockOnSelect} />
+ )
expect(getByText("High Battery Usage")).toBeTruthy()
})
diff --git a/apps/mobile/src/components/features/settings/__tests__/SyncStrategySettings.test.tsx b/apps/mobile/src/components/features/settings/__tests__/SyncStrategySettings.test.tsx
index 7c9123a6..3d0b2804 100644
--- a/apps/mobile/src/components/features/settings/__tests__/SyncStrategySettings.test.tsx
+++ b/apps/mobile/src/components/features/settings/__tests__/SyncStrategySettings.test.tsx
@@ -152,7 +152,7 @@ describe("SyncStrategySettings", () => {
expect(queryByText("Tracking Parameters")).toBeNull()
- fireEvent.press(getByText("+ Show Advanced Settings"))
+ fireEvent.press(getByText("Advanced Settings"))
expect(getByText("Tracking Parameters")).toBeTruthy()
expect(getByText("Network Settings")).toBeTruthy()
@@ -161,10 +161,10 @@ describe("SyncStrategySettings", () => {
it("hides advanced settings when toggle is pressed again", () => {
const { getByText, queryByText } = renderComponent()
- fireEvent.press(getByText("+ Show Advanced Settings"))
+ fireEvent.press(getByText("Advanced Settings"))
expect(getByText("Tracking Parameters")).toBeTruthy()
- fireEvent.press(getByText("− Hide Advanced Settings"))
+ fireEvent.press(getByText("Advanced Settings"))
expect(queryByText("Tracking Parameters")).toBeNull()
})
})
@@ -173,7 +173,7 @@ describe("SyncStrategySettings", () => {
it("shows custom configuration banner when preset is custom", () => {
const { getByText } = renderComponent({ syncPreset: "custom" })
- fireEvent.press(getByText("+ Show Advanced Settings"))
+ fireEvent.press(getByText("Advanced Settings"))
expect(getByText("Using custom configuration")).toBeTruthy()
})
@@ -181,7 +181,7 @@ describe("SyncStrategySettings", () => {
it("does not show custom banner when a named preset is selected", () => {
const { getByText, queryByText } = renderComponent({ syncPreset: "instant" })
- fireEvent.press(getByText("+ Show Advanced Settings"))
+ fireEvent.press(getByText("Advanced Settings"))
expect(queryByText("Using custom configuration")).toBeNull()
})
@@ -191,7 +191,7 @@ describe("SyncStrategySettings", () => {
it("renders all sync interval options inline", () => {
const { getByText, getAllByText } = renderComponent()
- fireEvent.press(getByText("+ Show Advanced Settings"))
+ fireEvent.press(getByText("Advanced Settings"))
expect(getAllByText("Instant").length).toBeGreaterThan(0)
expect(getByText("1 min")).toBeTruthy()
@@ -203,7 +203,7 @@ describe("SyncStrategySettings", () => {
it("selecting a sync interval sets preset to custom", () => {
const { getByText } = renderComponent()
- fireEvent.press(getByText("+ Show Advanced Settings"))
+ fireEvent.press(getByText("Advanced Settings"))
fireEvent.press(getByText("5 min"))
expect(mockOnSettingsChange).toHaveBeenCalledWith(
@@ -225,7 +225,7 @@ describe("SyncStrategySettings", () => {
it("shows delete hint when maxRetries is 5 (default)", () => {
const { getByText } = renderComponent({ maxRetries: 5 })
- fireEvent.press(getByText("+ Show Advanced Settings"))
+ fireEvent.press(getByText("Advanced Settings"))
expect(getByText("Failed uploads are permanently deleted after 5 failed send attempts")).toBeTruthy()
})
@@ -233,7 +233,7 @@ describe("SyncStrategySettings", () => {
it("shows keep hint when maxRetries is 0 (retry forever)", () => {
const { getByText } = renderComponent({ maxRetries: 0 })
- fireEvent.press(getByText("+ Show Advanced Settings"))
+ fireEvent.press(getByText("Advanced Settings"))
expect(getByText("Failed uploads stay in the queue until they succeed")).toBeTruthy()
})
@@ -241,7 +241,7 @@ describe("SyncStrategySettings", () => {
it("toggling retry on sets maxRetries to 0", () => {
const { getByText, getAllByRole } = renderComponent({ maxRetries: 5 })
- fireEvent.press(getByText("+ Show Advanced Settings"))
+ fireEvent.press(getByText("Advanced Settings"))
// Retry Failed Uploads is the second switch (after Pause GPS when stationary)
const retrySwitch = getAllByRole("switch")[1]
@@ -260,7 +260,7 @@ describe("SyncStrategySettings", () => {
it("toggling retry off sets maxRetries to 5", () => {
const { getByText, getAllByRole } = renderComponent({ maxRetries: 0 })
- fireEvent.press(getByText("+ Show Advanced Settings"))
+ fireEvent.press(getByText("Advanced Settings"))
// Retry Failed Uploads is the second switch (after Pause GPS when stationary)
const retrySwitch = getAllByRole("switch")[1]
@@ -280,7 +280,7 @@ describe("SyncStrategySettings", () => {
it("shows accuracy threshold input when filter is enabled", () => {
const { getByText } = renderComponent({ filterInaccurateLocations: true })
- fireEvent.press(getByText("+ Show Advanced Settings"))
+ fireEvent.press(getByText("Advanced Settings"))
expect(getByText("Accuracy Threshold")).toBeTruthy()
})
@@ -288,7 +288,7 @@ describe("SyncStrategySettings", () => {
it("hides accuracy threshold input when filter is disabled", () => {
const { getByText, queryByText } = renderComponent({ filterInaccurateLocations: false })
- fireEvent.press(getByText("+ Show Advanced Settings"))
+ fireEvent.press(getByText("Advanced Settings"))
expect(queryByText("Accuracy Threshold")).toBeNull()
})
@@ -301,7 +301,7 @@ describe("SyncStrategySettings", () => {
syncPreset: "custom"
})
- fireEvent.press(getByText("+ Show Advanced Settings"))
+ fireEvent.press(getByText("Advanced Settings"))
const intervalInput = getByDisplayValue("5")
fireEvent.changeText(intervalInput, "0")
@@ -318,7 +318,7 @@ describe("SyncStrategySettings", () => {
syncPreset: "custom"
})
- fireEvent.press(getByText("+ Show Advanced Settings"))
+ fireEvent.press(getByText("Advanced Settings"))
const intervalInput = getByDisplayValue("5")
fireEvent.changeText(intervalInput, "-3")
@@ -334,7 +334,7 @@ describe("SyncStrategySettings", () => {
syncPreset: "custom"
})
- fireEvent.press(getByText("+ Show Advanced Settings"))
+ fireEvent.press(getByText("Advanced Settings"))
const intervalInput = getByDisplayValue("5")
fireEvent.changeText(intervalInput, "abc")
@@ -350,7 +350,7 @@ describe("SyncStrategySettings", () => {
syncPreset: "custom"
})
- fireEvent.press(getByText("+ Show Advanced Settings"))
+ fireEvent.press(getByText("Advanced Settings"))
const intervalInput = getByDisplayValue("5")
fireEvent.changeText(intervalInput, "10")
@@ -368,7 +368,7 @@ describe("SyncStrategySettings", () => {
syncPreset: "custom"
})
- fireEvent.press(getByText("+ Show Advanced Settings"))
+ fireEvent.press(getByText("Advanced Settings"))
const distanceInput = getByDisplayValue("10")
fireEvent.changeText(distanceInput, "-5")
@@ -385,7 +385,7 @@ describe("SyncStrategySettings", () => {
syncPreset: "custom"
})
- fireEvent.press(getByText("+ Show Advanced Settings"))
+ fireEvent.press(getByText("Advanced Settings"))
const distanceInput = getByDisplayValue("10")
fireEvent.changeText(distanceInput, "abc")
@@ -403,7 +403,7 @@ describe("SyncStrategySettings", () => {
syncPreset: "custom"
})
- fireEvent.press(getByText("+ Show Advanced Settings"))
+ fireEvent.press(getByText("Advanced Settings"))
const thresholdInput = getByDisplayValue("100")
fireEvent.changeText(thresholdInput, "0")
@@ -421,7 +421,7 @@ describe("SyncStrategySettings", () => {
syncPreset: "custom"
})
- fireEvent.press(getByText("+ Show Advanced Settings"))
+ fireEvent.press(getByText("Advanced Settings"))
const thresholdInput = getByDisplayValue("100")
fireEvent.changeText(thresholdInput, "200")
diff --git a/apps/mobile/src/constants/index.ts b/apps/mobile/src/constants/index.ts
index 434274a7..5623f8bb 100644
--- a/apps/mobile/src/constants/index.ts
+++ b/apps/mobile/src/constants/index.ts
@@ -74,7 +74,12 @@ export const SYNC_INTERVAL_LABELS: Record<number, string> = {
export const HIGH_QUEUE_THRESHOLD = 50
export const CRITICAL_QUEUE_THRESHOLD = 100
+// Map style
+export const MAP_STYLE_URL_LIGHT = "https://maps.mxd.codes/styles/bright/style.json"
+export const MAP_STYLE_URL_DARK = "https://maps.mxd.codes/styles/dark/style.json"
+
// URLs
export const REPO_URL = "https://github.com/dietrichmax/colota"
export const ISSUES_URL = `${REPO_URL}/issues`
export const PRIVACY_POLICY_URL = "https://colota.app/privacy-policy"
+export const TILE_SERVER_DOCS_URL = "https://colota.app/docs/guides/tile-server"
diff --git a/apps/mobile/src/screens/AboutScreen.tsx b/apps/mobile/src/screens/AboutScreen.tsx
index 800415c6..00b3bb30 100644
--- a/apps/mobile/src/screens/AboutScreen.tsx
+++ b/apps/mobile/src/screens/AboutScreen.tsx
@@ -3,7 +3,7 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
-import React, { useState, useEffect, useCallback } from "react"
+import React, { useState, useEffect, useCallback, useMemo } from "react"
import { Text, StyleSheet, View, ScrollView, Linking, Pressable, Image, ActivityIndicator } from "react-native"
import { ScreenProps, ThemeColors } from "../types/global"
import { useTheme } from "../hooks/useTheme"
@@ -13,7 +13,7 @@ import { Card, Container, Divider, SectionTitle, Footer } from "../components"
import { useTimeout } from "../hooks/useTimeout"
import NativeLocationService from "../services/NativeLocationService"
import icon from "../assets/icons/icon.png"
-import { REPO_URL, ISSUES_URL, PRIVACY_POLICY_URL } from "../constants"
+import { REPO_URL, ISSUES_URL, PRIVACY_POLICY_URL, TILE_SERVER_DOCS_URL } from "../constants"
import { logger, getLogEntries, setLogCollecting } from "../utils/logger"
// Helper function to map SDK to Android version
@@ -75,6 +75,23 @@ const LinkRow = ({
const DEBUG_MODE_SETTING_KEY = "debug_mode_enabled"
+function InfoCard({ rows }: { rows: { label: string; value: string }[] }) {
+ const { colors } = useTheme()
+ return (
+ <Card>
+ {rows.map((row, i) => (
+ <React.Fragment key={row.label}>
+ <View style={styles.techRow}>
+ <Text style={[styles.techLabel, { color: colors.textSecondary }]}>{row.label}</Text>
+ <Text style={[styles.techValue, { color: colors.text }]}>{row.value}</Text>
+ </View>
+ {i < rows.length - 1 && <Divider />}
+ </React.Fragment>
+ ))}
+ </Card>
+ )
+}
+
export function AboutScreen({}: ScreenProps) {
const { colors } = useTheme()
const [showDebugInfo, setShowDebugInfo] = useState(false)
@@ -90,7 +107,7 @@ export function AboutScreen({}: ScreenProps) {
apiLevel: string
} | null>(null)
- const buildConfig = NativeLocationService.getBuildConfig()
+ const buildConfig = useMemo(() => NativeLocationService.getBuildConfig(), [])
// Load persisted debug mode
useEffect(() => {
@@ -134,7 +151,7 @@ export function AboutScreen({}: ScreenProps) {
}
}, [tapCount])
- const handleVersionTap = () => {
+ const handleVersionTap = useCallback(() => {
const newCount = tapCount + 1
setTapCount(newCount)
@@ -142,11 +159,11 @@ export function AboutScreen({}: ScreenProps) {
toggleDebugMode(true)
setTapCount(0)
}
- }
+ }, [tapCount, toggleDebugMode])
- const handleOpenURL = (url: string) => {
+ const handleOpenURL = useCallback((url: string) => {
Linking.openURL(url).catch((err) => logger.error("Failed to open URL:", err))
- }
+ }, [])
const handleCopyDebugInfo = useCallback(async () => {
if (!buildConfig) return
@@ -359,17 +376,17 @@ export function AboutScreen({}: ScreenProps) {
</Card>
{/* Map Data Attribution */}
- <View style={styles.debugSection}>
+ <View style={styles.section}>
<SectionTitle>Map Data</SectionTitle>
<Card>
<Pressable
style={({ pressed }) => [styles.linkRow, pressed && { opacity: 0.7 }]}
- onPress={() => handleOpenURL("https://openfreemap.org")}
+ onPress={() => handleOpenURL(TILE_SERVER_DOCS_URL)}
>
<View style={styles.linkTextContainer}>
- <Text style={[styles.linkTitle, { color: colors.text }]}>OpenFreeMap</Text>
+ <Text style={[styles.linkTitle, { color: colors.text }]}>Colota Tiles</Text>
<Text style={[styles.linkSubtitle, { color: colors.textLight }]}>
- Free and open-source map tile hosting
+ Self-hosted map tile server - configure your own
</Text>
</View>
<ChevronRight size={18} color={colors.textLight} />
@@ -393,35 +410,15 @@ export function AboutScreen({}: ScreenProps) {
{/* Debug Info - Only shown when enabled */}
{showDebugInfo && (
<>
- <View style={styles.debugSection}>
+ <View style={styles.section}>
<SectionTitle>BUILD</SectionTitle>
- <Card>
- {debugRows.map((row, i) => (
- <React.Fragment key={row.label}>
- <View style={styles.techRow}>
- <Text style={[styles.techLabel, { color: colors.textSecondary }]}>{row.label}</Text>
- <Text style={[styles.techValue, { color: colors.text }]}>{row.value}</Text>
- </View>
- {i < debugRows.length - 1 && <Divider />}
- </React.Fragment>
- ))}
- </Card>
+ <InfoCard rows={debugRows} />
</View>
{deviceRows.length > 0 && (
- <View style={styles.debugSection}>
+ <View style={styles.section}>
<SectionTitle>DEVICE</SectionTitle>
- <Card>
- {deviceRows.map((row, i) => (
- <React.Fragment key={row.label}>
- <View style={styles.techRow}>
- <Text style={[styles.techLabel, { color: colors.textSecondary }]}>{row.label}</Text>
- <Text style={[styles.techValue, { color: colors.text }]}>{row.value}</Text>
- </View>
- {i < deviceRows.length - 1 && <Divider />}
- </React.Fragment>
- ))}
- </Card>
+ <InfoCard rows={deviceRows} />
</View>
)}
@@ -538,7 +535,7 @@ const styles = StyleSheet.create({
fontSize: 14,
...fonts.semiBold
},
- debugSection: {
+ section: {
marginTop: 24
},
debugHint: {
diff --git a/apps/mobile/src/screens/GeofenceScreen.tsx b/apps/mobile/src/screens/GeofenceScreen.tsx
index f6cb6e5b..a9cd12be 100644
--- a/apps/mobile/src/screens/GeofenceScreen.tsx
+++ b/apps/mobile/src/screens/GeofenceScreen.tsx
@@ -11,11 +11,9 @@ import { showAlert, showConfirm } from "../services/modalService"
import { Geofence, ScreenProps } from "../types/global"
import { useTracking, useCoords } from "../contexts/TrackingProvider"
import { fonts } from "../styles/typography"
-import { X, WifiOff } from "lucide-react-native"
+import { X } from "lucide-react-native"
import { Container, SectionTitle, Card } from "../components"
-import { useFocusEffect } from "@react-navigation/native"
import {
- STATS_REFRESH_IDLE,
DEFAULT_MAP_ZOOM,
WORLD_MAP_ZOOM,
GEOFENCE_ZOOM_PADDING,
@@ -43,7 +41,6 @@ export function GeofenceScreen({}: ScreenProps) {
const isCenteredRef = useRef(true)
const [hasInitialCoords, setHasInitialCoords] = useState(false)
const [currentPauseZone, setCurrentPauseZone] = useState<string | null>(null)
- const [isOffline, setIsOffline] = useState(false)
const mapRef = useRef<ColotaMapRef>(null)
const initialCenter = useRef<{
@@ -52,17 +49,6 @@ export function GeofenceScreen({}: ScreenProps) {
accuracy: number
} | null>(null)
- useFocusEffect(
- useCallback(() => {
- const check = () => {
- NativeLocationService.isNetworkAvailable().then((available) => setIsOffline(!available))
- }
- check()
- const interval = setInterval(check, STATS_REFRESH_IDLE)
- return () => clearInterval(interval)
- }, [])
- )
-
// Set initial map center
useEffect(() => {
if (hasInitialCoords) return
@@ -313,15 +299,6 @@ export function GeofenceScreen({}: ScreenProps) {
) : null}
<MapCenterButton visible={!isCentered && tracking} onPress={handleCenterMe} />
-
- {isOffline && (
- <View style={[styles.offlineBanner, { backgroundColor: colors.card }]}>
- <WifiOff size={14} color={colors.textSecondary} />
- <Text style={[styles.offlineText, { color: colors.textSecondary }]}>
- Map tiles unavailable — no internet
- </Text>
- </View>
- )}
</View>
<FlatList
@@ -350,7 +327,7 @@ export function GeofenceScreen({}: ScreenProps) {
borderColor: colors.border
}
]}
- placeholder="Home, Office..."
+ placeholder="Home, Work..."
placeholderTextColor={colors.placeholder}
value={newName}
onChangeText={setNewName}
@@ -471,23 +448,5 @@ const styles = StyleSheet.create({
textAlign: "center",
maxWidth: 260,
lineHeight: 18
- },
- offlineBanner: {
- position: "absolute",
- top: 14,
- left: 14,
- right: 14,
- flexDirection: "row",
- alignItems: "center",
- gap: 8,
- padding: 12,
- borderRadius: 12,
- elevation: 8,
- shadowOpacity: 0.2,
- zIndex: 5
- },
- offlineText: {
- fontSize: 13,
- ...fonts.medium
}
})
diff --git a/apps/mobile/src/screens/OfflineMapsScreen.tsx b/apps/mobile/src/screens/OfflineMapsScreen.tsx
new file mode 100644
index 00000000..d672ce98
--- /dev/null
+++ b/apps/mobile/src/screens/OfflineMapsScreen.tsx
@@ -0,0 +1,918 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * 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, StyleSheet, TextInput, Pressable, FlatList, ActivityIndicator, AppState } from "react-native"
+import { ShapeSource, FillLayer, LineLayer, type OnPressEvent } from "@maplibre/maplibre-react-native"
+import { useTheme } from "../hooks/useTheme"
+import { showAlert, showConfirm } from "../services/modalService"
+import { ScreenProps } from "../types/global"
+import { useCoords } from "../contexts/TrackingProvider"
+import { fonts } from "../styles/typography"
+import { X, CheckCircle, RefreshCw, AlertTriangle } from "lucide-react-native"
+import { Container, SectionTitle, Card } from "../components"
+import { useFocusEffect } from "@react-navigation/native"
+import { DEFAULT_MAP_ZOOM, WORLD_MAP_ZOOM, MAP_ANIMATION_DURATION_MS, MAP_STYLE_URL_LIGHT } from "../constants"
+import { MapCenterButton } from "../components/features/map/MapCenterButton"
+import { ColotaMapView, ColotaMapRef } from "../components/features/map/ColotaMapView"
+import { logger } from "../utils/logger"
+import NativeLocationService from "../services/NativeLocationService"
+import {
+ createOfflinePack,
+ loadOfflineAreas,
+ deleteOfflineArea,
+ unsubscribeOfflinePack,
+ formatBytes,
+ DOWNLOAD_STATE,
+ OfflinePackStatus,
+ OfflineAreaInfo,
+ OfflineAreaBounds,
+ estimateSizeLabel,
+ estimateSizeBytes,
+ willExceedTileLimit,
+ loadOfflineAreaBounds,
+ saveOfflineAreaBounds,
+ removeOfflineAreaBounds
+} from "../components/features/map/OfflinePackManager"
+
+type ItemAction = { area: string; action: "deleting" | "canceling" | "refreshing" }
+type ThemeColors = ReturnType<typeof useTheme>["colors"]
+
+function formatRelativeTime(timestamp: number): string {
+ const diffDays = Math.floor((Date.now() - timestamp) / (1000 * 60 * 60 * 24))
+ if (diffDays < 1) return "Today"
+ if (diffDays === 1) return "Yesterday"
+ if (diffDays < 14) return `${diffDays} days ago`
+ if (diffDays < 60) return `${Math.floor(diffDays / 7)} weeks ago`
+ return new Date(timestamp).toLocaleDateString(undefined, { month: "short", year: "numeric" })
+}
+
+// ---------------------------------------------------------------------------
+// DownloadForm
+// ---------------------------------------------------------------------------
+
+interface DownloadFormProps {
+ colors: ThemeColors
+ estimatedSizeLabel: string | null
+ downloading: boolean
+ downloadProgress: OfflinePackStatus | null
+ downloadError: string | null
+ areasCount: number
+ totalStorageBytes: number
+ nameInputRef: React.RefObject<TextInput | null>
+ onNameChange: (v: string) => void
+ onDownload: () => void
+ onCancelDownload: () => void
+}
+
+const DownloadForm = memo(
+ ({
+ colors,
+ estimatedSizeLabel,
+ downloading,
+ downloadProgress,
+ downloadError,
+ areasCount,
+ totalStorageBytes,
+ nameInputRef,
+ onNameChange,
+ onDownload,
+ onCancelDownload
+ }: DownloadFormProps) => {
+ const progressPct = downloadProgress?.percentage ?? 0
+ const progressLabel =
+ downloadProgress?.state === DOWNLOAD_STATE.COMPLETE
+ ? "Complete"
+ : downloadProgress
+ ? `${Math.round(progressPct)}%`
+ : "Starting..."
+
+ const sizeLabel = useMemo(() => {
+ if (!downloadProgress || downloadProgress.completedResourceSize <= 0) return null
+ const {
+ completedResourceSize: done,
+ completedResourceCount: count,
+ requiredResourceCount: total
+ } = downloadProgress
+ const downloaded = formatBytes(done)
+ if (count > 0 && total > 0) return `${downloaded} / ~${formatBytes((done / count) * total)}`
+ return downloaded
+ }, [downloadProgress])
+
+ return (
+ <>
+ <View style={styles.section}>
+ <SectionTitle>Download Area</SectionTitle>
+ <Card>
+ <Text style={[styles.hint, { color: colors.textSecondary }]}>
+ Pan and zoom the map to frame the area you want to download, then enter a name and tap Download. Size
+ estimates may be significantly higher in dense urban areas.
+ </Text>
+
+ <View style={styles.inputGroup}>
+ <Text style={[styles.label, { color: colors.textSecondary }]}>Name</Text>
+ <TextInput
+ ref={nameInputRef}
+ style={[
+ styles.input,
+ { backgroundColor: colors.background, color: colors.text, borderColor: colors.border }
+ ]}
+ placeholder="Home area, Trail..."
+ placeholderTextColor={colors.placeholder}
+ onChangeText={onNameChange}
+ editable={!downloading}
+ />
+ </View>
+
+ {estimatedSizeLabel && (
+ <Text style={[styles.sizeEstimate, { color: colors.textSecondary }]}>{estimatedSizeLabel} estimated</Text>
+ )}
+
+ {downloading ? (
+ <View style={styles.progressContainer}>
+ <View style={styles.progressHeader}>
+ <ActivityIndicator size="small" color={colors.primary} />
+ <Text style={[styles.progressLabel, { color: colors.text }]}>Downloading {progressLabel}</Text>
+ </View>
+ <View style={[styles.progressTrack, { backgroundColor: colors.border }]}>
+ <View style={[styles.progressFill, { backgroundColor: colors.primary, width: `${progressPct}%` }]} />
+ </View>
+ {downloadProgress && (
+ <Text style={[styles.progressSub, { color: colors.textSecondary }]}>
+ {downloadProgress.completedResourceCount} / {downloadProgress.requiredResourceCount} resources
+ {sizeLabel ? ` - ${sizeLabel}` : ""}
+ </Text>
+ )}
+ <Pressable
+ testID="cancel-download-btn"
+ onPress={onCancelDownload}
+ style={({ pressed }) => [
+ styles.cancelBtn,
+ { borderColor: colors.error + "60" },
+ pressed && { opacity: 0.7 }
+ ]}
+ >
+ <Text style={[styles.cancelBtnText, { color: colors.error }]}>Cancel Download</Text>
+ </Pressable>
+ </View>
+ ) : (
+ <Pressable
+ testID="download-btn"
+ style={({ pressed }) => [
+ styles.downloadBtn,
+ { backgroundColor: estimatedSizeLabel ? colors.primary : colors.border },
+ pressed && { opacity: 0.7 }
+ ]}
+ onPress={onDownload}
+ disabled={!estimatedSizeLabel}
+ >
+ <Text style={[styles.downloadBtnText, { color: colors.textOnPrimary }]}>Download Area</Text>
+ </Pressable>
+ )}
+
+ {downloadError && <Text style={[styles.errorText, { color: colors.error }]}>{downloadError}</Text>}
+ </Card>
+ </View>
+
+ {areasCount > 0 && (
+ <>
+ <SectionTitle>Saved Areas</SectionTitle>
+ {totalStorageBytes > 0 && (
+ <Text style={[styles.savedAreasMeta, { color: colors.textSecondary }]}>
+ {areasCount} {areasCount === 1 ? "area" : "areas"} · {formatBytes(totalStorageBytes)}
+ </Text>
+ )}
+ </>
+ )}
+ </>
+ )
+ }
+)
+
+// ---------------------------------------------------------------------------
+// OfflineMapsScreen
+// ---------------------------------------------------------------------------
+
+export function OfflineMapsScreen({}: ScreenProps) {
+ const coords = useCoords()
+ const { colors } = useTheme()
+
+ const [areas, setAreas] = useState<OfflineAreaInfo[]>([])
+ const [areaBounds, setAreaBounds] = useState<OfflineAreaBounds[]>([])
+ const newNameRef = useRef("")
+ const nameInputRef = useRef<TextInput>(null)
+
+ const currentBoundsRef = useRef<[[number, number], [number, number]] | null>(null)
+ const [estimatedSizeLabel, setEstimatedSizeLabel] = useState<string | null>(null)
+
+ const [isCentered, setIsCentered] = useState(true)
+ const [hasInitialCoords, setHasInitialCoords] = useState(false)
+ const [isOffline, setIsOffline] = useState(false)
+
+ const [itemAction, setItemAction] = useState<ItemAction | null>(null)
+ const [currentStyleUrl, setCurrentStyleUrl] = useState<string | null>(null)
+
+ // Download state
+ const [downloading, setDownloading] = useState(false)
+ const [downloadProgress, setDownloadProgress] = useState<OfflinePackStatus | null>(null)
+ const [downloadBounds, setDownloadBounds] = useState<[[number, number], [number, number]] | null>(null)
+ const [downloadError, setDownloadError] = useState<string | null>(null)
+
+ // Track the active pack name so we can unsubscribe on unmount
+ const activePackNameRef = useRef<string | null>(null)
+
+ const mapRef = useRef<ColotaMapRef>(null)
+ const initialCenter = useRef<{ latitude: number; longitude: number } | null>(null)
+
+ // Unsubscribe listeners when the screen unmounts mid-download
+ useEffect(() => {
+ return () => {
+ if (activePackNameRef.current) {
+ unsubscribeOfflinePack(activePackNameRef.current)
+ }
+ }
+ }, [])
+
+ // Re-check network state when the app comes back to the foreground
+ useEffect(() => {
+ const sub = AppState.addEventListener("change", (state) => {
+ if (state === "active") {
+ NativeLocationService.isNetworkAvailable().then((available) => setIsOffline(!available))
+ }
+ })
+ return () => sub.remove()
+ }, [])
+
+ const loadAreas = useCallback(async () => {
+ try {
+ const [data, bounds] = await Promise.all([loadOfflineAreas(), loadOfflineAreaBounds()])
+ setAreas(data)
+ // Remove bounds entries for packs that no longer exist
+ const packNames = new Set(data.map((a) => a.name))
+ const validBounds = bounds.filter((b) => packNames.has(b.name))
+ if (validBounds.length < bounds.length) {
+ const orphaned = bounds.filter((b) => !packNames.has(b.name))
+ await Promise.all(orphaned.map((b) => removeOfflineAreaBounds(b.name)))
+ }
+ setAreaBounds(validBounds)
+ } catch (err) {
+ logger.error("[OfflineMapsScreen] Failed to load offline areas:", err)
+ }
+ }, [])
+
+ useFocusEffect(
+ useCallback(() => {
+ loadAreas()
+ NativeLocationService.isNetworkAvailable().then((available) => setIsOffline(!available))
+ NativeLocationService.getSetting("mapStyleUrlLight").then((url) => {
+ setCurrentStyleUrl(url || MAP_STYLE_URL_LIGHT)
+ })
+ }, [loadAreas])
+ )
+
+ // Set initial map center from live coords or last known location
+ useEffect(() => {
+ if (hasInitialCoords) return
+
+ if (coords) {
+ initialCenter.current = { latitude: coords.latitude, longitude: coords.longitude }
+ setHasInitialCoords(true)
+ return
+ }
+
+ NativeLocationService.getMostRecentLocation().then((latest) => {
+ if (initialCenter.current) return
+ initialCenter.current = latest
+ ? { latitude: latest.latitude, longitude: latest.longitude }
+ : { latitude: 0, longitude: 0 }
+ setHasInitialCoords(true)
+ })
+ }, [coords, hasInitialCoords])
+
+ const handleCenterMe = useCallback(() => {
+ if (coords && mapRef.current?.camera) {
+ mapRef.current.camera.setCamera({
+ centerCoordinate: [coords.longitude, coords.latitude],
+ zoomLevel: DEFAULT_MAP_ZOOM,
+ animationDuration: MAP_ANIMATION_DURATION_MS,
+ animationMode: "flyTo"
+ })
+ setIsCentered(true)
+ }
+ }, [coords])
+
+ const updateBoundsAndEstimate = useCallback((ne: [number, number], sw: [number, number]) => {
+ currentBoundsRef.current = [ne, sw]
+ setEstimatedSizeLabel(estimateSizeLabel(ne, sw))
+ }, [])
+
+ const handleRegionChange = useCallback(
+ (payload: { isUserInteraction: boolean; visibleBounds?: number[][] }) => {
+ if (payload.isUserInteraction) setIsCentered(false)
+ if (payload.visibleBounds && payload.visibleBounds.length >= 2) {
+ updateBoundsAndEstimate(
+ payload.visibleBounds[0] as [number, number],
+ payload.visibleBounds[1] as [number, number]
+ )
+ }
+ },
+ [updateBoundsAndEstimate]
+ )
+
+ const handleMapReady = useCallback(async () => {
+ try {
+ const bounds = await mapRef.current?.mapView?.getVisibleBounds()
+ if (bounds) updateBoundsAndEstimate(bounds[0] as [number, number], bounds[1] as [number, number])
+ } catch {
+ // map not ready yet
+ }
+ }, [updateBoundsAndEstimate])
+
+ const beginDownload = useCallback(
+ (name: string, ne: [number, number], sw: [number, number], onComplete?: () => void) => {
+ setDownloading(true)
+ setDownloadBounds([ne, sw])
+ setDownloadProgress(null)
+ setDownloadError(null)
+ activePackNameRef.current = name
+
+ const onFailure = (message: string) => {
+ activePackNameRef.current = null
+ setDownloading(false)
+ setDownloadBounds(null)
+ setDownloadError(message)
+ removeOfflineAreaBounds(name)
+ setAreaBounds((prev) => prev.filter((b) => b.name !== name))
+ }
+
+ createOfflinePack(
+ name,
+ ne,
+ sw,
+ (status: OfflinePackStatus) => {
+ setDownloadProgress(status)
+ if (status.state === DOWNLOAD_STATE.COMPLETE) {
+ activePackNameRef.current = null
+ setDownloading(false)
+ setDownloadBounds(null)
+ onComplete?.()
+ loadAreas()
+ } else if (status.state === DOWNLOAD_STATE.FAILED) {
+ logger.error("[OfflineMapsScreen] Download failed via progress callback")
+ onFailure("Download failed. Please try again.")
+ }
+ },
+ (err: unknown) => {
+ logger.error("[OfflineMapsScreen] Download error:", err)
+ onFailure("Download failed. Please try again.")
+ }
+ ).catch(() => {
+ onFailure("Failed to start download. Please try again.")
+ deleteOfflineArea(name).catch(() => {})
+ })
+ },
+ [loadAreas]
+ )
+
+ const handleDownload = useCallback(async () => {
+ if (!newNameRef.current.trim()) {
+ showAlert("Missing Name", "Please enter a name for this area.", "warning")
+ return
+ }
+ if (isOffline) {
+ showAlert("Offline", "An internet connection is required to download map tiles.", "warning")
+ return
+ }
+
+ const name = newNameRef.current.trim()
+ const bounds = currentBoundsRef.current
+ if (!bounds) {
+ showAlert("Map Not Ready", "Wait for the map to load before downloading.", "warning")
+ return
+ }
+ const [ne, sw] = bounds
+
+ if (areas.some((a) => a.name === name)) {
+ showAlert("Duplicate Name", `An area named "${name}" already exists. Choose a different name.`, "warning")
+ return
+ }
+
+ const isUnmetered = await NativeLocationService.isUnmeteredConnection()
+ if (!isUnmetered) {
+ const wifiConfirmed = await showConfirm({
+ title: "Mobile Data",
+ message: "You're not on WiFi. Downloading map tiles may use significant mobile data. Continue?",
+ confirmText: "Download Anyway",
+ destructive: false
+ })
+ if (!wifiConfirmed) return
+ }
+
+ const estimatedBytes = estimateSizeBytes(ne, sw)
+ const availableMB = await NativeLocationService.getAvailableStorageMB()
+ if (availableMB > 0 && estimatedBytes / (1024 * 1024) > availableMB * 0.9) {
+ showAlert("Storage Full", "Not enough storage space for this download.", "warning")
+ return
+ }
+
+ const sizeLabel = estimateSizeLabel(ne, sw)
+ const exceedsLimit = willExceedTileLimit(ne, sw)
+ const confirmed = await showConfirm({
+ title: `Download "${name}"?`,
+ message: `${sizeLabel} estimated${exceedsLimit ? "\n\nThis area is large - outer edges may have incomplete coverage." : ""}`,
+ confirmText: "Download",
+ destructive: false
+ })
+ if (!confirmed) return
+
+ const entry: OfflineAreaBounds = {
+ name,
+ ne,
+ sw,
+ styleUrl: currentStyleUrl ?? MAP_STYLE_URL_LIGHT,
+ downloadedAt: Date.now()
+ }
+ await saveOfflineAreaBounds(entry)
+ setAreaBounds((prev) => [...prev.filter((b) => b.name !== name), entry])
+ beginDownload(name, ne, sw, () => {
+ nameInputRef.current?.clear()
+ newNameRef.current = ""
+ })
+ }, [isOffline, areas, currentStyleUrl, beginDownload])
+
+ const handleCancelDownload = useCallback(async () => {
+ const name = activePackNameRef.current
+ activePackNameRef.current = null
+ setDownloading(false)
+ setDownloadBounds(null)
+ setDownloadProgress(null)
+ setDownloadError(null)
+ if (name) {
+ setAreaBounds((prev) => prev.filter((b) => b.name !== name))
+ try {
+ await deleteOfflineArea(name)
+ await removeOfflineAreaBounds(name)
+ } catch (err) {
+ logger.error("[OfflineMapsScreen] Failed to delete cancelled pack:", err)
+ }
+ }
+ }, [])
+
+ const handleRefresh = useCallback(
+ async (area: OfflineAreaInfo) => {
+ if (downloading) return
+ const bounds = areaBounds.find((b) => b.name === area.name)
+ if (!bounds) {
+ showAlert("Cannot Refresh", "No bounds saved for this area. Delete and re-download it.", "warning")
+ return
+ }
+ if (isOffline) {
+ showAlert("Offline", "An internet connection is required to download map tiles.", "warning")
+ return
+ }
+ const sizeLabel = estimateSizeLabel(bounds.ne, bounds.sw)
+
+ const isUnmetered = await NativeLocationService.isUnmeteredConnection()
+ if (!isUnmetered) {
+ const wifiConfirmed = await showConfirm({
+ title: "Mobile Data",
+ message: "You're not on WiFi. Re-downloading may use significant mobile data. Continue?",
+ confirmText: "Continue",
+ destructive: false
+ })
+ if (!wifiConfirmed) return
+ }
+
+ const confirmed = await showConfirm({
+ title: `Re-download "${area.name}"?`,
+ message: `Replaces existing tiles with a fresh download. ${sizeLabel} estimated.`,
+ confirmText: "Re-download",
+ destructive: false
+ })
+ if (!confirmed) return
+
+ setItemAction({ area: area.name, action: "refreshing" })
+ try {
+ await deleteOfflineArea(area.name)
+ } catch {
+ // pack may already be gone
+ }
+ setItemAction(null)
+ setAreas((prev) => prev.filter((a) => a.name !== area.name))
+
+ const styleUrl = currentStyleUrl ?? MAP_STYLE_URL_LIGHT
+ const entry: OfflineAreaBounds = {
+ name: area.name,
+ ne: bounds.ne,
+ sw: bounds.sw,
+ styleUrl,
+ downloadedAt: Date.now()
+ }
+ await saveOfflineAreaBounds(entry)
+ setAreaBounds((prev) => [...prev.filter((b) => b.name !== area.name), entry])
+
+ beginDownload(area.name, bounds.ne, bounds.sw)
+ },
+ [downloading, isOffline, areaBounds, currentStyleUrl, beginDownload]
+ )
+
+ const handleDelete = useCallback(
+ async (area: OfflineAreaInfo) => {
+ const confirmed = await showConfirm({
+ title: "Delete Area",
+ message: `Delete "${area.name}"? The downloaded tiles will be removed from your device.`,
+ confirmText: "Delete",
+ destructive: true
+ })
+ if (!confirmed) return
+
+ setItemAction({ area: area.name, action: "deleting" })
+ try {
+ await deleteOfflineArea(area.name)
+ await removeOfflineAreaBounds(area.name)
+ await loadAreas()
+ } catch {
+ showAlert("Error", "Failed to delete area.", "error")
+ } finally {
+ setItemAction(null)
+ }
+ },
+ [loadAreas]
+ )
+
+ const handleCancelArea = useCallback(
+ async (area: OfflineAreaInfo) => {
+ setItemAction({ area: area.name, action: "canceling" })
+ try {
+ await deleteOfflineArea(area.name)
+ await removeOfflineAreaBounds(area.name)
+ await loadAreas()
+ } catch {
+ showAlert("Error", "Failed to cancel download.", "error")
+ } finally {
+ setItemAction(null)
+ }
+ },
+ [loadAreas]
+ )
+
+ const fitToArea = useCallback(
+ (name: string) => {
+ const entry = areaBounds.find((b) => b.name === name)
+ if (!entry || !mapRef.current?.camera) return
+ mapRef.current.camera.fitBounds(entry.ne, entry.sw, 40, MAP_ANIMATION_DURATION_MS)
+ },
+ [areaBounds]
+ )
+
+ const handleAreaPress = useCallback(
+ (event: OnPressEvent) => {
+ if (downloading) return
+ const name: string | undefined = event.features?.[0]?.properties?.name
+ if (name) fitToArea(name)
+ },
+ [downloading, fitToArea]
+ )
+
+ const handleNameChange = useCallback((v: string) => {
+ newNameRef.current = v
+ }, [])
+
+ const savedAreasGeoJSON = useMemo(
+ (): GeoJSON.FeatureCollection => ({
+ type: "FeatureCollection",
+ features: areaBounds.map((b) => {
+ const [neLon, neLat] = b.ne
+ const [swLon, swLat] = b.sw
+ return {
+ type: "Feature",
+ geometry: {
+ type: "Polygon",
+ coordinates: [
+ [
+ [swLon, neLat],
+ [neLon, neLat],
+ [neLon, swLat],
+ [swLon, swLat],
+ [swLon, neLat]
+ ]
+ ]
+ },
+ properties: { name: b.name }
+ }
+ })
+ }),
+ [areaBounds]
+ )
+
+ const downloadAreaGeoJSON = useMemo((): GeoJSON.Feature | null => {
+ if (!downloadBounds) return null
+ const [ne, sw] = downloadBounds
+ const [neLon, neLat] = ne
+ const [swLon, swLat] = sw
+ return {
+ type: "Feature",
+ geometry: {
+ type: "Polygon",
+ coordinates: [
+ [
+ [swLon, neLat],
+ [neLon, neLat],
+ [neLon, swLat],
+ [swLon, swLat],
+ [swLon, neLat]
+ ]
+ ]
+ },
+ properties: {}
+ }
+ }, [downloadBounds])
+
+ const hasRealCoords =
+ initialCenter.current && (initialCenter.current.latitude !== 0 || initialCenter.current.longitude !== 0)
+ const initialZoom = hasRealCoords ? DEFAULT_MAP_ZOOM : WORLD_MAP_ZOOM
+
+ const totalStorageBytes = useMemo(() => areas.reduce((sum, a) => sum + (a.sizeBytes ?? 0), 0), [areas])
+
+ // For the map overlay hint only - DownloadForm computes its own copy
+ const progressPct = downloadProgress?.percentage ?? 0
+ const progressLabel =
+ downloadProgress?.state === DOWNLOAD_STATE.COMPLETE
+ ? "Complete"
+ : downloadProgress
+ ? `${Math.round(progressPct)}%`
+ : "Starting..."
+
+ const renderItem = useCallback(
+ ({ item }: { item: OfflineAreaInfo }) => {
+ const isDeleting = itemAction?.area === item.name && itemAction?.action === "deleting"
+ const isCanceling = itemAction?.area === item.name && itemAction?.action === "canceling"
+ const isRefreshing = itemAction?.area === item.name && itemAction?.action === "refreshing"
+ const bounds = areaBounds.find((b) => b.name === item.name)
+ const isStale = item.isComplete && !!bounds?.styleUrl && !!currentStyleUrl && bounds.styleUrl !== currentStyleUrl
+ return (
+ <Card style={styles.card}>
+ <View style={styles.row}>
+ <Pressable
+ style={({ pressed }) => [styles.info, pressed && { opacity: 0.6 }]}
+ onPress={() => fitToArea(item.name)}
+ disabled={item.isActive}
+ >
+ <View style={styles.nameRow}>
+ {item.isComplete && <CheckCircle size={14} color={colors.success} />}
+ {item.isActive && <ActivityIndicator size="small" color={colors.primary} />}
+ <Text style={[styles.areaName, { color: colors.text }]}>{item.name}</Text>
+ {isStale && (
+ <View testID={`stale-indicator-${item.name}`}>
+ <AlertTriangle size={13} color={colors.warning} />
+ </View>
+ )}
+ </View>
+ <Text style={[styles.areaSub, { color: colors.textSecondary }]}>
+ {item.isActive ? "Downloading..." : item.sizeBytes !== null ? formatBytes(item.sizeBytes) : ""}
+ </Text>
+ {!item.isActive && bounds?.downloadedAt && (
+ <Text style={[styles.areaSubDate, { color: colors.textSecondary }]}>
+ {formatRelativeTime(bounds.downloadedAt)}
+ </Text>
+ )}
+ </Pressable>
+
+ {item.isActive ? (
+ <Pressable
+ onPress={() => handleCancelArea(item)}
+ disabled={isCanceling}
+ style={({ pressed }) => [
+ styles.cancelAreaBtn,
+ { backgroundColor: colors.error + "15", borderColor: colors.error + "40" },
+ pressed && { opacity: 0.7 }
+ ]}
+ >
+ {isCanceling ? (
+ <ActivityIndicator size="small" color={colors.error} />
+ ) : (
+ <Text style={[styles.cancelAreaLabel, { color: colors.error }]}>Cancel</Text>
+ )}
+ </Pressable>
+ ) : (
+ <View style={styles.actionBtns}>
+ {item.isComplete && (
+ <Pressable
+ testID={`refresh-btn-${item.name}`}
+ onPress={() => handleRefresh(item)}
+ disabled={downloading || isRefreshing}
+ style={({ pressed }) => [
+ styles.actionBtn,
+ { backgroundColor: colors.primary + "15" },
+ pressed && { opacity: 0.7 }
+ ]}
+ >
+ {isRefreshing ? (
+ <ActivityIndicator size="small" color={colors.primary} />
+ ) : (
+ <RefreshCw size={14} color={colors.primary} />
+ )}
+ </Pressable>
+ )}
+ <Pressable
+ testID={`delete-btn-${item.name}`}
+ onPress={() => handleDelete(item)}
+ disabled={isDeleting}
+ style={({ pressed }) => [
+ styles.actionBtn,
+ { backgroundColor: colors.error + "15" },
+ pressed && { opacity: 0.7 }
+ ]}
+ >
+ {isDeleting ? (
+ <ActivityIndicator size="small" color={colors.error} />
+ ) : (
+ <X size={16} color={colors.error} />
+ )}
+ </Pressable>
+ </View>
+ )}
+ </View>
+ </Card>
+ )
+ },
+ [
+ colors,
+ itemAction,
+ areaBounds,
+ currentStyleUrl,
+ downloading,
+ fitToArea,
+ handleDelete,
+ handleCancelArea,
+ handleRefresh
+ ]
+ )
+
+ const listHeader = useMemo(
+ () => (
+ <DownloadForm
+ colors={colors}
+ estimatedSizeLabel={estimatedSizeLabel}
+ downloading={downloading}
+ downloadProgress={downloadProgress}
+ downloadError={downloadError}
+ areasCount={areas.length}
+ totalStorageBytes={totalStorageBytes}
+ nameInputRef={nameInputRef}
+ onNameChange={handleNameChange}
+ onDownload={handleDownload}
+ onCancelDownload={handleCancelDownload}
+ />
+ ),
+ [
+ colors,
+ estimatedSizeLabel,
+ downloading,
+ downloadProgress,
+ downloadError,
+ areas.length,
+ totalStorageBytes,
+ handleDownload,
+ handleCancelDownload,
+ handleNameChange
+ ]
+ )
+
+ const mapDownloadingStyle = downloading ? { borderColor: colors.primary, borderWidth: 2 as const } : null
+ const savedAreasFillStyle = { fillColor: colors.success, fillOpacity: 0.1 }
+ const savedAreasBorderStyle = { lineColor: colors.success, lineWidth: 1.5, lineOpacity: 0.6 }
+ const downloadAreaFillStyle = { fillColor: colors.info, fillOpacity: 0.2 }
+ const downloadAreaBorderStyle = { lineColor: colors.info, lineWidth: 1.5, lineOpacity: 0.6 }
+
+ return (
+ <Container>
+ <View style={[styles.map, mapDownloadingStyle]}>
+ {hasInitialCoords && initialCenter.current ? (
+ <ColotaMapView
+ ref={mapRef}
+ initialCenter={[initialCenter.current.longitude, initialCenter.current.latitude]}
+ initialZoom={initialZoom}
+ onRegionDidChange={handleRegionChange}
+ onMapReady={handleMapReady}
+ >
+ {savedAreasGeoJSON.features.length > 0 && (
+ <ShapeSource id="saved-areas" shape={savedAreasGeoJSON} onPress={handleAreaPress}>
+ <FillLayer id="saved-areas-fill" style={savedAreasFillStyle} />
+ <LineLayer id="saved-areas-border" style={savedAreasBorderStyle} />
+ </ShapeSource>
+ )}
+ {downloadAreaGeoJSON && (
+ <ShapeSource id="offline-area" shape={downloadAreaGeoJSON}>
+ <FillLayer id="offline-area-fill" style={downloadAreaFillStyle} />
+ <LineLayer id="offline-area-border" style={downloadAreaBorderStyle} />
+ </ShapeSource>
+ )}
+ </ColotaMapView>
+ ) : null}
+
+ <MapCenterButton visible={!isCentered && !!coords} onPress={handleCenterMe} />
+
+ {downloading && (
+ <View style={[styles.mapHint, { backgroundColor: colors.card }]}>
+ <Text style={[styles.mapHintText, { color: colors.text }]}>Downloading... {progressLabel}</Text>
+ </View>
+ )}
+ </View>
+
+ <FlatList
+ data={areas}
+ keyExtractor={(item) => item.name}
+ contentContainerStyle={styles.list}
+ showsVerticalScrollIndicator={false}
+ ListHeaderComponent={listHeader}
+ ListEmptyComponent={
+ areas.length === 0 && !downloading ? (
+ <View style={styles.empty}>
+ <Text style={[styles.emptyText, { color: colors.textSecondary }]}>No saved areas yet</Text>
+ <Text style={[styles.emptyHint, { color: colors.textLight }]}>
+ Download map tiles to browse your tracks offline while hiking or camping
+ </Text>
+ </View>
+ ) : null
+ }
+ renderItem={renderItem}
+ />
+ </Container>
+ )
+}
+
+const styles = StyleSheet.create({
+ map: { height: 450, overflow: "hidden" },
+ list: { padding: 20, paddingBottom: 40 },
+ section: { marginBottom: 16 },
+ hint: { fontSize: 13, ...fonts.regular, lineHeight: 18, marginBottom: 16 },
+ inputGroup: { marginBottom: 16 },
+ label: {
+ fontSize: 12,
+ ...fonts.semiBold,
+ marginBottom: 6,
+ textTransform: "uppercase",
+ letterSpacing: 0.5
+ },
+ input: { padding: 14, borderWidth: 1.5, borderRadius: 10, fontSize: 15 },
+ sizeEstimate: { fontSize: 12, ...fonts.regular, marginBottom: 12 },
+ downloadBtn: { padding: 16, borderRadius: 12, alignItems: "center" },
+ downloadBtnText: { fontSize: 15, ...fonts.semiBold },
+ progressContainer: { gap: 10 },
+ progressHeader: { flexDirection: "row", alignItems: "center", gap: 10 },
+ progressLabel: { fontSize: 14, ...fonts.semiBold },
+ progressTrack: { height: 6, borderRadius: 3, overflow: "hidden" },
+ progressFill: { height: "100%", borderRadius: 3 },
+ progressSub: { fontSize: 12, ...fonts.regular },
+ cancelBtn: {
+ padding: 12,
+ borderRadius: 10,
+ borderWidth: 1.5,
+ alignItems: "center",
+ marginTop: 4
+ },
+ cancelBtnText: { fontSize: 14, ...fonts.semiBold },
+ errorText: { fontSize: 13, ...fonts.regular, marginTop: 10 },
+ card: { marginBottom: 12, padding: 14 },
+ row: { flexDirection: "row", alignItems: "center", justifyContent: "space-between" },
+ info: { flex: 1, marginRight: 12 },
+ nameRow: { flexDirection: "row", alignItems: "center", gap: 6, marginBottom: 2 },
+ areaName: { fontSize: 15, ...fonts.semiBold },
+ areaSub: { fontSize: 12 },
+ areaSubDate: { fontSize: 11, ...fonts.regular, marginTop: 2, opacity: 0.7 },
+ savedAreasMeta: { fontSize: 12, ...fonts.regular, marginTop: 2, marginBottom: 12, paddingHorizontal: 4 },
+ actionBtns: { flexDirection: "row", gap: 6, alignItems: "center" },
+ actionBtn: {
+ width: 32,
+ height: 32,
+ borderRadius: 16,
+ alignItems: "center",
+ justifyContent: "center"
+ },
+ cancelAreaBtn: {
+ paddingHorizontal: 12,
+ paddingVertical: 6,
+ borderRadius: 8,
+ borderWidth: 1
+ },
+ cancelAreaLabel: { fontSize: 13, ...fonts.semiBold },
+ empty: { alignItems: "center", paddingVertical: 40 },
+ emptyText: { fontSize: 15, ...fonts.semiBold, marginBottom: 6 },
+ emptyHint: { fontSize: 13, textAlign: "center", maxWidth: 260, lineHeight: 18 },
+ mapHint: {
+ position: "absolute",
+ top: 14,
+ left: 14,
+ right: 14,
+ padding: 12,
+ borderRadius: 12,
+ elevation: 8,
+ shadowOpacity: 0.2,
+ zIndex: 5,
+ alignItems: "center"
+ },
+ mapHintText: { fontSize: 13, ...fonts.semiBold }
+})
diff --git a/apps/mobile/src/screens/SettingsScreen.tsx b/apps/mobile/src/screens/SettingsScreen.tsx
index dd30be9d..a93ab5c4 100644
--- a/apps/mobile/src/screens/SettingsScreen.tsx
+++ b/apps/mobile/src/screens/SettingsScreen.tsx
@@ -4,7 +4,7 @@
*/
import React, { useState, useCallback, useEffect } from "react"
-import { Text, StyleSheet, Switch, View, ScrollView, Pressable } from "react-native"
+import { Text, StyleSheet, Switch, View, ScrollView, Pressable, TextInput } from "react-native"
import { ScreenProps, Settings } from "../types/global"
import { useTheme } from "../hooks/useTheme"
import { useAutoSave } from "../hooks/useAutoSave"
@@ -13,9 +13,8 @@ import NativeLocationService from "../services/NativeLocationService"
import { useTracking } from "../contexts/TrackingProvider"
import { FloatingSaveIndicator } from "../components/ui/FloatingSaveIndicator"
import { fonts } from "../styles/typography"
-import { SectionTitle, Card, Container, Divider, SettingRow } from "../components"
-import { ChevronRight } from "lucide-react-native"
-import { StatsCard } from "../components"
+import { SectionTitle, Card, Container, Divider, SettingRow, StatsCard } from "../components"
+import { ChevronRight, ChevronDown, ChevronUp } from "lucide-react-native"
import { logger } from "../utils/logger"
import { ConnectionSettings } from "../components/features/settings/ConnectionSettings"
import { SyncStrategySettings } from "../components/features/settings/SyncStrategySettings"
@@ -43,6 +42,11 @@ export function SettingsScreen({ navigation }: ScreenProps) {
const [unitSystem, setUnitSystem] = useState<UnitSystem>(getUnitSystem)
const [timeFormat, setTimeFormat] = useState<TimeFormat>(getTimeFormat)
+ // Map style URLs
+ const [mapStyleUrlLight, setMapStyleUrlLight] = useState("")
+ const [mapStyleUrlDark, setMapStyleUrlDark] = useState("")
+ const [showMapTileServer, setShowMapTileServer] = useState(false)
+
const selectUnitSystem = useCallback(
async (value: UnitSystem) => {
const prev = unitSystem
@@ -71,6 +75,36 @@ export function SettingsScreen({ navigation }: ScreenProps) {
[timeFormat]
)
+ // Load map style URLs from settings
+ useEffect(() => {
+ Promise.all([
+ NativeLocationService.getSetting("mapStyleUrlLight"),
+ NativeLocationService.getSetting("mapStyleUrlDark")
+ ])
+ .then(([light, dark]) => {
+ setMapStyleUrlLight(light ?? "")
+ setMapStyleUrlDark(dark ?? "")
+ })
+ .catch(() => {})
+ }, [])
+
+ const saveMapStyleUrl = useCallback(async (key: "mapStyleUrlLight" | "mapStyleUrlDark", value: string) => {
+ try {
+ await NativeLocationService.saveSetting(key, value.trim())
+ } catch (err) {
+ logger.error("[SettingsScreen] Failed to save map style URL:", err)
+ }
+ }, [])
+
+ const resetMapStyle = useCallback(() => {
+ setMapStyleUrlLight("")
+ setMapStyleUrlDark("")
+ Promise.all([
+ NativeLocationService.saveSetting("mapStyleUrlLight", ""),
+ NativeLocationService.saveSetting("mapStyleUrlDark", "")
+ ]).catch((err) => logger.error("[SettingsScreen] Failed to reset map style URLs:", err))
+ }, [])
+
// Sync endpoint input with settings changes
useEffect(() => {
setEndpointInput(settings.endpoint || "")
@@ -117,6 +151,10 @@ export function SettingsScreen({ navigation }: ScreenProps) {
[setSettings, immediateSaveAndRestart, restartTracking]
)
+ const handleNavigateDataManagement = useCallback(() => {
+ navigation.navigate("Data Management")
+ }, [navigation])
+
return (
<Container>
<ScrollView
@@ -135,7 +173,7 @@ export function SettingsScreen({ navigation }: ScreenProps) {
sentCount={sentCount}
todayCount={todayCount}
interval={settings.interval.toString()}
- onManageClick={() => navigation.navigate("Data Management")}
+ onManageClick={handleNavigateDataManagement}
colors={colors}
/>
@@ -219,14 +257,74 @@ export function SettingsScreen({ navigation }: ScreenProps) {
]}
onPress={() => selectTimeFormat(fmt)}
>
- <Text style={[styles.chipLabel, { color: selected ? colors.primary : colors.text }]}>
- {fmt === "24h" ? "24h" : "12h"}
- </Text>
+ <Text style={[styles.chipLabel, { color: selected ? colors.primary : colors.text }]}>{fmt}</Text>
</Pressable>
)
})}
</View>
</SettingRow>
+
+ <Divider />
+
+ <Pressable
+ style={({ pressed }) => [styles.linkRow, pressed && { opacity: 0.6 }]}
+ onPress={() => setShowMapTileServer(!showMapTileServer)}
+ >
+ <Text style={[styles.linkLabel, { color: colors.text }]}>Map Tile Server</Text>
+ {showMapTileServer ? (
+ <ChevronUp size={20} color={colors.textLight} />
+ ) : (
+ <ChevronDown size={20} color={colors.textLight} />
+ )}
+ </Pressable>
+
+ {showMapTileServer && (
+ <View style={styles.mapTilePanel}>
+ <Divider />
+ <Text style={[styles.mapStyleSub, styles.mapStyleSubFirst, { color: colors.textSecondary }]}>
+ Light style URL
+ </Text>
+ <TextInput
+ style={[
+ styles.mapStyleInput,
+ { borderColor: colors.border, color: colors.text, backgroundColor: colors.background }
+ ]}
+ value={mapStyleUrlLight}
+ onChangeText={setMapStyleUrlLight}
+ onBlur={() => saveMapStyleUrl("mapStyleUrlLight", mapStyleUrlLight)}
+ placeholder="Default"
+ placeholderTextColor={colors.placeholder}
+ autoCapitalize="none"
+ autoCorrect={false}
+ keyboardType="url"
+ />
+ <Text style={[styles.mapStyleSub, styles.mapStyleSubSecond, { color: colors.textSecondary }]}>
+ Dark style URL
+ </Text>
+ <TextInput
+ style={[
+ styles.mapStyleInput,
+ { borderColor: colors.border, color: colors.text, backgroundColor: colors.background }
+ ]}
+ value={mapStyleUrlDark}
+ onChangeText={setMapStyleUrlDark}
+ onBlur={() => saveMapStyleUrl("mapStyleUrlDark", mapStyleUrlDark)}
+ placeholder="Default"
+ placeholderTextColor={colors.placeholder}
+ autoCapitalize="none"
+ autoCorrect={false}
+ keyboardType="url"
+ />
+ <View style={styles.mapStyleFooter}>
+ <Text style={[styles.mapStyleHint, { color: colors.textLight }]}>Leave empty to use the default</Text>
+ {mapStyleUrlLight.trim() || mapStyleUrlDark.trim() ? (
+ <Pressable onPress={resetMapStyle} style={({ pressed }) => pressed && { opacity: 0.6 }}>
+ <Text style={[styles.mapStyleHint, { color: colors.primary }]}>Reset to default</Text>
+ </Pressable>
+ ) : null}
+ </View>
+ </View>
+ )}
</Card>
</View>
@@ -249,6 +347,21 @@ export function SettingsScreen({ navigation }: ScreenProps) {
<Divider />
+ <Pressable
+ style={({ pressed }) => [styles.linkRow, pressed && { opacity: 0.6 }]}
+ onPress={() => navigation.navigate("Offline Maps")}
+ >
+ <View style={styles.linkContent}>
+ <Text style={[styles.linkLabel, { color: colors.text }]}>Offline Maps</Text>
+ <Text style={[styles.linkSub, { color: colors.textSecondary }]}>
+ Download map tiles for use without internet
+ </Text>
+ </View>
+ <ChevronRight size={20} color={colors.textLight} />
+ </Pressable>
+
+ <Divider />
+
<Pressable
style={({ pressed }) => [styles.linkRow, pressed && { opacity: 0.6 }]}
onPress={() => navigation.navigate("Data Management")}
@@ -335,5 +448,33 @@ const styles = StyleSheet.create({
chipLabel: {
fontSize: 13,
...fonts.semiBold
+ },
+ mapTilePanel: {
+ marginTop: 4,
+ paddingBottom: 4
+ },
+ mapStyleSub: {
+ fontSize: 12,
+ ...fonts.medium,
+ marginBottom: 6
+ },
+ mapStyleSubFirst: { marginTop: 12 },
+ mapStyleSubSecond: { marginTop: 10 },
+ mapStyleInput: {
+ borderWidth: 1.5,
+ padding: 12,
+ borderRadius: 12,
+ fontSize: 13,
+ ...fonts.regular
+ },
+ mapStyleFooter: {
+ flexDirection: "row",
+ justifyContent: "space-between",
+ alignItems: "center",
+ marginTop: 8
+ },
+ mapStyleHint: {
+ fontSize: 11,
+ ...fonts.regular
}
})
diff --git a/apps/mobile/src/screens/__tests__/GeofenceScreen.test.tsx b/apps/mobile/src/screens/__tests__/GeofenceScreen.test.tsx
index e0ff6de9..662fb13b 100644
--- a/apps/mobile/src/screens/__tests__/GeofenceScreen.test.tsx
+++ b/apps/mobile/src/screens/__tests__/GeofenceScreen.test.tsx
@@ -77,7 +77,8 @@ jest.mock("../../services/NativeLocationService", () => ({
checkCurrentPauseZone: (...args: any[]) => mockCheckCurrentPauseZone(...args),
isNetworkAvailable: (...args: any[]) => mockIsNetworkAvailable(...args),
recheckZoneSettings: (...args: any[]) => mockRecheckZoneSettings(...args),
- getMostRecentLocation: (...args: any[]) => mockGetMostRecentLocation(...args)
+ getMostRecentLocation: (...args: any[]) => mockGetMostRecentLocation(...args),
+ getSetting: jest.fn().mockResolvedValue(null)
}
}))
@@ -236,7 +237,7 @@ describe("GeofenceScreen", () => {
expect(getByText("Place Geofence")).toBeTruthy()
})
- fireEvent.changeText(getByPlaceholderText("Home, Office..."), "Test Zone")
+ fireEvent.changeText(getByPlaceholderText("Home, Work..."), "Test Zone")
fireEvent.changeText(getByDisplayValue("50"), "0")
fireEvent.press(getByText("Place Geofence"))
@@ -250,7 +251,7 @@ describe("GeofenceScreen", () => {
expect(getByText("Place Geofence")).toBeTruthy()
})
- fireEvent.changeText(getByPlaceholderText("Home, Office..."), "Test Zone")
+ fireEvent.changeText(getByPlaceholderText("Home, Work..."), "Test Zone")
fireEvent.changeText(getByDisplayValue("50"), "100")
fireEvent.press(getByText("Place Geofence"))
diff --git a/apps/mobile/src/screens/__tests__/OfflineMapsScreen.test.tsx b/apps/mobile/src/screens/__tests__/OfflineMapsScreen.test.tsx
new file mode 100644
index 00000000..64d752a4
--- /dev/null
+++ b/apps/mobile/src/screens/__tests__/OfflineMapsScreen.test.tsx
@@ -0,0 +1,416 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+import React from "react"
+import { render, fireEvent, waitFor } from "@testing-library/react-native"
+import { OfflineMapsScreen } from "../OfflineMapsScreen"
+
+// --- MapLibre ---
+jest.mock("@maplibre/maplibre-react-native", () => ({
+ ShapeSource: () => null,
+ FillLayer: () => null,
+ LineLayer: () => null
+}))
+
+// --- Navigation ---
+const mockNavigation = { navigate: jest.fn() }
+
+// --- Focus hook: call immediately on mount ---
+jest.mock("@react-navigation/native", () => ({
+ useFocusEffect: (cb: Function) => {
+ const { useEffect } = require("react")
+ useEffect(() => {
+ const cleanup = cb()
+ return cleanup
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [])
+ }
+}))
+
+// --- Theme ---
+jest.mock("../../hooks/useTheme", () => ({
+ useTheme: () => ({
+ colors: {
+ primary: "#0d9488",
+ primaryDark: "#115E59",
+ border: "#e5e7eb",
+ text: "#111",
+ textSecondary: "#6b7280",
+ textLight: "#9ca3af",
+ background: "#fff",
+ info: "#3b82f6",
+ success: "#22c55e",
+ error: "#ef4444",
+ warning: "#f59e0b",
+ card: "#fff",
+ backgroundElevated: "#f9fafb",
+ placeholder: "#9ca3af",
+ textOnPrimary: "#fff",
+ link: "#0d9488"
+ }
+ })
+}))
+
+// --- Tracking context ---
+jest.mock("../../contexts/TrackingProvider", () => ({
+ useCoords: () => ({ latitude: 52.52, longitude: 13.405 })
+}))
+
+// --- Modal service ---
+const mockShowAlert = jest.fn()
+const mockShowConfirm = jest.fn()
+
+jest.mock("../../services/modalService", () => ({
+ showAlert: (...args: any[]) => mockShowAlert(...args),
+ showConfirm: (...args: any[]) => mockShowConfirm(...args)
+}))
+
+// --- Native service ---
+const mockIsNetworkAvailable = jest.fn()
+const mockIsUnmeteredConnection = jest.fn()
+const mockGetAvailableStorageMB = jest.fn()
+
+jest.mock("../../services/NativeLocationService", () => ({
+ __esModule: true,
+ default: {
+ isNetworkAvailable: (...args: any[]) => mockIsNetworkAvailable(...args),
+ isUnmeteredConnection: (...args: any[]) => mockIsUnmeteredConnection(...args),
+ getAvailableStorageMB: (...args: any[]) => mockGetAvailableStorageMB(...args),
+ getMostRecentLocation: jest.fn().mockResolvedValue(null),
+ getSetting: jest.fn().mockResolvedValue(null)
+ }
+}))
+
+// --- OfflinePackManager ---
+const mockLoadOfflineAreas = jest.fn()
+const mockLoadOfflineAreaBounds = jest.fn()
+const mockCreateOfflinePack = jest.fn()
+const mockDeleteOfflineArea = jest.fn()
+const mockSaveOfflineAreaBounds = jest.fn()
+const mockRemoveOfflineAreaBounds = jest.fn()
+const mockEstimateSizeLabel = jest.fn()
+const mockEstimateSizeBytes = jest.fn()
+const mockWillExceedTileLimit = jest.fn()
+
+jest.mock("../../components/features/map/OfflinePackManager", () => ({
+ DOWNLOAD_STATE: { INACTIVE: 0, ACTIVE: 1, COMPLETE: 2, FAILED: 3 },
+ formatBytes: jest.fn().mockReturnValue("5.0 MB"),
+ loadOfflineAreas: (...args: any[]) => mockLoadOfflineAreas(...args),
+ loadOfflineAreaBounds: (...args: any[]) => mockLoadOfflineAreaBounds(...args),
+ createOfflinePack: (...args: any[]) => mockCreateOfflinePack(...args),
+ deleteOfflineArea: (...args: any[]) => mockDeleteOfflineArea(...args),
+ saveOfflineAreaBounds: (...args: any[]) => mockSaveOfflineAreaBounds(...args),
+ removeOfflineAreaBounds: (...args: any[]) => mockRemoveOfflineAreaBounds(...args),
+ unsubscribeOfflinePack: jest.fn(),
+ estimateSizeLabel: (...args: any[]) => mockEstimateSizeLabel(...args),
+ estimateSizeBytes: (...args: any[]) => mockEstimateSizeBytes(...args),
+ willExceedTileLimit: (...args: any[]) => mockWillExceedTileLimit(...args)
+}))
+
+// --- ColotaMapView: fires onRegionDidChange on mount to supply bounds ---
+jest.mock("../../components/features/map/ColotaMapView", () => {
+ const R = require("react")
+ const { View } = require("react-native")
+ return {
+ ColotaMapView: R.forwardRef(({ onRegionDidChange, children }: any, _ref: any) => {
+ R.useEffect(() => {
+ onRegionDidChange?.({
+ isUserInteraction: false,
+ visibleBounds: [
+ [13.5, 52.6],
+ [13.4, 52.5]
+ ]
+ })
+ }, [])
+ return R.createElement(View, { testID: "map-view" }, children)
+ })
+ }
+})
+
+// --- MapCenterButton ---
+jest.mock("../../components/features/map/MapCenterButton", () => ({
+ MapCenterButton: () => null
+}))
+
+// --- UI components ---
+jest.mock("../../components", () => {
+ const R = require("react")
+ const { View, Text } = require("react-native")
+ return {
+ Container: ({ children }: any) => R.createElement(View, null, children),
+ SectionTitle: ({ children }: any) => R.createElement(Text, null, children),
+ Card: ({ children, style }: any) => R.createElement(View, { style }, children)
+ }
+})
+
+// ---------------------------------------------------------------------------
+
+beforeEach(() => {
+ jest.clearAllMocks()
+ mockIsNetworkAvailable.mockResolvedValue(true)
+ mockIsUnmeteredConnection.mockResolvedValue(true)
+ mockGetAvailableStorageMB.mockResolvedValue(1000)
+ mockLoadOfflineAreas.mockResolvedValue([])
+ mockLoadOfflineAreaBounds.mockResolvedValue([])
+ mockSaveOfflineAreaBounds.mockResolvedValue(undefined)
+ mockRemoveOfflineAreaBounds.mockResolvedValue(undefined)
+ mockDeleteOfflineArea.mockResolvedValue(undefined)
+ mockEstimateSizeLabel.mockReturnValue("~5 MB")
+ mockEstimateSizeBytes.mockReturnValue(5 * 1024 * 1024)
+ mockWillExceedTileLimit.mockReturnValue(false)
+ mockCreateOfflinePack.mockResolvedValue(undefined)
+ mockShowConfirm.mockResolvedValue(false)
+})
+
+function renderScreen() {
+ return render(<OfflineMapsScreen navigation={mockNavigation as any} />)
+}
+
+// Waits for map bounds to be set and the estimate label to appear
+async function waitForMapReady(findByText: ReturnType<typeof render>["findByText"]) {
+ return findByText("~5 MB estimated")
+}
+
+// ---------------------------------------------------------------------------
+
+describe("OfflineMapsScreen", () => {
+ it("renders the name input and download button", async () => {
+ const { getByPlaceholderText, findByText, getByTestId } = renderScreen()
+ await waitForMapReady(findByText)
+ expect(getByPlaceholderText("Home area, Trail...")).toBeTruthy()
+ expect(getByTestId("download-btn")).toBeTruthy()
+ })
+
+ it("shows 'Missing Name' alert when downloading with empty name", async () => {
+ const { findByText, getByTestId } = renderScreen()
+ await waitForMapReady(findByText)
+ fireEvent.press(getByTestId("download-btn"))
+ expect(mockShowAlert).toHaveBeenCalledWith("Missing Name", expect.any(String), "warning")
+ })
+
+ it("shows 'Offline' alert when downloading while offline", async () => {
+ mockIsNetworkAvailable.mockResolvedValue(false)
+ const { findByText, getByTestId, getByPlaceholderText } = renderScreen()
+ await waitForMapReady(findByText)
+ fireEvent.changeText(getByPlaceholderText("Home area, Trail..."), "my area")
+ fireEvent.press(getByTestId("download-btn"))
+ await waitFor(() => {
+ expect(mockShowAlert).toHaveBeenCalledWith("Offline", expect.any(String), "warning")
+ })
+ })
+
+ it("shows 'Duplicate Name' alert when name matches an existing area", async () => {
+ mockLoadOfflineAreas.mockResolvedValue([{ name: "home", sizeBytes: 1024, isComplete: true, isActive: false }])
+ const { findByText, getByTestId, getByPlaceholderText } = renderScreen()
+ await waitForMapReady(findByText)
+ fireEvent.changeText(getByPlaceholderText("Home area, Trail..."), "home")
+ fireEvent.press(getByTestId("download-btn"))
+ expect(mockShowAlert).toHaveBeenCalledWith("Duplicate Name", expect.any(String), "warning")
+ })
+
+ it("shows mobile data confirm dialog when not on WiFi before downloading", async () => {
+ mockIsUnmeteredConnection.mockResolvedValue(false)
+ const { findByText, getByTestId, getByPlaceholderText } = renderScreen()
+ await waitForMapReady(findByText)
+ fireEvent.changeText(getByPlaceholderText("Home area, Trail..."), "my area")
+ fireEvent.press(getByTestId("download-btn"))
+ await waitFor(() => {
+ expect(mockShowConfirm).toHaveBeenCalledWith(expect.objectContaining({ title: "Mobile Data" }))
+ })
+ })
+
+ it("aborts download when user cancels the mobile data warning", async () => {
+ mockIsUnmeteredConnection.mockResolvedValue(false)
+ mockShowConfirm.mockResolvedValue(false)
+ const { findByText, getByTestId, getByPlaceholderText } = renderScreen()
+ await waitForMapReady(findByText)
+ fireEvent.changeText(getByPlaceholderText("Home area, Trail..."), "my area")
+ fireEvent.press(getByTestId("download-btn"))
+ await waitFor(() => {
+ expect(mockShowConfirm).toHaveBeenCalledWith(expect.objectContaining({ title: "Mobile Data" }))
+ expect(mockCreateOfflinePack).not.toHaveBeenCalled()
+ })
+ })
+
+ it("shows 'Storage Full' alert when estimated size exceeds available storage", async () => {
+ mockGetAvailableStorageMB.mockResolvedValue(1)
+ mockEstimateSizeBytes.mockReturnValue(10 * 1024 * 1024)
+ const { findByText, getByTestId, getByPlaceholderText } = renderScreen()
+ await waitForMapReady(findByText)
+ fireEvent.changeText(getByPlaceholderText("Home area, Trail..."), "big area")
+ fireEvent.press(getByTestId("download-btn"))
+ await waitFor(() => {
+ expect(mockShowAlert).toHaveBeenCalledWith("Storage Full", expect.any(String), "warning")
+ })
+ })
+
+ it("calls createOfflinePack with correct args when user confirms download", async () => {
+ mockShowConfirm.mockResolvedValue(true)
+ const { findByText, getByTestId, getByPlaceholderText } = renderScreen()
+ await waitForMapReady(findByText)
+ fireEvent.changeText(getByPlaceholderText("Home area, Trail..."), "new area")
+ fireEvent.press(getByTestId("download-btn"))
+ await waitFor(() => {
+ expect(mockCreateOfflinePack).toHaveBeenCalledWith(
+ "new area",
+ expect.any(Array),
+ expect.any(Array),
+ expect.any(Function),
+ expect.any(Function)
+ )
+ })
+ })
+
+ it("does not call createOfflinePack when user cancels the confirmation", async () => {
+ mockShowConfirm.mockResolvedValue(false)
+ const { findByText, getByTestId, getByPlaceholderText } = renderScreen()
+ await waitForMapReady(findByText)
+ fireEvent.changeText(getByPlaceholderText("Home area, Trail..."), "new area")
+ fireEvent.press(getByTestId("download-btn"))
+ await waitFor(() => {
+ expect(mockShowConfirm).toHaveBeenCalled()
+ expect(mockCreateOfflinePack).not.toHaveBeenCalled()
+ })
+ })
+
+ it("cancels an in-flight download and deletes the partial pack", async () => {
+ mockShowConfirm.mockResolvedValue(true)
+ mockCreateOfflinePack.mockReturnValue(new Promise(() => {})) // never resolves - simulates active download
+ const { findByText, getByTestId, getByPlaceholderText } = renderScreen()
+ await waitForMapReady(findByText)
+ fireEvent.changeText(getByPlaceholderText("Home area, Trail..."), "my area")
+ fireEvent.press(getByTestId("download-btn"))
+ fireEvent.press(await findByText("Cancel Download"))
+ await waitFor(() => {
+ expect(mockDeleteOfflineArea).toHaveBeenCalledWith("my area")
+ expect(mockRemoveOfflineAreaBounds).toHaveBeenCalledWith("my area")
+ })
+ })
+
+ it("shows saved areas loaded on mount", async () => {
+ mockLoadOfflineAreas.mockResolvedValue([
+ { name: "forest trail", sizeBytes: 5_000_000, isComplete: true, isActive: false }
+ ])
+ const { findByText } = renderScreen()
+ await findByText("forest trail")
+ })
+
+ it("shows size for a saved area", async () => {
+ mockLoadOfflineAreas.mockResolvedValue([
+ { name: "my park", sizeBytes: 2_000_000, isComplete: true, isActive: false }
+ ])
+ const { findByText } = renderScreen()
+ await findByText("5.0 MB")
+ })
+
+ it("shows stale indicator when style URL has changed", async () => {
+ mockLoadOfflineAreas.mockResolvedValue([
+ { name: "old area", sizeBytes: 1_000_000, isComplete: true, isActive: false }
+ ])
+ mockLoadOfflineAreaBounds.mockResolvedValue([
+ { name: "old area", ne: [13.5, 52.6], sw: [13.4, 52.5], styleUrl: "https://old.server/style.json" }
+ ])
+ // getSetting returns a different URL only for the style key
+ const NativeService = require("../../services/NativeLocationService").default
+ NativeService.getSetting.mockImplementation((key: string) =>
+ key === "mapStyleUrlLight" ? Promise.resolve("https://new.server/style.json") : Promise.resolve(null)
+ )
+ const { findByTestId } = renderScreen()
+ await findByTestId("stale-indicator-old area")
+ })
+
+ it("calls deleteOfflineArea and removeOfflineAreaBounds when user confirms delete", async () => {
+ mockLoadOfflineAreas.mockResolvedValue([
+ { name: "my park", sizeBytes: 2_000_000, isComplete: true, isActive: false }
+ ])
+ mockShowConfirm.mockResolvedValue(true)
+ const { findByText, getByTestId } = renderScreen()
+ await findByText("my park")
+ fireEvent.press(getByTestId("delete-btn-my park"))
+ await waitFor(() => {
+ expect(mockDeleteOfflineArea).toHaveBeenCalledWith("my park")
+ expect(mockRemoveOfflineAreaBounds).toHaveBeenCalledWith("my park")
+ })
+ })
+
+ it("does not delete when user cancels the delete confirmation", async () => {
+ mockLoadOfflineAreas.mockResolvedValue([
+ { name: "my park", sizeBytes: 2_000_000, isComplete: true, isActive: false }
+ ])
+ mockShowConfirm.mockResolvedValue(false)
+ const { findByText, getByTestId } = renderScreen()
+ await findByText("my park")
+ fireEvent.press(getByTestId("delete-btn-my park"))
+ await waitFor(() => {
+ expect(mockShowConfirm).toHaveBeenCalled()
+ expect(mockDeleteOfflineArea).not.toHaveBeenCalled()
+ })
+ })
+
+ it("calls deleteOfflineArea and createOfflinePack when user confirms re-download", async () => {
+ mockLoadOfflineAreas.mockResolvedValue([
+ { name: "existing area", sizeBytes: 5_000_000, isComplete: true, isActive: false }
+ ])
+ mockLoadOfflineAreaBounds.mockResolvedValue([
+ {
+ name: "existing area",
+ ne: [13.5, 52.6],
+ sw: [13.4, 52.5],
+ styleUrl: "https://maps.mxd.codes/styles/bright/style.json"
+ }
+ ])
+ mockShowConfirm.mockResolvedValue(true)
+ mockDeleteOfflineArea.mockResolvedValue(undefined)
+ const { findByText, getByTestId } = renderScreen()
+ await findByText("existing area")
+ fireEvent.press(getByTestId("refresh-btn-existing area"))
+ await waitFor(() => {
+ expect(mockDeleteOfflineArea).toHaveBeenCalledWith("existing area")
+ expect(mockCreateOfflinePack).toHaveBeenCalledWith(
+ "existing area",
+ [13.5, 52.6],
+ [13.4, 52.5],
+ expect.any(Function),
+ expect.any(Function)
+ )
+ })
+ })
+
+ it("does not re-download when user cancels refresh confirmation", async () => {
+ mockLoadOfflineAreas.mockResolvedValue([
+ { name: "existing area", sizeBytes: 5_000_000, isComplete: true, isActive: false }
+ ])
+ mockLoadOfflineAreaBounds.mockResolvedValue([
+ {
+ name: "existing area",
+ ne: [13.5, 52.6],
+ sw: [13.4, 52.5],
+ styleUrl: "https://maps.mxd.codes/styles/bright/style.json"
+ }
+ ])
+ mockShowConfirm.mockResolvedValue(false)
+ const { findByText, getByTestId } = renderScreen()
+ await findByText("existing area")
+ fireEvent.press(getByTestId("refresh-btn-existing area"))
+ await waitFor(() => {
+ expect(mockShowConfirm).toHaveBeenCalled()
+ expect(mockCreateOfflinePack).not.toHaveBeenCalled()
+ })
+ })
+
+ it("shows tile limit warning in the confirmation when area is large", async () => {
+ mockWillExceedTileLimit.mockReturnValue(true)
+ mockShowConfirm.mockResolvedValue(false)
+ const { findByText, getByTestId, getByPlaceholderText } = renderScreen()
+ await waitForMapReady(findByText)
+ fireEvent.changeText(getByPlaceholderText("Home area, Trail..."), "big area")
+ fireEvent.press(getByTestId("download-btn"))
+ await waitFor(() => {
+ expect(mockShowConfirm).toHaveBeenCalledWith(
+ expect.objectContaining({ message: expect.stringContaining("large") })
+ )
+ })
+ })
+})
diff --git a/apps/mobile/src/screens/__tests__/SettingsScreen.test.tsx b/apps/mobile/src/screens/__tests__/SettingsScreen.test.tsx
index 80c7fc19..cb9080a8 100644
--- a/apps/mobile/src/screens/__tests__/SettingsScreen.test.tsx
+++ b/apps/mobile/src/screens/__tests__/SettingsScreen.test.tsx
@@ -64,7 +64,8 @@ jest.mock("../../services/NativeLocationService", () => ({
today: 10,
databaseSizeMB: 1.2
}),
- saveSetting: (...args: any[]) => mockSaveSetting(...args)
+ saveSetting: (...args: any[]) => mockSaveSetting(...args),
+ getSetting: jest.fn().mockResolvedValue(null)
}
}))
diff --git a/apps/mobile/src/screens/index.ts b/apps/mobile/src/screens/index.ts
index 56cac680..9c266cc0 100644
--- a/apps/mobile/src/screens/index.ts
+++ b/apps/mobile/src/screens/index.ts
@@ -18,3 +18,4 @@ export { ProfileEditorScreen } from "./ProfileEditorScreen"
export { AboutScreen } from "./AboutScreen"
export { SetupImportScreen } from "./SetupImportScreen"
export { TripDetailScreen } from "./TripDetailScreen"
+export { OfflineMapsScreen } from "./OfflineMapsScreen"
diff --git a/apps/mobile/src/services/NativeLocationService.ts b/apps/mobile/src/services/NativeLocationService.ts
index 8317d0bd..64dcb164 100644
--- a/apps/mobile/src/services/NativeLocationService.ts
+++ b/apps/mobile/src/services/NativeLocationService.ts
@@ -487,6 +487,23 @@ class NativeLocationService {
return this.safeExecute(() => LocationServiceModule.isNetworkAvailable(), false, "isNetworkAvailable failed")
}
+ /**
+ * Returns true if the current connection is unmetered (WiFi or ethernet).
+ * Returns false on mobile data or when offline.
+ */
+ static async isUnmeteredConnection(): Promise<boolean> {
+ this.ensureModule()
+ return this.safeExecute(() => LocationServiceModule.isUnmeteredConnection(), false, "isUnmeteredConnection failed")
+ }
+
+ /**
+ * Returns available device storage in MB, or -1 if the check fails.
+ */
+ static async getAvailableStorageMB(): Promise<number> {
+ this.ensureModule()
+ return this.safeExecute(() => LocationServiceModule.getAvailableStorageMB(), -1, "getAvailableStorageMB failed")
+ }
+
// ============================================================================
// BATTERY OPTIMIZATION
// ============================================================================
diff --git a/apps/mobile/src/utils/__tests__/geo.test.ts b/apps/mobile/src/utils/__tests__/geo.test.ts
index f73a8b57..cc179b09 100644
--- a/apps/mobile/src/utils/__tests__/geo.test.ts
+++ b/apps/mobile/src/utils/__tests__/geo.test.ts
@@ -109,6 +109,12 @@ describe("formatDistance", () => {
expect(formatDistance(1609.344)).toBe("1.0 mi")
})
+ it("normalizes extended locale tags - en-US-u-nu-latn treated as imperial", async () => {
+ await setPreferences("", "")
+ mockLocale("en-US-u-nu-latn")
+ expect(formatDistance(1609.344)).toBe("1.0 mi")
+ })
+
it("formats 0 meters correctly", async () => {
await setPreferences("metric", "")
expect(formatDistance(0)).toBe("0.0 km")
diff --git a/apps/mobile/src/utils/geo.ts b/apps/mobile/src/utils/geo.ts
index 8ecd9894..be4f9761 100644
--- a/apps/mobile/src/utils/geo.ts
+++ b/apps/mobile/src/utils/geo.ts
@@ -5,7 +5,9 @@
import NativeLocationService from "../services/NativeLocationService"
-const EARTH_RADIUS_METERS = 6371000.0
+const EARTH_RADIUS_METERS = 6_371_000
+const FEET_PER_METER = 3.28084
+const MPH_PER_MPS = 2.23694
/** Haversine formula - mirrors GeofenceHelper.kt */
export function haversine(lat1: number, lon1: number, lat2: number, lon2: number): number {
@@ -49,16 +51,6 @@ function localeUses12h(): boolean {
}
}
-/** Resolve the effective unit system, using locale detection as fallback. */
-function resolveUnitSystem(): UnitSystem {
- return cachedUnitSystem ?? (localeUsesMiles() ? "imperial" : "metric")
-}
-
-/** Resolve the effective time format, using locale detection as fallback. */
-function resolveTimeFormat(): TimeFormat {
- return cachedTimeFormat ?? (localeUses12h() ? "12h" : "24h")
-}
-
/** Load display preferences from native storage. Call on app start and after saving. */
export async function loadDisplayPreferences(): Promise<void> {
try {
@@ -73,29 +65,29 @@ export async function loadDisplayPreferences(): Promise<void> {
}
}
-export function getUnitSystem(): UnitSystem {
- return resolveUnitSystem()
-}
-
-export function getTimeFormat(): TimeFormat {
- return resolveTimeFormat()
-}
-
// -- Unit detection --
const MILE_LOCALES = new Set(["en-US", "en-GB", "en-MM", "en-LR"])
function localeUsesMiles(): boolean {
try {
- const locale = Intl.NumberFormat().resolvedOptions().locale
+ const locale = Intl.NumberFormat().resolvedOptions().locale.split("-").slice(0, 2).join("-")
return MILE_LOCALES.has(locale)
} catch {
return false
}
}
+export function getUnitSystem(): UnitSystem {
+ return cachedUnitSystem ?? (localeUsesMiles() ? "imperial" : "metric")
+}
+
+export function getTimeFormat(): TimeFormat {
+ return cachedTimeFormat ?? (localeUses12h() ? "12h" : "24h")
+}
+
function usesMiles(): boolean {
- return resolveUnitSystem() === "imperial"
+ return getUnitSystem() === "imperial"
}
// -- Formatting functions --
@@ -103,7 +95,7 @@ function usesMiles(): boolean {
/** Format m/s into a human-readable speed string. */
export function formatSpeed(metersPerSecond: number): string {
if (usesMiles()) {
- const mph = metersPerSecond * 2.23694
+ const mph = metersPerSecond * MPH_PER_MPS
return `${mph.toFixed(1)} mph`
}
const kmh = metersPerSecond * 3.6
@@ -112,7 +104,7 @@ export function formatSpeed(metersPerSecond: number): string {
/** Return the speed unit info (used by TrackMap). */
export function getSpeedUnit(): { factor: number; unit: string } {
- return usesMiles() ? { factor: 2.23694, unit: "mph" } : { factor: 3.6, unit: "km/h" }
+ return usesMiles() ? { factor: MPH_PER_MPS, unit: "mph" } : { factor: 3.6, unit: "km/h" }
}
/** Format seconds duration as "Xh Ym" or "Ym" */
@@ -152,7 +144,7 @@ export function formatDistance(meters: number): string {
/** Format meters as a short distance string (e.g. "50m" / "164 ft"). */
export function formatShortDistance(meters: number): string {
- if (usesMiles()) return `${Math.round(meters * 3.28084)} ft`
+ if (usesMiles()) return `${Math.round(meters * FEET_PER_METER)} ft`
return `${Math.round(meters)}m`
}
@@ -163,10 +155,10 @@ export function shortDistanceUnit(): string {
/** Convert a user-entered short distance to meters. */
export function inputToMeters(value: number): number {
- return usesMiles() ? value / 3.28084 : value
+ return usesMiles() ? value / FEET_PER_METER : value
}
/** Convert meters to the user's short distance unit for pre-filling inputs. */
export function metersToInput(meters: number): number {
- return usesMiles() ? Math.round(meters * 3.28084) : meters
+ return usesMiles() ? Math.round(meters * FEET_PER_METER) : meters
}