diff --git a/client/src/App.tsx b/client/src/App.tsx
index 6e1a76e4f..301816bbb 100644
--- a/client/src/App.tsx
+++ b/client/src/App.tsx
@@ -3,6 +3,7 @@ import { Routes, Route, Navigate, useLocation, useNavigationType } from 'react-r
import LegacyCollectionsRedirect from './components/Collections/LegacyCollectionsRedirect'
import { useAuthStore } from './store/authStore'
import { useSettingsStore } from './store/settingsStore'
+import { preloadTripMapRenderer } from './components/Map/glLazy'
import { applyAppearance } from './theme/applyAppearance'
import { useAddonStore } from './store/addonStore'
import { usePluginStore } from './store/pluginStore'
@@ -406,6 +407,10 @@ export default function App() {
const { settings } = useSettingsStore()
+ useEffect(() => {
+ if (isAuthenticated) preloadTripMapRenderer(settings.map_provider, settings.mapbox_access_token)
+ }, [isAuthenticated, settings.map_provider, settings.mapbox_access_token])
+
useInAppNotificationListener()
useRoadtripPreferencesSync()
useTripAddonsSync()
diff --git a/client/src/components/Journey/JourneyMapAuto.tsx b/client/src/components/Journey/JourneyMapAuto.tsx
index b02024ef3..f956f8a31 100644
--- a/client/src/components/Journey/JourneyMapAuto.tsx
+++ b/client/src/components/Journey/JourneyMapAuto.tsx
@@ -79,10 +79,10 @@ function JourneyMapAuto({ ref, ...props }: Props) {
const glProvider = engine ?? 'mapbox-gl'
useImperativeHandle(ref, () => ({
- highlightMarker: (id) => (useGL ? glRef.current : leafletRef.current)?.highlightMarker(id),
- focusMarker: (id) => (useGL ? glRef.current : leafletRef.current)?.focusMarker(id),
- invalidateSize: () => (useGL ? glRef.current : leafletRef.current)?.invalidateSize(),
- }), [useGL])
+ highlightMarker: (id) => (glRef.current ?? leafletRef.current)?.highlightMarker(id),
+ focusMarker: (id) => (glRef.current ?? leafletRef.current)?.focusMarker(id),
+ invalidateSize: () => (glRef.current ?? leafletRef.current)?.invalidateSize(),
+ }), [])
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const leaflet =
@@ -94,7 +94,7 @@ function JourneyMapAuto({ ref, ...props }: Props) {
// See MapViewAuto: the boundary has to sit outside the Suspense to catch a
// chunk that never arrives.
-
+ }>
{/* eslint-disable-next-line @typescript-eslint/no-explicit-any */}
diff --git a/client/src/components/Journey/JourneyMapGL.tsx b/client/src/components/Journey/JourneyMapGL.tsx
index 153c6b50b..0ec19a1d1 100644
--- a/client/src/components/Journey/JourneyMapGL.tsx
+++ b/client/src/components/Journey/JourneyMapGL.tsx
@@ -245,11 +245,11 @@ function JourneyMapGL(
const mapboxQuality = useSettingsStore(s => s.settings.mapbox_quality_mode === true)
const mapLang = useSettingsStore(s => s.settings.language)
const isMapLibre = glProvider === 'maplibre-gl'
- const glStyle = useGlStyle(glProvider, styleOverride)
const enableMapbox3d = !isMapLibre && mapbox3d
const containerRef = useRef(null)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const mapRef = useRef(null)
+ const { style: glStyle, latestStyle, rebuildKey } = useGlStyle(glProvider, styleOverride, mapRef)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const markersRef = useRef
diff --git a/client/src/components/Map/MapViewGL.tsx b/client/src/components/Map/MapViewGL.tsx
index 860359857..eacc2ee92 100644
--- a/client/src/components/Map/MapViewGL.tsx
+++ b/client/src/components/Map/MapViewGL.tsx
@@ -441,7 +441,6 @@ export function MapViewGL({
const mapboxQuality = useSettingsStore(s => s.settings.mapbox_quality_mode === true)
const showEndpointLabels = useSettingsStore(s => s.settings.map_booking_labels) === true
const isMapLibre = glProvider === 'maplibre-gl'
- const glStyle = useGlStyle(glProvider, styleOverride)
const enableMapbox3d = !isMapLibre && mapbox3d
const [mapReady, setMapReady] = useState(false)
const [readyMap, setReadyMap] = useState(null) // the ready map, read without touching mapRef
@@ -470,6 +469,7 @@ export function MapViewGL({
const containerRef = useRef(null)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const mapRef = useRef(null)
+ const { style: glStyle, latestStyle, rebuildKey } = useGlStyle(glProvider, styleOverride, mapRef)
const hazardPopupFactory = useCallback(() => new gl.Popup({ className: 'map-tooltip trek-hazard-popup', maxWidth: '320px' }), [gl])
useHazardLayerGL(mapRef.current, mapReady, hazards, hazardPopupFactory)
useTourMapLayersGL(mapReady ? readyMap : null, ferrataLayer, tourLayers)
@@ -925,10 +925,10 @@ export function MapViewGL({
// nothing left to do on mount.
const framedOnMountRef = useRef(false)
- // Build/rebuild the map on provider/style/token/3d change
useEffect(() => {
if (!containerRef.current || (!isMapLibre && !mapboxToken)) return
if (!isMapLibre) gl.accessToken = mapboxToken
+ const styleAtCreation = latestStyle.current
// Open framed on the places rather than on the caller's default: a trip in Japan should
// show Japan straight away, not the world view followed by a flight across the planet.
@@ -944,7 +944,7 @@ export function MapViewGL({
const mapOptions = glMapOptions({
provider: glProvider,
container: containerRef.current,
- style: initialMapStyle(glProvider, glStyle),
+ style: initialMapStyle(glProvider, styleAtCreation),
center: [initial.center[1], initial.center[0]],
zoom: initial.zoom,
pitch: enableMapbox3d ? 45 : 0,
@@ -954,7 +954,7 @@ export function MapViewGL({
})
// Null when the GPU refused WebGL2: MapViewAuto has switched to Leaflet by then.
- const map = buildGlMap(() => new gl.Map(mapOptions as any), glStyle)
+ const map = buildGlMap(() => new gl.Map(mapOptions as any), styleAtCreation, glProvider)
if (!map) return
mapRef.current = map
popupRef.current = new gl.Popup({
@@ -990,7 +990,7 @@ export function MapViewGL({
;(window as any).__trek_map = map
map.on('load', () => {
- applyGl3d(map, glStyle, enableMapbox3d, document.documentElement.classList.contains('dark'))
+ applyGl3d(map, styleAtCreation, enableMapbox3d, document.documentElement.classList.contains('dark'))
// The ways of driving one leg, offered while the picker is open (#1797). Added
// BEFORE the route source so its layers sit underneath: the current route stays the
// brightest thing on the map, and the options read as what they are — suggestions.
@@ -1416,7 +1416,7 @@ export function MapViewGL({
if ((window as any).__trek_map === map) delete (window as any).__trek_map
setMapReady(false)
}
- }, [glProvider, glStyle, mapboxToken, enableMapbox3d, mapboxQuality]) // rebuild on provider/style changes only
+ }, [glProvider, rebuildKey, latestStyle, mapboxToken, enableMapbox3d, mapboxQuality])
// The label language (#1299) and the basemap's own points of interest (#1761) on Mapbox Standard.
useStandardBasemapConfig(mapRef, mapReady, !isMapLibre && isStandardFamily(glStyle))
diff --git a/client/src/components/Map/VectorBasemap.tsx b/client/src/components/Map/VectorBasemap.tsx
index 4b364951c..c53b8de61 100644
--- a/client/src/components/Map/VectorBasemap.tsx
+++ b/client/src/components/Map/VectorBasemap.tsx
@@ -9,6 +9,7 @@ import {
} from '../../constants/mapDefaults'
import { hasWebGL, reportWebGLFailure } from '../../utils/webgl'
import { isGpuInitFailure } from './glSupport'
+import { mapDeviceTier } from './deviceTier'
import { isChunkLoadError, reloadOnceForChunk } from '../../utils/chunkReload'
import { offlineStyle } from '../../native/offlineTiles'
import { isNativeIos } from '../../native/platform'
@@ -267,6 +268,7 @@ export function VectorBasemap({ style, hideLabels = false }: { style: string; hi
style: offlineStyle(styleRef.current),
interactive: false,
attributionControl: false,
+ padding: mapDeviceTier() === 'full' ? 0.25 : 0.1,
})
if (!attachGlLayer(map, layer, styleRef.current)) {
setGlUsable(false)
diff --git a/client/src/components/Map/deviceTier.test.ts b/client/src/components/Map/deviceTier.test.ts
new file mode 100644
index 000000000..3155e4cd9
--- /dev/null
+++ b/client/src/components/Map/deviceTier.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it } from 'vitest';
+
+import { mapDeviceTier } from './deviceTier';
+
+const chromium = { userAgent: 'AppleWebKit/537.36 Chrome/132.0', hardwareConcurrency: 8, deviceMemory: 8 };
+
+describe('mapDeviceTier', () => {
+ it('uses the full tier on capable Chromium and desktop Firefox', () => {
+ expect(mapDeviceTier(chromium, false, true)).toBe('full');
+ expect(mapDeviceTier({ userAgent: 'Firefox/135.0', hardwareConcurrency: 8 }, false, true)).toBe('full');
+ });
+
+ it('uses the lite tier on a WebView, WebKit, constrained devices and data saver', () => {
+ expect(mapDeviceTier(chromium, true, true)).toBe('lite');
+ expect(mapDeviceTier({ ...chromium, userAgent: 'AppleWebKit/605.1 Safari/605.1' }, false, true)).toBe('lite');
+ expect(mapDeviceTier({ ...chromium, deviceMemory: 4 }, false, true)).toBe('lite');
+ expect(mapDeviceTier({ ...chromium, hardwareConcurrency: 4 }, false, true)).toBe('lite');
+ expect(mapDeviceTier({ ...chromium, connection: { saveData: true } }, false, true)).toBe('lite');
+ });
+});
diff --git a/client/src/components/Map/deviceTier.ts b/client/src/components/Map/deviceTier.ts
new file mode 100644
index 000000000..c1b4f2aa1
--- /dev/null
+++ b/client/src/components/Map/deviceTier.ts
@@ -0,0 +1,22 @@
+import { isNativeApp } from '../../native/platform';
+
+type DeviceTier = 'lite' | 'full';
+
+type MapDevice = Pick & {
+ deviceMemory?: number;
+ connection?: { saveData?: boolean };
+};
+
+export function mapDeviceTier(
+ device: MapDevice | undefined = globalThis.navigator,
+ native = isNativeApp(),
+ finePointer = globalThis.matchMedia?.('(pointer: fine)').matches ?? false
+): DeviceTier {
+ if (native || !device) return 'lite';
+ const { userAgent, hardwareConcurrency, deviceMemory, connection } = device;
+ const webKit = /AppleWebKit/.test(userAgent) && !/(Chrome|Chromium)\//.test(userAgent);
+ const ios = /iPhone|iPad|iPod/.test(userAgent);
+ if (webKit || ios || connection?.saveData || !(hardwareConcurrency > 4)) return 'lite';
+ if (deviceMemory !== undefined) return deviceMemory > 4 ? 'full' : 'lite';
+ return finePointer && /Firefox\//.test(userAgent) ? 'full' : 'lite';
+}
diff --git a/client/src/components/Map/glBasemapSwap.test.ts b/client/src/components/Map/glBasemapSwap.test.ts
new file mode 100644
index 000000000..85f03f6a2
--- /dev/null
+++ b/client/src/components/Map/glBasemapSwap.test.ts
@@ -0,0 +1,59 @@
+import type { StyleSpecification, TransformStyleFunction } from 'maplibre-gl';
+import { describe, expect, it, vi } from 'vitest';
+
+import { mapLibreBasemap, type GlStyle } from './glBasemap';
+import { rememberMapLibreBasemap, swapMapLibreBasemap } from './glBasemapSwap';
+
+const LIBERTY = 'https://tiles.openfreemap.org/styles/liberty';
+const RASTER = mapLibreBasemap('trek:template', 'https://tile.openstreetmap.de/{z}/{x}/{y}.png', false, []).style;
+
+const vectorStyle: StyleSpecification = {
+ version: 8,
+ sources: {},
+ layers: [{ id: 'land', type: 'background', paint: { 'background-color': '#fff' } }],
+};
+
+function fixture(initial: StyleSpecification, ceiling: number) {
+ let style = structuredClone(initial);
+ const listeners = new Map void>>();
+ const map = {
+ once: (name: string, listener: () => void) => {
+ const handlers = listeners.get(name) ?? [];
+ handlers.push(listener);
+ listeners.set(name, handlers);
+ },
+ fire: (name: string) => {
+ for (const listener of listeners.get(name) ?? []) listener();
+ listeners.delete(name);
+ },
+ getStyle: () => style,
+ getMaxZoom: () => ceiling,
+ setMaxZoom: vi.fn(),
+ setStyle: vi.fn((next: GlStyle, options: { transformStyle: TransformStyleFunction }) => {
+ style = options.transformStyle(style, typeof next === 'string' ? vectorStyle : next);
+ }),
+ };
+ return map;
+}
+
+describe('changing the MapLibre basemap in place', () => {
+ it('keeps the live trip data and restores the vector zoom ceiling after a raster style', () => {
+ expect(RASTER).toBeDefined();
+ if (!RASTER) return;
+ const map = fixture(vectorStyle, 22);
+ rememberMapLibreBasemap(map, LIBERTY);
+ map.fire('load');
+ const overlay = { type: 'geojson', data: { type: 'FeatureCollection', features: [] } } as const;
+ map.getStyle().sources.route = { ...overlay, data: { ...overlay.data, features: [] } };
+ map.getStyle().layers.push({ id: 'trip-route', type: 'line', source: 'route' });
+ swapMapLibreBasemap(map, RASTER);
+ expect(map.getStyle().sources.route).toEqual(overlay);
+ expect(map.getStyle().layers.map(({ id }) => id)).toEqual(['basemap', 'trip-route']);
+ expect(map.setMaxZoom).toHaveBeenLastCalledWith(19);
+ swapMapLibreBasemap(map, LIBERTY);
+ expect(map.getStyle().sources.route).toEqual(overlay);
+ expect(map.getStyle().layers.map(({ id }) => id)).toEqual(['land', 'trip-route']);
+ expect(map.setMaxZoom).toHaveBeenLastCalledWith(22);
+ map.fire('remove');
+ });
+});
diff --git a/client/src/components/Map/glBasemapSwap.ts b/client/src/components/Map/glBasemapSwap.ts
new file mode 100644
index 000000000..d0a132126
--- /dev/null
+++ b/client/src/components/Map/glBasemapSwap.ts
@@ -0,0 +1,93 @@
+import { OPENFREEMAP_HOST } from '@trek/shared';
+import type { Map as MapLibreMap, StyleSpecification } from 'maplibre-gl';
+
+import { MAP_MAX_ZOOM } from '../../constants/mapDefaults';
+import { offlineStyle } from '../../native/offlineTiles';
+import { isGlRasterStyle, type GlStyle } from './glBasemap';
+import { watchRasterHealth } from './rasterHealth';
+
+type SwapMap = Pick;
+type BasemapIds = { sources: Set; layers: Set };
+
+interface SwapState {
+ basemap?: BasemapIds;
+ requested: GlStyle;
+ vectorCeiling: number;
+ stopWatchingRaster?: () => void;
+}
+
+const swaps = new WeakMap