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);
}