mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 17:41:51 +00:00
feat(maps): MapLibre draws the user's map template on trek:template
A MapLibre user could only draw OpenFreeMap styles; a raster template was Leaflet's alone. With maplibre_style set to trek:template, MapLibre now draws the template the trip map already resolves for Leaflet (CARTO key, keyless fallback and dark default included), so both renderers show the same map. No stored row holds the keyword, so every existing user sees exactly the map they saw before, and Mapbox is untouched. - glBasemap turns the basemap spec into a raster style document (256px tiles as Leaflet requests them, the provider's deepest zoom, the credit, OpenFreeMap glyphs for the map's own labels) and resolves trek:ofm-auto to Liberty or OpenFreeMap Dark with the colour scheme. - glCanFetch decides whether a GL map may fetch a basemap here: https on a host the CSP names, the shipped ones or MAP_EXTRA_CONNECT_HOSTS from the app config. GCJ-02 tiles (Amap) and other hosts are drawn by Leaflet for that render, the setting untouched. - rasterHealth watches the first tiles of a template map: a CSP refusal or twelve failures without a success move every map drawing that template to Leaflet for the session, with a pill that says so. - useEffectiveMapEngine decides this on the engine that actually draws and runs the offline checks after it; a stored raster template keeps drawing offline where Leaflet would keep the same tiles. - The journey map uses the same hook: the same template, the same fallback and now the offline basemap with its pill as the trip map has it. - A MapLibre raster style stops at zoom 19 like Leaflet; the Mapbox options stay as they were. The offline pill moves to BasemapPill for both maps. Dropping the unused imports there lowers the eslint baseline.
This commit is contained in:
@@ -87,6 +87,8 @@ interface Props {
|
||||
paddingStart?: number
|
||||
/** CARTO key from the share payload: the public journey has no settings store to read. */
|
||||
cartoApiKey?: string
|
||||
/** Draws this basemap instead of the user's template: the stored offline one (useEffectiveMapEngine). */
|
||||
basemapOverride?: string
|
||||
/**
|
||||
* Which drawn layers the reader shows (JRN-04). A hidden one is taken off the
|
||||
* map and put back as it was, never rebuilt, so the view stays where it is.
|
||||
@@ -381,7 +383,7 @@ function useJourneyBase(satellite: boolean, { mapRef, tileUrlRef, tileLayerRef,
|
||||
}
|
||||
|
||||
function JourneyMap(
|
||||
{ entries, photos, onPhotoClick, trail, tracks, height = 220, dark, activeMarkerId, onMarkerClick, fullScreen, paddingBottom, paddingStart = 0, cartoApiKey, onMarkerCardClick, layerVisibility = EVERY_LAYER, marks, onMarksPick, plannedEntryIds = NO_PLANNED, baseLayer = 'default', ref }: Props,
|
||||
{ entries, photos, onPhotoClick, trail, tracks, height = 220, dark, activeMarkerId, onMarkerClick, fullScreen, paddingBottom, paddingStart = 0, cartoApiKey, basemapOverride, onMarkerCardClick, layerVisibility = EVERY_LAYER, marks, onMarksPick, plannedEntryIds = NO_PLANNED, baseLayer = 'default', ref }: Props,
|
||||
) {
|
||||
// The leading inset is read when the map frames, not a reason to rebuild it.
|
||||
const paddingStartRef = useRef(paddingStart)
|
||||
@@ -397,7 +399,7 @@ function JourneyMap(
|
||||
const mapTileUrl = useSettingsStore(s => s.settings.map_tile_url)
|
||||
const storedCartoKey = useCartoApiKey()
|
||||
const cartoKey = cartoApiKey || storedCartoKey
|
||||
const tileUrl = resolveTileUrl(mapTileUrl, dark ? OFM_DARK : OFM_POSITRON, cartoKey)
|
||||
const tileUrl = basemapOverride ?? resolveTileUrl(mapTileUrl, dark ? OFM_DARK : OFM_POSITRON, cartoKey)
|
||||
// Amap's tiles are GCJ-02 (see gcj02Crs.ts), the same shift the planner map
|
||||
// applies. Leaflet fixes a map's CRS at construction, so this one value is
|
||||
// allowed to rebuild the map where a template change only retiles it.
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import { Suspense, useImperativeHandle, useRef, type Ref } from 'react'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import { OFM_DARK, OFM_POSITRON } from '../../constants/mapDefaults'
|
||||
import { useTileUrl } from '../../hooks/useTileUrl'
|
||||
import JourneyMap, { type JourneyMapHandle } from './JourneyMap'
|
||||
import ErrorBoundary from '../shared/ErrorBoundary'
|
||||
import type { JourneyMapGLHandle } from './JourneyMapGL'
|
||||
|
||||
import { BasemapPill } from '../Map/BasemapPill'
|
||||
import { JourneyMapGLMapbox, JourneyMapGLMaplibre } from '../Map/glLazy'
|
||||
import { useGlRenderer } from '../Map/glSupport'
|
||||
import { useEffectiveMapEngine } from '../Map/useEffectiveMapEngine'
|
||||
import type { JourneyTrack } from '@trek/shared'
|
||||
import type { MapPhoto } from './journeyPhotoLayer'
|
||||
import type { JourneyMapLayerVisibility } from './journeyMapLayers'
|
||||
@@ -63,16 +65,18 @@ interface Props {
|
||||
}
|
||||
|
||||
function JourneyMapAuto({ ref, ...props }: Props) {
|
||||
const provider = useSettingsStore(s => s.settings.map_provider)
|
||||
const token = useSettingsStore(s => s.settings.mapbox_access_token)
|
||||
const leafletRef = useRef<JourneyMapHandle>(null)
|
||||
const glRef = useRef<JourneyMapGLHandle>(null)
|
||||
|
||||
// Fall back to Leaflet when the user selected Mapbox GL but hasn't supplied a
|
||||
// token yet (MapLibre/OpenFreeMap is tokenless), or when the browser has no WebGL2.
|
||||
const glRenderer = useGlRenderer(provider, token)
|
||||
const useGL = glRenderer !== null
|
||||
const glProvider = glRenderer ?? 'mapbox-gl'
|
||||
// The template the Leaflet journey map resolves for itself (JourneyMap.tsx), so
|
||||
// a MapLibre map drawing the user's template shows the same one.
|
||||
const tileUrl = useTileUrl(props.dark ? OFM_DARK : OFM_POSITRON)
|
||||
// The engine and the offline basemap, decided as for the trip map: a token-less
|
||||
// Mapbox, a browser without WebGL2 or a template MapLibre cannot draw here
|
||||
// falls back to Leaflet, and offline the stored basemap stands in with a pill.
|
||||
const { engine, styleOverride, tileUrlOverride, pill } = useEffectiveMapEngine(tileUrl)
|
||||
const useGL = engine !== null
|
||||
const glProvider = engine ?? 'mapbox-gl'
|
||||
|
||||
useImperativeHandle(ref, () => ({
|
||||
highlightMarker: (id) => (useGL ? glRef.current : leafletRef.current)?.highlightMarker(id),
|
||||
@@ -80,23 +84,25 @@ function JourneyMapAuto({ ref, ...props }: Props) {
|
||||
invalidateSize: () => (useGL ? glRef.current : leafletRef.current)?.invalidateSize(),
|
||||
}), [useGL])
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const leaflet = <JourneyMap ref={leafletRef} {...(props as any)} basemapOverride={tileUrlOverride} />
|
||||
// One chunk per engine — see MapViewAuto.
|
||||
const JourneyMapGL = glProvider === 'maplibre-gl' ? JourneyMapGLMaplibre : JourneyMapGLMapbox
|
||||
if (useGL) {
|
||||
return (
|
||||
// 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
|
||||
<ErrorBoundary boundaryId="journey-map:gl" resetKeys={[glProvider]} fallback={<JourneyMap ref={leafletRef} {...(props as any)} />}>
|
||||
<Suspense fallback={null}>
|
||||
{/* eslint-disable-next-line @typescript-eslint/no-explicit-any */}
|
||||
<JourneyMapGL ref={glRef} {...(props as any)} glProvider={glProvider} />
|
||||
</Suspense>
|
||||
</ErrorBoundary>
|
||||
)
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
return <JourneyMap ref={leafletRef} {...(props as any)} />
|
||||
return (
|
||||
<>
|
||||
{useGL ? (
|
||||
// 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}>
|
||||
{/* eslint-disable-next-line @typescript-eslint/no-explicit-any */}
|
||||
<JourneyMapGL ref={glRef} {...(props as any)} glProvider={glProvider} styleOverride={styleOverride} />
|
||||
</Suspense>
|
||||
</ErrorBoundary>
|
||||
) : leaflet}
|
||||
<BasemapPill state={pill} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default JourneyMapAuto
|
||||
|
||||
@@ -133,6 +133,7 @@ import { useSettingsStore } from '../../store/settingsStore'
|
||||
import { isStandardFamily, supportsCustom3d, wantsTerrain, addCustom3dBuildings, addTerrainAndSky } from '../Map/mapboxSetup'
|
||||
import JourneyMapGLWithEngine from './JourneyMapGL'
|
||||
import type { JourneyMapGLHandle } from './JourneyMapGL'
|
||||
import { mapLibreBasemap } from '../Map/glBasemap'
|
||||
|
||||
// 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
|
||||
@@ -222,6 +223,14 @@ describe('JourneyMapGL', () => {
|
||||
expect(options).not.toHaveProperty('projection')
|
||||
})
|
||||
|
||||
it('FE-COMP-JMAPGL-003b: maplibre draws the style the engine hook resolved, a raster template up to zoom 19', () => {
|
||||
const style = mapLibreBasemap('trek:template', 'https://tile.openstreetmap.de/{z}/{x}/{y}.png', false, []).style
|
||||
render(<JourneyMapGL checkins={[]} entries={entries} glProvider="maplibre-gl" styleOverride={style} />)
|
||||
const options = vi.mocked(maplibregl.Map).mock.calls[0][0] as unknown as Record<string, unknown>
|
||||
expect(options.style).toBe(style)
|
||||
expect(options.maxZoom).toBe(19)
|
||||
})
|
||||
|
||||
it('FE-COMP-JMAPGL-004: quality mode turns on the globe projection and antialiasing', () => {
|
||||
withToken({ mapbox_quality_mode: true })
|
||||
render(<JourneyMapGL checkins={[]} entries={entries} />)
|
||||
|
||||
@@ -3,7 +3,9 @@ import type mapboxgl from 'mapbox-gl'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import { isStandardFamily } from '../Map/mapboxSetup'
|
||||
import { applyGl3d, glMapOptions } from '../Map/glMapOptions'
|
||||
import { MAPBOX_DEFAULT_STYLE, styleForActiveProvider, basemapLanguage, type GlMapProvider } from '../Map/glProviders'
|
||||
import { basemapLanguage, type GlMapProvider } from '../Map/glProviders'
|
||||
import type { GlStyle } from '../Map/glBasemap'
|
||||
import { useGlStyle } from '../Map/useGlStyle'
|
||||
import { buildGlMap, initialMapStyle } from '../Map/glSupport'
|
||||
import { applySatellite } from '../Map/glRasterLayers'
|
||||
import type { BaseLayer } from '../Map/MapLayerSwitcher'
|
||||
@@ -75,6 +77,8 @@ interface Props {
|
||||
/** See the Leaflet twin (#2594): the imagery goes on under the journey's own layers. */
|
||||
baseLayer?: BaseLayer
|
||||
glProvider?: GlMapProvider
|
||||
/** Draws this style instead of the user's own: the offline basemap or a resolved keyword (useGlStyle). */
|
||||
styleOverride?: GlStyle
|
||||
/**
|
||||
* 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
|
||||
@@ -221,7 +225,7 @@ function fitOptions(paddingBottom: number | undefined, tilted: boolean | undefin
|
||||
}
|
||||
|
||||
function JourneyMapGL(
|
||||
{ entries, trail, tracks, height = 220, dark, activeMarkerId, onMarkerClick, fullScreen, paddingBottom, paddingStart = 0, glProvider = 'mapbox-gl', gl, onMarkerCardClick, onMarkerPhotoClick, photos, onPhotoClick, layerVisibility = EVERY_LAYER, marks, onMarksPick, plannedEntryIds = NO_PLANNED, baseLayer = 'default', ref }: Props,
|
||||
{ entries, trail, tracks, height = 220, dark, activeMarkerId, onMarkerClick, fullScreen, paddingBottom, paddingStart = 0, glProvider = 'mapbox-gl', styleOverride, gl, onMarkerCardClick, onMarkerPhotoClick, photos, onPhotoClick, layerVisibility = EVERY_LAYER, marks, onMarksPick, plannedEntryIds = NO_PLANNED, baseLayer = 'default', ref }: Props,
|
||||
) {
|
||||
// The leading inset is read when the map frames, not a reason to rebuild it.
|
||||
const paddingStartRef = useRef(paddingStart)
|
||||
@@ -236,14 +240,12 @@ function JourneyMapGL(
|
||||
const popupItemIdRef = useRef<string | null>(null)
|
||||
const stableTrail = trail || EMPTY_TRAIL
|
||||
const stableTracks = tracks || EMPTY_TRACKS
|
||||
const rawMapboxStyle = useSettingsStore(s => s.settings.mapbox_style || MAPBOX_DEFAULT_STYLE)
|
||||
const rawMaplibreStyle = useSettingsStore(s => s.settings.maplibre_style || '')
|
||||
const mapboxToken = useSettingsStore(s => s.settings.mapbox_access_token || '')
|
||||
const mapbox3d = useSettingsStore(s => s.settings.mapbox_3d_enabled !== false)
|
||||
const mapboxQuality = useSettingsStore(s => s.settings.mapbox_quality_mode === true)
|
||||
const mapLang = useSettingsStore(s => s.settings.language)
|
||||
const isMapLibre = glProvider === 'maplibre-gl'
|
||||
const glStyle = styleForActiveProvider(glProvider, rawMapboxStyle, rawMaplibreStyle)
|
||||
const glStyle = useGlStyle(glProvider, styleOverride)
|
||||
const enableMapbox3d = !isMapLibre && mapbox3d
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
@@ -436,7 +438,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))
|
||||
const map = buildGlMap(() => new gl.Map(mapOptions as any), glStyle)
|
||||
if (!map) return
|
||||
mapRef.current = map
|
||||
marksFramedRef.current = false
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { CloudOff, Layers } from 'lucide-react';
|
||||
|
||||
import { useTranslation } from '../../i18n/TranslationContext';
|
||||
import type { BasemapPillState } from './useEffectiveMapEngine';
|
||||
|
||||
const PILL =
|
||||
'absolute inset-x-0 z-[5] mx-auto flex w-fit 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)]';
|
||||
|
||||
/**
|
||||
* Says the basemap on screen is not the one the user picked: the stored offline
|
||||
* basemap, or the classic 2D map drawing a template MapLibre could not load.
|
||||
* The toggle kind is a switch between the user's map (as far as it was viewed
|
||||
* and stored) and the stored trip region. The trip and journey maps share it,
|
||||
* since useEffectiveMapEngine decides for both.
|
||||
*/
|
||||
export function BasemapPill({ state }: { state: BasemapPillState | null }) {
|
||||
const { t } = useTranslation();
|
||||
if (!state) return null;
|
||||
if (state.kind === 'toggle') {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={state.onToggle}
|
||||
aria-pressed={state.pressed}
|
||||
className={`${PILL} pointer-events-auto`}
|
||||
>
|
||||
<CloudOff size={13} strokeWidth={2.2} aria-hidden="true" />
|
||||
{state.pressed ? t('map.offlineBasemap') : t('map.offlineShowStored')}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
const Icon = state.kind === 'classic' ? Layers : CloudOff;
|
||||
return (
|
||||
<div role="status" className={`${PILL} pointer-events-none`}>
|
||||
<Icon size={13} strokeWidth={2.2} aria-hidden="true" />
|
||||
{state.kind === 'classic' ? t('map.templateClassic') : t('map.offlineBasemap')}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,12 +1,10 @@
|
||||
import { Suspense } from 'react'
|
||||
import { AlertTriangle, Clock, CloudOff, Info } from 'lucide-react'
|
||||
import { Tooltip } from '../shared/Tooltip'
|
||||
import { MapView } from './MapView'
|
||||
import ErrorBoundary from '../shared/ErrorBoundary'
|
||||
import { MapViewGLMapbox, MapViewGLMaplibre } from './glLazy'
|
||||
import { useEffectiveMapEngine } from './useEffectiveMapEngine'
|
||||
import { BasemapPill } from './BasemapPill'
|
||||
import { useRoadtripHazards } from './useRoadtripHazards'
|
||||
import { useTranslation } from '../../i18n/TranslationContext'
|
||||
import type { MapViewAutoProps, MapViewProps } from './mapViewContract'
|
||||
|
||||
// Picks the renderer for the trip map from the user's settings, Leaflet or one
|
||||
@@ -21,7 +19,6 @@ import type { MapViewAutoProps, MapViewProps } from './mapViewContract'
|
||||
// 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)
|
||||
// `dawarichTrack` arrives as a prop rather than being fetched here: the pill
|
||||
// that switches it on lives at page level and needs the load status, so the
|
||||
@@ -31,15 +28,7 @@ export function MapViewAuto(props: MapViewAutoProps) {
|
||||
const mapProps = { ...props, hazards: hazards.feed?.hazards } as MapViewProps
|
||||
const { engine: glProvider, styleOverride, tileUrlOverride, pill: pillState } = useEffectiveMapEngine(mapProps.tileUrl)
|
||||
if (tileUrlOverride) mapProps.tileUrl = tileUrlOverride
|
||||
const pill = pillState?.kind === 'toggle'
|
||||
? (
|
||||
<OfflineBasemapPill
|
||||
label={pillState.pressed ? t('map.offlineBasemap') : t('map.offlineShowStored')}
|
||||
pressed={pillState.pressed}
|
||||
onToggle={pillState.onToggle}
|
||||
/>
|
||||
)
|
||||
: pillState && <OfflineBasemapPill label={t('map.offlineBasemap')} />
|
||||
const pill = <BasemapPill state={pillState} />
|
||||
// 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
|
||||
@@ -69,27 +58,3 @@ export function MapViewAuto(props: MapViewAutoProps) {
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
const PILL = 'absolute inset-x-0 z-[5] mx-auto flex w-fit 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)]'
|
||||
|
||||
/**
|
||||
* Says the map on screen is the stored offline basemap, not the user's own. With
|
||||
* onToggle it is a switch between the user's map (as far as it was viewed and
|
||||
* stored) and the stored trip region.
|
||||
*/
|
||||
function OfflineBasemapPill({ label, pressed, onToggle }: { label: string; pressed?: boolean; onToggle?: () => void }) {
|
||||
if (onToggle) {
|
||||
return (
|
||||
<button type="button" onClick={onToggle} aria-pressed={pressed} className={`${PILL} pointer-events-auto`}>
|
||||
<CloudOff size={13} strokeWidth={2.2} aria-hidden="true" />
|
||||
{label}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<div role="status" className={`${PILL} pointer-events-none`}>
|
||||
<CloudOff size={13} strokeWidth={2.2} aria-hidden="true" />
|
||||
{label}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -28,7 +28,9 @@ import { useFlightAircraftGL } from './useFlightAircraftGL'
|
||||
import { useTransportRoutes } from '../../hooks/useTransportRoutes'
|
||||
import { visibleRouteReservations } from '../../utils/reservationRoutes'
|
||||
import { safeHexColor } from '../../utils/safeColor'
|
||||
import { MAPBOX_DEFAULT_STYLE, styleForActiveProvider, type GlMapProvider } from './glProviders'
|
||||
import type { GlMapProvider } from './glProviders'
|
||||
import type { GlStyle } from './glBasemap'
|
||||
import { useGlStyle } from './useGlStyle'
|
||||
import { useStandardBasemapConfig } from './useStandardBasemapConfig'
|
||||
import { buildGlMap, initialMapStyle } from './glSupport'
|
||||
import LocationButton from './LocationButton'
|
||||
@@ -107,8 +109,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
|
||||
/** Draws this style instead of the user's own: the offline basemap or a resolved keyword (useGlStyle). */
|
||||
styleOverride?: GlStyle
|
||||
/**
|
||||
* 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
|
||||
@@ -423,8 +425,6 @@ export function MapViewGL({
|
||||
...assistant
|
||||
}: Props) {
|
||||
const { t } = useTranslation()
|
||||
const rawMapboxStyle = useSettingsStore(s => s.settings.mapbox_style || MAPBOX_DEFAULT_STYLE)
|
||||
const rawMaplibreStyle = useSettingsStore(s => s.settings.maplibre_style || '')
|
||||
const mapboxToken = useSettingsStore(s => s.settings.mapbox_access_token || '')
|
||||
// The same stored choice the Leaflet map reads, so the two renderers agree.
|
||||
const globalBaseLayer = useSettingsStore(s => s.settings.map_base_layer) || 'default'
|
||||
@@ -441,7 +441,7 @@ 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 = styleOverride ?? styleForActiveProvider(glProvider, rawMapboxStyle, rawMaplibreStyle)
|
||||
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
|
||||
@@ -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))
|
||||
const map = buildGlMap(() => new gl.Map(mapOptions as any), glStyle)
|
||||
if (!map) return
|
||||
mapRef.current = map
|
||||
popupRef.current = new gl.Popup({
|
||||
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
OFM_POSITRON,
|
||||
OPENTOPOMAP_TILE_URL,
|
||||
} from '../../constants/mapDefaults';
|
||||
import { resolveBasemapSpec } from './basemapSpec';
|
||||
import { glCanFetch, resolveBasemapSpec } from './basemapSpec';
|
||||
|
||||
const OSM = 'https://tile.openstreetmap.org/{z}/{x}/{y}.png';
|
||||
const OSM_DE = 'https://tile.openstreetmap.de/{z}/{x}/{y}.png';
|
||||
@@ -168,3 +168,40 @@ describe('resolveBasemapSpec: raster templates', () => {
|
||||
expect(resolveBasemapSpec(ofmRaster, OFM_POSITRON)).toMatchObject({ attribution: OFM_ATTRIBUTION });
|
||||
});
|
||||
});
|
||||
|
||||
describe('glCanFetch: what a GL map may fetch under the CSP', () => {
|
||||
const NO_EXTRA: string[] = [];
|
||||
const spec = (template: string) => resolveBasemapSpec(template, OFM_POSITRON, 'k', 2);
|
||||
|
||||
it('FE-MAP-BASEMAPSPEC-020: every shipped raster preset on its own host', () => {
|
||||
for (const template of [OSM, OSM_DE, STADIA, CARTO_LIGHT, OPENTOPOMAP_TILE_URL]) {
|
||||
expect(glCanFetch(spec(template), NO_EXTRA), template).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('FE-MAP-BASEMAPSPEC-021: Amap stays with Leaflet, its tiles are GCJ-02', () => {
|
||||
expect(glCanFetch(spec(AMAP_ROAD), NO_EXTRA)).toBe(false);
|
||||
expect(glCanFetch(spec(AMAP_SATELLITE), ['*.is.autonavi.com'])).toBe(false);
|
||||
});
|
||||
|
||||
it("FE-MAP-BASEMAPSPEC-022: a host of the operator's own only once MAP_EXTRA_CONNECT_HOSTS names it", () => {
|
||||
const own = spec('https://tiles.example.com/osm/{z}/{x}/{y}.png');
|
||||
expect(glCanFetch(own, NO_EXTRA)).toBe(false);
|
||||
expect(glCanFetch(own, ['tiles.example.com'])).toBe(true);
|
||||
expect(glCanFetch(own, ['*.example.com'])).toBe(true);
|
||||
expect(glCanFetch(spec('https://tiles.example.com:8443/{z}/{x}/{y}.png'), ['tiles.example.com'])).toBe(false);
|
||||
expect(glCanFetch(spec('https://tiles.example.com:8443/{z}/{x}/{y}.png'), ['tiles.example.com:8443'])).toBe(true);
|
||||
});
|
||||
|
||||
it('FE-MAP-BASEMAPSPEC-023: plain http is never fetched, whatever the list says', () => {
|
||||
expect(glCanFetch(spec('http://tiles.example.com/{z}/{x}/{y}.png'), ['tiles.example.com'])).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-MAP-BASEMAPSPEC-024: a vector style on OpenFreeMap or a named host, never on a raster host', () => {
|
||||
expect(glCanFetch(spec(OFM_DARK), NO_EXTRA)).toBe(true);
|
||||
expect(glCanFetch(spec('https://maps.example.com/style.json'), NO_EXTRA)).toBe(false);
|
||||
expect(glCanFetch(spec('https://maps.example.com/style.json'), ['maps.example.com'])).toBe(true);
|
||||
expect(glCanFetch(spec('https://tile.openstreetmap.org/style.json'), NO_EXTRA)).toBe(false);
|
||||
expect(glCanFetch(spec('mapbox://styles/mapbox/streets-v12'), NO_EXTRA)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { OPENFREEMAP_HOST, RASTER_TILE_HOSTS, mapConnectHostAllows } from '@trek/shared';
|
||||
|
||||
import {
|
||||
CYCLOSM_TILE_MAXZOOM,
|
||||
MAP_MAX_ZOOM,
|
||||
@@ -17,7 +19,7 @@ import { isGcj02Basemap, resolveBasemap, templateHost } from '../../utils/tileUr
|
||||
* pixel-density placeholders decided exactly as Leaflet decides them, so both
|
||||
* renderers ask the provider for the same tiles. Pure and free of both GL SDKs.
|
||||
*/
|
||||
type BasemapSpec = VectorBasemapSpec | RasterBasemapSpec;
|
||||
export type BasemapSpec = VectorBasemapSpec | RasterBasemapSpec;
|
||||
|
||||
interface VectorBasemapSpec {
|
||||
kind: 'vector';
|
||||
@@ -103,3 +105,33 @@ export function resolveBasemapSpec(
|
||||
host,
|
||||
};
|
||||
}
|
||||
|
||||
/** The https host of a URL, `host:port` where it names a port, or null for anything that is not https. */
|
||||
function httpsHost(url: string): string | null {
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
return parsed.protocol === 'https:' ? parsed.host : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a GL map may fetch this basemap here: every URL it would request is
|
||||
* https on a host the server's connect-src names, the shipped ones (shared
|
||||
* map-defaults) or the operator's own (MAP_EXTRA_CONNECT_HOSTS, `extraHosts`).
|
||||
* Leaflet loads raster tiles as images, which the policy allows from any https
|
||||
* host, so it can draw what this refuses.
|
||||
*
|
||||
* A raster basemap in GCJ-02 is refused as well: no GL map projects through
|
||||
* that datum, so every marker would sit off its street.
|
||||
*/
|
||||
export function glCanFetch(spec: BasemapSpec, extraHosts: readonly string[]): boolean {
|
||||
const urls = spec.kind === 'vector' ? [spec.styleUrl] : spec.tiles;
|
||||
if (spec.kind === 'raster' && spec.datum !== 'wgs84') return false;
|
||||
const allowed = [...(spec.kind === 'vector' ? [OPENFREEMAP_HOST] : RASTER_TILE_HOSTS), ...extraHosts];
|
||||
return urls.every((url) => {
|
||||
const host = httpsHost(url);
|
||||
return host !== null && allowed.some((entry) => mapConnectHostAllows(entry, host));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
/**
|
||||
* What MapLibre draws for the maplibre_style keywords (FE-MAP-GLBASEMAP-*).
|
||||
*
|
||||
* The template arrives resolved, as useTileUrl hands it to Leaflet, so the GL
|
||||
* style must request exactly the tiles Leaflet requests on the same screen.
|
||||
*/
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { AMAP_ROAD, CARTO_LIGHT, OFM_DARK, OFM_POSITRON } from '../../constants/mapDefaults';
|
||||
import { resolveTileUrl } from '../../utils/tileUrl';
|
||||
import { GL_BASEMAP_SOURCE, isGlRasterStyle, mapLibreBasemap } from './glBasemap';
|
||||
import { OPENFREEMAP_DEFAULT_STYLE } from './glProviders';
|
||||
|
||||
const OSM = 'https://tile.openstreetmap.org/{z}/{x}/{y}.png';
|
||||
const NO_EXTRA: string[] = [];
|
||||
|
||||
function rasterOf(template: string, extra: string[] = NO_EXTRA) {
|
||||
const { style } = mapLibreBasemap('trek:template', template, false, extra);
|
||||
if (!isGlRasterStyle(style)) throw new Error('expected a raster style');
|
||||
return style;
|
||||
}
|
||||
|
||||
describe('mapLibreBasemap', () => {
|
||||
it('FE-MAP-GLBASEMAP-001: any value but a keyword is left to the map', () => {
|
||||
for (const slot of [
|
||||
undefined,
|
||||
null,
|
||||
'',
|
||||
OPENFREEMAP_DEFAULT_STYLE,
|
||||
'https://tiles.openfreemap.org/styles/bright',
|
||||
]) {
|
||||
expect(mapLibreBasemap(slot, OSM, false, NO_EXTRA)).toEqual({ needsLeaflet: false });
|
||||
}
|
||||
});
|
||||
|
||||
it('FE-MAP-GLBASEMAP-002: trek:ofm-auto follows the colour scheme', () => {
|
||||
expect(mapLibreBasemap('trek:ofm-auto', OSM, false, NO_EXTRA).style).toBe(OPENFREEMAP_DEFAULT_STYLE);
|
||||
expect(mapLibreBasemap(' trek:ofm-auto ', OSM, true, NO_EXTRA).style).toBe(OFM_DARK);
|
||||
});
|
||||
|
||||
it('FE-MAP-GLBASEMAP-003: a raster template becomes one 256px raster source with the glyphs for the map labels', () => {
|
||||
const style = rasterOf(OSM);
|
||||
expect(style.version).toBe(8);
|
||||
expect(style.glyphs).toBe('https://tiles.openfreemap.org/fonts/{fontstack}/{range}.pbf');
|
||||
expect(style.metadata).toEqual({ 'trek:template': OSM });
|
||||
expect(style.sources[GL_BASEMAP_SOURCE]).toEqual({
|
||||
type: 'raster',
|
||||
tiles: [OSM],
|
||||
tileSize: 256,
|
||||
maxzoom: 19,
|
||||
scheme: 'xyz',
|
||||
attribution: expect.stringContaining('OpenStreetMap'),
|
||||
});
|
||||
expect(style.layers).toEqual([
|
||||
{ id: GL_BASEMAP_SOURCE, type: 'raster', source: GL_BASEMAP_SOURCE, paint: { 'raster-fade-duration': 100 } },
|
||||
]);
|
||||
});
|
||||
|
||||
it('FE-MAP-GLBASEMAP-004: CARTO keeps its key, its shards and its density as Leaflet asks for them', () => {
|
||||
vi.stubGlobal('devicePixelRatio', 2);
|
||||
try {
|
||||
const template = resolveTileUrl(CARTO_LIGHT, OFM_POSITRON, 'secret');
|
||||
const tiles = rasterOf(template).sources[GL_BASEMAP_SOURCE]?.tiles;
|
||||
expect(tiles).toEqual(
|
||||
['a', 'b', 'c'].map((s) => `https://${s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}@2x.png?key=secret`)
|
||||
);
|
||||
} finally {
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
});
|
||||
|
||||
it('FE-MAP-GLBASEMAP-005: a template counting rows from the south reads as TMS', () => {
|
||||
const source = rasterOf('https://tiles.example.com/{z}/{x}/{-y}.png', ['tiles.example.com']).sources[
|
||||
GL_BASEMAP_SOURCE
|
||||
];
|
||||
expect(source?.scheme).toBe('tms');
|
||||
expect(source?.tiles).toEqual(['https://tiles.example.com/{z}/{x}/{y}.png']);
|
||||
});
|
||||
|
||||
it('FE-MAP-GLBASEMAP-006: GCJ-02 and hosts outside the policy need Leaflet for this render', () => {
|
||||
expect(mapLibreBasemap('trek:template', AMAP_ROAD, false, NO_EXTRA)).toEqual({ needsLeaflet: true });
|
||||
expect(mapLibreBasemap('trek:template', 'https://tiles.example.com/{z}/{x}/{y}.png', false, NO_EXTRA)).toEqual({
|
||||
needsLeaflet: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('FE-MAP-GLBASEMAP-007: a vector template draws itself where allowed, Liberty where not', () => {
|
||||
expect(mapLibreBasemap('trek:template', OFM_POSITRON, false, NO_EXTRA).style).toBe(OFM_POSITRON);
|
||||
expect(mapLibreBasemap('trek:template', 'https://maps.example.com/style.json', false, NO_EXTRA).style).toBe(
|
||||
OPENFREEMAP_DEFAULT_STYLE
|
||||
);
|
||||
expect(
|
||||
mapLibreBasemap('trek:template', 'https://maps.example.com/style.json', false, ['maps.example.com']).style
|
||||
).toBe('https://maps.example.com/style.json');
|
||||
expect(mapLibreBasemap('trek:template', 'mapbox://styles/mapbox/streets-v12', false, NO_EXTRA).style).toBe(
|
||||
OPENFREEMAP_DEFAULT_STYLE
|
||||
);
|
||||
});
|
||||
|
||||
it('FE-MAP-GLBASEMAP-008: a style URL is no raster style', () => {
|
||||
expect(isGlRasterStyle(OPENFREEMAP_DEFAULT_STYLE)).toBe(false);
|
||||
expect(isGlRasterStyle(null)).toBe(false);
|
||||
expect(isGlRasterStyle(rasterOf(OSM))).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
import { MAPLIBRE_FROM_TEMPLATE, MAPLIBRE_OFM_AUTO, OPENFREEMAP_DEFAULT_STYLE, OPENFREEMAP_HOST } from '@trek/shared';
|
||||
|
||||
import { OFM_DARK } from '../../constants/mapDefaults';
|
||||
import { glCanFetch, resolveBasemapSpec, type BasemapSpec } from './basemapSpec';
|
||||
|
||||
/*
|
||||
* The style a MapLibre map draws for the two maplibre_style keywords, from the
|
||||
* renderer-neutral basemap spec. Pure and free of both GL SDKs (`check:gl-split`).
|
||||
*/
|
||||
|
||||
/** The id of the raster source and layer a template style draws; the health watch listens for it. */
|
||||
export const GL_BASEMAP_SOURCE = 'basemap';
|
||||
|
||||
/**
|
||||
* OpenFreeMap's glyph server. A raster style has no labels of its own, but the
|
||||
* map's own layers do (cluster counts, route labels), and a style without a
|
||||
* glyph URL drops them. The host is already in the CSP for the default style.
|
||||
*/
|
||||
const OPENFREEMAP_GLYPHS = `https://${OPENFREEMAP_HOST}/fonts/{fontstack}/{range}.pbf`;
|
||||
|
||||
/** A MapLibre style document drawing one raster template, built in memory. */
|
||||
interface GlRasterStyle {
|
||||
version: 8;
|
||||
glyphs: string;
|
||||
/** The template it was built from, for the offline check: style documents carry free-form metadata. */
|
||||
metadata: { 'trek:template': string };
|
||||
sources: Record<
|
||||
string,
|
||||
{
|
||||
type: 'raster';
|
||||
tiles: string[];
|
||||
tileSize: number;
|
||||
maxzoom: number;
|
||||
scheme: 'xyz' | 'tms';
|
||||
attribution: string;
|
||||
}
|
||||
>;
|
||||
layers: { id: string; type: 'raster'; source: string; paint: { 'raster-fade-duration': number } }[];
|
||||
}
|
||||
|
||||
/** What a GL map is built with: a style URL, or a style document built here. */
|
||||
export type GlStyle = string | GlRasterStyle;
|
||||
|
||||
export function isGlRasterStyle(style: unknown): style is GlRasterStyle {
|
||||
return typeof style === 'object' && style !== null && 'metadata' in style && 'sources' in style;
|
||||
}
|
||||
|
||||
/** A raster spec as a style document: one source, one layer, the tiles exactly as Leaflet requests them. */
|
||||
function rasterStyle(spec: Extract<BasemapSpec, { kind: 'raster' }>): GlRasterStyle {
|
||||
return {
|
||||
version: 8,
|
||||
glyphs: OPENFREEMAP_GLYPHS,
|
||||
metadata: { 'trek:template': spec.template },
|
||||
sources: {
|
||||
[GL_BASEMAP_SOURCE]: {
|
||||
type: 'raster',
|
||||
tiles: spec.tiles,
|
||||
tileSize: spec.tileSize,
|
||||
maxzoom: spec.maxNativeZoom,
|
||||
scheme: spec.scheme,
|
||||
attribution: spec.attribution,
|
||||
},
|
||||
},
|
||||
layers: [
|
||||
{ id: GL_BASEMAP_SOURCE, type: 'raster', source: GL_BASEMAP_SOURCE, paint: { 'raster-fade-duration': 100 } },
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
interface MapLibreBasemap {
|
||||
/** The style to draw instead of the slot's own; undefined keeps the map's own reading of the slot. */
|
||||
style?: GlStyle;
|
||||
/** The template cannot be drawn by a GL map here, so this render takes Leaflet with the same template. */
|
||||
needsLeaflet: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* What a MapLibre map draws for the user's `maplibre_style`.
|
||||
*
|
||||
* Any value but a keyword is left to the map, which reads it exactly as before.
|
||||
* `trek:ofm-auto` follows the colour scheme. `trek:template` draws `template`,
|
||||
* the template the caller already resolved for Leaflet (CARTO key, keyless
|
||||
* fallback and the dark default included), so both renderers show the same
|
||||
* map: a raster template as a raster style, an OpenFreeMap or allowed vector
|
||||
* style as itself. A raster template a GL map may not fetch (GCJ-02, a host the
|
||||
* CSP does not name) needs Leaflet; a vector style it may not fetch draws
|
||||
* Liberty, which is what MapLibre drew for any foreign style before.
|
||||
*/
|
||||
export function mapLibreBasemap(
|
||||
maplibreStyle: string | null | undefined,
|
||||
template: string,
|
||||
dark: boolean,
|
||||
extraHosts: readonly string[]
|
||||
): MapLibreBasemap {
|
||||
const keyword = (maplibreStyle || '').trim();
|
||||
if (keyword === MAPLIBRE_OFM_AUTO) return { style: dark ? OFM_DARK : OPENFREEMAP_DEFAULT_STYLE, needsLeaflet: false };
|
||||
if (keyword !== MAPLIBRE_FROM_TEMPLATE) return { needsLeaflet: false };
|
||||
// The template is resolved already; resolving it again with itself as the fallback changes nothing.
|
||||
const spec = resolveBasemapSpec(template, template);
|
||||
const fetchable = glCanFetch(spec, extraHosts);
|
||||
if (spec.kind === 'vector')
|
||||
return { style: fetchable ? spec.styleUrl : OPENFREEMAP_DEFAULT_STYLE, needsLeaflet: false };
|
||||
return fetchable ? { style: rasterStyle(spec), needsLeaflet: false } : { needsLeaflet: true };
|
||||
}
|
||||
@@ -1,13 +1,14 @@
|
||||
import type { ComponentType } from 'react'
|
||||
import { lazyWithRetry } from '../../utils/lazyWithRetry'
|
||||
import type { GlStyle } from './glBasemap'
|
||||
import type { GlMapProvider } from './glProviders'
|
||||
import type { MapViewProps } from './mapViewContract'
|
||||
|
||||
/** What a caller hands the GL trip map: the shared map contract and which provider's style to load. */
|
||||
export type MapViewGLProps = MapViewProps & {
|
||||
glProvider?: GlMapProvider
|
||||
/** A style URL that replaces the provider's, as the offline fallback map (MapViewAuto). */
|
||||
styleOverride?: string
|
||||
/** A style that replaces the provider's: the offline basemap or a resolved keyword (useEffectiveMapEngine). */
|
||||
styleOverride?: GlStyle
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { mapLibreBasemap } from './glBasemap';
|
||||
import { applyGl3d, glMapOptions } from './glMapOptions';
|
||||
|
||||
const env = vi.hoisted(() => ({ tileStore: false }));
|
||||
@@ -24,7 +25,9 @@ const STANDARD = 'mapbox://styles/mapbox/standard';
|
||||
const SATELLITE = 'mapbox://styles/mapbox/satellite-v9';
|
||||
const LIBERTY = 'https://tiles.openfreemap.org/styles/liberty';
|
||||
|
||||
function tripMap(provider: 'mapbox-gl' | 'maplibre-gl', quality: boolean, style = STREETS) {
|
||||
const RASTER = mapLibreBasemap('trek:template', 'https://tile.openstreetmap.de/{z}/{x}/{y}.png', false, []).style;
|
||||
|
||||
function tripMap(provider: 'mapbox-gl' | 'maplibre-gl', quality: boolean, style: unknown = STREETS) {
|
||||
return glMapOptions({
|
||||
provider,
|
||||
container,
|
||||
@@ -137,6 +140,16 @@ describe('glMapOptions: MapLibre', () => {
|
||||
'aroundCenter',
|
||||
]);
|
||||
});
|
||||
|
||||
it('FE-MAP-GLOPTIONS-011: a raster template stops at the zoom Leaflet stops at', () => {
|
||||
const options = tripMap('maplibre-gl', false, RASTER);
|
||||
expect(options.style).toBe(RASTER);
|
||||
expect(options.maxZoom).toBe(19);
|
||||
});
|
||||
|
||||
it('FE-MAP-GLOPTIONS-012: a style document never moves the Mapbox ceiling', () => {
|
||||
expect(tripMap('mapbox-gl', false, RASTER)).not.toHaveProperty('maxZoom');
|
||||
});
|
||||
});
|
||||
|
||||
describe('applyGl3d', () => {
|
||||
@@ -196,6 +209,13 @@ describe('applyGl3d', () => {
|
||||
expect(map.setTerrain).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-MAP-GLOPTIONS-026: a raster template style is left as it is', () => {
|
||||
const map = fakeMap();
|
||||
applyGl3d(map as unknown as GlMap, RASTER ?? '', true, false);
|
||||
expect(map.addLayer).not.toHaveBeenCalled();
|
||||
expect(map.setTerrain).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-MAP-GLOPTIONS-025: a MapLibre style is left as it is', () => {
|
||||
const map = fakeMap();
|
||||
applyGl3d(map as unknown as GlMap, LIBERTY, false, false);
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import type mapboxgl from 'mapbox-gl';
|
||||
|
||||
import { MAP_MAX_ZOOM } from '../../constants/mapDefaults';
|
||||
import { mapboxTileCacheRequest, tileCacheActive } from '../../native/tileCache';
|
||||
import { isGlRasterStyle, type GlStyle } from './glBasemap';
|
||||
import { MAPBOX_DEFAULT_STYLE, type GlMapProvider } from './glProviders';
|
||||
import {
|
||||
addCustom3dBuildings,
|
||||
@@ -57,6 +59,9 @@ export function glMapOptions(input: GlMapOptionsInput): Record<string, unknown>
|
||||
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;
|
||||
// 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;
|
||||
return options;
|
||||
}
|
||||
|
||||
@@ -71,7 +76,8 @@ export function glMapOptions(input: GlMapOptionsInput): Record<string, unknown>
|
||||
* on their coordinates at every zoom; the satellite variant keeps it, the DEM is
|
||||
* what gives it its character. A MapLibre style matches none of these.
|
||||
*/
|
||||
export function applyGl3d(map: mapboxgl.Map, style: string, enable3d: boolean, dark: boolean): void {
|
||||
export function applyGl3d(map: mapboxgl.Map, style: GlStyle, enable3d: boolean, dark: boolean): void {
|
||||
if (typeof style !== 'string') return;
|
||||
if (enable3d) {
|
||||
if (!isStandardFamily(style) && wantsTerrain(style)) addTerrainAndSky(map);
|
||||
if (supportsCustom3d(style)) addCustom3dBuildings(map, dark);
|
||||
|
||||
@@ -6,6 +6,8 @@ import {
|
||||
normalizeStyleForProvider,
|
||||
styleForActiveProvider,
|
||||
basemapLanguage,
|
||||
isMapLibreKeyword,
|
||||
normalizeMapLibreSelection,
|
||||
} from './glProviders'
|
||||
|
||||
describe('glProviders', () => {
|
||||
@@ -69,4 +71,21 @@ describe('glProviders', () => {
|
||||
expect(basemapLanguage(undefined)).toBe('en')
|
||||
expect(basemapLanguage('')).toBe('en')
|
||||
})
|
||||
|
||||
it('keeps the MapLibre keywords in the forms and nowhere else', () => {
|
||||
expect(isMapLibreKeyword('trek:template')).toBe(true)
|
||||
expect(isMapLibreKeyword(' trek:ofm-auto ')).toBe(true)
|
||||
expect(isMapLibreKeyword('trek:other')).toBe(false)
|
||||
expect(isMapLibreKeyword(undefined)).toBe(false)
|
||||
expect(normalizeMapLibreSelection('trek:template')).toBe('trek:template')
|
||||
expect(normalizeMapLibreSelection(' trek:ofm-auto ')).toBe('trek:ofm-auto')
|
||||
expect(normalizeMapLibreSelection('https://tiles.openfreemap.org/styles/bright')).toBe(
|
||||
'https://tiles.openfreemap.org/styles/bright',
|
||||
)
|
||||
expect(normalizeMapLibreSelection('mapbox://styles/mapbox/streets-v12')).toBe(OPENFREEMAP_DEFAULT_STYLE)
|
||||
expect(normalizeMapLibreSelection('')).toBe(OPENFREEMAP_DEFAULT_STYLE)
|
||||
// The render paths that cannot draw a keyword still read it as the default.
|
||||
expect(normalizeStyleForProvider('maplibre-gl', 'trek:template')).toBe(OPENFREEMAP_DEFAULT_STYLE)
|
||||
expect(styleForActiveProvider('maplibre-gl', null, 'trek:ofm-auto')).toBe(OPENFREEMAP_DEFAULT_STYLE)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { OPENFREEMAP_DEFAULT_STYLE } from '@trek/shared'
|
||||
import { MAPLIBRE_FROM_TEMPLATE, MAPLIBRE_OFM_AUTO, OPENFREEMAP_DEFAULT_STYLE } from '@trek/shared'
|
||||
|
||||
// The server builds its CSP from the same shared map defaults, so the style a
|
||||
// MapLibre map falls back to is always one the policy lets it fetch.
|
||||
@@ -54,6 +54,28 @@ export function normalizeStyleForProvider(provider: GlMapProvider, style?: strin
|
||||
return trimmed
|
||||
}
|
||||
|
||||
/**
|
||||
* A maplibre_style keyword (trek:template, trek:ofm-auto) rather than a style
|
||||
* URL. Only the trip and journey maps resolve one (useEffectiveMapEngine); every
|
||||
* other reader of the slot goes through normalizeStyleForProvider and draws the
|
||||
* default, as a client from before the keywords does.
|
||||
*/
|
||||
export function isMapLibreKeyword(style?: string | null): boolean {
|
||||
const trimmed = (style || '').trim()
|
||||
return trimmed === MAPLIBRE_FROM_TEMPLATE || trimmed === MAPLIBRE_OFM_AUTO
|
||||
}
|
||||
|
||||
/**
|
||||
* What the settings forms keep in the MapLibre slot: an OpenFreeMap style or a
|
||||
* keyword, anything else becomes Liberty. The forms load and save through this
|
||||
* rather than normalizeStyleForProvider, which would turn a keyword into Liberty
|
||||
* on the first unchanged save.
|
||||
*/
|
||||
export function normalizeMapLibreSelection(style?: string | null): string {
|
||||
const trimmed = (style || '').trim()
|
||||
return isMapLibreKeyword(trimmed) ? trimmed : normalizeStyleForProvider('maplibre-gl', trimmed)
|
||||
}
|
||||
|
||||
/** The settings key that holds the style for a given GL provider. */
|
||||
export function styleSettingKey(provider: GlMapProvider): 'mapbox_style' | 'maplibre_style' {
|
||||
return provider === 'maplibre-gl' ? 'maplibre_style' : 'mapbox_style'
|
||||
|
||||
@@ -9,7 +9,9 @@
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { hasWebGL, resetWebGLProbe } from '../../utils/webgl';
|
||||
import { GL_BASEMAP_SOURCE, mapLibreBasemap } from './glBasemap';
|
||||
import { buildGlMap, initialMapStyle, isGpuInitFailure, pickGlRenderer, useGlRenderer, useWebGL2 } from './glSupport';
|
||||
import { rasterTemplateFailed, resetRasterHealth } from './rasterHealth';
|
||||
|
||||
const realGetContext = HTMLCanvasElement.prototype.getContext;
|
||||
|
||||
@@ -103,6 +105,29 @@ describe('buildGlMap', () => {
|
||||
).toThrow('style is undefined');
|
||||
expect(hasWebGL()).toBe(true);
|
||||
});
|
||||
|
||||
it('FE-MAP-GLSUP-010: a map built on a raster template has its first tiles watched', () => {
|
||||
const template = 'https://tile.openstreetmap.de/{z}/{x}/{y}.png';
|
||||
const style = mapLibreBasemap('trek:template', template, false, []).style;
|
||||
const errors: ((event: { sourceId?: string }) => void)[] = [];
|
||||
const map = {
|
||||
on: vi.fn((type: string, fn: (event: { sourceId?: string }) => void) => type === 'error' && errors.push(fn)),
|
||||
once: vi.fn(),
|
||||
};
|
||||
try {
|
||||
buildGlMap(() => map, style);
|
||||
for (let i = 0; i < 12; i++) errors.forEach((fn) => fn({ sourceId: GL_BASEMAP_SOURCE }));
|
||||
expect(rasterTemplateFailed(template)).toBe(true);
|
||||
} finally {
|
||||
resetRasterHealth();
|
||||
}
|
||||
});
|
||||
|
||||
it('FE-MAP-GLSUP-011: a style URL adds no listener', () => {
|
||||
const map = { on: vi.fn(), once: vi.fn() };
|
||||
buildGlMap(() => map, 'https://tiles.openfreemap.org/styles/liberty');
|
||||
expect(map.on).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('followContainerSize', () => {
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { useSyncExternalStore } from 'react';
|
||||
import { offlineStyle } from '../../native/offlineTiles';
|
||||
import { hasWebGL, reportWebGLFailure, subscribeWebGL, webGLFailures } from '../../utils/webgl';
|
||||
import type { GlStyle } from './glBasemap';
|
||||
import type { GlMapProvider } from './glProviders';
|
||||
import { watchRasterHealth } from './rasterHealth';
|
||||
|
||||
/*
|
||||
* Whether a map may be drawn with a GL engine at all, for every place that would
|
||||
@@ -58,25 +60,31 @@ export function isGpuInitFailure(err: unknown): boolean {
|
||||
return err.name === 'GPUInitializationError' || /failed to initialize webgl/i.test(err.message);
|
||||
}
|
||||
|
||||
/**
|
||||
* The style a new GL map is built with. A MapLibre map inside the iOS app reads
|
||||
* its tiles through the offline protocol (native/offlineTiles.ts); Mapbox has no
|
||||
* protocol hook, so its style goes in untouched. A style document built in
|
||||
* memory (a raster template) goes in as it is: its tiles come from the network.
|
||||
*/
|
||||
export function initialMapStyle<T extends GlStyle>(provider: GlMapProvider, style: T): T {
|
||||
return provider === 'maplibre-gl' ? offlineStyle(style) : style;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a GL map, the second line of defence behind the probe: a GPU that
|
||||
* claims WebGL2 and still fails is reported, so every map switches to Leaflet,
|
||||
* and the caller gets null instead of a throw. Anything else is a bug and is
|
||||
* thrown on.
|
||||
*
|
||||
* `style` is the style the map was built with. A raster template's first tiles
|
||||
* are watched, so a template this browser cannot load moves its maps to Leaflet
|
||||
* (rasterHealth.ts); every other style is left alone.
|
||||
*/
|
||||
/**
|
||||
* The style a new GL map is built with. A MapLibre map inside the iOS app reads
|
||||
* its tiles through the offline protocol (native/offlineTiles.ts); Mapbox has no
|
||||
* protocol hook, so its style goes in untouched.
|
||||
*/
|
||||
export function initialMapStyle(provider: GlMapProvider, style: string): string {
|
||||
return provider === 'maplibre-gl' ? offlineStyle(style) : style;
|
||||
}
|
||||
|
||||
export function buildGlMap<T>(construct: () => T): T | null {
|
||||
export function buildGlMap<T>(construct: () => T, style?: unknown): T | null {
|
||||
try {
|
||||
const map = construct();
|
||||
if (isResizableGlMap(map)) followContainerSize(map);
|
||||
watchRasterHealth(map, style);
|
||||
return map;
|
||||
} catch (err) {
|
||||
if (!isGpuInitFailure(err)) throw err;
|
||||
|
||||
@@ -196,8 +196,9 @@ export interface MapViewProps {
|
||||
*/
|
||||
onViewportChange?: (bbox: { south: number; west: number; north: number; east: number }, zoom: number) => void;
|
||||
/**
|
||||
* The raster tile URL template. Only the Leaflet renderer draws raster tiles;
|
||||
* the GL renderer draws the style of the chosen provider and ignores it.
|
||||
* The user's basemap template, resolved (useTileUrl). Leaflet always draws it.
|
||||
* A GL map draws the style of its provider instead, except MapLibre on the
|
||||
* `trek:template` keyword, which draws this same template (useEffectiveMapEngine).
|
||||
*/
|
||||
tileUrl?: string;
|
||||
/**
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import type mapboxgl from 'mapbox-gl'
|
||||
import type { GlStyle } from './glBasemap'
|
||||
|
||||
// "mapbox/standard" and "mapbox/standard-satellite" ship their own 3D
|
||||
// buildings and terrain. For every other style we inject a fill-extrusion
|
||||
// layer against the classic `composite` vector source so the user still
|
||||
// gets real 3D buildings (not just a tilted 2D view) when they toggle 3D.
|
||||
export function isStandardFamily(style: string): boolean {
|
||||
// A style document built in memory (a MapLibre raster template) is never one of them.
|
||||
export function isStandardFamily(style: GlStyle): boolean {
|
||||
return style === 'mapbox://styles/mapbox/standard' || style === 'mapbox://styles/mapbox/standard-satellite'
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { OFM_DARK, OFM_POSITRON } from '../../constants/mapDefaults';
|
||||
import { isOfflineForbiddenTemplate } from '../../utils/tileUrl';
|
||||
import { mapLibreBasemap } from './glBasemap';
|
||||
import { glWorksOffline, leafletWorksOffline, offlineStyleFor } from './offlineBasemap';
|
||||
|
||||
describe('offlineBasemap', () => {
|
||||
@@ -31,4 +32,17 @@ describe('offlineBasemap', () => {
|
||||
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);
|
||||
});
|
||||
|
||||
it('draws a MapLibre raster template offline where Leaflet would keep the same tiles', () => {
|
||||
const own = mapLibreBasemap('trek:template', 'https://tiles.example.com/{z}/{x}/{y}.png', false, [
|
||||
'tiles.example.com',
|
||||
]);
|
||||
const osm = mapLibreBasemap('trek:template', 'https://tile.openstreetmap.org/{z}/{x}/{y}.png', false, []);
|
||||
expect(glWorksOffline('maplibre-gl', own.style)).toBe(true);
|
||||
// The OSM tile usage policy forbids storing its tiles, so the stored basemap stands in.
|
||||
expect(glWorksOffline('maplibre-gl', osm.style)).toBe(false);
|
||||
expect(glWorksOffline('mapbox-gl', own.style)).toBe(false);
|
||||
// A keyword read as a slot value is not a stored style.
|
||||
expect(glWorksOffline('maplibre-gl', 'trek:template')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { OFM_DARK, OFM_POSITRON } from '../../constants/mapDefaults';
|
||||
import { isNativeIos } from '../../native/platform';
|
||||
import { isOfflineForbiddenTemplate, isVectorStyle } from '../../utils/tileUrl';
|
||||
import { isGlRasterStyle, type GlStyle } from './glBasemap';
|
||||
import { normalizeStyleForProvider, type GlMapProvider } from './glProviders';
|
||||
|
||||
/**
|
||||
@@ -22,12 +23,16 @@ export function offlineStyleFor(dark: boolean): string {
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Whether a GL map can be drawn offline as configured. Only MapLibre can, on
|
||||
* one of the stored styles (another OpenFreeMap style lacks its sprite and
|
||||
* glyphs offline) or on a raster template whose tiles the prefetch stored the
|
||||
* way Leaflet's are; Mapbox has nothing stored to draw from. `style` is what the
|
||||
* map draws: the slot's value, or the style a keyword resolved to.
|
||||
*/
|
||||
export function glWorksOffline(provider: GlMapProvider, maplibreStyle: string | null | undefined): boolean {
|
||||
return provider === 'maplibre-gl' && OFFLINE_STYLES.includes(normalizeStyleForProvider('maplibre-gl', maplibreStyle));
|
||||
export function glWorksOffline(provider: GlMapProvider, style: GlStyle | null | undefined): boolean {
|
||||
if (provider !== 'maplibre-gl') return false;
|
||||
if (isGlRasterStyle(style)) return leafletWorksOffline(style.metadata['trek:template']);
|
||||
return OFFLINE_STYLES.includes(normalizeStyleForProvider('maplibre-gl', style));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
* The session watch over a raster template a MapLibre map draws (FE-MAP-RASTERHEALTH-*).
|
||||
*/
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
|
||||
import { GL_BASEMAP_SOURCE, mapLibreBasemap } from './glBasemap';
|
||||
import { rasterTemplateFailed, resetRasterHealth, useRasterHealth, watchRasterHealth } from './rasterHealth';
|
||||
|
||||
const TEMPLATE = 'https://tile.openstreetmap.de/{z}/{x}/{y}.png';
|
||||
const STYLE = mapLibreBasemap('trek:template', TEMPLATE, false, []).style;
|
||||
|
||||
type Listener = (event: { sourceId?: string; tile?: unknown }) => void;
|
||||
|
||||
/** Just enough of a GL map: the events the watch listens for, fired by hand. */
|
||||
function fakeMap() {
|
||||
const listeners: Record<string, Listener[]> = {};
|
||||
const add = (type: string, listener: Listener) => {
|
||||
(listeners[type] ??= []).push(listener);
|
||||
};
|
||||
return {
|
||||
on: add,
|
||||
once: add,
|
||||
fire: (type: string, event: { sourceId?: string; tile?: unknown } = {}) =>
|
||||
listeners[type]?.forEach((listener) => listener(event)),
|
||||
};
|
||||
}
|
||||
|
||||
function violation(blockedURI: string): Event {
|
||||
return Object.assign(new Event('securitypolicyviolation'), { blockedURI });
|
||||
}
|
||||
|
||||
afterEach(() => resetRasterHealth());
|
||||
|
||||
describe('watchRasterHealth', () => {
|
||||
it('FE-MAP-RASTERHEALTH-001: twelve failed tiles without a success mark the template', () => {
|
||||
const map = fakeMap();
|
||||
watchRasterHealth(map, STYLE);
|
||||
for (let i = 0; i < 11; i++) map.fire('error', { sourceId: GL_BASEMAP_SOURCE });
|
||||
expect(rasterTemplateFailed(TEMPLATE)).toBe(false);
|
||||
map.fire('error', { sourceId: GL_BASEMAP_SOURCE });
|
||||
expect(rasterTemplateFailed(TEMPLATE)).toBe(true);
|
||||
});
|
||||
|
||||
it('FE-MAP-RASTERHEALTH-002: one tile that arrived ends the watch, later failures are an outage', () => {
|
||||
const map = fakeMap();
|
||||
watchRasterHealth(map, STYLE);
|
||||
map.fire('data', { sourceId: GL_BASEMAP_SOURCE, tile: {} });
|
||||
for (let i = 0; i < 20; i++) map.fire('error', { sourceId: GL_BASEMAP_SOURCE });
|
||||
expect(rasterTemplateFailed(TEMPLATE)).toBe(false);
|
||||
});
|
||||
|
||||
it("FE-MAP-RASTERHEALTH-003: errors of the map's other sources do not count", () => {
|
||||
const map = fakeMap();
|
||||
watchRasterHealth(map, STYLE);
|
||||
for (let i = 0; i < 20; i++) map.fire('error', { sourceId: 'route' });
|
||||
map.fire('data', { sourceId: GL_BASEMAP_SOURCE });
|
||||
expect(rasterTemplateFailed(TEMPLATE)).toBe(false);
|
||||
// Still watching: removing the map ends it, so no later test meets this one's listener.
|
||||
map.fire('remove');
|
||||
});
|
||||
|
||||
it('FE-MAP-RASTERHEALTH-004: a CSP refusal of one of its tiles marks the template at once', () => {
|
||||
watchRasterHealth(fakeMap(), STYLE);
|
||||
document.dispatchEvent(violation('https://tile.openstreetmap.de.evil.test/1/2/3.png'));
|
||||
expect(rasterTemplateFailed(TEMPLATE)).toBe(false);
|
||||
document.dispatchEvent(violation('https://tile.openstreetmap.de/5/16/10.png'));
|
||||
expect(rasterTemplateFailed(TEMPLATE)).toBe(true);
|
||||
});
|
||||
|
||||
it('FE-MAP-RASTERHEALTH-005: a removed map stops listening for refusals', () => {
|
||||
const map = fakeMap();
|
||||
watchRasterHealth(map, STYLE);
|
||||
map.fire('remove');
|
||||
document.dispatchEvent(violation('https://tile.openstreetmap.de/5/16/10.png'));
|
||||
expect(rasterTemplateFailed(TEMPLATE)).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-MAP-RASTERHEALTH-006: a style URL is not watched', () => {
|
||||
const map = fakeMap();
|
||||
watchRasterHealth(map, 'https://tiles.openfreemap.org/styles/liberty');
|
||||
for (let i = 0; i < 20; i++) map.fire('error', { sourceId: GL_BASEMAP_SOURCE });
|
||||
expect(rasterTemplateFailed(TEMPLATE)).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-MAP-RASTERHEALTH-007: a mark re-renders the maps that read the health', () => {
|
||||
const { result } = renderHook(() => useRasterHealth());
|
||||
const before = result.current;
|
||||
const map = fakeMap();
|
||||
watchRasterHealth(map, STYLE);
|
||||
act(() => {
|
||||
for (let i = 0; i < 12; i++) map.fire('error', { sourceId: GL_BASEMAP_SOURCE });
|
||||
});
|
||||
expect(result.current).toBeGreaterThan(before);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,115 @@
|
||||
import { useSyncExternalStore } from 'react';
|
||||
|
||||
import { GL_BASEMAP_SOURCE, isGlRasterStyle } from './glBasemap';
|
||||
|
||||
/*
|
||||
* Whether a raster template a MapLibre map draws actually loads here.
|
||||
*
|
||||
* glCanFetch answers from the policy TREK ships, but a reverse proxy can send a
|
||||
* different Content-Security-Policy, and a tile server can refuse cross-origin
|
||||
* requests that Leaflet's images never made. Either way every tile fails and the
|
||||
* GL map stays empty while Leaflet would have drawn the template. So the first
|
||||
* requests are watched: when the browser reports a CSP refusal for one of the
|
||||
* template's tiles, or the first FIRST_TILES all fail without one success, the
|
||||
* template is marked for the rest of the session and every map drawing it takes
|
||||
* Leaflet instead, with a pill that says so. Nothing is stored: the next session
|
||||
* tries GL again.
|
||||
*/
|
||||
|
||||
/** How many tile results decide: all of them failing is no outage of one tile. */
|
||||
const FIRST_TILES = 12;
|
||||
|
||||
const failed = new Set<string>();
|
||||
const listeners = new Set<() => void>();
|
||||
let version = 0;
|
||||
|
||||
function markFailed(template: string): void {
|
||||
if (failed.has(template)) return;
|
||||
failed.add(template);
|
||||
version++;
|
||||
for (const listener of listeners) listener();
|
||||
}
|
||||
|
||||
/** Whether a GL map failed to load this template's tiles in this session. */
|
||||
export function rasterTemplateFailed(template: string): boolean {
|
||||
return failed.has(template);
|
||||
}
|
||||
|
||||
function subscribe(listener: () => void): () => void {
|
||||
listeners.add(listener);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
/** Re-renders the caller when a template was marked, so its map can switch to Leaflet. */
|
||||
export function useRasterHealth(): number {
|
||||
return useSyncExternalStore(
|
||||
subscribe,
|
||||
() => version,
|
||||
() => version
|
||||
);
|
||||
}
|
||||
|
||||
/** The events of a GL map this module reads; both engines fire them in this shape. */
|
||||
interface WatchedMap {
|
||||
on(type: 'data' | 'error', listener: (event: { sourceId?: string; tile?: unknown }) => void): unknown;
|
||||
once(type: 'remove', listener: () => void): unknown;
|
||||
}
|
||||
|
||||
/** The origins of a style's tile URLs, `https://host[:port]`, to match a refused URL against. */
|
||||
function tileOrigins(tiles: string[]): string[] {
|
||||
return tiles.flatMap((url) => {
|
||||
try {
|
||||
return [new URL(url).origin];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function isWatchable(map: unknown): map is WatchedMap {
|
||||
const candidate = map as Partial<WatchedMap> | null;
|
||||
return typeof candidate?.on === 'function' && typeof candidate.once === 'function';
|
||||
}
|
||||
|
||||
/**
|
||||
* Watches a freshly built map whose style draws a raster template (buildGlMap
|
||||
* 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 {
|
||||
if (!isGlRasterStyle(style) || !isWatchable(map)) return;
|
||||
const template = style.metadata['trek:template'];
|
||||
const origins = tileOrigins(style.sources[GL_BASEMAP_SOURCE]?.tiles ?? []);
|
||||
let failures = 0;
|
||||
let settled = false;
|
||||
|
||||
function settle(broken: boolean): void {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
document.removeEventListener('securitypolicyviolation', onViolation);
|
||||
if (broken) markFailed(template);
|
||||
}
|
||||
function onViolation(event: SecurityPolicyViolationEvent): void {
|
||||
const blocked = event.blockedURI;
|
||||
if (origins.some((origin) => blocked === origin || blocked.startsWith(`${origin}/`))) settle(true);
|
||||
}
|
||||
|
||||
document.addEventListener('securitypolicyviolation', onViolation);
|
||||
map.on('data', (event) => {
|
||||
if (event.sourceId === GL_BASEMAP_SOURCE && event.tile) settle(false);
|
||||
});
|
||||
map.on('error', (event) => {
|
||||
if (event.sourceId !== GL_BASEMAP_SOURCE || settled) return;
|
||||
failures++;
|
||||
if (failures >= FIRST_TILES) settle(true);
|
||||
});
|
||||
map.once('remove', () => settle(false));
|
||||
}
|
||||
|
||||
/** Test seam: a fresh session. */
|
||||
export function resetRasterHealth(): void {
|
||||
failed.clear();
|
||||
version++;
|
||||
}
|
||||
@@ -10,8 +10,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
|
||||
import { OFM_DARK, OFM_POSITRON } from '../../constants/mapDefaults';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import { resetWebGLProbe } from '../../utils/webgl';
|
||||
import { GL_BASEMAP_SOURCE } from './glBasemap';
|
||||
import { OPENFREEMAP_DEFAULT_STYLE } from './glProviders';
|
||||
import { resetRasterHealth, watchRasterHealth } from './rasterHealth';
|
||||
import { useEffectiveMapEngine } from './useEffectiveMapEngine';
|
||||
|
||||
const env = vi.hoisted(() => ({ offline: false, dark: false, tileStore: false }));
|
||||
@@ -56,6 +60,7 @@ beforeEach(() => {
|
||||
afterEach(() => {
|
||||
HTMLCanvasElement.prototype.getContext = realGetContext;
|
||||
resetWebGLProbe();
|
||||
resetRasterHealth();
|
||||
});
|
||||
|
||||
describe('useEffectiveMapEngine online', () => {
|
||||
@@ -173,3 +178,121 @@ describe('useEffectiveMapEngine offline', () => {
|
||||
expect(result.current).toMatchObject({ engine: null, tileUrlOverride: undefined, pill: null });
|
||||
});
|
||||
});
|
||||
|
||||
describe('useEffectiveMapEngine: the MapLibre keywords', () => {
|
||||
const OSM_DE = 'https://tile.openstreetmap.de/{z}/{x}/{y}.png';
|
||||
const AMAP = 'https://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}';
|
||||
const NOTHING_SWAPPED = { engine: null, styleOverride: undefined, tileUrlOverride: undefined, pill: null };
|
||||
|
||||
function styleSource(style: unknown) {
|
||||
return (style as { sources: Record<string, { tiles: string[] }> }).sources[GL_BASEMAP_SOURCE];
|
||||
}
|
||||
|
||||
it('FE-MAP-EFFENGINE-030: trek:template draws the resolved template as a raster style', () => {
|
||||
settings({ map_provider: 'maplibre-gl', maplibre_style: 'trek:template' });
|
||||
const { result } = renderHook(() => useEffectiveMapEngine(OSM_DE));
|
||||
expect(result.current.engine).toBe('maplibre-gl');
|
||||
expect(styleSource(result.current.styleOverride)?.tiles).toEqual([OSM_DE]);
|
||||
expect(result.current.pill).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-MAP-EFFENGINE-031: the style is one object across renders, so the map is not rebuilt', () => {
|
||||
settings({ map_provider: 'maplibre-gl', maplibre_style: 'trek:template' });
|
||||
const { result, rerender } = renderHook(() => useEffectiveMapEngine(OSM_DE));
|
||||
const first = result.current.styleOverride;
|
||||
rerender();
|
||||
expect(result.current.styleOverride).toBe(first);
|
||||
});
|
||||
|
||||
it('FE-MAP-EFFENGINE-032: Amap and a host outside the policy are drawn by Leaflet for this render, no pill', () => {
|
||||
settings({ map_provider: 'maplibre-gl', maplibre_style: 'trek:template' });
|
||||
for (const template of [AMAP, OWN_RASTER]) {
|
||||
const { result } = renderHook(() => useEffectiveMapEngine(template));
|
||||
expect(result.current).toEqual(NOTHING_SWAPPED);
|
||||
}
|
||||
expect(useSettingsStore.getState().settings.map_provider).toBe('maplibre-gl');
|
||||
});
|
||||
|
||||
it('FE-MAP-EFFENGINE-033: a host of the operator is drawn by MapLibre once the app config names it', () => {
|
||||
settings({ map_provider: 'maplibre-gl', maplibre_style: 'trek:template' });
|
||||
seedStore(useAuthStore, { mapExtraConnectHosts: ['tiles.example.com'] });
|
||||
const { result } = renderHook(() => useEffectiveMapEngine(OWN_RASTER));
|
||||
expect(result.current.engine).toBe('maplibre-gl');
|
||||
expect(styleSource(result.current.styleOverride)?.tiles).toEqual([OWN_RASTER]);
|
||||
});
|
||||
|
||||
it('FE-MAP-EFFENGINE-034: a template whose tiles all failed moves to Leaflet with a pill', () => {
|
||||
settings({ map_provider: 'maplibre-gl', maplibre_style: 'trek:template' });
|
||||
const { result } = renderHook(() => useEffectiveMapEngine(OSM_DE));
|
||||
const errors: ((event: { sourceId?: string }) => void)[] = [];
|
||||
const map = {
|
||||
on: (type: string, fn: (event: { sourceId?: string }) => void) => type === 'error' && errors.push(fn),
|
||||
once: () => {},
|
||||
};
|
||||
watchRasterHealth(map, result.current.styleOverride);
|
||||
act(() => {
|
||||
for (let i = 0; i < 12; i++) errors.forEach((fn) => fn({ sourceId: GL_BASEMAP_SOURCE }));
|
||||
});
|
||||
expect(result.current).toEqual({ ...NOTHING_SWAPPED, pill: { kind: 'classic' } });
|
||||
});
|
||||
|
||||
it('FE-MAP-EFFENGINE-035: trek:ofm-auto follows the colour scheme', () => {
|
||||
settings({ map_provider: 'maplibre-gl', maplibre_style: 'trek:ofm-auto' });
|
||||
expect(renderHook(() => useEffectiveMapEngine(undefined)).result.current.styleOverride).toBe(
|
||||
OPENFREEMAP_DEFAULT_STYLE
|
||||
);
|
||||
env.dark = true;
|
||||
expect(renderHook(() => useEffectiveMapEngine(undefined)).result.current.styleOverride).toBe(OFM_DARK);
|
||||
});
|
||||
|
||||
it('FE-MAP-EFFENGINE-036: a keyword means nothing to the other providers', () => {
|
||||
settings({ map_provider: 'mapbox-gl', mapbox_access_token: 'pk.test', maplibre_style: 'trek:template' });
|
||||
const { result } = renderHook(() => useEffectiveMapEngine(OSM_DE));
|
||||
expect(result.current).toMatchObject({ engine: 'mapbox-gl', styleOverride: undefined });
|
||||
});
|
||||
|
||||
describe('offline', () => {
|
||||
beforeEach(() => {
|
||||
env.offline = true;
|
||||
});
|
||||
|
||||
it('FE-MAP-EFFENGINE-037: a stored raster template keeps drawing in MapLibre', () => {
|
||||
settings({ map_provider: 'maplibre-gl', maplibre_style: 'trek:template' });
|
||||
const { result } = renderHook(() => useEffectiveMapEngine(OSM_DE));
|
||||
expect(result.current.engine).toBe('maplibre-gl');
|
||||
expect(styleSource(result.current.styleOverride)?.tiles).toEqual([OSM_DE]);
|
||||
expect(result.current.pill).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-MAP-EFFENGINE-038: OpenStreetMap, never stored, swaps to the stored basemap', () => {
|
||||
settings({ map_provider: 'maplibre-gl', maplibre_style: 'trek:template' });
|
||||
const { result } = renderHook(() => useEffectiveMapEngine('https://tile.openstreetmap.org/{z}/{x}/{y}.png'));
|
||||
expect(result.current).toMatchObject({
|
||||
engine: 'maplibre-gl',
|
||||
styleOverride: OFM_POSITRON,
|
||||
pill: { kind: 'stored' },
|
||||
});
|
||||
});
|
||||
|
||||
it('FE-MAP-EFFENGINE-039: an Amap template on MapLibre is checked as the Leaflet map that draws it', () => {
|
||||
settings({ map_provider: 'maplibre-gl', maplibre_style: 'trek:template' });
|
||||
const { result } = renderHook(() => useEffectiveMapEngine(AMAP));
|
||||
// Amap tiles may be stored, so Leaflet keeps them offline, with no swap and no pill.
|
||||
expect(result.current).toEqual(NOTHING_SWAPPED);
|
||||
});
|
||||
|
||||
it('FE-MAP-EFFENGINE-040: trek:ofm-auto offline draws the stored style of the scheme', () => {
|
||||
settings({ map_provider: 'maplibre-gl', maplibre_style: 'trek:ofm-auto' });
|
||||
env.dark = true;
|
||||
expect(renderHook(() => useEffectiveMapEngine(undefined)).result.current).toMatchObject({
|
||||
styleOverride: OFM_DARK,
|
||||
pill: null,
|
||||
});
|
||||
env.dark = false;
|
||||
expect(renderHook(() => useEffectiveMapEngine(undefined)).result.current).toMatchObject({
|
||||
styleOverride: OFM_POSITRON,
|
||||
pill: { kind: 'stored' },
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,29 +1,34 @@
|
||||
import { useState } from 'react';
|
||||
import { useMemo, useState } from 'react';
|
||||
|
||||
import { OFM_POSITRON } from '../../constants/mapDefaults';
|
||||
import { useIsDark } from '../../hooks/useIsDark';
|
||||
import { useNetworkMode } from '../../hooks/useNetworkMode';
|
||||
import { glTileStoreActive, tileCacheActive } from '../../native/tileCache';
|
||||
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 { glWorksOffline, leafletWorksOffline, offlineStyleFor } from './offlineBasemap';
|
||||
import { rasterTemplateFailed, useRasterHealth } from './rasterHealth';
|
||||
|
||||
/** What the map says about the basemap on screen when it is not the user's own. */
|
||||
type OfflineBasemapPill =
|
||||
export type BasemapPillState =
|
||||
/** The stored basemap stands in, and that is all there is to say. */
|
||||
| { kind: 'stored' }
|
||||
/** The user's map is kept as far as it was viewed; the pill switches to the stored region and back. */
|
||||
| { kind: 'toggle'; pressed: boolean; onToggle: () => void };
|
||||
| { kind: 'toggle'; pressed: boolean; onToggle: () => void }
|
||||
/** The user's template did not load in MapLibre here, so the classic 2D map draws it. */
|
||||
| { kind: 'classic' };
|
||||
|
||||
interface EffectiveMapEngine {
|
||||
/** The GL engine that draws this render, or null for Leaflet. */
|
||||
engine: GlMapProvider | null;
|
||||
/** The style a GL map draws instead of the user's: the stored offline basemap. */
|
||||
styleOverride?: string;
|
||||
/** The style a GL map draws instead of its own slot: the stored offline basemap, or a resolved keyword. */
|
||||
styleOverride?: GlStyle;
|
||||
/** The basemap the Leaflet map draws instead of the user's template, for the same reason. */
|
||||
tileUrlOverride?: string;
|
||||
pill: OfflineBasemapPill | null;
|
||||
pill: BasemapPillState | null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -33,6 +38,13 @@ interface EffectiveMapEngine {
|
||||
* and both GL engines need WebGL2, so a map never fails to start and falls back
|
||||
* to Leaflet with the user's template instead. Nothing here writes a setting.
|
||||
*
|
||||
* A MapLibre user may have chosen a keyword instead of a style
|
||||
* (glBasemap.ts): `trek:ofm-auto` follows the colour scheme, `trek:template`
|
||||
* draws `tileUrl`, the template the caller resolved for Leaflet. A template a
|
||||
* GL map cannot draw here (GCJ-02, a host the CSP does not name, tiles that
|
||||
* failed in this session) is drawn by Leaflet for this render, the setting
|
||||
* untouched; only a failure at runtime is worth a pill.
|
||||
*
|
||||
* Offline, a basemap with nothing stored to draw from switches to the stored
|
||||
* OpenFreeMap one ("prepare for offline" keeps it for every trip, whatever the
|
||||
* provider, sync/tilePrefetcher.ts), with the same markers and routes, and says
|
||||
@@ -40,37 +52,68 @@ interface EffectiveMapEngine {
|
||||
* with its tile store, a Mapbox map keeps what was viewed for 30 days, so offline
|
||||
* it stays Mapbox and the pill offers the stored trip region instead.
|
||||
*
|
||||
* `tileUrl` is the template the caller resolved for Leaflet. The offline checks
|
||||
* run on the engine that actually draws, so the decision and the fallback can
|
||||
* never disagree.
|
||||
* The offline checks run on the engine that actually draws, after the template
|
||||
* decided it, so the decision and the fallback can never disagree.
|
||||
*/
|
||||
export function useEffectiveMapEngine(tileUrl: string | undefined): EffectiveMapEngine {
|
||||
const provider = useSettingsStore((s) => s.settings.map_provider);
|
||||
const token = useSettingsStore((s) => s.settings.mapbox_access_token);
|
||||
const maplibreStyle = useSettingsStore((s) => s.settings.maplibre_style);
|
||||
const extraHosts = useAuthStore((s) => s.mapExtraConnectHosts);
|
||||
const configuredGl = useGlRenderer(provider, token);
|
||||
const { offline } = useNetworkMode();
|
||||
const offlineStyle = offlineStyleFor(useIsDark());
|
||||
const dark = useIsDark();
|
||||
const offlineStyle = offlineStyleFor(dark);
|
||||
const [preferStored, setPreferStored] = useState(false);
|
||||
useRasterHealth();
|
||||
|
||||
const mapboxKept = configuredGl === 'mapbox-gl' && glTileStoreActive();
|
||||
const template = tileUrl ?? OFM_POSITRON;
|
||||
const keyword = useMemo(
|
||||
() => mapLibreBasemap(maplibreStyle, template, dark, extraHosts),
|
||||
[maplibreStyle, template, dark, extraHosts]
|
||||
);
|
||||
const drawn = templateEngine(configuredGl, keyword);
|
||||
|
||||
const mapboxKept = drawn.engine === 'mapbox-gl' && glTileStoreActive();
|
||||
const glFallback =
|
||||
!!configuredGl && offline && !glWorksOffline(configuredGl, maplibreStyle) && (!mapboxKept || preferStored);
|
||||
!!drawn.engine &&
|
||||
offline &&
|
||||
!glWorksOffline(drawn.engine, drawn.style ?? maplibreStyle) &&
|
||||
(!mapboxKept || preferStored);
|
||||
// A raster template cannot be served offline in the iOS app unless it has its tile store.
|
||||
const nativeIos = tileCacheActive() ? false : undefined;
|
||||
const leafletFallback = !configuredGl && offline && !leafletWorksOffline(tileUrl ?? OFM_POSITRON, nativeIos);
|
||||
const leafletFallback = !drawn.engine && offline && !leafletWorksOffline(template, nativeIos);
|
||||
|
||||
let pill: OfflineBasemapPill | null = null;
|
||||
let pill: BasemapPillState | null = null;
|
||||
if (offline && mapboxKept) {
|
||||
pill = { kind: 'toggle', pressed: preferStored, onToggle: () => setPreferStored((v) => !v) };
|
||||
} else if (glFallback || leafletFallback) {
|
||||
pill = { kind: 'stored' };
|
||||
} else if (drawn.templateFailed) {
|
||||
pill = { kind: 'classic' };
|
||||
}
|
||||
|
||||
return {
|
||||
engine: glFallback ? 'maplibre-gl' : configuredGl,
|
||||
styleOverride: glFallback ? offlineStyle : undefined,
|
||||
engine: glFallback ? 'maplibre-gl' : drawn.engine,
|
||||
styleOverride: glFallback ? offlineStyle : drawn.style,
|
||||
tileUrlOverride: leafletFallback ? offlineStyle : undefined,
|
||||
pill,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The engine a render takes once the MapLibre keyword had its say: MapLibre
|
||||
* with the style the keyword resolved to, or Leaflet for a template it cannot
|
||||
* draw here or whose tiles failed in this session. Any other provider, and
|
||||
* MapLibre without a keyword, draws as configured.
|
||||
*/
|
||||
function templateEngine(
|
||||
configuredGl: GlMapProvider | null,
|
||||
keyword: ReturnType<typeof mapLibreBasemap>
|
||||
): { engine: GlMapProvider | null; style?: GlStyle; templateFailed: boolean } {
|
||||
if (configuredGl !== 'maplibre-gl') return { engine: configuredGl, templateFailed: false };
|
||||
const templateFailed =
|
||||
isGlRasterStyle(keyword.style) && rasterTemplateFailed(keyword.style.metadata['trek:template']);
|
||||
if (keyword.needsLeaflet || templateFailed) return { engine: null, templateFailed };
|
||||
return { engine: 'maplibre-gl', style: keyword.style, templateFailed: false };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import type { GlStyle } from './glBasemap';
|
||||
import { MAPBOX_DEFAULT_STYLE, styleForActiveProvider, type GlMapProvider } from './glProviders';
|
||||
|
||||
/**
|
||||
* The style a trip or journey GL map is built with: `override` where the
|
||||
* caller decided one (the stored offline basemap, or what a maplibre_style
|
||||
* 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 {
|
||||
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);
|
||||
}
|
||||
Reference in New Issue
Block a user