feat(map): never leave an offline map grey, whatever the basemap

Offline, a Mapbox map, another OpenFreeMap style or a raster template the
device cannot serve now switches to the stored OpenFreeMap basemap, light or
dark with the colour scheme, keeping every marker, route and track, with a
small Offline map pill. It switches back once the connection returns.

"Prepare for offline" stores that basemap's region for every trip, whatever
the provider, and both styles' sprites and glyphs, including the scripts a
trip in East or South Asia labels its places in. The vector prefetch keeps to
OpenFreeMap's download rules (four requests at a time, 50 MB per run), raster
tiles are no longer prefetched from OpenStreetMap's own servers, which their
policy forbids, nor inside the iOS app, which has no service worker to serve
them.
This commit is contained in:
Maurice
2026-11-06 12:25:29 +01:00
parent 83f0bd2ead
commit b07b38b5b7
36 changed files with 473 additions and 40 deletions
@@ -0,0 +1,123 @@
/**
* The trip map offline (FE-COMP-MAPAUTO-OFFLINE-*).
*
* Whatever basemap the user picked, offline the map never goes grey: a basemap
* with nothing stored switches to the stored OpenFreeMap one, with the same
* markers and routes, and says so.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { render, screen } from '../../../tests/helpers/render';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { OFM_DARK, OFM_POSITRON } from '../../constants/mapDefaults';
import { useSettingsStore } from '../../store/settingsStore';
import { resetWebGLProbe } from '../../utils/webgl';
import { MapViewAuto } from './MapViewAuto';
const env = vi.hoisted(() => ({ offline: false, dark: false }));
const seen = vi.hoisted(() => ({
leaflet: null as null | { tileUrl?: string },
gl: null as null | { engine: string; glProvider?: string; styleOverride?: string },
}));
vi.mock('./MapView', () => ({
MapView: (props: { tileUrl?: string }) => {
seen.leaflet = props;
return <div data-testid="leaflet-map" />;
},
}));
vi.mock('./glLazy', () => ({
MapViewGLMaplibre: (props: { glProvider?: string; styleOverride?: string }) => {
seen.gl = { engine: 'maplibre', ...props };
return <div data-testid="gl-map" />;
},
MapViewGLMapbox: (props: { glProvider?: string; styleOverride?: string }) => {
seen.gl = { engine: 'mapbox', ...props };
return <div data-testid="gl-map" />;
},
}));
vi.mock('./useRoadtripHazards', () => ({ useRoadtripHazards: () => ({ feed: null }) }));
vi.mock('../../hooks/useNetworkMode', () => ({
useNetworkMode: () => ({ offline: env.offline, forced: false, setForced: () => {} }),
}));
vi.mock('../../hooks/useIsDark', () => ({ useIsDark: () => env.dark }));
vi.mock('../../native/platform', async (importOriginal) => ({
...(await importOriginal<typeof import('../../native/platform')>()),
isNativeIos: () => false,
}));
const realGetContext = HTMLCanvasElement.prototype.getContext;
beforeEach(() => {
resetAllStores();
resetWebGLProbe();
env.offline = false;
env.dark = false;
seen.leaflet = null;
seen.gl = null;
const ctx = { getExtension: () => ({ loseContext: () => {} }) };
HTMLCanvasElement.prototype.getContext = vi.fn((type: string) =>
type === 'webgl2' ? ctx : null
) as unknown as typeof realGetContext;
});
afterEach(() => {
HTMLCanvasElement.prototype.getContext = realGetContext;
resetWebGLProbe();
});
const pill = () => screen.queryByRole('status');
describe('MapViewAuto offline', () => {
it('FE-COMP-MAPAUTO-OFFLINE-001: a Mapbox map online stays Mapbox, with no pill', async () => {
seedStore(useSettingsStore, { settings: { map_provider: 'mapbox-gl', mapbox_access_token: 'pk.test' } });
render(<MapViewAuto places={[]} />);
await screen.findByTestId('gl-map');
expect(seen.gl).toMatchObject({ engine: 'mapbox', glProvider: 'mapbox-gl', styleOverride: undefined });
expect(pill()).not.toBeInTheDocument();
});
it('FE-COMP-MAPAUTO-OFFLINE-002: offline, a Mapbox map draws the stored basemap with MapLibre and says so', async () => {
seedStore(useSettingsStore, { settings: { map_provider: 'mapbox-gl', mapbox_access_token: 'pk.test' } });
env.offline = true;
env.dark = true;
render(<MapViewAuto places={[]} />);
await screen.findByTestId('gl-map');
expect(seen.gl).toMatchObject({ engine: 'maplibre', glProvider: 'maplibre-gl', styleOverride: OFM_DARK });
expect(pill()).toBeInTheDocument();
});
it('FE-COMP-MAPAUTO-OFFLINE-003: a MapLibre map already on a stored style stays as it is', async () => {
seedStore(useSettingsStore, { settings: { map_provider: 'maplibre-gl', maplibre_style: OFM_POSITRON } });
env.offline = true;
render(<MapViewAuto places={[]} />);
await screen.findByTestId('gl-map');
expect(seen.gl?.styleOverride).toBeUndefined();
expect(pill()).not.toBeInTheDocument();
});
it('FE-COMP-MAPAUTO-OFFLINE-004: offline, Leaflet on OpenStreetMap tiles switches to the stored basemap', () => {
seedStore(useSettingsStore, { settings: { map_provider: 'leaflet' } });
env.offline = true;
render(<MapViewAuto places={[]} tileUrl="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />);
expect(seen.leaflet?.tileUrl).toBe(OFM_POSITRON);
expect(pill()).toBeInTheDocument();
});
it('FE-COMP-MAPAUTO-OFFLINE-005: offline, a raster template the service worker stored stays', () => {
seedStore(useSettingsStore, { settings: { map_provider: 'leaflet' } });
env.offline = true;
render(<MapViewAuto places={[]} tileUrl="https://tiles.example.com/{z}/{x}/{y}.png" />);
expect(seen.leaflet?.tileUrl).toBe('https://tiles.example.com/{z}/{x}/{y}.png');
expect(pill()).not.toBeInTheDocument();
});
});
+49 -12
View File
@@ -1,5 +1,5 @@
import { Suspense } from 'react'
import { AlertTriangle, Clock, Info } from 'lucide-react'
import { AlertTriangle, Clock, CloudOff, Info } from 'lucide-react'
import { Tooltip } from '../shared/Tooltip'
import { useSettingsStore } from '../../store/settingsStore'
import { MapView } from './MapView'
@@ -9,15 +9,21 @@ import { useGlRenderer } from './glSupport'
import { useRoadtripHazards } from './useRoadtripHazards'
import { useTranslation } from '../../i18n/TranslationContext'
import type { MapViewAutoProps, MapViewProps } from './mapViewContract'
import { useNetworkMode } from '../../hooks/useNetworkMode'
import { useIsDark } from '../../hooks/useIsDark'
import { OFM_POSITRON } from '../../constants/mapDefaults'
import { glWorksOffline, leafletWorksOffline, offlineStyleFor } from './offlineBasemap'
// Auto-selects the map renderer based on user settings. Keeps the existing
// Leaflet MapView untouched so the Mapbox GL variant can mature iteratively
// behind a toggle. Atlas is not affected — it imports Leaflet directly.
//
// Offline maps: only the Leaflet renderer supports full pre-download (raster
// tiles via sync/tilePrefetcher.ts). GL maps are best-effort offline — their
// vector tiles are cached opportunistically by the Service Worker as you view
// them online (see the GL tile rules in vite.config.js), not prefetched.
// Offline maps: "prepare for offline" stores the OpenFreeMap basemap for every
// trip, whatever the provider (sync/tilePrefetcher.ts). Offline, a map whose own
// basemap cannot be drawn from storage (Mapbox, another OpenFreeMap style, a
// raster template the device cannot serve) switches to that stored basemap,
// with the same markers, routes and tracks, and says so with a small pill. It
// switches back once the connection returns. See offlineBasemap.ts.
export function MapViewAuto(props: MapViewAutoProps) {
const { t } = useTranslation()
const hazards = useRoadtripHazards(props.tripId, !!props.clusterLoosely)
@@ -32,7 +38,17 @@ export function MapViewAuto(props: MapViewAutoProps) {
// Fall back to Leaflet when Mapbox is selected but no token is set, or when the
// browser has no WebGL2 (both GL engines need it), so the trip planner never
// shows an empty map or one that fails to start.
const glProvider = useGlRenderer(provider, token)
const configuredGl = useGlRenderer(provider, token)
const maplibreStyle = useSettingsStore(s => s.settings.maplibre_style)
const { offline } = useNetworkMode()
const dark = useIsDark()
const offlineStyle = offlineStyleFor(dark)
// Offline on a basemap that has nothing stored: draw the stored one with MapLibre.
const glFallback = !!configuredGl && offline && !glWorksOffline(configuredGl, maplibreStyle)
const glProvider = glFallback ? 'maplibre-gl' : configuredGl
const leafletFallback = !configuredGl && offline && !leafletWorksOffline(mapProps.tileUrl ?? OFM_POSITRON)
if (leafletFallback) mapProps.tileUrl = offlineStyle
const pill = (glFallback || leafletFallback) && <OfflineBasemapPill label={t('map.offlineBasemap')} />
// One chunk per engine: picking the binding here is what keeps mapbox-gl and
// maplibre-gl out of each other's downloads.
const MapViewGL = glProvider === 'maplibre-gl' ? MapViewGLMaplibre : MapViewGLMapbox
@@ -45,12 +61,33 @@ export function MapViewAuto(props: MapViewAutoProps) {
// to Leaflet keeps a usable map instead of an error card.
// resetKeys: with two engine chunks, a failure under one provider must not
// keep showing Leaflet after the user switches to the other.
<ErrorBoundary boundaryId="map:gl" resetKeys={[glProvider]} fallback={<MapView {...mapProps} />}>
<Suspense fallback={<MapView {...mapProps} />}>
<MapViewGL {...mapProps} glProvider={glProvider} />
</Suspense>
</ErrorBoundary>
<>
<ErrorBoundary boundaryId="map:gl" resetKeys={[glProvider]} fallback={<MapView {...mapProps} />}>
<Suspense fallback={<MapView {...mapProps} />}>
<MapViewGL {...mapProps} glProvider={glProvider} styleOverride={glFallback ? offlineStyle : undefined} />
</Suspense>
</ErrorBoundary>
{pill}
</>
)
}
return <MapView {...mapProps} />
return (
<>
<MapView {...mapProps} />
{pill}
</>
)
}
/** Says the map on screen is the stored offline basemap, not the user's own. */
function OfflineBasemapPill({ label }: { label: string }) {
return (
<div
role="status"
className="pointer-events-none absolute left-1/2 z-[5] flex -translate-x-1/2 items-center gap-1.5 rounded-full border border-edge bg-surface-card px-3 py-1 text-caption font-semibold text-content-secondary shadow-sm backdrop-blur-md bottom-[calc(var(--bottom-nav-h,0px)+12px)]"
>
<CloudOff size={13} strokeWidth={2.2} aria-hidden="true" />
{label}
</div>
)
}
+4 -1
View File
@@ -100,6 +100,8 @@ const NO_DAYS: Day[] = []
/** The GL renderer: the shared map contract plus the engine it is bound to. */
interface Props extends MapViewProps {
glProvider?: GlMapProvider
/** Draws this style instead of the user's: the offline basemap (offlineBasemap.ts). */
styleOverride?: string
/**
* The GL engine, injected instead of imported. Both SDKs used to be pulled in
* statically here, so a single 2.8 MB chunk carried mapbox-gl and maplibre-gl
@@ -482,6 +484,7 @@ export function MapViewGL({
onRemoveVia,
onViewportChange,
glProvider = 'mapbox-gl',
styleOverride,
gl,
onMapReady,
...assistant
@@ -506,7 +509,7 @@ export function MapViewGL({
const showEndpointLabels = useSettingsStore(s => s.settings.map_booking_labels) === true
const mapLang = useSettingsStore(s => s.settings.language)
const isMapLibre = glProvider === 'maplibre-gl'
const glStyle = styleForActiveProvider(glProvider, rawMapboxStyle, rawMaplibreStyle)
const glStyle = styleOverride ?? styleForActiveProvider(glProvider, rawMapboxStyle, rawMaplibreStyle)
const enableMapbox3d = !isMapLibre && mapbox3d
const [mapReady, setMapReady] = useState(false)
const [readyMap, setReadyMap] = useState<FerrataGlMap | null>(null) // the ready map, read without touching mapRef
@@ -0,0 +1,33 @@
import { describe, expect, it } from 'vitest';
import { OFM_DARK, OFM_POSITRON } from '../../constants/mapDefaults';
import { glWorksOffline, isOfflineForbiddenTemplate, leafletWorksOffline, offlineStyleFor } from './offlineBasemap';
describe('offlineBasemap', () => {
it('picks the stored style for the colour scheme', () => {
expect(offlineStyleFor(false)).toBe(OFM_POSITRON);
expect(offlineStyleFor(true)).toBe(OFM_DARK);
});
it('knows OpenStreetMap standard tiles may not be stored, sharded or not', () => {
expect(isOfflineForbiddenTemplate('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png')).toBe(true);
expect(isOfflineForbiddenTemplate('https://tile.openstreetmap.org/{z}/{x}/{y}.png')).toBe(true);
expect(isOfflineForbiddenTemplate('https://tile.openstreetmap.de/{z}/{x}/{y}.png')).toBe(false);
expect(isOfflineForbiddenTemplate('not a url')).toBe(false);
});
it('lets only MapLibre on a stored style draw offline as configured', () => {
expect(glWorksOffline('maplibre-gl', OFM_POSITRON)).toBe(true);
expect(glWorksOffline('maplibre-gl', OFM_DARK)).toBe(true);
// The default MapLibre style is Liberty, whose sprite and glyphs are not stored.
expect(glWorksOffline('maplibre-gl', '')).toBe(false);
expect(glWorksOffline('mapbox-gl', OFM_POSITRON)).toBe(false);
});
it('keeps a stored raster template on the web, never in the iOS app or for OSM', () => {
expect(leafletWorksOffline(OFM_POSITRON, true)).toBe(true);
expect(leafletWorksOffline('https://tiles.openfreemap.org/styles/liberty', false)).toBe(false);
expect(leafletWorksOffline('https://tiles.example.com/{z}/{x}/{y}.png', false)).toBe(true);
expect(leafletWorksOffline('https://tiles.example.com/{z}/{x}/{y}.png', true)).toBe(false);
expect(leafletWorksOffline('https://tile.openstreetmap.org/{z}/{x}/{y}.png', false)).toBe(false);
});
});
@@ -0,0 +1,54 @@
import { OFM_DARK, OFM_POSITRON } from '../../constants/mapDefaults';
import { isNativeIos } from '../../native/platform';
import { isVectorStyle } from '../../utils/tileUrl';
import { normalizeStyleForProvider, type GlMapProvider } from './glProviders';
/**
* The basemap a map falls back to offline, so that whatever the user picked
* online (Mapbox, a raster template, another OpenFreeMap style) they never
* face a grey map once the connection goes.
*
* The two OpenFreeMap styles below are the ones "prepare for offline" stores
* for every trip, whatever the configured provider (sync/tilePrefetcher.ts):
* both share one planet tile set, so the dark one only adds its style, sprite
* and glyphs. A fallback has to be exactly a style that was stored, or its
* sprite and labels are missing offline.
*/
export const OFFLINE_STYLES: readonly string[] = [OFM_POSITRON, OFM_DARK];
/** The stored style that matches the colour scheme. */
export function offlineStyleFor(dark: boolean): string {
return dark ? OFM_DARK : OFM_POSITRON;
}
/** Hosts whose tiles may not be stored for offline use at all (OSM tile usage policy). */
const NO_OFFLINE_HOSTS = ['tile.openstreetmap.org'];
export function isOfflineForbiddenTemplate(template: string): boolean {
try {
const host = new URL(template.replace(/\{s\}/g, 'a')).hostname;
return NO_OFFLINE_HOSTS.some((h) => host === h || host.endsWith(`.${h}`));
} catch {
return false;
}
}
/**
* Whether a GL map can be drawn offline as configured. Only MapLibre on one of
* the stored styles can: Mapbox has nothing stored to draw from, and another
* OpenFreeMap style lacks its sprite and glyphs offline.
*/
export function glWorksOffline(provider: GlMapProvider, maplibreStyle: string | null | undefined): boolean {
return provider === 'maplibre-gl' && OFFLINE_STYLES.includes(normalizeStyleForProvider('maplibre-gl', maplibreStyle));
}
/**
* Whether the Leaflet map's basemap can be drawn offline as configured. A
* stored vector style can. A raster template can where the service worker
* serves the prefetched tiles, which the iOS app's WebView does not run for a
* self-hosted server, and never for a host whose tiles may not be stored.
*/
export function leafletWorksOffline(tileUrl: string, nativeIos: boolean = isNativeIos()): boolean {
if (isVectorStyle(tileUrl)) return OFFLINE_STYLES.includes(tileUrl);
return !nativeIos && !isOfflineForbiddenTemplate(tileUrl);
}
+91 -23
View File
@@ -25,8 +25,15 @@ const VECTOR_MAX_ZOOM = 14
// The low zooms cost a few dozen tiles at most.
const VECTOR_MIN_ZOOM = 0
/** Requests in flight, kept low for the same reason the raster side keeps it low. */
const CONCURRENCY = 6
/**
* Requests in flight. OpenFreeMap allows offline downloads with at most four
* parallel requests, at most 3000 tiles and at most 50 MB each
* (openfreemap.org/tos), so the run keeps under all three.
*/
const CONCURRENCY = 4
/** Byte budget per run, the 50 MB OpenFreeMap allows for one download. */
const MAX_RUN_BYTES = 50 * 1024 * 1024
/**
* Hard cap on vector tiles per run. Each is far larger than a raster tile but
@@ -38,12 +45,52 @@ const MAX_VECTOR_TILES = 2000
export const VECTOR_CACHE = 'gl-map-offline'
/**
* Latin glyph ranges. A label needs the range its codepoints fall in, and Latin
* text lives in the first few; asking for all 256 ranges would download megabytes
* of CJK nobody on this map is going to render.
* Glyph ranges every map needs: Latin, Greek, Cyrillic, Hebrew, Arabic and the
* punctuation blocks. A label needs the range its codepoints fall in; asking for
* all 256 ranges would download megabytes of scripts nobody on this map renders.
*/
const GLYPH_RANGES = ['0-255', '256-511', '512-767', '768-1023', '1024-1279', '1280-1535', '1536-1791', '8192-8447', '8448-8703']
/** One range string per 256 codepoints from `from` up to `to`. */
function rangesBetween(from: number, to: number): string[] {
const out: string[] = []
for (let start = from - (from % 256); start <= to; start += 256) out.push(`${start}-${start + 255}`)
return out
}
/**
* Scripts whose labels a trip in that part of the world shows in the local
* name, so a trip there gets their ranges too, or its labels render blank
* offline. Boxes are generous [minLng, minLat, maxLng, maxLat].
*/
const REGIONAL_GLYPHS: { box: [number, number, number, number]; ranges: string[] }[] = [
// China, Japan, Korea, Taiwan: kana and CJK punctuation, unified ideographs, Hangul, full-width forms.
{
box: [73, 18, 146, 54],
ranges: [...rangesBetween(0x3000, 0x30ff), ...rangesBetween(0x4e00, 0x9fff), ...rangesBetween(0xac00, 0xd7af), ...rangesBetween(0xff00, 0xffef)],
},
// Thailand, Laos, Cambodia, Myanmar.
{ box: [92, 5, 110, 28], ranges: rangesBetween(0x0e00, 0x0eff).concat(rangesBetween(0x1000, 0x109f), rangesBetween(0x1780, 0x17ff)) },
// India, Nepal, Bangladesh, Sri Lanka: Devanagari through Malayalam, Sinhala.
{ box: [60, 5, 98, 36], ranges: rangesBetween(0x0900, 0x0dff) },
// Georgia and Armenia.
{ box: [39, 38, 47, 44], ranges: rangesBetween(0x0530, 0x058f).concat(rangesBetween(0x10a0, 0x10ff)) },
// Ethiopia and Eritrea.
{ box: [33, 3, 48, 18], ranges: rangesBetween(0x1200, 0x139f) },
]
/** The glyph ranges a map of `bbox` needs: the common ones plus its region's scripts. */
export function glyphRangesFor(bbox: TileBbox | null): string[] {
const out = new Set(GLYPH_RANGES)
if (bbox) {
for (const { box, ranges } of REGIONAL_GLYPHS) {
const overlaps = bbox.minLng <= box[2] && bbox.maxLng >= box[0] && bbox.minLat <= box[3] && bbox.maxLat >= box[1]
if (overlaps) for (const r of ranges) out.add(r)
}
}
return [...out]
}
interface StyleSource {
type?: string
url?: string
@@ -96,15 +143,18 @@ function fontStacks(style: StyleDoc): string[] {
* the Service Worker's handler, so a repeated or resumed run over a warm cache
* costs almost nothing. Same reasoning as the raster side.
*/
async function warm(cache: Cache | null, url: string): Promise<boolean> {
async function warm(cache: Cache | null, url: string): Promise<number> {
try {
if (cache && (await cache.match(url))) return false
if (cache && (await cache.match(url))) return 0
const res = await fetch(url, { mode: 'cors' })
if (!res.ok) return false
await cache?.put(url, res.clone())
return true
if (!res.ok) return 0
// The length header when the server sends one; otherwise the body itself.
const header = Number(res.headers.get('content-length'))
const size = header > 0 ? header : (await res.clone().blob()).size || 1
await cache?.put(url, res)
return size
} catch {
return false
return 0
}
}
@@ -178,11 +228,11 @@ async function readTileSources(style: StyleDoc, cache: Cache | null): Promise<Ti
* The device-wide half: the style, its TileJSON, the sprite and the glyphs.
* Returns the vector tile URL template, or null when the style could not be read.
*/
export async function prefetchStyleAssets(styleUrl: string): Promise<string | null> {
return (await prefetchStyle(styleUrl))?.[0]?.template ?? null
export async function prefetchStyleAssets(styleUrl: string, bbox: TileBbox | null = null): Promise<string | null> {
return (await prefetchStyle(styleUrl, bbox))?.[0]?.template ?? null
}
async function prefetchStyle(styleUrl: string): Promise<TileSource[] | null> {
async function prefetchStyle(styleUrl: string, bbox: TileBbox | null = null): Promise<TileSource[] | null> {
const cache = await openVectorCache()
const style = await fetchJson<StyleDoc>(styleUrl)
if (!style) return null
@@ -199,14 +249,14 @@ async function prefetchStyle(styleUrl: string): Promise<TileSource[] | null> {
}
if (style.glyphs) {
const stacks = fontStacks(style)
await Promise.all(
stacks.flatMap(stack =>
GLYPH_RANGES.map(range =>
warm(cache, style.glyphs!.replace('{fontstack}', encodeURIComponent(stack)).replace('{range}', range)),
),
// Through the same pool as the tiles: a trip in East Asia asks for a few
// hundred glyph ranges, and OpenFreeMap allows four requests at a time.
const urls = fontStacks(style).flatMap(stack =>
glyphRangesFor(bbox).map(range =>
style.glyphs!.replace('{fontstack}', encodeURIComponent(stack)).replace('{range}', range),
),
)
await inPool(urls, url => warm(cache, url))
}
return readTileSources(style, cache)
@@ -233,7 +283,7 @@ export async function prefetchVectorForPlaces(
const bbox = computeBbox(places)
if (!bbox) return { tiles: 0, template: null }
const sources = await prefetchStyle(styleUrl)
const sources = await prefetchStyle(styleUrl, bbox)
const template = sources?.[0]?.template ?? null
if (!sources?.length || isCancelled()) return { tiles: 0, template }
@@ -242,13 +292,18 @@ export async function prefetchVectorForPlaces(
let cursor = 0
let fetched = 0
let bytes = 0
async function worker(): Promise<void> {
while (cursor < urls.length) {
if (isCancelled() || !navigator.onLine) return
if (isCancelled() || !navigator.onLine || bytes >= MAX_RUN_BYTES) return
const url = urls[cursor++]
if (!url) return
if (await warm(cache, url)) fetched++
const size = await warm(cache, url)
if (size > 0) {
fetched++
bytes += size
}
}
}
@@ -256,6 +311,19 @@ export async function prefetchVectorForPlaces(
return { tiles: fetched, template }
}
/** Runs `task` over `items`, CONCURRENCY at a time. */
async function inPool<T>(items: T[], task: (item: T) => Promise<unknown>): Promise<void> {
let cursor = 0
async function worker(): Promise<void> {
while (cursor < items.length) {
const item = items[cursor++]
if (item === undefined) return
await task(item)
}
}
await Promise.all(Array.from({ length: CONCURRENCY }, () => worker()))
}
/** Drop the offline vector basemap, alongside the raster cache. */
export async function clearVectorCache(): Promise<void> {
try {
+34 -4
View File
@@ -28,8 +28,10 @@ import { offlineDb, upsertSyncMeta } from '../db/offlineDb'
import { isAuthed } from './authGate'
import { isStoragePersisted } from './persistentStorage'
import { isVectorStyle, normalizeTileUrl, resolveTileUrl, withTileApiKey } from '../utils/tileUrl'
import { OFM_POSITRON } from '../constants/mapDefaults'
import { clearVectorCache, prefetchVectorForPlaces } from './glPrefetcher'
import { OFM_DARK, OFM_POSITRON } from '../constants/mapDefaults'
import { clearVectorCache, prefetchStyleAssets, prefetchVectorForPlaces } from './glPrefetcher'
import { isOfflineForbiddenTemplate } from '../components/Map/offlineBasemap'
import { isNativeIos } from '../native/platform'
// ── Constants ─────────────────────────────────────────────────────────────────
@@ -385,6 +387,21 @@ function sameBbox(a: [number, number, number, number], b: TileBbox): boolean {
)
}
/** The OpenFreeMap styles the offline fallback draws; they share one tile set. */
const OFFLINE_BASEMAPS: readonly string[] = [OFM_POSITRON, OFM_DARK]
/**
* The trip's region of the offline basemap: the light style's tiles, style,
* sprite and glyphs, and the dark style's own style, sprite and glyphs on top,
* whose tiles are the same ones.
*/
async function prefetchOfflineBasemap(places: Place[], template: string, cancelled: () => boolean): Promise<void> {
const light = template === OFM_DARK ? OFM_DARK : OFM_POSITRON
const other = light === OFM_DARK ? OFM_POSITRON : OFM_DARK
await prefetchVectorForPlaces(places, light, cancelled).catch(console.error)
if (!cancelled()) await prefetchStyleAssets(other, computeBbox(places)).catch(console.error)
}
/**
* Full pipeline: compute bbox → guard → prefetch → update syncMeta.
* Designed to be called fire-and-forget from tripSyncManager.
@@ -415,8 +432,16 @@ export async function prefetchTilesForTrip(
// The default basemap is a vector style, and walking a {z}/{x}/{y} template
// over one would fetch nothing the map ever asks for. A user who configured
// their own raster template keeps the path below unchanged.
const cancelled = () => !navigator.onLine || !isAuthed()
// Whatever the map is set to, the trip's region of the offline basemap goes
// along: offline, a Mapbox map or one the device cannot serve switches to it
// (components/Map/offlineBasemap.ts).
await prefetchOfflineBasemap(places, template, cancelled)
if (isVectorStyle(template)) {
const { tiles } = await prefetchVectorForPlaces(places, template, () => !navigator.onLine || !isAuthed())
const { tiles } = OFFLINE_BASEMAPS.includes(template)
? { tiles: 0 }
: await prefetchVectorForPlaces(places, template, cancelled)
const meta = await offlineDb.syncMeta.get(tripId)
if (meta) {
await upsertSyncMeta({
@@ -447,7 +472,12 @@ export async function prefetchTilesForTrip(
// dozen tiles (#2180); the deep ones are the volume, and they are what the
// user loses rather than the ability to start the app at all (#2228).
const maxZoom = isStoragePersisted() ? 16 : UNPERSISTED_MAX_ZOOM
const fetched = await prefetchTiles(bbox, template, 0, maxZoom, cartoKey)
// Not for a host whose tiles may not be stored (OSM's tile usage policy), and
// not inside the iOS app, whose WebView runs no service worker to serve them:
// the offline basemap above stands in there.
const fetched = isOfflineForbiddenTemplate(template) || isNativeIos()
? 0
: await prefetchTiles(bbox, template, 0, maxZoom, cartoKey)
// Update syncMeta with bbox and tile count
const meta = await offlineDb.syncMeta.get(tripId)