perf(map): load one GL engine instead of both (#1819)

* perf(map): load one GL engine instead of both

MapViewGL, JourneyMapGL and the settings preview each imported mapbox-gl and
maplibre-gl statically, so rollup emitted one 2.83 MB chunk carrying both.
Every map user downloaded 1.8 MB of mapbox plus 1.03 MB of maplibre and then
ran exactly one of them. The 110 kB stylesheet was merged the same way.

  mapbox users     2,827,647 -> 1,797,952 B   (-1.03 MB, CSS 110.6 -> 40.8 kB)
  maplibre users   2,827,647 -> 1,027,635 B   (-1.80 MB, CSS 110.6 -> 69.8 kB)

The engine is a prop now rather than a module import, and the pairing happens
behind the lazy boundary in glLazy.tsx. No module reaches both SDKs statically
any more, which is the whole mechanism — the components themselves stayed
engine-agnostic, they already guarded on the provider everywhere the two
genuinely differ.

Both imports of a pair start together instead of in sequence: the engine is by
far the larger half, and fetching the component first would put its round trip
in front of the download that actually costs time.

check:gl-split guards it. A stray static import anywhere in the map tree brings
the merged chunk straight back with a green build and a working app, so the
script greps the built chunks for a marker of each SDK and fails when one file
holds both. Not on the bare string "maplibre" — the provider value and the
maplibre_style setting key appear in app code too, so that matches the shared
core chunk as well.

Two boundaries were missing and are added here, because the split makes them
reachable: the GL boundaries had no resetKeys, so a chunk failure under one
provider kept showing Leaflet after switching to the other, and the settings
preview had a Suspense but no boundary at all — that is the one place a user
flips providers live, so it is the likeliest chunk to fail.

Worth being precise about the gain: the service worker precaches every chunk,
so an installed PWA still downloads both engines. What this buys is the
critical path on a cold cache, and parse/compile/execute always — a megabyte
of unused engine ran on every map open.

* perf(client): split out the video player and the ISO subdivision data

Two heavyweights that shipped with routes that rarely use them.

plyr (112 kB raw / 33 kB gzip, plus 32 kB of CSS) hung off three lightboxes and
through them off the FileManager, JournalBody and MTripShell chunks. The
lightboxes only render the player on their video branch anyway, so the split
costs one frame of placeholder — a black rectangle in the target geometry, so
the lightbox does not jump when the chunk lands.

iso-3166-2 is a single 238 kB data blob with no tree-shaking to be had, and
only fetchRegionOptions touches it. It now loads after the hasRegions check,
so it is fetched only for countries that get a region picker at all:
holidayRegions drops from 257 kB to 14 kB. The import sits inside the existing
try — a failed chunk yields the same empty array as a failed request, rather
than an unhandled rejection in the two callers that only do .then(setRegions).

tz-lookup is deliberately left alone. TransitSearchPanel builds the departure
time it sends to MOTIS out of tzAt(), so a not-yet-loaded window there is a
wrong query rather than a late pixel — that one needs its own change with its
own care.
This commit is contained in:
Maurice
2026-08-07 12:46:03 +02:00
committed by GitHub
parent 49e68fb07c
commit c089e75f08
22 changed files with 323 additions and 51 deletions
+8 -6
View File
@@ -1,11 +1,8 @@
import { lazy, Suspense } from 'react'
import { Suspense } from 'react'
import { useSettingsStore } from '../../store/settingsStore'
import { MapView } from './MapView'
import ErrorBoundary from '../shared/ErrorBoundary'
// MapLibre/Mapbox pull in a ~230 KB (gzip) GL engine. Lazy-load the GL renderer so
// Leaflet-only installs never download it — it ships only once a GL provider is picked.
const MapViewGL = lazy(() => import('./MapViewGL').then(m => ({ default: m.MapViewGL })))
import { MapViewGLMapbox, MapViewGLMaplibre } from './glLazy'
// Auto-selects the map renderer based on user settings. Keeps the existing
// Leaflet MapView untouched so the Mapbox GL variant can mature iteratively
@@ -24,6 +21,9 @@ export function MapViewAuto(props: any) {
const glProvider = provider === 'maplibre-gl' ? 'maplibre-gl'
: provider === 'mapbox-gl' && token ? 'mapbox-gl'
: null
// 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
if (glProvider) {
// Render the previous Leaflet map as the fallback so there's no blank flash
// while the GL chunk loads on first use.
@@ -31,7 +31,9 @@ export function MapViewAuto(props: any) {
// Outside the Suspense on purpose: Suspense handles the pending promise,
// a rejected one (chunk gone after a deploy) throws past it. Falling back
// to Leaflet keeps a usable map instead of an error card.
<ErrorBoundary boundaryId="map:gl" fallback={<MapView {...props} />}>
// 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 {...props} />}>
<Suspense fallback={<MapView {...props} />}>
<MapViewGL {...props} glProvider={glProvider} />
</Suspense>
+11 -1
View File
@@ -208,7 +208,17 @@ vi.mock('../../services/photoService', () => ({
getAllThumbs: vi.fn(() => ({})),
}))
import { MapViewGL } from './MapViewGL'
import mapboxgl from 'mapbox-gl'
import { MapViewGL as MapViewGLWithEngine } from './MapViewGL'
// The engine is a prop now, not a module import — that is what keeps mapbox-gl and
// maplibre-gl in separate chunks. This shim preserves the suite's existing call
// shape and makes the same choice glLazy.tsx makes in production, so the vi.mock
// factories below still stand in for the right SDK.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function MapViewGL(props: any) {
return <MapViewGLWithEngine {...props} gl={props.glProvider === 'maplibre-gl' ? maplibregl : mapboxgl} />
}
import * as mapboxSetup from './mapboxSetup'
import * as photoService from '../../services/photoService'
import { ReservationMapboxOverlay } from './reservationsMapbox'
+10 -6
View File
@@ -1,9 +1,6 @@
import { useEffect, useRef, useMemo, useState, createElement } from 'react'
import { renderToStaticMarkup } from 'react-dom/server'
import mapboxgl from 'mapbox-gl'
import maplibregl from 'maplibre-gl'
import 'mapbox-gl/dist/mapbox-gl.css'
import 'maplibre-gl/dist/maplibre-gl.css'
import type mapboxgl from 'mapbox-gl'
import { useSettingsStore } from '../../store/settingsStore'
import { useAuthStore } from '../../store/authStore'
import { getCached, isLoading, fetchPhoto, onThumbReady, getAllThumbs } from '../../services/photoService'
@@ -120,6 +117,13 @@ interface Props {
onPoiClick?: (poi: Poi) => void
onViewportChange?: (bbox: { south: number; west: number; north: number; east: number }) => void
glProvider?: GlMapProvider
/**
* 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
* together and every map user downloaded both while only one ever ran.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
gl: any
// eslint-disable-next-line @typescript-eslint/no-explicit-any
onMapReady?: (map: any | null) => void
}
@@ -357,6 +361,7 @@ export function MapViewGL({
onPoiClick,
onViewportChange,
glProvider = 'mapbox-gl',
gl,
onMapReady,
}: Props) {
const rawMapboxStyle = useSettingsStore(s => s.settings.mapbox_style || MAPBOX_DEFAULT_STYLE)
@@ -367,7 +372,6 @@ 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 gl = (isMapLibre ? maplibregl : mapboxgl) as any
const glStyle = styleForActiveProvider(glProvider, rawMapboxStyle, rawMaplibreStyle)
const enableMapbox3d = !isMapLibre && mapbox3d
const placesPhotosEnabled = useAuthStore(s => s.placesPhotosEnabled)
@@ -444,7 +448,7 @@ export function MapViewGL({
// Build/rebuild the map on provider/style/token/3d change
useEffect(() => {
if (!containerRef.current || (!isMapLibre && !mapboxToken)) return
if (!isMapLibre) mapboxgl.accessToken = mapboxToken
if (!isMapLibre) gl.accessToken = mapboxToken
// 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.
@@ -0,0 +1,11 @@
import mapboxgl from 'mapbox-gl'
import 'mapbox-gl/dist/mapbox-gl.css'
/**
* The only module in the client that pulls mapbox-gl in at runtime.
*
* It has to stay reachable through `import('./engines/mapbox')` and nothing else:
* a static import from anywhere in the tree drags 1.8 MB into the parent chunk and
* quietly undoes the split. `npm run check:gl-split` fails on that.
*/
export default mapboxgl
@@ -0,0 +1,13 @@
import maplibregl from 'maplibre-gl'
import 'maplibre-gl/dist/maplibre-gl.css'
/**
* The only module in the client that pulls maplibre-gl in at runtime. Same rule as
* its mapbox sibling: reachable through a dynamic import and no other way.
*
* The two engines share their API surface for everything TREK uses — Map, Marker,
* Popup, LngLatBounds — which is why the components take the engine as a prop and
* stay engine-agnostic. Where the two genuinely differ, the caller already guards
* on the provider (projection, accessToken, aroundCenter).
*/
export default maplibregl
+86
View File
@@ -0,0 +1,86 @@
import { forwardRef } from 'react'
import { lazyWithRetry } from '../../utils/lazyWithRetry'
/**
* The six ways into a GL map, one chunk per engine.
*
* mapbox-gl and maplibre-gl used to be static imports inside MapViewGL,
* JourneyMapGL and the settings preview, so rollup put both SDKs into a single
* 2.8 MB chunk. Every map user downloaded 1.8 MB of mapbox plus 1.1 MB of
* maplibre and then ran exactly one of them.
*
* Pairing the component with its engine behind the lazy boundary is what
* separates them: no module reaches both SDKs statically any more, so rolldown
* emits one shared core chunk and two engine chunks. The engine arrives as a
* prop — see the `gl` prop on each component.
*
* Both imports start together rather than in sequence: the engine is by far the
* larger of the two, and waiting for the component first would add its round
* trip in front of the download that actually costs time.
*/
export const MapViewGLMapbox = lazyWithRetry(async () => {
const [component, engine] = await Promise.all([import('./MapViewGL'), import('./engines/mapbox')])
const MapViewGL = component.MapViewGL
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return { default: (props: any) => <MapViewGL {...props} gl={engine.default} /> }
})
export const MapViewGLMaplibre = lazyWithRetry(async () => {
const [component, engine] = await Promise.all([import('./MapViewGL'), import('./engines/maplibre')])
const MapViewGL = component.MapViewGL
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return { default: (props: any) => <MapViewGL {...props} gl={engine.default} /> }
})
export const JourneyMapGLMapbox = lazyWithRetry(async () => {
const [component, engine] = await Promise.all([
import('../Journey/JourneyMapGL'),
import('./engines/mapbox'),
])
const JourneyMapGL = component.default
return {
// forwardRef because the journey map exposes an imperative handle
// (highlightMarker / focusMarker / invalidateSize) that has to survive the wrapper.
/* eslint-disable @typescript-eslint/no-explicit-any */
default: forwardRef(function JourneyMapGLMapboxBinding(props: any, ref: any) {
return <JourneyMapGL ref={ref} {...props} gl={engine.default} />
}),
/* eslint-enable @typescript-eslint/no-explicit-any */
}
})
export const JourneyMapGLMaplibre = lazyWithRetry(async () => {
const [component, engine] = await Promise.all([
import('../Journey/JourneyMapGL'),
import('./engines/maplibre'),
])
const JourneyMapGL = component.default
return {
/* eslint-disable @typescript-eslint/no-explicit-any */
default: forwardRef(function JourneyMapGLMaplibreBinding(props: any, ref: any) {
return <JourneyMapGL ref={ref} {...props} gl={engine.default} />
}),
/* eslint-enable @typescript-eslint/no-explicit-any */
}
})
export const GlMapPreviewMapbox = lazyWithRetry(async () => {
const [component, engine] = await Promise.all([
import('../Settings/MapboxPreview'),
import('./engines/mapbox'),
])
const GlMapPreview = component.default
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return { default: (props: any) => <GlMapPreview {...props} gl={engine.default} /> }
})
export const GlMapPreviewMaplibre = lazyWithRetry(async () => {
const [component, engine] = await Promise.all([
import('../Settings/MapboxPreview'),
import('./engines/maplibre'),
])
const GlMapPreview = component.default
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return { default: (props: any) => <GlMapPreview {...props} gl={engine.default} /> }
})