Colota - Android GPS Location tracker
refactor(offline-maps): keep the download live across focus and name what each action costs (#858)
Max Dietrich4e689da65444
diff --git a/apps/docs/docs/guides/offline-maps.md b/apps/docs/docs/guides/offline-maps.mdindex 961e42f9..18692a74 100644--- a/apps/docs/docs/guides/offline-maps.md+++ b/apps/docs/docs/guides/offline-maps.md@@ -2,23 +2,23 @@sidebar_position: 5----# Offline Maps+# Offline mapsDownload 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.import ScreenshotGallery from '@site/src/components/ScreenshotGallery'-<ScreenshotGallery screenshots={[ { src: "/img/screenshots/OfflineMaps.png", label: "Offline Maps" }, ]} />+<ScreenshotGallery screenshots={[ { src: "/img/screenshots/OfflineMaps.png", label: "Offline maps" }, ]} />## Downloading an Area-1. Go to **Settings > Offline Maps**+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+3. Tap the location button to return the map to your last recorded position if needed4. Enter a **name** for the area-5. Check the estimated size and tap **Download 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.+The download runs in the background. A progress bar shows the percentage and the bytes so far. You can leave the screen and come back: the download keeps running and the screen picks it up again.## Zoom Levels@@ -26,29 +26,25 @@ Offline packs cover zoom levels 8-14. This matches the maximum resolution served## 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+The size estimate stops counting at **100,000 tiles**. Above that the screen says "At least" instead of a figure, and the whole framed area still downloads, so the real size can be well past the estimate. Frame a smaller area, or download several smaller ones 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.+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 and the date each finished.-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.+To free up space, delete areas you no longer need. When the last area is deleted, the tile database is reset, including the map's online tile cache, and the storage is reclaimed by the OS.## Managing Areas-From the **Offline Maps** screen you can:+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+- See every downloaded area with its size and the date it finished. Tap a row, or its rectangle on the map, to show it+- An area reads **Map style changed** when it was downloaded from a different light style URL than the one set now, and **Incomplete** when a download was interrupted. **Download again** replaces its tiles from the current style+- Delete an area. The confirmation names how much it removes, and whether the map's online cache goes with it+- Start a new download. If you are on mobile data the confirmation says so, and a download that would not fit in free storage is refused with both numbers## 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+- For long routes, download the corridor rather than a large bounding box- Offline maps only affect map rendering - GPS tracking, sync, and all other features work independently of the map tile cachediff --git a/apps/docs/docs/guides/tile-server.md b/apps/docs/docs/guides/tile-server.mdindex cb433743..b922eb9c 100644--- a/apps/docs/docs/guides/tile-server.md+++ b/apps/docs/docs/guides/tile-server.md@@ -32,7 +32,7 @@ If you find Colota useful and want to help keep the default server running, cont:::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.+Offline map packs are downloaded from the **light** style URL, whichever tile server that points at. Filling only the dark field leaves downloads coming from the default server. Switching servers won't affect packs you've already downloaded, but new downloads will come from the new one. A pack downloaded under a different light style URL is marked **Map style changed** in Offline maps; **Download again** fetches it from the current one.:::@@ -41,6 +41,8 @@ Offline map packs are downloaded from whichever tile server is configured at the3. Enter your style JSON URLs for light and dark mode4. Leave a field empty to fall back to the default+A URL is checked when you leave the field. If it doesn't start with `http://` or `https://` and name a host, it is refused and the previous value stays in place, so a typo can't leave you with a blank map.+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.**Free hosted alternatives**diff --git a/apps/mobile/src/screens/OfflineMapsScreen.tsx b/apps/mobile/src/screens/OfflineMapsScreen.tsxindex 54ed3ac3..f26993da 100644--- a/apps/mobile/src/screens/OfflineMapsScreen.tsx+++ b/apps/mobile/src/screens/OfflineMapsScreen.tsx@@ -3,954 +3,699 @@* 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 React, { useCallback, useEffect, useMemo, useRef, useState } from "react"+import { ActivityIndicator, ScrollView, StyleSheet, Text, useWindowDimensions, View } from "react-native"+import type { NativeSyntheticEvent } from "react-native"import { GeoJSONSource, Layer, type PressEventWithFeatures } from "@maplibre/maplibre-react-native"-import type { NativeSyntheticEvent, TextInputInstance } from "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 { RefreshCw, Trash2, X } from "lucide-react-native"+import { radius } from "@colota/shared"+import {+ Button,+ Card,+ Container,+ Divider,+ EmptyState,+ FieldMessage,+ IconButton,+ ListItem,+ SectionTitle,+ TextField+} from "../components"+import { ColotaMapView, type ColotaMapRef, type RegionChangePayload } from "../components/features/map/ColotaMapView"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 { formatBytes } from "../utils/format"import {createOfflinePack,- loadOfflineAreas,deleteOfflineArea,- unsubscribeOfflinePack,DOWNLOAD_STATE,- OfflinePackStatus,- OfflineAreaInfo,- OfflineAreaBounds,- estimateSizeLabel,estimateSizeBytes,- willExceedTileLimit,+ estimateSizeLabel,loadOfflineAreaBounds,+ loadOfflineAreas,+ pruneOfflineAreaBounds,+ removeOfflineAreaBounds,saveOfflineAreaBounds,- removeOfflineAreaBounds+ subscribeOfflinePack,+ unsubscribeOfflinePack,+ willExceedTileLimit,+ type OfflineAreaBounds,+ type OfflineAreaInfo,+ type OfflinePackStatus} 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<TextInputInstance | null>- onNameChange: (v: string) => void- onDownload: () => void- onCancelDownload: () => void+import { useCoords } from "../contexts/TrackingProvider"+import { useTheme } from "../hooks/useTheme"+import NativeLocationService from "../services/NativeLocationService"+import { showAlert, showConfirm } from "../services/modalService"+import { logger } from "../utils/logger"+import {+ areaFeature,+ areasCollection,+ cornersOf,+ deleteAreaConfirm,+ describeArea,+ downloadConfirm,+ downloadLine,+ duplicateNameError,+ INTRO_LINE,+ progressCaption,+ redownloadConfirm,+ ROW_HINT,+ storageMessage,+ type Bounds,+ type Estimate,+ type RowTone+} from "../utils/offlineArea"+import { fonts, fontSizes, lineHeights } from "../styles/typography"+import {+ DEFAULT_MAP_ZOOM,+ GEOFENCE_ZOOM_PADDING,+ MAP_ANIMATION_DURATION_MS,+ MAP_STYLE_URL_LIGHT,+ space,+ WORLD_MAP_ZOOM+} from "../constants"+import type { ScreenProps } from "../types/global"++const MAP_VIEWPORT_SHARE = 0.5+const WORLD_CENTER: [number, number] = [0, 20]+const STORAGE_HEADROOM = 0.9+const BYTES_PER_MB = 1024 * 1024+const [FIT_TOP, FIT_RIGHT, FIT_BOTTOM, FIT_LEFT] = GEOFENCE_ZOOM_PADDING+const FIT_PADDING = { top: FIT_TOP, right: FIT_RIGHT, bottom: FIT_BOTTOM, left: FIT_LEFT }++type Fix = { latitude: number; longitude: number; accuracy: number }+type Download = { name: string; bounds: Bounds | null }+type Busy = { kind: "start" | "stop" | "delete" | "redownload"; name: string }++const NO_CONNECTION = {+ title: "No connection",+ message: "Downloading map tiles needs a network. Saved areas still work."+} as const++function estimateFor(bounds: Bounds): Estimate {+ const { ne, sw } = cornersOf(bounds)+ return { label: estimateSizeLabel(ne, sw), bytes: estimateSizeBytes(ne, sw), large: willExceedTileLimit(ne, sw) }}-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 + "40" },- pressed && { opacity: colors.pressedOpacity }- ]}- >- <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: colors.pressedOpacity }- ]}- 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 { height: viewportHeight } = useWindowDimensions()+ const mapHeight = Math.round(viewportHeight * MAP_VIEWPORT_SHARE)+ const coords = useCoords()- const [areas, setAreas] = useState<OfflineAreaInfo[]>([])+ const [areas, setAreas] = useState<OfflineAreaInfo[] | null>(null)const [areaBounds, setAreaBounds] = useState<OfflineAreaBounds[]>([])- const newNameRef = useRef("")- const nameInputRef = useRef<TextInputInstance>(null)-- const currentBoundsRef = useRef<[[number, number], [number, number]] | null>(null)- const [estimatedSizeLabel, setEstimatedSizeLabel] = useState<string | null>(null)-+ const [name, setName] = useState("")+ const [estimate, setEstimate] = useState<Estimate | null>(null)+ // `undefined` until the database has answered, so the tiles never open on the world view and jump.+ const [lastFix, setLastFix] = useState<Fix | null | undefined>(undefined)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 [download, setDownload] = useState<Download | null>(null)const [downloadProgress, setDownloadProgress] = useState<OfflinePackStatus | null>(null)- const [downloadBounds, setDownloadBounds] = useState<[[number, number], [number, number]] | null>(null)- const [downloadError, setDownloadError] = useState<string | null>(null)+ const [busy, setBusy] = useState<Busy | null>(null)- // Track the active pack name so we can unsubscribe on unmount+ // A ref, not the state, because two presses inside one render both read the same state value.+ const busyRef = useRef(false)const activePackNameRef = useRef<string | null>(null)-+ // True between createOfflinePack being called and its promise settling: a cancel in that window+ // has nothing to delete yet, so the post-create continuation deletes it once, when native answers.+ const createPendingRef = useRef(false)+ const currentBoundsRef = useRef<Bounds | null>(null)+ const tileErrorCountRef = useRef(0)+ const lastTileErrorRef = useRef<unknown>(null)const mapRef = useRef<ColotaMapRef>(null)- const initialCenter = useRef<{ latitude: number; longitude: number } | null>(null)- // Unsubscribe listeners when the screen unmounts mid-download+ const listAreas = useMemo(() => (areas ?? []).filter((a) => a.name !== download?.name), [areas, download])+ const takenNames = useMemo(() => listAreas.map((a) => a.name), [listAreas])+ const nameError = duplicateNameError(name, takenNames)+useEffect(() => {+ if (coords) {+ setLastFix({ latitude: coords.latitude, longitude: coords.longitude, accuracy: coords.accuracy ?? 0 })+ return+ }+ let active = true+ NativeLocationService.getMostRecentLocation()+ .then((latest) => {+ if (!active) return+ setLastFix(+ latest ? { latitude: latest.latitude, longitude: latest.longitude, accuracy: latest.accuracy ?? 0 } : null+ )+ })+ .catch((err) => {+ logger.error("[OfflineMapsScreen] Failed to read the last known location:", err)+ if (active) setLastFix(null)+ })return () => {- if (activePackNameRef.current) {- unsubscribeOfflinePack(activePackNameRef.current)- }+ active = false}- }, [])+ }, [coords])- // Re-check network state when the app comes back to the foregrounduseEffect(() => {- const sub = AppState.addEventListener("change", (state) => {- if (state === "active") {- NativeLocationService.isNetworkAvailable().then((available) => setIsOffline(!available))- }- })- return () => sub.remove()+ return () => {+ if (activePackNameRef.current) unsubscribeOfflinePack(activePackNameRef.current)+ }}, [])- 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)))+ const reportTileErrors = useCallback((packName: string) => {+ if (tileErrorCountRef.current === 0) return+ logger.warn(+ `[OfflineMapsScreen] ${tileErrorCountRef.current} tile error(s) total downloading '${packName}', last:`,+ lastTileErrorRef.current+ )+ tileErrorCountRef.current = 0+ }, [])++ const handleTileError = useCallback(+ (packName: string) => (err: unknown) => {+ if (activePackNameRef.current !== packName) return+ tileErrorCountRef.current += 1+ lastTileErrorRef.current = err+ if (tileErrorCountRef.current === 1) {+ logger.warn(`[OfflineMapsScreen] Tile error downloading '${packName}':`, err)}- setAreaBounds(validBounds)+ },+ []+ )++ const loadAreasRef = useRef<() => Promise<void>>(async () => {})++ const finishDownload = useCallback(async (packName: string) => {+ try {+ const entry = (await loadOfflineAreaBounds()).find((b) => b.name === packName)+ if (entry) await saveOfflineAreaBounds({ ...entry, downloadedAt: Date.now() })} catch (err) {- logger.error("[OfflineMapsScreen] Failed to load offline areas:", err)+ logger.error("[OfflineMapsScreen] Failed to stamp completion:", err)}+ await loadAreasRef.current()}, [])- useFocusEffect(- useCallback(() => {- loadAreas()- NativeLocationService.isNetworkAvailable().then((available) => setIsOffline(!available))- NativeLocationService.getSetting("mapStyleUrlLight").then((url) => {- setCurrentStyleUrl(url || MAP_STYLE_URL_LIGHT)- })- }, [loadAreas])+ const handleProgress = useCallback(+ (packName: string) => (status: OfflinePackStatus) => {+ if (activePackNameRef.current !== packName) return+ setDownloadProgress(status)+ if (status.state !== DOWNLOAD_STATE.COMPLETE) return+ reportTileErrors(packName)+ activePackNameRef.current = null+ setDownload(null)+ setDownloadProgress(null)+ setName("")+ finishDownload(packName).catch(() => {})+ },+ [reportTileErrors, finishDownload])- // 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)+ const loadAreas = useCallback(async () => {+ const [packsResult, entriesResult, styleResult] = await Promise.allSettled([+ loadOfflineAreas(),+ loadOfflineAreaBounds(),+ NativeLocationService.getSetting("mapStyleUrlLight")+ ])+ if (packsResult.status === "rejected") {+ logger.error("[OfflineMapsScreen] Failed to load offline areas:", packsResult.reason)+ }+ if (styleResult.status === "rejected") {+ logger.error("[OfflineMapsScreen] Failed to read the map style:", styleResult.reason)+ }+ const packs = packsResult.status === "fulfilled" ? packsResult.value : null+ const entries = entriesResult.status === "fulfilled" ? entriesResult.value : null+ if (styleResult.status === "fulfilled") setCurrentStyleUrl(styleResult.value || MAP_STYLE_URL_LIGHT)+ if (!packs) return++ const keep = new Set(packs.map((p) => p.name))+ if (entries) {+ if (entries.some((e) => !keep.has(e.name))) await pruneOfflineAreaBounds(keep)+ setAreaBounds(entries.filter((e) => keep.has(e.name)))+ }+ setAreas(packs)++ // Only a pack native already reports active is ever attached: observing one sets it active.+ const active = packs.find((p) => p.isActive)+ if (!active || activePackNameRef.current !== null || createPendingRef.current) return+ activePackNameRef.current = active.name+ const status = await subscribeOfflinePack(active.name, handleProgress(active.name), handleTileError(active.name))+ if (!status) {+ activePackNameRef.current = nullreturn}+ setDownload({ name: active.name, bounds: active.bounds })+ setName(active.name)+ handleProgress(active.name)(status)+ }, [handleProgress, handleTileError])+ loadAreasRef.current = loadAreas- 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.flyTo({- center: [coords.longitude, coords.latitude],- zoom: DEFAULT_MAP_ZOOM,- duration: MAP_ANIMATION_DURATION_MS- })- setIsCentered(true)- }- }, [coords])+ useFocusEffect(+ useCallback(() => {+ loadAreas()+ }, [loadAreas])+ )- const updateBoundsAndEstimate = useCallback((ne: [number, number], sw: [number, number]) => {- currentBoundsRef.current = [ne, sw]- setEstimatedSizeLabel(estimateSizeLabel(ne, sw))+ const noteBounds = useCallback((bounds: Bounds) => {+ currentBoundsRef.current = bounds+ setEstimate(estimateFor(bounds))}, [])const handleRegionChange = useCallback(- (payload: { isUserInteraction: boolean; bounds?: [number, number, number, number] }) => {+ (payload: RegionChangePayload) => {if (payload.isUserInteraction) setIsCentered(false)- if (payload.bounds) {- const [west, south, east, north] = payload.bounds- updateBoundsAndEstimate([east, north], [west, south])- }+ if (payload.bounds) noteBounds(payload.bounds)},- [updateBoundsAndEstimate]+ [noteBounds])const handleMapReady = useCallback(async () => {try {const bounds = await mapRef.current?.mapView?.getBounds()- if (bounds) {- const [west, south, east, north] = bounds- updateBoundsAndEstimate([east, north], [west, south])- }- } catch {- // map not ready yet+ if (bounds) noteBounds(bounds)+ } catch (err) {+ logger.warn("[OfflineMapsScreen] Map bounds unavailable on ready:", err)}- }, [updateBoundsAndEstimate])+ }, [noteBounds])- const beginDownload = useCallback(- (name: string, ne: [number, number], sw: [number, number], onComplete?: () => void) => {- const MAX_RETRIES = 3- const RETRY_DELAY_MS = 5000+ const handleCenterMe = useCallback(() => {+ const target = coords ?? lastFix+ if (!target || !mapRef.current?.camera) return+ mapRef.current.camera.flyTo({+ center: [target.longitude, target.latitude],+ zoom: DEFAULT_MAP_ZOOM,+ duration: MAP_ANIMATION_DURATION_MS+ })+ setIsCentered(true)+ }, [coords, lastFix])- setDownloading(true)- setDownloadBounds([ne, sw])- setDownloadProgress(null)- setDownloadError(null)- activePackNameRef.current = name-- const attempt = (retriesLeft: number) => {- let tileErrors = 0- let lastTileError: unknown = null- const reportTileErrors = () => {- if (tileErrors === 0) return- logger.warn(- `[OfflineMapsScreen] ${tileErrors} tile error(s) total downloading '${name}', last:`,- lastTileError- )- tileErrors = 0- }+ const fitToArea = useCallback((bounds: Bounds) => {+ if (!mapRef.current?.camera) return+ mapRef.current.camera.fitBounds(bounds, { padding: FIT_PADDING, duration: MAP_ANIMATION_DURATION_MS })+ setIsCentered(false)+ }, [])- const onFailure = (message: string) => {- reportTileErrors()- if (retriesLeft > 0) {- const attempt_num = MAX_RETRIES - retriesLeft + 1- logger.warn(`[OfflineMapsScreen] Download failed, retrying (${attempt_num}/${MAX_RETRIES})...`)- setDownloadError(`Retrying... (${attempt_num}/${MAX_RETRIES})`)- setDownloadProgress(null)- setTimeout(async () => {- try {- await deleteOfflineArea(name)- } catch {}- attempt(retriesLeft - 1)- }, RETRY_DELAY_MS)- } else {- activePackNameRef.current = null- setDownloading(false)- setDownloadBounds(null)- setDownloadError(message)- removeOfflineAreaBounds(name)- setAreaBounds((prev) => prev.filter((b) => b.name !== name))- }- }+ const handleAreaPress = useCallback(+ (event: NativeSyntheticEvent<PressEventWithFeatures>) => {+ const pressed: string | undefined = event.nativeEvent.features?.[0]?.properties?.name+ const area = pressed ? areas?.find((a) => a.name === pressed) : undefined+ if (area?.bounds) fitToArea(area.bounds)+ },+ [areas, fitToArea]+ )- createOfflinePack(- name,- ne,- sw,- (status: OfflinePackStatus) => {- setDownloadProgress(status)- setDownloadError(null)- if (status.state === DOWNLOAD_STATE.COMPLETE) {- reportTileErrors()- activePackNameRef.current = null- setDownloading(false)- setDownloadBounds(null)- onComplete?.()- loadAreas()- }- },- (err: unknown) => {- tileErrors += 1- lastTileError = err- if (tileErrors === 1) logger.warn(`[OfflineMapsScreen] Tile error downloading '${name}':`, err)- }- ).catch(() => {- onFailure("Failed to start download. Please try again.")- deleteOfflineArea(name).catch((err) => {- logger.error(`[OfflineMapsScreen] Failed to clean up pack '${name}':`, err)- })- })+ const beginDownload = useCallback(+ async (packName: string, bounds: Bounds) => {+ activePackNameRef.current = packName+ tileErrorCountRef.current = 0+ setDownload({ name: packName, bounds })+ setDownloadProgress(null)+ createPendingRef.current = true+ const { ne, sw } = cornersOf(bounds)+ try {+ await createOfflinePack(packName, ne, sw, handleProgress(packName), handleTileError(packName))+ } catch (err) {+ createPendingRef.current = false+ // Cancelled while pending: native created nothing, so there is nothing to say.+ if (activePackNameRef.current !== packName) return+ logger.error("[OfflineMapsScreen] Failed to start download:", err)+ activePackNameRef.current = null+ setDownload(null)+ showAlert("Could not start the download", "Nothing was downloaded. Try again.", "error")+ return}-- attempt(MAX_RETRIES)+ createPendingRef.current = false+ if (activePackNameRef.current !== packName) {+ try {+ await deleteOfflineArea(packName)+ } catch (err) {+ logger.error("[OfflineMapsScreen] Failed to delete a pack cancelled during creation:", err)+ }+ return+ }+ try {+ await saveOfflineAreaBounds({ name: packName, ne, sw, styleUrl: currentStyleUrl ?? MAP_STYLE_URL_LIGHT })+ } catch (err) {+ logger.error("[OfflineMapsScreen] Failed to save area bounds:", err)+ }+ await loadAreas()},- [loadAreas]+ [currentStyleUrl, handleProgress, handleTileError, 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 trimmed = name.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")+ if (busyRef.current || !trimmed || !bounds || !estimate) return+ busyRef.current = true+ setBusy({ kind: "start", name: trimmed })+ try {+ if (!(await NativeLocationService.isNetworkAvailable())) {+ showAlert(NO_CONNECTION.title, NO_CONNECTION.message, "warning")+ return+ }+ const fresh = await loadOfflineAreas()+ setAreas(fresh)+ if (fresh.some((a) => a.name === trimmed)) return+ const availableMB = await NativeLocationService.getAvailableStorageMB()+ if (availableMB > 0 && estimate.bytes / BYTES_PER_MB > availableMB * STORAGE_HEADROOM) {+ showAlert("Not enough storage", storageMessage(estimate, availableMB), "warning")+ return+ }+ const metered = !(await NativeLocationService.isUnmeteredConnection())+ if (!(await showConfirm({ ...downloadConfirm(trimmed, estimate, metered), destructive: false }))) return+ } catch (err) {+ logger.error("[OfflineMapsScreen] Failed to start download:", err)+ showAlert("Could not start the download", "Nothing was downloaded. Try again.", "error")return+ } finally {+ busyRef.current = false+ setBusy(null)}-- 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])+ await beginDownload(trimmed, bounds)+ }, [name, estimate, beginDownload])const handleCancelDownload = useCallback(async () => {- const name = activePackNameRef.current+ const packName = activePackNameRef.current+ if (!packName || busyRef.current) returnactivePackNameRef.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)- }+ if (createPendingRef.current) {+ setDownload(null)+ setDownloadProgress(null)+ return}- }, [])+ busyRef.current = true+ setBusy({ kind: "stop", name: packName })+ try {+ await deleteOfflineArea(packName)+ await removeOfflineAreaBounds(packName)+ } catch (err) {+ logger.error("[OfflineMapsScreen] Failed to stop the download:", err)+ showAlert("Could not stop the download", "The download may still be running. Try again.", "error")+ } finally {+ busyRef.current = false+ setBusy(null)+ setDownload(null)+ setDownloadProgress(null)+ }+ await loadAreas()+ }, [loadAreas])- const handleRefresh = useCallback(+ const handleCancelArea = 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" })+ if (busyRef.current) return+ busyRef.current = true+ setBusy({ kind: "stop", name: area.name })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 removeOfflineAreaBounds(area.name)+ } catch (err) {+ logger.error("[OfflineMapsScreen] Failed to stop the download:", err)+ showAlert("Could not stop the download", "The download may still be running. Try again.", "error")+ } finally {+ busyRef.current = false+ setBusy(null)}- await saveOfflineAreaBounds(entry)- setAreaBounds((prev) => [...prev.filter((b) => b.name !== area.name), entry])-- beginDownload(area.name, bounds.ne, bounds.sw)+ await loadAreas()},- [downloading, isOffline, areaBounds, currentStyleUrl, beginDownload]+ [loadAreas])- const handleDelete = useCallback(+ const handleRedownload = 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" })+ if (busyRef.current || download) return+ busyRef.current = true+ setBusy({ kind: "redownload", name: area.name })+ let go = falsetry {+ if (!area.bounds) {+ showAlert(+ "Cannot download again",+ "This area's extent could not be read. Delete it and download it again.",+ "warning"+ )+ return+ }+ if (!(await NativeLocationService.isNetworkAvailable())) {+ showAlert(NO_CONNECTION.title, NO_CONNECTION.message, "warning")+ return+ }+ const metered = !(await NativeLocationService.isUnmeteredConnection())+ const areaEstimate = estimateFor(area.bounds)+ if (!(await showConfirm({ ...redownloadConfirm(area.name, areaEstimate, metered), destructive: false }))) returnawait deleteOfflineArea(area.name)- await removeOfflineAreaBounds(area.name)- await loadAreas()- } catch {- showAlert("Error", "Failed to delete area.", "error")+ go = true+ } catch (err) {+ logger.error("[OfflineMapsScreen] Failed to download again:", err)+ showAlert(+ "Could not download again",+ "The old tiles could not be removed, so nothing was downloaded. Try again.",+ "error"+ )} finally {- setItemAction(null)+ busyRef.current = false+ setBusy(null)}+ if (!go || !area.bounds) return+ setName(area.name)+ await beginDownload(area.name, area.bounds)},- [loadAreas]+ [download, beginDownload])- const handleCancelArea = useCallback(+ const handleDelete = useCallback(async (area: OfflineAreaInfo) => {- setItemAction({ area: area.name, action: "canceling" })+ if (busyRef.current) return+ busyRef.current = true+ setBusy({ kind: "delete", name: area.name })try {+ const isLast = (areas?.length ?? 0) === 1+ if (!(await showConfirm({ ...deleteAreaConfirm(area.name, area.sizeBytes, isLast), destructive: true }))) returnawait deleteOfflineArea(area.name)await removeOfflineAreaBounds(area.name)- await loadAreas()- } catch {- showAlert("Error", "Failed to cancel download.", "error")+ } catch (err) {+ logger.error("[OfflineMapsScreen] Failed to delete area:", err)+ showAlert("Could not delete the area", "Its tiles are still on the device. Try again.", "error")} finally {- setItemAction(null)+ busyRef.current = false+ setBusy(null)}+ await loadAreas()},- [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.sw[0], entry.sw[1], entry.ne[0], entry.ne[1]], {- padding: { top: 40, right: 40, bottom: 40, left: 40 },- duration: MAP_ANIMATION_DURATION_MS- })- },- [areaBounds]- )-- const handleAreaPress = useCallback(- (event: NativeSyntheticEvent<PressEventWithFeatures>) => {- if (downloading) return- const name: string | undefined = event.nativeEvent.features?.[0]?.properties?.name- if (name) fitToArea(name)- },- [downloading, fitToArea]+ [areas, loadAreas])- 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 }- }- })+ const savedAreasGeoJSON = useMemo(() => areasCollection(listAreas), [listAreas])+ const layerStyles = useMemo(+ () => ({+ savedFill: { fillColor: colors.success, fillOpacity: 0.1 },+ savedLine: { lineColor: colors.success, lineWidth: 1.5, lineOpacity: 0.6 },+ frameFill: { fillColor: colors.info, fillOpacity: 0.2 },+ frameLine: { lineColor: colors.info, lineWidth: 1.5, lineOpacity: 0.6 }}),- [areaBounds]+ [colors.success, colors.info])-- 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: colors.pressedOpacity }]}- 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: colors.pressedOpacity }- ]}- >- {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: colors.pressedOpacity }- ]}- >- {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: colors.pressedOpacity }- ]}- >- {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 }+ const downloadAreaGeoJSON = download?.bounds ? areaFeature(download.name, download.bounds) : null+ const entryFor = useCallback((areaName: string) => areaBounds.find((b) => b.name === areaName), [areaBounds])+ const toneColor = (tone: RowTone) =>+ tone === "active" ? colors.primary : tone === "attention" ? colors.warning : undefined+ const pct = downloadProgress?.percentage ?? 0+ const downloadDisabled =+ areas === null || estimate === null || name.trim() === "" || nameError !== undefined || busy !== nullreturn (<Container>- <View style={[styles.map, mapDownloadingStyle]}>- {hasInitialCoords && initialCenter.current ? (+ <View+ testID="offline-map"+ style={[styles.map, { height: mapHeight }, download !== null && { borderColor: colors.primary }]}+ >+ {lastFix !== undefined && (<ColotaMapViewref={mapRef}- initialCenter={[initialCenter.current.longitude, initialCenter.current.latitude]}- initialZoom={initialZoom}+ initialCenter={lastFix ? [lastFix.longitude, lastFix.latitude] : WORLD_CENTER}+ initialZoom={lastFix ? DEFAULT_MAP_ZOOM : WORLD_MAP_ZOOM}onRegionDidChange={handleRegionChange}onMapReady={handleMapReady}>{savedAreasGeoJSON.features.length > 0 && (<GeoJSONSource id="saved-areas" data={savedAreasGeoJSON} onPress={handleAreaPress}>- <Layer id="saved-areas-fill" type="fill" style={savedAreasFillStyle} />- <Layer id="saved-areas-border" type="line" style={savedAreasBorderStyle} />+ <Layer id="saved-areas-fill" type="fill" style={layerStyles.savedFill} />+ <Layer id="saved-areas-border" type="line" style={layerStyles.savedLine} /></GeoJSONSource>)}{downloadAreaGeoJSON && (<GeoJSONSource id="offline-area" data={downloadAreaGeoJSON}>- <Layer id="offline-area-fill" type="fill" style={downloadAreaFillStyle} />- <Layer id="offline-area-border" type="line" style={downloadAreaBorderStyle} />+ <Layer id="offline-area-fill" type="fill" style={layerStyles.frameFill} />+ <Layer id="offline-area-border" type="line" style={layerStyles.frameLine} /></GeoJSONSource>)}</ColotaMapView>- ) : null}+ )}+ <MapCenterButton visible={!isCentered && !!(coords ?? lastFix)} onPress={handleCenterMe} />+ </View>- <MapCenterButton visible={!isCentered && !!coords} onPress={handleCenterMe} />+ <ScrollView contentContainerStyle={styles.content} keyboardShouldPersistTaps="handled">+ <Text style={[styles.intro, { color: colors.textSecondary }]}>{INTRO_LINE}</Text>- {downloading && (- <View style={[styles.mapHint, { backgroundColor: colors.card }]}>- <Text style={[styles.mapHintText, { color: colors.text }]}>Downloading... {progressLabel}</Text>+ <View style={styles.section}>+ <SectionTitle>New area</SectionTitle>+ <Card>+ <TextField+ testID="area-name-input"+ label="Name"+ placeholder="Home area, Trail…"+ value={name}+ onChangeText={setName}+ error={nameError}+ disabled={download !== null}+ />+ </Card>+ {download === null ? (+ <View>+ <Button+ testID="download-btn"+ title="Download area"+ loading={busy?.kind === "start"}+ disabled={downloadDisabled}+ onPress={handleDownload}+ />+ <FieldMessage variant={estimate?.large ? "warning" : "info"}>{downloadLine(estimate, name)}</FieldMessage>+ </View>+ ) : (+ <View>+ <View style={styles.progressHeader}>+ <ActivityIndicator size="small" color={colors.primary} />+ <Text style={[styles.progressLabel, { color: colors.text }]}>Downloading {download.name}</Text>+ </View>+ <View+ testID="download-progress"+ accessible+ accessibilityRole="progressbar"+ accessibilityLabel={`Downloading ${download.name}`}+ accessibilityValue={{ min: 0, max: 100, now: Math.round(pct) }}+ style={[styles.progressTrack, { backgroundColor: colors.well }]}+ >+ <View style={[styles.progressFill, { backgroundColor: colors.primary, width: `${pct}%` }]} />+ </View>+ <FieldMessage>{progressCaption(downloadProgress)}</FieldMessage>+ <Button+ testID="cancel-download-btn"+ variant="ghost"+ color={colors.error}+ icon={X}+ title="Cancel download"+ loading={busy?.kind === "stop"}+ disabled={busy !== null}+ onPress={handleCancelDownload}+ />+ </View>+ )}+ </View>++ {areas !== null && listAreas.length > 0 && (+ <View style={styles.section}>+ <SectionTitle>Saved areas</SectionTitle>+ <Card rows>+ {listAreas.map((area, i) => {+ const row = describeArea(area, entryFor(area.name), currentStyleUrl)+ const mine = (kind: Busy["kind"]) => busy?.kind === kind && busy.name === area.name+ return (+ <React.Fragment key={area.name}>+ {i > 0 && <Divider tight inset />}+ <ListItem+ testID={`area-${area.name}`}+ icon={row.icon}+ iconColor={toneColor(row.tone)}+ label={area.name}+ sub={row.sub}+ subLines={2}+ accessibilityHint={ROW_HINT}+ onPress={() => area.bounds && fitToArea(area.bounds)}+ trailing={+ area.isActive ? (+ <IconButton+ icon={X}+ tone="danger"+ accessibilityLabel={`Stop downloading ${area.name}`}+ loading={mine("stop")}+ disabled={busy !== null}+ onPress={() => handleCancelArea(area)}+ testID={`stop-btn-${area.name}`}+ />+ ) : (+ <View style={styles.rowActions}>+ <IconButton+ icon={RefreshCw}+ tone="primary"+ accessibilityLabel={`Download ${area.name} again`}+ loading={mine("redownload")}+ disabled={download !== null || busy !== null}+ onPress={() => handleRedownload(area)}+ testID={`refresh-btn-${area.name}`}+ />+ <IconButton+ icon={Trash2}+ tone="danger"+ accessibilityLabel={`Delete ${area.name}`}+ loading={mine("delete")}+ disabled={busy !== null}+ onPress={() => handleDelete(area)}+ testID={`delete-btn-${area.name}`}+ />+ </View>+ )+ }+ />+ </React.Fragment>+ )+ })}+ </Card></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>- ) : undefined- }- renderItem={renderItem}- />+ {areas !== null && listAreas.length === 0 && download === null && (+ <EmptyState+ title="No saved areas yet"+ hint="Download map tiles to browse your tracks offline while hiking or camping"+ style={styles.empty}+ />+ )}+ </ScrollView></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+ // The border is always drawn and only changes colour: a width that comes and goes on a+ // view that clips leaves its children unpainted on Android.+ map: { overflow: "hidden", borderWidth: 2, borderColor: "transparent" },+ content: {+ paddingHorizontal: space.lg,+ paddingTop: space.lg,+ paddingBottom: space.xxl},- 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: 16, ...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+ intro: {+ fontSize: fontSizes.body,+ ...fonts.regular,+ lineHeight: lineHeights.body,+ marginBottom: space.lg+ },+ section: {+ marginBottom: space.xl},- cancelBtnText: { fontSize: 14, ...fonts.semiBold },- errorText: { fontSize: 13, ...fonts.regular, marginTop: 10 },- card: { marginBottom: 12 },- 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,+ progressHeader: {+ flexDirection: "row",alignItems: "center",- justifyContent: "center"+ gap: space.md,+ marginTop: space.lg,+ marginBottom: space.md},- cancelAreaBtn: {- paddingHorizontal: 12,- paddingVertical: 6,- borderRadius: 8,- borderWidth: 1+ progressLabel: {+ fontSize: fontSizes.body,+ ...fonts.semiBold},- 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"+ progressTrack: { height: 6, borderRadius: radius.pill, overflow: "hidden" },+ progressFill: { height: "100%" },+ rowActions: {+ flexDirection: "row",+ alignItems: "center",+ gap: space.lg},- mapHintText: { fontSize: 13, ...fonts.semiBold }+ // the list around it already insets its rows+ empty: { paddingHorizontal: 0 }})diff --git a/apps/mobile/src/screens/__tests__/OfflineMapsScreen.test.tsx b/apps/mobile/src/screens/__tests__/OfflineMapsScreen.test.tsxindex fa7462f8..d072fce7 100644--- a/apps/mobile/src/screens/__tests__/OfflineMapsScreen.test.tsx+++ b/apps/mobile/src/screens/__tests__/OfflineMapsScreen.test.tsx@@ -1,441 +1,720 @@-/**- * Copyright (C) 2026 Max Dietrich- * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.- */-import React from "react"+import { Dimensions, StyleSheet } from "react-native"import { render, fireEvent, waitFor, act } from "@testing-library/react-native"-import { OfflineMapsScreen } from "../OfflineMapsScreen"-import { logger } from "../../utils/logger"--// --- MapLibre ----jest.mock("@maplibre/maplibre-react-native", () => ({- GeoJSONSource: () => null,- Layer: () => null-}))+import { lightColors } from "@colota/shared"+import { GEOFENCE_ZOOM_PADDING, MAP_ANIMATION_DURATION_MS } from "../../constants"-// --- Navigation ----const mockNavigation = { navigate: jest.fn() }+jest.mock("@maplibre/maplibre-react-native", () => {+ const R = require("react")+ const { View } = require("react-native")+ return {+ GeoJSONSource: ({ id, data, children }: any) =>+ R.createElement(View, { testID: `source-${id}`, accessibilityValue: { text: JSON.stringify(data) } }, children),+ Layer: () => null+ }+})-// --- Focus hook: call immediately on mount ---jest.mock("@react-navigation/native", () => ({- useFocusEffect: (cb: Function) => {- const { useEffect } = require("react")- useEffect(() => {+ useFocusEffect: (cb: () => (() => void) | void) => {+ const R = require("react")+ R.useEffect(() => {const cleanup = cb()- return cleanup- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [])+ return typeof cleanup === "function" ? cleanup : undefined+ }, [cb])}}))-// --- 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"- }- })+ useTheme: () => ({ colors: require("@colota/shared").lightColors, mode: "light" })}))-// --- Tracking context ---+let mockCoords: { latitude: number; longitude: number; accuracy: number } | null = nulljest.mock("../../contexts/TrackingProvider", () => ({- useCoords: () => ({ latitude: 52.52, longitude: 13.405 })+ useCoords: () => mockCoords}))-// --- 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()-+const mockGetMostRecentLocation = jest.fn()+const mockGetSetting = 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)+ isNetworkAvailable: (...a: any[]) => mockIsNetworkAvailable(...a),+ isUnmeteredConnection: (...a: any[]) => mockIsUnmeteredConnection(...a),+ getAvailableStorageMB: (...a: any[]) => mockGetAvailableStorageMB(...a),+ getMostRecentLocation: (...a: any[]) => mockGetMostRecentLocation(...a),+ getSetting: (...a: any[]) => mockGetSetting(...a)+ }+}))++const mockShowAlert = jest.fn()+const mockShowConfirm = jest.fn()+jest.mock("../../services/modalService", () => ({+ showAlert: (...a: any[]) => mockShowAlert(...a),+ showConfirm: (...a: any[]) => mockShowConfirm(...a)+}))++const mockLogger = { error: jest.fn(), warn: jest.fn(), info: jest.fn(), debug: jest.fn() }+jest.mock("../../utils/logger", () => ({+ logger: {+ error: (...a: any[]) => mockLogger.error(...a),+ warn: (...a: any[]) => mockLogger.warn(...a),+ info: (...a: any[]) => mockLogger.info(...a),+ debug: (...a: any[]) => mockLogger.debug(...a)}}))-// --- 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 mockSubscribeOfflinePack = jest.fn()+const mockPruneOfflineAreaBounds = jest.fn()+const mockUnsubscribeOfflinePack = jest.fn()const mockEstimateSizeLabel = jest.fn()const mockEstimateSizeBytes = jest.fn()const mockWillExceedTileLimit = jest.fn()--jest.mock("../../utils/format", () => ({- formatBytes: jest.fn().mockReturnValue("5.0 MB")-}))-jest.mock("../../components/features/map/OfflinePackManager", () => ({DOWNLOAD_STATE: { INACTIVE: "inactive", ACTIVE: "active", COMPLETE: "complete" },- 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)+ loadOfflineAreas: (...a: any[]) => mockLoadOfflineAreas(...a),+ loadOfflineAreaBounds: (...a: any[]) => mockLoadOfflineAreaBounds(...a),+ createOfflinePack: (...a: any[]) => mockCreateOfflinePack(...a),+ deleteOfflineArea: (...a: any[]) => mockDeleteOfflineArea(...a),+ saveOfflineAreaBounds: (...a: any[]) => mockSaveOfflineAreaBounds(...a),+ removeOfflineAreaBounds: (...a: any[]) => mockRemoveOfflineAreaBounds(...a),+ subscribeOfflinePack: (...a: any[]) => mockSubscribeOfflinePack(...a),+ pruneOfflineAreaBounds: (...a: any[]) => mockPruneOfflineAreaBounds(...a),+ unsubscribeOfflinePack: (...a: any[]) => mockUnsubscribeOfflinePack(...a),+ estimateSizeLabel: (...a: any[]) => mockEstimateSizeLabel(...a),+ estimateSizeBytes: (...a: any[]) => mockEstimateSizeBytes(...a),+ willExceedTileLimit: (...a: any[]) => mockWillExceedTileLimit(...a)}))-// --- ColotaMapView: fires onRegionDidChange on mount to supply bounds ---+const BOUNDS: [number, number, number, number] = [13.4, 52.5, 13.5, 52.6]+const mockFitBounds = jest.fn()+const mockFlyTo = jest.fn()+const mockGetBounds = jest.fn()+const mockMapProps = jest.fn()jest.mock("../../components/features/map/ColotaMapView", () => {const R = require("react")- const { View } = require("react-native")+ const { View, Pressable } = require("react-native")return {- ColotaMapView: R.forwardRef(({ onRegionDidChange, children }: any, _ref: any) => {- R.useEffect(() => {- onRegionDidChange?.({- isUserInteraction: false,- bounds: [13.4, 52.5, 13.5, 52.6]- })- }, [])- return R.createElement(View, { testID: "map-view" }, children)+ ColotaMapView: R.forwardRef((props: any, ref: any) => {+ R.useImperativeHandle(ref, () => ({+ camera: { fitBounds: mockFitBounds, flyTo: mockFlyTo },+ mapView: { getBounds: mockGetBounds }+ }))+ mockMapProps(props)+ return R.createElement(+ View,+ { testID: "colota-map" },+ R.createElement(Pressable, { testID: "map-ready", onPress: () => props.onMapReady?.() }),+ R.createElement(Pressable, {+ testID: "map-pan",+ onPress: () =>+ props.onRegionDidChange?.({ heading: 0, isUserInteraction: true, bounds: [13.4, 52.5, 13.5, 52.6] })+ }),+ props.children+ )})}})-// --- MapCenterButton ----jest.mock("../../components/features/map/MapCenterButton", () => ({- MapCenterButton: () => null-}))+jest.mock("../../components/features/map/MapCenterButton", () => {+ const R = require("react")+ const { Pressable } = require("react-native")+ return {+ MapCenterButton: ({ visible, onPress }: any) =>+ visible ? R.createElement(Pressable, { testID: "center-btn", onPress }) : null+ }+})-// --- UI components ---jest.mock("../../components", () => {const R = require("react")- const { View, Text } = require("react-native")+ const { View, Text, Pressable } = require("react-native")+ const stubs = require("../../testing/componentStubs")return {Container: ({ children }: any) => R.createElement(View, null, children),+ Card: ({ children }: any) => R.createElement(View, null, children),SectionTitle: ({ children }: any) => R.createElement(Text, null, children),- Card: ({ children, style }: any) => R.createElement(View, { style }, children)+ Divider: () => null,+ TextField: stubs.TextFieldStub,+ IconButton: stubs.IconButtonStub,+ EmptyState: stubs.EmptyStateStub,+ FieldMessage: ({ children, variant }: any) =>+ R.createElement(Text, { accessibilityValue: { text: variant ?? "info" } }, children),+ Button: ({ title, onPress, disabled, loading, testID }: any) =>+ R.createElement(+ Pressable,+ {+ testID,+ onPress,+ disabled: disabled || loading,+ accessibilityState: { disabled: !!disabled, busy: !!loading }+ },+ R.createElement(Text, null, title)+ ),+ ListItem: ({ label, sub, onPress, testID, trailing, iconColor }: any) =>+ R.createElement(+ View,+ { testID, accessibilityValue: { text: iconColor ?? "" } },+ R.createElement(Pressable, { testID: `${testID}-press`, onPress }, R.createElement(Text, null, label)),+ sub ? R.createElement(Text, null, sub) : null,+ trailing+ )}})-// ---------------------------------------------------------------------------+import { OfflineMapsScreen } from "../OfflineMapsScreen"++const area = (name: string, over: Record<string, unknown> = {}) => ({+ name,+ sizeBytes: 2_097_152,+ isComplete: true,+ isActive: false,+ bounds: BOUNDS,+ ...over+})+const entry = (name: string, over: Record<string, unknown> = {}) => ({+ name,+ ne: [13.5, 52.6],+ sw: [13.4, 52.5],+ styleUrl: "https://tiles.example/light.json",+ ...over+})++const mapBox = (api: ReturnType<typeof render>) => StyleSheet.flatten(api.getByTestId("offline-map").props.style)++const renderScreen = () => render(<OfflineMapsScreen navigation={{} as any} />)++/** Renders, lets the database answer, then lets the map report its bounds. */+async function renderReady(name = "") {+ const api = renderScreen()+ await waitFor(() => expect(api.getByTestId("map-ready")).toBeTruthy())+ await act(async () => {+ fireEvent.press(api.getByTestId("map-ready"))+ })+ if (name) fireEvent.changeText(api.getByTestId("area-name-input"), name)+ await waitFor(() => expect(mockLoadOfflineAreas).toHaveBeenCalled())+ return api+}++async function press(api: ReturnType<typeof render>, testID: string) {+ await act(async () => {+ fireEvent.press(api.getByTestId(testID))+ })+}++const progressOf = (call = 0) => mockCreateOfflinePack.mock.calls[call][3] as (status: unknown) => void+const status = (percentage: number, over: Record<string, unknown> = {}) => ({+ state: "active",+ percentage,+ completedResourceCount: 0,+ requiredResourceCount: 0,+ completedResourceSize: 0,+ ...over+})beforeEach(() => {jest.clearAllMocks()+ mockCoords = nullmockIsNetworkAvailable.mockResolvedValue(true)mockIsUnmeteredConnection.mockResolvedValue(true)mockGetAvailableStorageMB.mockResolvedValue(1000)+ mockGetMostRecentLocation.mockResolvedValue({ latitude: 52.52, longitude: 13.405, accuracy: 8 })+ mockGetSetting.mockResolvedValue("https://tiles.example/light.json")mockLoadOfflineAreas.mockResolvedValue([])mockLoadOfflineAreaBounds.mockResolvedValue([])+ mockCreateOfflinePack.mockResolvedValue(undefined)+ mockDeleteOfflineArea.mockResolvedValue(undefined)mockSaveOfflineAreaBounds.mockResolvedValue(undefined)mockRemoveOfflineAreaBounds.mockResolvedValue(undefined)- mockDeleteOfflineArea.mockResolvedValue(undefined)+ mockSubscribeOfflinePack.mockResolvedValue(null)+ mockPruneOfflineAreaBounds.mockResolvedValue(undefined)+ mockGetBounds.mockResolvedValue(BOUNDS)mockEstimateSizeLabel.mockReturnValue("~5 MB")mockEstimateSizeBytes.mockReturnValue(5 * 1024 * 1024)mockWillExceedTileLimit.mockReturnValue(false)- mockCreateOfflinePack.mockResolvedValue(undefined)- mockShowConfirm.mockResolvedValue(false)+ mockShowConfirm.mockResolvedValue(true)})-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("the map", () => {+ // Tiles that open on the world view and then jump to the fix read as a broken map.+ it("draws no tiles until the database has answered, then opens on the last fix", async () => {+ let answer: (v: unknown) => void = () => {}+ mockGetMostRecentLocation.mockReturnValue(new Promise((r) => (answer = r)))+ const api = renderScreen()-// ---------------------------------------------------------------------------+ expect(api.queryByTestId("colota-map")).toBeNull()+ await act(async () => answer({ latitude: 52.52, longitude: 13.405, accuracy: 8 }))-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()+ expect(api.getByTestId("colota-map")).toBeTruthy()+ expect(mockMapProps.mock.calls.at(-1)![0]).toMatchObject({ initialCenter: [13.405, 52.52] })})- 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("opens on the world view when nothing was ever recorded", async () => {+ mockGetMostRecentLocation.mockResolvedValue(null)+ const api = renderScreen()+ await waitFor(() => expect(api.getByTestId("colota-map")).toBeTruthy())+ expect(mockMapProps.mock.calls.at(-1)![0]).toMatchObject({ initialCenter: [0, 20] })})- 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("takes half the viewport, with a border that is always drawn and only recoloured", async () => {+ const api = await renderReady()+ expect(mapBox(api)).toMatchObject({+ height: Math.round(Dimensions.get("window").height * 0.5),+ borderWidth: 2,+ borderColor: "transparent"})})- 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")+ // With tracking off the stored fix is the only way back to where the user is.+ it("offers the centre disc after a pan even with tracking off, and flies to the stored fix", async () => {+ const api = await renderReady()+ expect(api.queryByTestId("center-btn")).toBeNull()++ await press(api, "map-pan")+ expect(api.getByTestId("center-btn")).toBeTruthy()++ await press(api, "center-btn")+ expect(mockFlyTo).toHaveBeenCalledWith(+ expect.objectContaining({ center: [13.405, 52.52], duration: MAP_ANIMATION_DURATION_MS })+ )+ expect(api.queryByTestId("center-btn")).toBeNull()})+})- 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" }))- })+describe("framing and naming", () => {+ it("keeps Download area disabled until the map reports bounds, and says so", async () => {+ mockGetBounds.mockResolvedValue(undefined)+ const api = renderScreen()+ await waitFor(() => expect(api.getByTestId("download-btn")).toBeTruthy())++ expect(api.getByTestId("download-btn").props.accessibilityState.disabled).toBe(true)+ expect(api.getByText("Waiting for the map.")).toBeTruthy()+ })++ it("asks for a name once the estimate is in, then enables the button", async () => {+ const api = await renderReady()+ expect(api.getByText("~5 MB estimated. Name the area to download it.")).toBeTruthy()+ expect(api.getByTestId("download-btn").props.accessibilityState.disabled).toBe(true)++ fireEvent.changeText(api.getByTestId("area-name-input"), "my park")+ expect(api.getByText("~5 MB estimated.")).toBeTruthy()+ expect(api.getByTestId("download-btn").props.accessibilityState.disabled).toBe(false)+ })++ // The estimator stops counting at the tile cap, so the line is a floor and a warning.+ it("turns the line into a warning floor on a capped frame", async () => {+ mockEstimateSizeLabel.mockReturnValue("~470 MB")+ mockWillExceedTileLimit.mockReturnValue(true)+ const api = await renderReady("Alps")++ const line = api.getByText("At least ~470 MB. Zoom in to download less.")+ expect(line.props.accessibilityValue.text).toBe("warning")+ })++ it("puts a taken name on the field and keeps the button disabled, with no dialog", async () => {+ mockLoadOfflineAreas.mockResolvedValue([area("my park")])+ const api = await renderReady("my park")++ expect(api.getByText('An area named "my park" already exists.')).toBeTruthy()+ expect(api.getByTestId("download-btn").props.accessibilityState.disabled).toBe(true)+ expect(mockShowAlert).not.toHaveBeenCalled()+ })+})++describe("starting a download", () => {+ it("refuses without a network and creates nothing", async () => {+ mockIsNetworkAvailable.mockResolvedValue(false)+ const api = await renderReady("my park")++ await press(api, "download-btn")++ expect(mockShowAlert).toHaveBeenCalledWith(+ "No connection",+ expect.stringContaining("Saved areas still work"),+ "warning"+ )+ expect(mockCreateOfflinePack).not.toHaveBeenCalled()+ })++ it("refuses when the estimate would not fit, naming both numbers", async () => {+ mockGetAvailableStorageMB.mockResolvedValue(4)+ const api = await renderReady("my park")++ await press(api, "download-btn")++ expect(mockShowAlert).toHaveBeenCalledWith(+ "Not enough storage",+ "~5 MB is needed and the device has 4.0 MB free.",+ "warning"+ )+ expect(mockCreateOfflinePack).not.toHaveBeenCalled()})- it("aborts download when user cancels the mobile data warning", async () => {+ // One dialog on the happy path: the mobile-data warning is a sentence in it, not a second dialog.+ it("asks once, carrying the estimate and the mobile-data sentence when metered", 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()- })+ const api = await renderReady("my park")++ await press(api, "download-btn")++ expect(mockShowConfirm).toHaveBeenCalledTimes(1)+ expect(mockShowConfirm).toHaveBeenCalledWith(+ expect.objectContaining({+ title: 'Download "my park"?',+ message: "~5 MB estimated. You are on mobile data, not WiFi.",+ confirmText: "Download"+ })+ )+ 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("creates the pack from the framed corners, saves the extent without a date, and shows the block", async () => {+ let finish: () => void = () => {}+ mockCreateOfflinePack.mockReturnValue(new Promise<void>((r) => (finish = r)))+ const api = await renderReady("my park")++ await press(api, "download-btn")++ expect(mockCreateOfflinePack).toHaveBeenCalledWith(+ "my park",+ [13.5, 52.6],+ [13.4, 52.5],+ expect.any(Function),+ expect.any(Function)+ )+ expect(api.getByText("Downloading my park")).toBeTruthy()+ expect(api.getByText("Starting…")).toBeTruthy()+ expect(mapBox(api).borderColor).toBe(lightColors.primary)++ await act(async () => finish())+ expect(mockSaveOfflineAreaBounds).toHaveBeenCalledWith({+ name: "my park",+ ne: [13.5, 52.6],+ sw: [13.4, 52.5],+ styleUrl: "https://tiles.example/light.json"})+ expect(mockSaveOfflineAreaBounds.mock.calls[0][0]).not.toHaveProperty("downloadedAt")})- 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("moves the track and the caption with progress, and keeps the running pack out of the list", async () => {+ const api = await renderReady("my park")+ // Once the pack exists native reports it active; the reload after the create must not row it.+ mockLoadOfflineAreas.mockImplementation(() =>+ Promise.resolve(+ mockCreateOfflinePack.mock.calls.length > 0+ ? [area("my park", { isActive: true, isComplete: false, sizeBytes: 0 })]+ : [])- })+ )+ await press(api, "download-btn")++ await act(async () => progressOf()(status(42, { completedResourceSize: 5_347_737 })))++ expect(api.getByTestId("download-progress").props.accessibilityValue).toEqual({ min: 0, max: 100, now: 42 })+ expect(api.getByText("42% · 5.1 MB so far")).toBeTruthy()+ expect(api.queryByTestId("area-my park")).toBeNull()})- it("logs the first tile error and then only a total, not one line per tile", async () => {- // One line up front so a stalled download is not silent, one total at the end.- const warn = jest.spyOn(logger, "warn").mockImplementation(() => {})- mockShowConfirm.mockResolvedValue(true)- const { findByText, getByTestId, getByPlaceholderText } = renderScreen()- await waitForMapReady(findByText)- fireEvent.changeText(getByPlaceholderText("Home area, Trail..."), "flooded")- fireEvent.press(getByTestId("download-btn"))- await waitFor(() => expect(mockCreateOfflinePack).toHaveBeenCalled())+ /**+ * The date is the finish, not the start, and it is stamped by re-saving the entry the create+ * wrote, so an interrupted download never carries a completion date.+ */+ it("stamps the completion date, clears the field and reloads on COMPLETE", async () => {+ mockLoadOfflineAreaBounds.mockResolvedValue([entry("my park")])+ const api = await renderReady("my park")+ await press(api, "download-btn")+ const reloads = mockLoadOfflineAreas.mock.calls.length++ await act(async () => progressOf()(status(100, { state: "complete", completedResourceSize: 2_097_152 })))++ await waitFor(() =>+ expect(mockSaveOfflineAreaBounds).toHaveBeenLastCalledWith(+ expect.objectContaining({ name: "my park", downloadedAt: expect.any(Number) })+ )+ )+ expect(api.getByTestId("area-name-input").props.value).toBe("")+ expect(mockLoadOfflineAreas.mock.calls.length).toBeGreaterThan(reloads)+ expect(api.queryByText(/Downloading my park/)).toBeNull()+ })- const [, , , onProgress, onError] = mockCreateOfflinePack.mock.calls[0]- for (let i = 0; i < 50; i++) onError({ message: "HTTP status code 429" })+ // A create that fails did not create a pack, so there is nothing to clean up and nothing to retry.+ it("alerts on a rejected create, deletes nothing, writes no bounds and never retries", async () => {+ const api = await renderReady("my park")+ jest.useFakeTimers()+ mockCreateOfflinePack.mockRejectedValue(new Error("native said no"))- const tileLines = () => warn.mock.calls.filter((c) => String(c[0]).includes("Tile error"))- expect(tileLines()).toHaveLength(1)+ await press(api, "download-btn")++ expect(mockLogger.error).toHaveBeenCalledWith("[OfflineMapsScreen] Failed to start download:", expect.any(Error))+ expect(mockShowAlert).toHaveBeenCalledWith(+ "Could not start the download",+ "Nothing was downloaded. Try again.",+ "error"+ )+ expect(mockDeleteOfflineArea).not.toHaveBeenCalled()+ expect(mockSaveOfflineAreaBounds).not.toHaveBeenCalled()+ expect(api.getByTestId("download-btn")).toBeTruthy()await act(async () => {- onProgress({ state: "complete", percentage: 100, completedResourceSize: 1000 })+ jest.advanceTimersByTime(60_000)})-- const totals = warn.mock.calls.filter((c) => String(c[0]).includes("50 tile error(s) total"))- expect(totals).toHaveLength(1)- warn.mockRestore()+ expect(mockCreateOfflinePack).toHaveBeenCalledTimes(1)+ jest.useRealTimers()})- 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("logs the first tile error and then only a total", async () => {+ const api = await renderReady("my park")+ await press(api, "download-btn")+ const onError = mockCreateOfflinePack.mock.calls[0][4] as (err: unknown) => void++ await act(async () => {+ onError(new Error("tile 1"))+ onError(new Error("tile 2"))+ onError(new Error("tile 3"))+ progressOf()(status(100, { state: "complete" }))})++ const lines = mockLogger.warn.mock.calls.map((c) => c[0] as string)+ expect(lines.filter((l) => l.startsWith("[OfflineMapsScreen] Tile error downloading"))).toHaveLength(1)+ expect(lines).toContain("[OfflineMapsScreen] 3 tile error(s) total downloading 'my park', last:")})+})- 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")- })+describe("cancelling", () => {+ /**+ * Native only answers the create later. A cancel in that window has nothing to delete yet, so+ * the post-create continuation deletes the pack exactly once, and no bounds are ever written.+ */+ it("deletes a pack cancelled during the create exactly once, after native answers", async () => {+ let finish: () => void = () => {}+ mockCreateOfflinePack.mockReturnValue(new Promise<void>((r) => (finish = r)))+ const api = await renderReady("my park")+ await press(api, "download-btn")++ await press(api, "cancel-download-btn")+ expect(mockDeleteOfflineArea).not.toHaveBeenCalled()+ expect(api.getByTestId("download-btn")).toBeTruthy()++ await act(async () => finish())+ expect(mockDeleteOfflineArea).toHaveBeenCalledTimes(1)+ expect(mockDeleteOfflineArea).toHaveBeenCalledWith("my park")+ expect(mockSaveOfflineAreaBounds).not.toHaveBeenCalled()})- 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("deletes, removes the bounds and reloads on a cancel after the create", async () => {+ const api = await renderReady("my park")+ await press(api, "download-btn")+ const reloads = mockLoadOfflineAreas.mock.calls.length++ await press(api, "cancel-download-btn")++ expect(mockDeleteOfflineArea).toHaveBeenCalledWith("my park")+ expect(mockRemoveOfflineAreaBounds).toHaveBeenCalledWith("my park")+ expect(mockLoadOfflineAreas.mock.calls.length).toBeGreaterThan(reloads)+ expect(api.getByTestId("download-btn")).toBeTruthy()})- 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("logs, alerts and reloads when the stop fails", async () => {+ const api = await renderReady("my park")+ await press(api, "download-btn")+ mockDeleteOfflineArea.mockRejectedValueOnce(new Error("busy"))++ await press(api, "cancel-download-btn")++ expect(mockLogger.error).toHaveBeenCalledWith("[OfflineMapsScreen] Failed to stop the download:", expect.any(Error))+ expect(mockShowAlert).toHaveBeenCalledWith("Could not stop the download", expect.any(String), "error")})+})- 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")+describe("coming back to a download", () => {+ // A pack native still reports active belongs to the progress block, not to the list row.+ it("re-attaches to a pack native reports active and shows its progress", async () => {+ mockLoadOfflineAreas.mockResolvedValue([area("trail", { isActive: true, isComplete: false, sizeBytes: 0 })])+ mockSubscribeOfflinePack.mockResolvedValue(status(37, { completedResourceSize: 1_048_576 }))+ const api = await renderReady()++ expect(mockSubscribeOfflinePack).toHaveBeenCalledWith("trail", expect.any(Function), expect.any(Function))+ expect(api.getByText("Downloading trail")).toBeTruthy()+ expect(api.getByText("37% · 1.0 MB so far")).toBeTruthy()+ expect(api.queryByTestId("area-trail")).toBeNull()})- 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")- })+ // Observing a pack sets it active natively, so attaching to an inactive one would start it.+ it("never subscribes to a pack that is not already active", async () => {+ mockLoadOfflineAreas.mockResolvedValue([area("done"), area("half", { isComplete: false, sizeBytes: 100 })])+ await renderReady()+ expect(mockSubscribeOfflinePack).not.toHaveBeenCalled()})- it("does not delete when user cancels the delete confirmation", async () => {+ it("rows a second active pack as downloading, with a stop control", async () => {mockLoadOfflineAreas.mockResolvedValue([- { name: "my park", sizeBytes: 2_000_000, isComplete: true, isActive: false }+ area("mine", { isActive: true, isComplete: false, sizeBytes: 0 }),+ area("theirs", { isActive: true, isComplete: false, sizeBytes: 0 })])- 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()- })+ mockSubscribeOfflinePack.mockResolvedValue(status(10))+ const api = await renderReady()++ expect(api.getByTestId("area-theirs")).toBeTruthy()+ expect(api.getByText("Downloading…")).toBeTruthy()+ expect(api.getByTestId("stop-btn-theirs")).toBeTruthy()+ expect(api.queryByTestId("refresh-btn-theirs")).toBeNull()})+})- it("calls deleteOfflineArea and createOfflinePack when user confirms re-download", async () => {+describe("the saved list", () => {+ it("says what each row holds, and tints only the rows that need attention", async () => {mockLoadOfflineAreas.mockResolvedValue([- { name: "existing area", sizeBytes: 5_000_000, isComplete: true, isActive: false }+ area("fresh"),+ area("stale"),+ area("half", { isComplete: false, sizeBytes: 3_355_443 }),+ area("broken", { isComplete: false, sizeBytes: null })])mockLoadOfflineAreaBounds.mockResolvedValue([- {- name: "existing area",- ne: [13.5, 52.6],- sw: [13.4, 52.5],- styleUrl: "https://maps.mxd.codes/styles/bright/style.json"- }+ entry("fresh"),+ entry("stale", { styleUrl: "https://tiles.example/old.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)- )- })+ const api = await renderReady()++ expect(api.getByText("2.0 MB")).toBeTruthy()+ expect(api.getByTestId("area-fresh").props.accessibilityValue.text).toBe("")+ expect(api.getByText("Map style changed · 2.0 MB")).toBeTruthy()+ expect(api.getByTestId("area-stale").props.accessibilityValue.text).toBe(lightColors.warning)+ expect(api.getByText("Incomplete · 3.2 MB")).toBeTruthy()+ expect(api.getByText("Could not read this area")).toBeTruthy()+ for (const name of ["fresh", "stale", "half", "broken"]) {+ expect(api.getByTestId(`refresh-btn-${name}`)).toBeTruthy()+ expect(api.getByTestId(`delete-btn-${name}`)).toBeTruthy()+ }})- 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("fits the map to a row's own extent on tap", async () => {+ mockLoadOfflineAreas.mockResolvedValue([area("home")])+ const api = await renderReady()++ await press(api, "area-home-press")++ const [top, right, bottom, left] = GEOFENCE_ZOOM_PADDING+ expect(mockFitBounds).toHaveBeenCalledWith(BOUNDS, {+ padding: { top, right, bottom, left },+ duration: MAP_ANIMATION_DURATION_MS})})- 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") })- )- })+ // Orphans go in one write so a second reader never sees a half-pruned list.+ it("prunes orphaned sidecar entries in one call, and not at all when there are none", async () => {+ mockLoadOfflineAreas.mockResolvedValue([area("home")])+ mockLoadOfflineAreaBounds.mockResolvedValue([entry("home"), entry("gone-1"), entry("gone-2")])+ await renderReady()+ expect(mockPruneOfflineAreaBounds).toHaveBeenCalledTimes(1)+ expect([...mockPruneOfflineAreaBounds.mock.calls[0][0]]).toEqual(["home"])++ jest.clearAllMocks()+ mockLoadOfflineAreas.mockResolvedValue([area("home")])+ mockLoadOfflineAreaBounds.mockResolvedValue([entry("home")])+ mockGetMostRecentLocation.mockResolvedValue(null)+ mockGetSetting.mockResolvedValue("")+ mockGetBounds.mockResolvedValue(BOUNDS)+ await renderReady()+ expect(mockPruneOfflineAreaBounds).not.toHaveBeenCalled()+ })++ it("shows no empty state before the first read lands, and none during a first download", async () => {+ mockLoadOfflineAreas.mockReturnValue(new Promise(() => {}))+ const api = renderScreen()+ await waitFor(() => expect(api.getByTestId("map-ready")).toBeTruthy())+ expect(api.queryByText("No saved areas yet")).toBeNull()++ mockLoadOfflineAreas.mockResolvedValue([])+ const api2 = await renderReady("first")+ expect(api2.getByText("No saved areas yet")).toBeTruthy()+ await press(api2, "download-btn")+ expect(api2.queryByText("No saved areas yet")).toBeNull()+ })+})++describe("deleting", () => {+ it("names the bytes, and the cache reset only on the last area", async () => {+ mockLoadOfflineAreas.mockResolvedValue([area("home"), area("work")])+ const api = await renderReady()++ await press(api, "delete-btn-home")++ expect(mockShowConfirm).toHaveBeenCalledWith(+ expect.objectContaining({+ title: 'Delete "home"?',+ message: "Removes 2.0 MB of map tiles from this device.",+ destructive: true+ })+ )+ expect(mockDeleteOfflineArea).toHaveBeenCalledWith("home")+ expect(mockRemoveOfflineAreaBounds).toHaveBeenCalledWith("home")+ expect(mockDeleteOfflineArea.mock.invocationCallOrder[0]).toBeLessThan(+ mockRemoveOfflineAreaBounds.mock.invocationCallOrder[0]+ )+ })++ it("adds the cache sentence when the last area goes", async () => {+ mockLoadOfflineAreas.mockResolvedValue([area("home")])+ const api = await renderReady()++ await press(api, "delete-btn-home")++ expect(mockShowConfirm.mock.calls[0][0].message).toContain("the map's online tile cache is cleared too")+ })++ it("deletes nothing when the confirmation is dismissed, and alerts on a failure", async () => {+ mockLoadOfflineAreas.mockResolvedValue([area("home")])+ mockShowConfirm.mockResolvedValueOnce(false)+ const api = await renderReady()++ await press(api, "delete-btn-home")+ expect(mockDeleteOfflineArea).not.toHaveBeenCalled()++ mockDeleteOfflineArea.mockRejectedValueOnce(new Error("locked"))+ await press(api, "delete-btn-home")+ expect(mockShowAlert).toHaveBeenCalledWith("Could not delete the area", expect.any(String), "error")+ })+})++describe("downloading again", () => {+ it("confirms, deletes the old tiles, then creates from the pack's own extent", async () => {+ mockLoadOfflineAreas.mockResolvedValue([area("home")])+ const api = await renderReady()++ await press(api, "refresh-btn-home")++ expect(mockShowConfirm).toHaveBeenCalledWith(+ expect.objectContaining({ title: 'Download "home" again?', confirmText: "Download again" })+ )+ expect(mockDeleteOfflineArea).toHaveBeenCalledWith("home")+ expect(mockCreateOfflinePack).toHaveBeenCalledWith(+ "home",+ [13.5, 52.6],+ [13.4, 52.5],+ expect.any(Function),+ expect.any(Function)+ )+ expect(mockDeleteOfflineArea.mock.invocationCallOrder[0]).toBeLessThan(+ mockCreateOfflinePack.mock.invocationCallOrder[0]+ )+ })++ it("alerts and never creates when the old tiles cannot be removed", async () => {+ mockLoadOfflineAreas.mockResolvedValue([area("home")])+ mockDeleteOfflineArea.mockRejectedValueOnce(new Error("locked"))+ const api = await renderReady()++ await press(api, "refresh-btn-home")++ expect(mockShowAlert).toHaveBeenCalledWith("Could not download again", expect.any(String), "error")+ expect(mockCreateOfflinePack).not.toHaveBeenCalled()})})diff --git a/apps/mobile/src/utils/__tests__/offlineArea.test.ts b/apps/mobile/src/utils/__tests__/offlineArea.test.tsnew file mode 100644index 00000000..d09b94da--- /dev/null+++ b/apps/mobile/src/utils/__tests__/offlineArea.test.ts@@ -0,0 +1,202 @@+import type {+ OfflineAreaBounds,+ OfflineAreaInfo,+ OfflinePackStatus+} from "../../components/features/map/OfflinePackManager"+import { formatDateWithYear } from "../geo"+import {+ areaFeature,+ areasCollection,+ cornersOf,+ deleteAreaConfirm,+ describeArea,+ downloadConfirm,+ downloadLine,+ duplicateNameError,+ progressCaption,+ redownloadConfirm,+ storageMessage,+ type Bounds,+ type Estimate+} from "../offlineArea"++const BOUNDS: Bounds = [13.4, 52.5, 13.5, 52.6]+const DOWNLOADED_AT = Date.parse("2026-02-27T10:00:00Z")+const DATE = formatDateWithYear(Math.floor(DOWNLOADED_AT / 1000))++const small: Estimate = { label: "~5 MB", bytes: 5 * 1024 * 1024, large: false }+const large: Estimate = { label: "~470 MB", bytes: 470 * 1024 * 1024, large: true }++const area = (over: Partial<OfflineAreaInfo> = {}): OfflineAreaInfo => ({+ name: "Home",+ sizeBytes: 13_000_000,+ isComplete: true,+ isActive: false,+ bounds: BOUNDS,+ ...over+})++const entry = (over: Partial<OfflineAreaBounds> = {}): OfflineAreaBounds => ({+ name: "Home",+ ne: [13.5, 52.6],+ sw: [13.4, 52.5],+ styleUrl: "https://tiles.example/light.json",+ downloadedAt: DOWNLOADED_AT,+ ...over+})++const status = (percentage: number, completedResourceSize: number): OfflinePackStatus => ({+ state: "active",+ percentage,+ completedResourceCount: 0,+ requiredResourceCount: 0,+ completedResourceSize+})++describe("duplicateNameError", () => {+ it("names the clash, trimmed, and stays silent for a free name", () => {+ expect(duplicateNameError(" Home ", ["Home", "Work"])).toBe('An area named "Home" already exists.')+ expect(duplicateNameError("Lake", ["Home"])).toBeUndefined()+ expect(duplicateNameError(" ", ["Home"])).toBeUndefined()+ })+})++describe("downloadLine", () => {+ it("says why the button is disabled before it says what pressing it takes", () => {+ expect(downloadLine(null, "Lake")).toBe("Waiting for the map.")+ expect(downloadLine(small, "")).toBe("~5 MB estimated. Name the area to download it.")+ expect(downloadLine(small, "Lake")).toBe("~5 MB estimated.")+ })++ // The estimator stops counting at the tile cap, so past it the label is a floor, not a figure.+ it("calls a capped estimate a floor and tells the user how to lower it", () => {+ expect(downloadLine(large, "Lake")).toBe("At least ~470 MB. Zoom in to download less.")+ })+})++describe("progressCaption", () => {+ it("counts bytes only once some have landed", () => {+ expect(progressCaption(null)).toBe("Starting…")+ expect(progressCaption(status(42, 0))).toBe("42%")+ expect(progressCaption(status(42, 5_347_737))).toBe("42% · 5.1 MB so far")+ })+})++describe("describeArea", () => {+ it("prints the size and the date a finished download completed", () => {+ expect(describeArea(area(), entry(), "https://tiles.example/light.json").sub).toBe(`12.4 MB · ${DATE}`)+ })++ it("omits the date for an entry that never recorded one", () => {+ expect(describeArea(area(), entry({ downloadedAt: undefined }), null).sub).toBe("12.4 MB")+ })++ /**+ * The precedence matters: a pack another instance is downloading must not read as broken, a+ * status read that failed is not an interrupted download, and a stale pack is still complete.+ */+ it("orders the states so the more specific one wins", () => {+ expect(describeArea(area({ isActive: true, isComplete: false }), entry(), null)).toMatchObject({+ tone: "active",+ sub: "Downloading…"+ })+ expect(describeArea(area({ sizeBytes: null, isComplete: false }), entry(), null)).toMatchObject({+ tone: "attention",+ sub: "Could not read this area"+ })+ expect(describeArea(area({ isComplete: false, sizeBytes: 3_355_443 }), entry(), null).sub).toBe(+ "Incomplete · 3.2 MB"+ )+ expect(describeArea(area({ isComplete: false, sizeBytes: 0 }), entry(), null).sub).toBe("Incomplete")+ })++ // A stale pack is still complete, so the size and date stay beside the warning.+ it("says the map style changed, and keeps the size and date beside it", () => {+ const row = describeArea(area(), entry(), "https://tiles.example/other.json")+ expect(row.tone).toBe("attention")+ expect(row.sub).toBe(`Map style changed · 12.4 MB · ${DATE}`)+ })++ it("does not call a pack stale when either style URL is unknown", () => {+ expect(describeArea(area(), entry({ styleUrl: undefined }), "https://x").tone).toBe("plain")+ expect(describeArea(area(), entry(), null).tone).toBe("plain")+ })+})++describe("the confirmations", () => {+ it("carries the estimate, and the mobile-data sentence only when it applies", () => {+ expect(downloadConfirm("Lake", small, false)).toEqual({+ title: 'Download "Lake"?',+ message: "~5 MB estimated.",+ confirmText: "Download"+ })+ expect(downloadConfirm("Lake", small, true).message).toBe("~5 MB estimated. You are on mobile data, not WiFi.")+ })++ // Above the cap the download keeps going where the estimate stopped, which is the sentence to say.+ it("says the download outruns the estimate on a capped frame", () => {+ expect(downloadConfirm("Lake", large, false).message).toBe(+ "At least ~470 MB. The estimate stops counting at 100,000 tiles and the download does not."+ )+ })++ it("says a re-download replaces the tiles", () => {+ expect(redownloadConfirm("Home", small, false)).toEqual({+ title: 'Download "Home" again?',+ message: "Replaces its tiles with a fresh download. ~5 MB estimated.",+ confirmText: "Download again"+ })+ })++ /**+ * Deleting the last pack resets MapLibre's tile database, which the library documents as taking+ * the ambient online cache with it. That is worth a sentence, once, on the last delete only.+ */+ it("names the bytes a delete removes, and the cache reset on the last area", () => {+ expect(deleteAreaConfirm("Home", 13_000_000, false)).toEqual({+ title: 'Delete "Home"?',+ message: "Removes 12.4 MB of map tiles from this device.",+ confirmText: "Delete"+ })+ expect(deleteAreaConfirm("Home", null, false).message).toBe("Removes its map tiles from this device.")+ expect(deleteAreaConfirm("Home", 13_000_000, true).message).toBe(+ "Removes 12.4 MB of map tiles from this device. It is the last saved area, so the map's online tile cache is cleared too."+ )+ })+})++describe("storageMessage", () => {+ it("prints what is needed and what is free, as a floor when capped", () => {+ expect(storageMessage(small, 120)).toBe("~5 MB is needed and the device has 120.0 MB free.")+ expect(storageMessage(large, 120)).toBe("At least ~470 MB is needed and the device has 120.0 MB free.")+ })+})++describe("the geometry", () => {+ it("converts the map's [west, south, east, north] to the manager's corners once", () => {+ expect(cornersOf(BOUNDS)).toEqual({ ne: [13.5, 52.6], sw: [13.4, 52.5] })+ })++ it("draws a closed ring from the north-west corner", () => {+ const feature = areaFeature("Home", BOUNDS)+ expect(feature.properties).toEqual({ name: "Home" })+ expect(feature.geometry).toEqual({+ type: "Polygon",+ coordinates: [+ [+ [13.4, 52.6],+ [13.5, 52.6],+ [13.5, 52.5],+ [13.4, 52.5],+ [13.4, 52.6]+ ]+ ]+ })+ })++ it("skips an area whose bounds native did not report", () => {+ const collection = areasCollection([area(), area({ name: "Broken", bounds: null })])+ expect(collection.features).toHaveLength(1)+ expect(collection.features[0].properties).toEqual({ name: "Home" })+ })+})diff --git a/apps/mobile/src/utils/__tests__/tileHeaders.test.ts b/apps/mobile/src/utils/__tests__/tileHeaders.test.tsindex 43a06ca8..adcd0074 100644--- a/apps/mobile/src/utils/__tests__/tileHeaders.test.ts+++ b/apps/mobile/src/utils/__tests__/tileHeaders.test.ts@@ -30,7 +30,7 @@ describe("tileServerUserAgent", () => {VERSION_NAME: "1.14.0",VERSION_CODE: 45,FLAVOR: "gms",- NDK_VERSION: "27.1"+ APP_LANGUAGE: "de-DE"})expect(tileServerUserAgent()).toBe(`Colota/1.14.0 (+${REPO_URL})`)diff --git a/apps/mobile/src/utils/offlineArea.ts b/apps/mobile/src/utils/offlineArea.tsnew file mode 100644index 00000000..aa057fbe--- /dev/null+++ b/apps/mobile/src/utils/offlineArea.ts@@ -0,0 +1,164 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import type { LucideIcon } from "lucide-react-native"+import { CircleAlert, Loader, Map, TriangleAlert } from "lucide-react-native"+import type {+ OfflineAreaBounds,+ OfflineAreaInfo,+ OfflinePackStatus+} from "../components/features/map/OfflinePackManager"+import { formatBytes } from "./format"+import { formatDateWithYear } from "./geo"++/**+ * What an offline area holds and what a download takes, in the words the screen prints.+ *+ * Every row, caption and dialog is derived here so they cannot drift apart, and nothing reads the+ * bridge or the theme, so a test pins each sentence without rendering the screen.+ */++/** `[west, south, east, north]`, the order the map reports and the pack stores. */+export type Bounds = [number, number, number, number]++export interface Estimate {+ label: string+ bytes: number+ /** The estimator stopped counting at the tile cap, so the label is a floor and not a figure. */+ large: boolean+}++export const INTRO_LINE =+ "Frame an area on the map, name it and download it. The size is an estimate from the area alone: dense cities take more, open country less."++export const ROW_HINT = "Shows it on the map"++export function duplicateNameError(name: string, taken: readonly string[]): string | undefined {+ const trimmed = name.trim()+ return trimmed && taken.includes(trimmed) ? `An area named "${trimmed}" already exists.` : undefined+}++export function estimateSentence(estimate: Estimate): string {+ return estimate.large ? `At least ${estimate.label}.` : `${estimate.label} estimated.`+}++/** The line under Download area: why it is disabled, or what pressing it takes. */+export function downloadLine(estimate: Estimate | null, name: string): string {+ if (!estimate) return "Waiting for the map."+ const size = estimate.large ? `${estimateSentence(estimate)} Zoom in to download less.` : estimateSentence(estimate)+ return name.trim() ? size : `${size} Name the area to download it.`+}++export function progressCaption(status: OfflinePackStatus | null): string {+ if (!status) return "Starting…"+ const pct = `${Math.round(status.percentage)}%`+ return status.completedResourceSize > 0 ? `${pct} · ${formatBytes(status.completedResourceSize)} so far` : pct+}++export type RowTone = "active" | "attention" | "plain"++export interface AreaRow {+ icon: LucideIcon+ tone: RowTone+ sub: string+}++/**+ * Five states in precedence order. A pack this screen is not attached to but native reports active+ * is another instance's download; a null size is a status read that failed, which is not the same+ * as an interrupted download.+ */+export function describeArea(+ area: OfflineAreaInfo,+ entry: OfflineAreaBounds | undefined,+ currentStyleUrl: string | null+): AreaRow {+ if (area.isActive) return { icon: Loader, tone: "active", sub: "Downloading…" }+ if (area.sizeBytes === null) return { icon: CircleAlert, tone: "attention", sub: "Could not read this area" }+ if (!area.isComplete) {+ return {+ icon: CircleAlert,+ tone: "attention",+ sub: area.sizeBytes > 0 ? `Incomplete · ${formatBytes(area.sizeBytes)}` : "Incomplete"+ }+ }+ const when = entry?.downloadedAt ? ` · ${formatDateWithYear(Math.floor(entry.downloadedAt / 1000))}` : ""+ const size = `${formatBytes(area.sizeBytes)}${when}`+ const stale = !!entry?.styleUrl && !!currentStyleUrl && entry.styleUrl !== currentStyleUrl+ if (stale) return { icon: TriangleAlert, tone: "attention", sub: `Map style changed · ${size}` }+ return { icon: Map, tone: "plain", sub: size }+}++export interface ConfirmCopy {+ title: string+ message: string+ confirmText: string+}++const CAP_SENTENCE = "The estimate stops counting at 100,000 tiles and the download does not."+const METERED_SENTENCE = "You are on mobile data, not WiFi."++function sizeClause(estimate: Estimate, metered: boolean): string {+ const size = estimate.large ? `${estimateSentence(estimate)} ${CAP_SENTENCE}` : estimateSentence(estimate)+ return metered ? `${size} ${METERED_SENTENCE}` : size+}++export function downloadConfirm(name: string, estimate: Estimate, metered: boolean): ConfirmCopy {+ return { title: `Download "${name}"?`, message: sizeClause(estimate, metered), confirmText: "Download" }+}++export function redownloadConfirm(name: string, estimate: Estimate, metered: boolean): ConfirmCopy {+ return {+ title: `Download "${name}" again?`,+ message: `Replaces its tiles with a fresh download. ${sizeClause(estimate, metered)}`,+ confirmText: "Download again"+ }+}++/** Names the bytes, and the ambient tile cache the last delete takes with it. */+export function deleteAreaConfirm(name: string, sizeBytes: number | null, isLast: boolean): ConfirmCopy {+ const what = sizeBytes+ ? `Removes ${formatBytes(sizeBytes)} of map tiles from this device.`+ : "Removes its map tiles from this device."+ const last = isLast ? " It is the last saved area, so the map's online tile cache is cleared too." : ""+ return { title: `Delete "${name}"?`, message: `${what}${last}`, confirmText: "Delete" }+}++export function storageMessage(estimate: Estimate, availableMB: number): string {+ const needed = estimate.large ? `At least ${estimate.label}` : estimate.label+ return `${needed} is needed and the device has ${availableMB.toFixed(1)} MB free.`+}++export function cornersOf(bounds: Bounds): { ne: [number, number]; sw: [number, number] } {+ const [west, south, east, north] = bounds+ return { ne: [east, north], sw: [west, south] }+}++export function areaFeature(name: string, bounds: Bounds): GeoJSON.Feature {+ const [west, south, east, north] = bounds+ return {+ type: "Feature",+ geometry: {+ type: "Polygon",+ coordinates: [+ [+ [west, north],+ [east, north],+ [east, south],+ [west, south],+ [west, north]+ ]+ ]+ },+ properties: { name }+ }+}++export function areasCollection(areas: readonly Pick<OfflineAreaInfo, "name" | "bounds">[]): GeoJSON.FeatureCollection {+ return {+ type: "FeatureCollection",+ features: areas.flatMap((area) => (area.bounds ? [areaFeature(area.name, area.bounds)] : []))+ }+}