feat(maps): keep GL maps responsive through style and GPU changes

This commit is contained in:
Maurice
2026-11-30 16:24:49 +01:00
parent 69eacd5316
commit f814b0000d
24 changed files with 524 additions and 50 deletions
+5
View File
@@ -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()
@@ -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 = <JourneyMap ref={leafletRef} {...(props as any)} basemapOverride={tileUrlOverride} />
@@ -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.
<ErrorBoundary boundaryId="journey-map:gl" resetKeys={[glProvider]} fallback={leaflet}>
<Suspense fallback={null}>
<Suspense fallback={<div className="h-full w-full bg-surface-tertiary" style={{ height: props.height }} aria-busy="true" />}>
{/* eslint-disable-next-line @typescript-eslint/no-explicit-any */}
<JourneyMapGL ref={glRef} {...(props as any)} glProvider={glProvider} styleOverride={styleOverride} />
</Suspense>
@@ -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<HTMLDivElement>(null)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const mapRef = useRef<any | null>(null)
const { style: glStyle, latestStyle, rebuildKey } = useGlStyle(glProvider, styleOverride, mapRef)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const markersRef = useRef<Map<string, any>>(new Map())
const itemsRef = useRef<Item[]>([])
@@ -414,6 +414,7 @@ function JourneyMapGL(
useEffect(() => {
if (!containerRef.current || (!isMapLibre && !mapboxToken)) return
if (!isMapLibre) gl.accessToken = mapboxToken
const styleAtCreation = latestStyle.current
const items = buildItems(entries)
itemsRef.current = items
@@ -425,7 +426,7 @@ function JourneyMapGL(
const mapOptions = glMapOptions({
provider: glProvider,
container: containerRef.current,
style: initialMapStyle(glProvider, glStyle),
style: initialMapStyle(glProvider, styleAtCreation),
center: hasPoints ? bounds.getCenter() : [0, 30],
zoom: hasPoints ? 2 : 1,
pitch: enableMapbox3d && fullScreen ? 45 : 0,
@@ -438,7 +439,7 @@ function JourneyMapGL(
})
// Null when the GPU refused WebGL2: JourneyMapAuto 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
marksFramedRef.current = false
@@ -454,10 +455,10 @@ function JourneyMapGL(
visibilityRef.current[kind] ? base : { ...base, visibility: 'none' }
map.on('load', () => {
applyGl3d(map, glStyle, enableMapbox3d, !!darkRef.current)
applyGl3d(map, styleAtCreation, enableMapbox3d, !!darkRef.current)
// Pin the basemap label language to the UI language so labels don't fall back to the
// browser/OS locale and stack multiple scripts per place (#1299).
if (!isMapLibre && isStandardFamily(glStyle)) {
if (!isMapLibre && isStandardFamily(styleAtCreation)) {
try { map.setConfigProperty('basemap', 'language', basemapLanguage(mapLangRef.current)) } catch { /* style/SDK may not support it */ }
}
@@ -574,7 +575,7 @@ function JourneyMapGL(
try { map.remove() } catch { /* noop */ }
mapRef.current = null
}
}, [entries, stableTrail, stableTracks, glProvider, glStyle, mapboxToken, enableMapbox3d, mapboxQuality, fullScreen, paddingBottom])
}, [entries, stableTrail, stableTracks, glProvider, rebuildKey, latestStyle, mapboxToken, enableMapbox3d, mapboxQuality, fullScreen, paddingBottom])
// Photo layer (#2453), the GL twin of the Leaflet one: its own effect so photos
// arriving do not rebuild the map. Redrawn after every move, but the clusters
+2 -2
View File
@@ -11,11 +11,11 @@ import RoadtripViaMarkers from './RoadtripViaMarkers'
import PlannerWaypointMarker from './PlannerWaypointMarker'
import HazardLayers from './HazardLayers'
import { RouteHitBand } from './RouteHitBand'
import { rasterUpdatesWhenIdle } from './leafletRasterTuning'
import { formatViaDwell } from './routeViaDwell'
import { ALT_CASING, ALT_LABEL_TEXT } from '../Roadtrip/alternativeColors'
import { serviceMarkerHtml, serviceMarkerOuter } from '../Roadtrip/serviceMarker'
import type { AlternativeOverlay } from '../Roadtrip/alternativeOverlays'
/**
* The drive-time pill for one offered route.
*
@@ -919,7 +919,7 @@ export const MapView = memo(function MapView({
maxZoom={19}
keepBuffer={8}
updateWhenZooming={false}
updateWhenIdle={true}
updateWhenIdle={rasterUpdatesWhenIdle(basemap.template)}
referrerPolicy="strict-origin-when-cross-origin"
/>
)}
+1 -3
View File
@@ -33,8 +33,6 @@ export function MapViewAuto(props: MapViewAutoProps) {
// maplibre-gl out of each other's downloads.
const MapViewGL = glProvider === 'maplibre-gl' ? MapViewGLMaplibre : MapViewGLMapbox
if (glProvider) {
// Render the previous Leaflet map as the fallback so there's no blank flash
// while the GL chunk loads on first use.
return (
// Outside the Suspense on purpose: Suspense handles the pending promise,
// a rejected one (chunk gone after a deploy) throws past it. Falling back
@@ -43,7 +41,7 @@ export function MapViewAuto(props: MapViewAutoProps) {
// keep showing Leaflet after the user switches to the other.
<>
<ErrorBoundary boundaryId="map:gl" resetKeys={[glProvider]} fallback={<MapView {...mapProps} />}>
<Suspense fallback={<MapView {...mapProps} />}>
<Suspense fallback={<div className="h-full w-full bg-surface-tertiary" aria-busy="true" />}>
<MapViewGL {...mapProps} glProvider={glProvider} styleOverride={styleOverride} />
</Suspense>
</ErrorBoundary>
+6 -6
View File
@@ -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<FerrataGlMap | null>(null) // the ready map, read without touching mapRef
@@ -470,6 +469,7 @@ export function MapViewGL({
const containerRef = useRef<HTMLDivElement>(null)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const mapRef = useRef<any | null>(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))
@@ -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)
@@ -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');
});
});
+22
View File
@@ -0,0 +1,22 @@
import { isNativeApp } from '../../native/platform';
type DeviceTier = 'lite' | 'full';
type MapDevice = Pick<Navigator, 'hardwareConcurrency' | 'userAgent'> & {
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';
}
@@ -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<string, Array<() => 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');
});
});
@@ -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<MapLibreMap, 'getStyle' | 'once' | 'setStyle' | 'getMaxZoom' | 'setMaxZoom'>;
type BasemapIds = { sources: Set<string>; layers: Set<string> };
interface SwapState {
basemap?: BasemapIds;
requested: GlStyle;
vectorCeiling: number;
stopWatchingRaster?: () => void;
}
const swaps = new WeakMap<object, SwapState>();
function basemapIds(style: StyleSpecification): BasemapIds {
return {
sources: new Set(Object.keys(style.sources)),
layers: new Set(style.layers.map((layer) => layer.id)),
};
}
export function preservesMapLibreLayers(style: GlStyle): boolean {
return isGlRasterStyle(style) || style.startsWith(`https://${OPENFREEMAP_HOST}/styles/`);
}
function canSwap(map: unknown): map is SwapMap {
const value = map as Partial<SwapMap> | null;
return (
typeof value?.setStyle === 'function' &&
typeof value.getStyle === 'function' &&
typeof value.once === 'function' &&
typeof value.getMaxZoom === 'function' &&
typeof value.setMaxZoom === 'function'
);
}
function keepAppLayers(
previous: StyleSpecification,
next: StyleSpecification,
basemap: BasemapIds
): StyleSpecification {
const nextIds = basemapIds(next);
const sources = Object.fromEntries(
Object.entries(previous.sources).filter(([id]) => !basemap.sources.has(id) && !nextIds.sources.has(id))
);
const layers = previous.layers.filter((layer) => !basemap.layers.has(layer.id) && !nextIds.layers.has(layer.id));
return { ...next, sources: { ...next.sources, ...sources }, layers: [...next.layers, ...layers] };
}
/** Capture the renderer's own layers before the trip or Journey adds its overlays. */
export function rememberMapLibreBasemap(map: unknown, style: GlStyle): void {
if (!canSwap(map) || !preservesMapLibreLayers(style)) return;
const state: SwapState = {
requested: style,
vectorCeiling: isGlRasterStyle(style) ? 22 : map.getMaxZoom(),
stopWatchingRaster: watchRasterHealth(map, style),
};
swaps.set(map, state);
map.once('load', () => {
state.basemap = basemapIds(map.getStyle());
});
map.once('remove', () => state.stopWatchingRaster?.());
}
/** Swap the basemap while keeping the camera, the trip overlays and the map instance. */
export function swapMapLibreBasemap(map: unknown, style: GlStyle): void {
if (!canSwap(map) || !preservesMapLibreLayers(style)) return;
const state = swaps.get(map);
if (!state || state.requested === style) return;
state.requested = style;
const apply = () => {
const basemap = state.basemap;
if (!basemap || state.requested !== style) return;
map.setStyle(offlineStyle(style), {
transformStyle(previous, next) {
state.basemap = basemapIds(next);
state.stopWatchingRaster?.();
state.stopWatchingRaster = watchRasterHealth(map, style);
map.setMaxZoom(isGlRasterStyle(style) ? MAP_MAX_ZOOM : state.vectorCeiling);
return previous ? keepAppLayers(previous, next, basemap) : next;
},
});
};
if (state.basemap) apply();
else map.once('load', apply);
}
+8
View File
@@ -2,6 +2,7 @@ import type { ComponentType } from 'react'
import { lazyWithRetry } from '../../utils/lazyWithRetry'
import type { GlStyle } from './glBasemap'
import type { GlMapProvider } from './glProviders'
import { pickGlRenderer } from './glSupport'
import type { MapViewProps } from './mapViewContract'
/** What a caller hands the GL trip map: the shared map contract and which provider's style to load. */
@@ -43,6 +44,13 @@ export const MapViewGLMaplibre = lazyWithRetry(async () => {
return { default: bound satisfies ComponentType<MapViewGLProps> }
})
export function preloadTripMapRenderer(provider: string | undefined, token: string | undefined): void {
const engine = pickGlRenderer(provider, token)
if (!engine) return
const view = engine === 'maplibre-gl' ? MapViewGLMaplibre : MapViewGLMapbox
void view.preload().catch(() => { /* The map boundary handles this if the user opens a map. */ })
}
export const JourneyMapGLMapbox = lazyWithRetry(async () => {
const [component, engine] = await Promise.all([
import('../Journey/JourneyMapGL'),
+8 -10
View File
@@ -129,16 +129,14 @@ describe('glMapOptions: MapLibre', () => {
env.tileStore = true;
const options = tripMap('maplibre-gl', false, LIBERTY);
expect(options).toMatchObject({ style: LIBERTY, antialias: false, aroundCenter: false });
expect(Object.keys(options)).toEqual([
'container',
'style',
'center',
'zoom',
'pitch',
'attributionControl',
'antialias',
'aroundCenter',
]);
expect(options).not.toHaveProperty('projection');
expect(options).not.toHaveProperty('transformRequest');
expect(options).toMatchObject({
cancelPendingTileRequestsWhileZooming: true,
maxTileCacheSize: 200,
fadeDuration: 0,
maxCanvasSize: [2048, 2048],
});
});
it('FE-MAP-GLOPTIONS-011: a raster template stops at the zoom Leaflet stops at', () => {
+12 -1
View File
@@ -2,6 +2,7 @@ import type mapboxgl from 'mapbox-gl';
import { MAP_MAX_ZOOM } from '../../constants/mapDefaults';
import { mapboxTileCacheRequest, tileCacheActive } from '../../native/tileCache';
import { mapDeviceTier } from './deviceTier';
import { isGlRasterStyle, type GlStyle } from './glBasemap';
import { MAPBOX_DEFAULT_STYLE, type GlMapProvider } from './glProviders';
import {
@@ -58,7 +59,17 @@ export function glMapOptions(input: GlMapOptionsInput): Record<string, unknown>
if (!isMapLibre) options.projection = input.quality ? 'globe' : 'mercator';
if (!isMapLibre && input.appTileStore && tileCacheActive()) options.transformRequest = mapboxTileCacheRequest;
// MapLibre's around-center rotate ping-pongs near mid-screen (#1545); false is mapbox-gl's dx rotate.
if (isMapLibre) options.aroundCenter = false;
if (isMapLibre) {
const full = mapDeviceTier() === 'full';
options.aroundCenter = false;
options.cancelPendingTileRequestsWhileZooming = !full;
options.maxTileCacheSize = full ? 1000 : 200;
options.fadeDuration = full ? 150 : 0;
if (!full) {
options.maxCanvasSize = [2048, 2048];
options.pixelRatio = Math.min(2, globalThis.devicePixelRatio || 1);
}
}
// A raster template ends where Leaflet's map ends: past it the provider has no
// tiles and the map would only enlarge its last ones.
if (isMapLibre && isGlRasterStyle(input.style)) options.maxZoom = MAP_MAX_ZOOM;
+18 -5
View File
@@ -1,8 +1,10 @@
import { useSyncExternalStore } from 'react';
import { offlineStyle } from '../../native/offlineTiles';
import { hasWebGL, reportWebGLFailure, subscribeWebGL, webGLFailures } from '../../utils/webgl';
import type { GlStyle } from './glBasemap';
import { isGlRasterStyle, type GlStyle } from './glBasemap';
import { rememberMapLibreBasemap } from './glBasemapSwap';
import type { GlMapProvider } from './glProviders';
import { hasGlEngineFailure, reportGlEngineFailure, subscribeGlEngineFailure, watchGlEngine } from './glWatchdog';
import { watchRasterHealth } from './rasterHealth';
/*
@@ -41,7 +43,14 @@ export function useGlRenderer(
mapboxToken: string | null | undefined
): GlMapProvider | null {
useWebGLFailures();
return pickGlRenderer(provider, mapboxToken);
const engine = pickGlRenderer(provider, mapboxToken);
const failed = useGlEngineFailed(engine);
return failed ? null : engine;
}
export function useGlEngineFailed(provider: GlMapProvider | null): boolean {
const snapshot = () => provider !== null && hasGlEngineFailure(provider);
return useSyncExternalStore(subscribeGlEngineFailure, snapshot, snapshot);
}
/** Whether 3D (the GL terrain map) can run here, kept current the same way. */
@@ -80,15 +89,19 @@ export function initialMapStyle<T extends GlStyle>(provider: GlMapProvider, styl
* are watched, so a template this browser cannot load moves its maps to Leaflet
* (rasterHealth.ts); every other style is left alone.
*/
export function buildGlMap<T>(construct: () => T, style?: unknown): T | null {
export function buildGlMap<T>(construct: () => T, style?: unknown, provider?: GlMapProvider): T | null {
try {
const map = construct();
if (isResizableGlMap(map)) followContainerSize(map);
watchRasterHealth(map, style);
if (provider === 'maplibre-gl' && (typeof style === 'string' || isGlRasterStyle(style))) {
rememberMapLibreBasemap(map, style);
} else watchRasterHealth(map, style);
if (provider) watchGlEngine(map, provider, style);
return map;
} catch (err) {
if (!isGpuInitFailure(err)) throw err;
reportWebGLFailure();
if (provider) reportGlEngineFailure(provider);
else reportWebGLFailure();
return null;
}
}
@@ -0,0 +1,67 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { clearGlEngineFailure, hasGlEngineFailure, watchGlEngine } from './glWatchdog';
function fixture() {
const canvas = document.createElement('canvas');
const container = { clientWidth: 400, clientHeight: 300 };
const events = new Map<string, () => void>();
const map = {
getCanvas: () => canvas,
getContainer: () => container,
areTilesLoaded: vi.fn(() => false),
once: (event: string, action: () => void) => events.set(event, action),
triggerRepaint: vi.fn(),
};
watchGlEngine(map, 'maplibre-gl', 'https://tiles.openfreemap.org/styles/liberty');
return { canvas, events, map };
}
beforeEach(() => {
vi.useFakeTimers();
clearGlEngineFailure('maplibre-gl');
});
afterEach(() => {
clearGlEngineFailure('maplibre-gl');
vi.useRealTimers();
});
describe('GL watchdog', () => {
it('falls back only for the renderer whose lost context does not recover', () => {
const { canvas } = fixture();
canvas.dispatchEvent(new Event('webglcontextlost'));
vi.advanceTimersByTime(2999);
expect(hasGlEngineFailure('maplibre-gl')).toBe(false);
vi.advanceTimersByTime(1);
expect(hasGlEngineFailure('maplibre-gl')).toBe(true);
expect(hasGlEngineFailure('mapbox-gl')).toBe(false);
});
it('gives a first recovery a chance and falls back on a second loss', () => {
const { canvas } = fixture();
canvas.dispatchEvent(new Event('webglcontextlost'));
canvas.dispatchEvent(new Event('webglcontextrestored'));
vi.advanceTimersByTime(3000);
expect(hasGlEngineFailure('maplibre-gl')).toBe(false);
canvas.dispatchEvent(new Event('webglcontextlost'));
expect(hasGlEngineFailure('maplibre-gl')).toBe(true);
});
it('does not mistake pending tiles for a blank GPU frame', () => {
const { canvas, events } = fixture();
const getContext = vi.spyOn(canvas, 'getContext');
events.get('load')?.();
events.get('idle')?.();
events.get('render')?.();
expect(getContext).not.toHaveBeenCalled();
expect(hasGlEngineFailure('maplibre-gl')).toBe(false);
});
it('switches off a renderer that reports a zero-sized canvas in a visible container', () => {
const { canvas, events } = fixture();
canvas.width = 0;
events.get('load')?.();
expect(hasGlEngineFailure('maplibre-gl')).toBe(true);
});
});
+138
View File
@@ -0,0 +1,138 @@
import { OPENFREEMAP_HOST } from '@trek/shared';
import type { GlMapProvider } from './glProviders';
const RESTORE_GRACE_MS = 3000;
const REPEATED_LOSS_MS = 60_000;
const sessionKey = (provider: GlMapProvider) => `glBlank:${provider}`;
const failures = new Set<GlMapProvider>();
const listeners = new Set<() => void>();
export function hasGlEngineFailure(provider: GlMapProvider): boolean {
if (failures.has(provider)) return true;
try {
return globalThis.sessionStorage?.getItem(sessionKey(provider)) === '1';
} catch {
return false;
}
}
export function subscribeGlEngineFailure(listener: () => void): () => void {
listeners.add(listener);
return () => listeners.delete(listener);
}
export function reportGlEngineFailure(provider: GlMapProvider): void {
if (hasGlEngineFailure(provider)) return;
failures.add(provider);
try {
globalThis.sessionStorage?.setItem(sessionKey(provider), '1');
} catch {
// A browser that blocks storage still falls back on this page.
}
for (const listener of listeners) listener();
}
export function clearGlEngineFailure(provider: GlMapProvider): void {
if (!hasGlEngineFailure(provider)) return;
failures.delete(provider);
try {
globalThis.sessionStorage?.removeItem(sessionKey(provider));
} catch {
// The in-memory flag has already been cleared.
}
for (const listener of listeners) listener();
}
interface WatchedGlMap {
getCanvas(): HTMLCanvasElement;
getContainer(): HTMLElement;
areTilesLoaded(): boolean;
triggerRepaint(): void;
once(type: 'load' | 'idle' | 'render' | 'remove', listener: () => void): unknown;
}
function isWatchedMap(map: unknown): map is WatchedGlMap {
const candidate = map as Partial<WatchedGlMap> | null;
return (
typeof candidate?.getCanvas === 'function' &&
typeof candidate.getContainer === 'function' &&
typeof candidate.once === 'function'
);
}
function knownOpaqueStyle(style: unknown): boolean {
return (
typeof style === 'string' &&
(style.startsWith(`https://${OPENFREEMAP_HOST}/styles/`) || style.startsWith('mapbox://styles/mapbox/'))
);
}
function transparentFrame(canvas: HTMLCanvasElement): boolean {
const gl = canvas.getContext('webgl2');
if (!gl || gl.isContextLost() || !gl.drawingBufferWidth || !gl.drawingBufferHeight) return false;
const pixel = new Uint8Array(4);
const samples = [
[0.5, 0.5],
[0.25, 0.25],
[0.25, 0.75],
[0.75, 0.25],
[0.75, 0.75],
];
return samples.every(([x, y]) => {
gl.readPixels(
Math.floor(gl.drawingBufferWidth * x),
Math.floor(gl.drawingBufferHeight * y),
1,
1,
gl.RGBA,
gl.UNSIGNED_BYTE,
pixel
);
return pixel[3] === 0;
});
}
export function watchGlEngine(map: unknown, provider: GlMapProvider, style: unknown): void {
if (!isWatchedMap(map)) return;
const canvas = map.getCanvas();
if (!canvas) return;
let lossTimer: ReturnType<typeof setTimeout> | undefined;
let lastLoss: number | undefined;
const report = () => reportGlEngineFailure(provider);
const visible = () => {
const container = map.getContainer();
return container.clientWidth > 0 && container.clientHeight > 0;
};
const onRestore = () => clearTimeout(lossTimer);
const onLoss = () => {
const now = Date.now();
onRestore();
if (lastLoss !== undefined && now - lastLoss < REPEATED_LOSS_MS) report();
else lossTimer = setTimeout(report, RESTORE_GRACE_MS);
lastLoss = now;
};
canvas.addEventListener('webglcontextlost', onLoss);
canvas.addEventListener('webglcontextrestored', onRestore);
map.once('load', () => {
if (visible() && (canvas.width === 0 || canvas.height === 0)) report();
});
// Custom raster overlays may intentionally be transparent. The pixel probe
// only runs with a known opaque basemap after the map has finished loading tiles.
if (knownOpaqueStyle(style) && typeof map.triggerRepaint === 'function') {
map.once('idle', () => {
map.once('render', () => {
if (visible() && map.areTilesLoaded?.() && transparentFrame(canvas)) report();
});
map.triggerRepaint();
});
}
map.once('remove', () => {
onRestore();
canvas.removeEventListener('webglcontextlost', onLoss);
canvas.removeEventListener('webglcontextrestored', onRestore);
});
}
@@ -0,0 +1,9 @@
import { OPENFREEMAP_HOST } from '@trek/shared';
import L from 'leaflet';
import { templateHost } from '../../utils/tileUrl';
export function rasterUpdatesWhenIdle(template: string, mobile = L.Browser.mobile): boolean {
const host = templateHost(template);
return mobile || (host !== 'tile.openstreetmap.de' && host !== OPENFREEMAP_HOST);
}
+2 -1
View File
@@ -78,7 +78,7 @@ function isWatchable(map: unknown): map is WatchedMap {
* calls this for every map it builds). Any other style is left alone. Stops on
* its own once a tile arrived, the template was marked, or the map is removed.
*/
export function watchRasterHealth(map: unknown, style: unknown): void {
export function watchRasterHealth(map: unknown, style: unknown): (() => void) | undefined {
if (!isGlRasterStyle(style) || !isWatchable(map)) return;
const template = style.metadata['trek:template'];
const origins = tileOrigins(style.sources[GL_BASEMAP_SOURCE]?.tiles ?? []);
@@ -106,6 +106,7 @@ export function watchRasterHealth(map: unknown, style: unknown): void {
if (failures >= FIRST_TILES) settle(true);
});
map.once('remove', () => settle(false));
return () => settle(false);
}
/** Test seam: a fresh session. */
@@ -8,7 +8,7 @@ import { useAuthStore } from '../../store/authStore';
import { useSettingsStore } from '../../store/settingsStore';
import { isGlRasterStyle, mapLibreBasemap, type GlStyle } from './glBasemap';
import type { GlMapProvider } from './glProviders';
import { useGlRenderer } from './glSupport';
import { useGlEngineFailed, useGlRenderer } from './glSupport';
import { glWorksOffline, leafletWorksOffline, offlineStyleFor } from './offlineBasemap';
import { rasterTemplateFailed, useRasterHealth } from './rasterHealth';
@@ -61,6 +61,7 @@ export function useEffectiveMapEngine(tileUrl: string | undefined): EffectiveMap
const maplibreStyle = useSettingsStore((s) => s.settings.maplibre_style);
const extraHosts = useAuthStore((s) => s.mapExtraConnectHosts);
const configuredGl = useGlRenderer(provider, token);
const maplibreFailed = useGlEngineFailed('maplibre-gl');
const { offline } = useNetworkMode();
const dark = useIsDark();
const offlineStyle = offlineStyleFor(dark);
@@ -94,9 +95,9 @@ export function useEffectiveMapEngine(tileUrl: string | undefined): EffectiveMap
}
return {
engine: glFallback ? 'maplibre-gl' : drawn.engine,
styleOverride: glFallback ? offlineStyle : drawn.style,
tileUrlOverride: leafletFallback ? offlineStyle : undefined,
engine: glFallback ? (maplibreFailed ? null : 'maplibre-gl') : drawn.engine,
styleOverride: glFallback && !maplibreFailed ? offlineStyle : drawn.style,
tileUrlOverride: leafletFallback || (glFallback && maplibreFailed) ? offlineStyle : undefined,
pill,
};
}
+12 -2
View File
@@ -1,5 +1,8 @@
import { useEffect, useRef, type RefObject } from 'react';
import { useSettingsStore } from '../../store/settingsStore';
import type { GlStyle } from './glBasemap';
import { preservesMapLibreLayers, swapMapLibreBasemap } from './glBasemapSwap';
import { MAPBOX_DEFAULT_STYLE, styleForActiveProvider, type GlMapProvider } from './glProviders';
/**
@@ -8,8 +11,15 @@ import { MAPBOX_DEFAULT_STYLE, styleForActiveProvider, type GlMapProvider } from
* keyword resolved to, both from useEffectiveMapEngine), otherwise the user's
* own style slot for the engine, read exactly as the maps always read it.
*/
export function useGlStyle(provider: GlMapProvider, override?: GlStyle): GlStyle {
export function useGlStyle(provider: GlMapProvider, override: GlStyle | undefined, map: RefObject<unknown>) {
const mapboxStyle = useSettingsStore((s) => s.settings.mapbox_style || MAPBOX_DEFAULT_STYLE);
const maplibreStyle = useSettingsStore((s) => s.settings.maplibre_style || '');
return override ?? styleForActiveProvider(provider, mapboxStyle, maplibreStyle);
const style = override ?? styleForActiveProvider(provider, mapboxStyle, maplibreStyle);
const latestStyle = useRef(style);
latestStyle.current = style;
const canSwap = provider === 'maplibre-gl' && preservesMapLibreLayers(style);
useEffect(() => {
if (canSwap) swapMapLibreBasemap(map.current, style);
}, [canSwap, map, style]);
return { style, latestStyle, rebuildKey: canSwap ? null : style };
}
+7
View File
@@ -9,6 +9,11 @@ import { normalizeTileUrl, stripTileApiKey } from '../utils/tileUrl'
import { clearTileCache } from '../sync/tilePrefetcher'
import { cacheAccountSettings, cacheAccountSettingsPatch, cachedAccountSettings } from '../db/cacheAccountSettings'
import { rememberStartDestination, DEFAULT_START_PAGE, DEFAULT_START_TRIP_TAB } from '../utils/startDestination'
import { clearGlEngineFailure } from '../components/Map/glWatchdog'
function retrySelectedEngine(previous: Settings['map_provider'], next: Settings[keyof Settings]) {
if (previous !== next && (next === 'mapbox-gl' || next === 'maplibre-gl')) clearGlEngineFailure(next)
}
interface SettingsState {
settings: Settings
@@ -202,6 +207,7 @@ export const useSettingsStore = create<SettingsState>((set, get) => ({
const next =
key === 'map_tile_url' && typeof value === 'string' ? cleanTileTemplate(value) : value
if (key === 'carto_api_key' && next !== get().settings.carto_api_key) void clearTileCache()
if (key === 'map_provider') retrySelectedEngine(get().settings.map_provider, next)
set((state) => ({
settings: { ...state.settings, [key]: next },
}))
@@ -236,6 +242,7 @@ export const useSettingsStore = create<SettingsState>((set, get) => ({
if ('carto_api_key' in patch && patch.carto_api_key !== get().settings.carto_api_key) {
void clearTileCache()
}
retrySelectedEngine(get().settings.map_provider, patch.map_provider)
set((state) => ({
settings: { ...state.settings, ...patch },
}))
+11
View File
@@ -43,6 +43,17 @@ describe('retryUrlFor', () => {
})
describe('lazyWithRetry', () => {
it('shares the preloaded promise with the lazy component', async () => {
const load = vi.fn(async () => ({ default: () => <div>Map view</div> }))
const Page = lazyWithRetry(load)
const pending = Page.preload()
expect(Page.preload()).toBe(pending)
await pending
render(<Suspense><Page /></Suspense>)
expect(await screen.findByText('Map view')).toBeInTheDocument()
expect(load).toHaveBeenCalledTimes(1)
})
it('FE-UTIL-LAZYRETRY-006: renders the default export once the chunk arrives', async () => {
const Page = lazyWithRetry(async () => ({ default: () => <div>Atlas</div> }))
render(
+5 -5
View File
@@ -46,9 +46,9 @@ export function retryUrlFor(error: unknown): string | null {
export function lazyWithRetry<T extends ComponentType<any>>(
load: () => Promise<{ default: T }>
): LazyExoticComponent<T> {
return lazy(() =>
load()
): LazyExoticComponent<T> & { preload: () => Promise<{ default: T }> } {
let pending: Promise<{ default: T }> | undefined;
const preload = () => (pending ??= load()
.catch((error: unknown) => {
const url = retryUrlFor(error);
// Rethrown on purpose: React.lazy hands the rejection to the nearest
@@ -64,6 +64,6 @@ export function lazyWithRetry<T extends ComponentType<any>>(
// missing could put the tab in the reload loop the marker exists to prevent.
clearChunkReloadMarker();
return module;
})
);
}));
return Object.assign(lazy(preload), { preload });
}